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
# Note: if you intend to run this script make sure you look under scripts/fsmt/ # to locate the appropriate script to do the work correctly. There is a set of scripts to: # - download and prepare data and run the conversion script # - perform eval to get the best hparam into the config # - generate model_cards - useful if you have multiple models from the same paper import argparse import json import os import re from collections import OrderedDict from os.path import basename, dirname import fairseq import torch from fairseq import hub_utils from fairseq.data.dictionary import Dictionary from transformers import FSMTConfig, FSMTForConditionalGeneration from transformers.models.fsmt.tokenization_fsmt import VOCAB_FILES_NAMES from transformers.tokenization_utils_base import TOKENIZER_CONFIG_FILE from transformers.utils import WEIGHTS_NAME, logging logging.set_verbosity_warning() _snake_case : Any = 2 # based on the results of a search on a range of `num_beams`, `length_penalty` and `early_stopping` # values against wmt19 test data to obtain the best BLEU scores, we will use the following defaults: # # * `num_beams`: 5 (higher scores better, but requires more memory/is slower, can be adjusted by users) # * `early_stopping`: `False` consistently scored better # * `length_penalty` varied, so will assign the best one depending on the model _snake_case : Optional[int] = { # fairseq: "wmt19-ru-en": {"length_penalty": 1.1}, "wmt19-en-ru": {"length_penalty": 1.15}, "wmt19-en-de": {"length_penalty": 1.0}, "wmt19-de-en": {"length_penalty": 1.1}, # allenai: "wmt16-en-de-dist-12-1": {"length_penalty": 0.6}, "wmt16-en-de-dist-6-1": {"length_penalty": 0.6}, "wmt16-en-de-12-1": {"length_penalty": 0.8}, "wmt19-de-en-6-6-base": {"length_penalty": 0.6}, "wmt19-de-en-6-6-big": {"length_penalty": 0.6}, } # this remaps the different models to their organization names _snake_case : Optional[Any] = {} for m in ["wmt19-ru-en", "wmt19-en-ru", "wmt19-en-de", "wmt19-de-en"]: _snake_case : List[str] = "facebook" for m in [ "wmt16-en-de-dist-12-1", "wmt16-en-de-dist-6-1", "wmt16-en-de-12-1", "wmt19-de-en-6-6-base", "wmt19-de-en-6-6-big", ]: _snake_case : Optional[Any] = "allenai" def lowerCAmelCase_ ( __lowerCamelCase ): # (1) remove word breaking symbol, (2) add word ending symbol where the word is not broken up, # e.g.: d = {'le@@': 5, 'tt@@': 6, 'er': 7} => {'le': 5, 'tt': 6, 'er</w>': 7} __snake_case : Union[str, Any] = dict((re.sub(R"@@$" , "" , lowercase__ ), v) if k.endswith("@@" ) else (re.sub(R"$" , "</w>" , lowercase__ ), v) for k, v in d.items() ) __snake_case : Tuple = '''<s> <pad> </s> <unk>'''.split() # restore the special tokens for k in keep_keys: del da[F'{k}</w>'] __snake_case : int = d[k] # restore return da def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase ): # prep assert os.path.exists(lowercase__ ) os.makedirs(lowercase__ , exist_ok=lowercase__ ) print(F'Writing results to {pytorch_dump_folder_path}' ) # handle various types of models __snake_case : Optional[Any] = basename(lowercase__ ) __snake_case : Union[str, Any] = dirname(lowercase__ ) __snake_case : Tuple = fairseq.model_parallel.models.transformer.ModelParallelTransformerModel __snake_case : int = cls.hub_models() __snake_case : str = {'''bpe''': '''fastbpe''', '''tokenizer''': '''moses'''} __snake_case : Union[str, Any] = '''.''' # note: since the model dump is old, fairseq has upgraded its model some # time later, and it does a whole lot of rewrites and splits on the saved # weights, therefore we can't use torch.load() directly on the model file. # see: upgrade_state_dict(state_dict) in fairseq_model.py print(F'using checkpoint {checkpoint_file}' ) __snake_case : Union[str, Any] = hub_utils.from_pretrained( lowercase__ , lowercase__ , lowercase__ , archive_map=lowercase__ , **lowercase__ ) __snake_case : Dict = vars(chkpt["args"]["model"] ) __snake_case : Union[str, Any] = args['''source_lang'''] __snake_case : List[Any] = args['''target_lang'''] __snake_case : int = dirname(lowercase__ ) __snake_case : int = basename(lowercase__ ) # dicts __snake_case : Optional[Any] = os.path.join(lowercase__ , F'dict.{src_lang}.txt' ) __snake_case : Optional[Any] = os.path.join(lowercase__ , F'dict.{tgt_lang}.txt' ) __snake_case : Union[str, Any] = Dictionary.load(lowercase__ ) __snake_case : Optional[int] = rewrite_dict_keys(src_dict.indices ) __snake_case : str = len(lowercase__ ) __snake_case : Optional[Any] = os.path.join(lowercase__ , "vocab-src.json" ) print(F'Generating {src_vocab_file} of {src_vocab_size} of {src_lang} records' ) with open(lowercase__ , "w" , encoding="utf-8" ) as f: f.write(json.dumps(lowercase__ , ensure_ascii=lowercase__ , indent=lowercase__ ) ) # detect whether this is a do_lower_case situation, which can be derived by checking whether we # have at least one uppercase letter in the source vocab __snake_case : List[Any] = True for k in src_vocab.keys(): if not k.islower(): __snake_case : Union[str, Any] = False break __snake_case : int = Dictionary.load(lowercase__ ) __snake_case : Optional[Any] = rewrite_dict_keys(tgt_dict.indices ) __snake_case : Tuple = len(lowercase__ ) __snake_case : Union[str, Any] = os.path.join(lowercase__ , "vocab-tgt.json" ) print(F'Generating {tgt_vocab_file} of {tgt_vocab_size} of {tgt_lang} records' ) with open(lowercase__ , "w" , encoding="utf-8" ) as f: f.write(json.dumps(lowercase__ , ensure_ascii=lowercase__ , indent=lowercase__ ) ) # merges_file (bpecodes) __snake_case : Optional[int] = os.path.join(lowercase__ , VOCAB_FILES_NAMES["merges_file"] ) for fn in ["bpecodes", "code"]: # older fairseq called the merges file "code" __snake_case : Dict = os.path.join(lowercase__ , lowercase__ ) if os.path.exists(lowercase__ ): break with open(lowercase__ , encoding="utf-8" ) as fin: __snake_case : Dict = fin.read() __snake_case : Tuple = re.sub(R" \d+$" , "" , lowercase__ , 0 , re.M ) # remove frequency number print(F'Generating {merges_file}' ) with open(lowercase__ , "w" , encoding="utf-8" ) as fout: fout.write(lowercase__ ) # model config __snake_case : str = os.path.join(lowercase__ , "config.json" ) # validate bpe/tokenizer config, as currently it's hardcoded to moses+fastbpe - # may have to modify the tokenizer if a different type is used by a future model assert args["bpe"] == "fastbpe", F'need to extend tokenizer to support bpe={args["bpe"]}' assert args["tokenizer"] == "moses", F'need to extend tokenizer to support bpe={args["tokenizer"]}' __snake_case : Dict = { '''architectures''': ['''FSMTForConditionalGeneration'''], '''model_type''': '''fsmt''', '''activation_dropout''': args['''activation_dropout'''], '''activation_function''': '''relu''', '''attention_dropout''': args['''attention_dropout'''], '''d_model''': args['''decoder_embed_dim'''], '''dropout''': args['''dropout'''], '''init_std''': 0.0_2, '''max_position_embeddings''': args['''max_source_positions'''], '''num_hidden_layers''': args['''encoder_layers'''], '''src_vocab_size''': src_vocab_size, '''tgt_vocab_size''': tgt_vocab_size, '''langs''': [src_lang, tgt_lang], '''encoder_attention_heads''': args['''encoder_attention_heads'''], '''encoder_ffn_dim''': args['''encoder_ffn_embed_dim'''], '''encoder_layerdrop''': args['''encoder_layerdrop'''], '''encoder_layers''': args['''encoder_layers'''], '''decoder_attention_heads''': args['''decoder_attention_heads'''], '''decoder_ffn_dim''': args['''decoder_ffn_embed_dim'''], '''decoder_layerdrop''': args['''decoder_layerdrop'''], '''decoder_layers''': args['''decoder_layers'''], '''bos_token_id''': 0, '''pad_token_id''': 1, '''eos_token_id''': 2, '''is_encoder_decoder''': True, '''scale_embedding''': not args['''no_scale_embedding'''], '''tie_word_embeddings''': args['''share_all_embeddings'''], } # good hparam defaults to start with __snake_case : int = 5 __snake_case : Optional[int] = False if model_dir in best_score_hparams and "length_penalty" in best_score_hparams[model_dir]: __snake_case : Optional[int] = best_score_hparams[model_dir]['''length_penalty'''] else: __snake_case : Optional[Any] = 1.0 print(F'Generating {fsmt_model_config_file}' ) with open(lowercase__ , "w" , encoding="utf-8" ) as f: f.write(json.dumps(lowercase__ , ensure_ascii=lowercase__ , indent=lowercase__ ) ) # tokenizer config __snake_case : Tuple = os.path.join(lowercase__ , lowercase__ ) __snake_case : int = { '''langs''': [src_lang, tgt_lang], '''model_max_length''': 1_0_2_4, '''do_lower_case''': do_lower_case, } print(F'Generating {fsmt_tokenizer_config_file}' ) with open(lowercase__ , "w" , encoding="utf-8" ) as f: f.write(json.dumps(lowercase__ , ensure_ascii=lowercase__ , indent=lowercase__ ) ) # model __snake_case : List[Any] = chkpt['''models'''][0] __snake_case : List[Any] = model.state_dict() # rename keys to start with 'model.' __snake_case : Any = OrderedDict(("model." + k, v) for k, v in model_state_dict.items() ) # remove unneeded keys __snake_case : List[str] = [ '''model.model''', '''model.encoder.version''', '''model.decoder.version''', '''model.encoder_embed_tokens.weight''', '''model.decoder_embed_tokens.weight''', '''model.encoder.embed_positions._float_tensor''', '''model.decoder.embed_positions._float_tensor''', ] for k in ignore_keys: model_state_dict.pop(lowercase__ , lowercase__ ) __snake_case : Optional[Any] = FSMTConfig.from_pretrained(lowercase__ ) __snake_case : Any = FSMTForConditionalGeneration(lowercase__ ) # check that it loads ok model_new.load_state_dict(lowercase__ , strict=lowercase__ ) # save __snake_case : Dict = os.path.join(lowercase__ , lowercase__ ) print(F'Generating {pytorch_weights_dump_path}' ) torch.save(lowercase__ , lowercase__ ) print("Conversion is done!" ) print("\nLast step is to upload the files to s3" ) print(F'cd {data_root}' ) print(F'transformers-cli upload {model_dir}' ) if __name__ == "__main__": _snake_case : Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--fsmt_checkpoint_path", default=None, type=str, required=True, help=( "Path to the official PyTorch checkpoint file which is expected to reside in the dump dir with dicts," " bpecodes, etc." ), ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) _snake_case : int = parser.parse_args() convert_fsmt_checkpoint_to_pytorch(args.fsmt_checkpoint_path, args.pytorch_dump_folder_path)
123
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConfig, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaForCTC, WavaVecaForPreTraining, WavaVecaProcessor, logging, ) from transformers.models.wavaveca.modeling_wavaveca import WavaVecaForSequenceClassification logging.set_verbosity_info() _UpperCamelCase = logging.get_logger(__name__) _UpperCamelCase = { "post_extract_proj": "feature_projection.projection", "encoder.pos_conv.0": "encoder.pos_conv_embed.conv", "self_attn.k_proj": "encoder.layers.*.attention.k_proj", "self_attn.v_proj": "encoder.layers.*.attention.v_proj", "self_attn.q_proj": "encoder.layers.*.attention.q_proj", "self_attn.out_proj": "encoder.layers.*.attention.out_proj", "self_attn_layer_norm": "encoder.layers.*.layer_norm", "fc1": "encoder.layers.*.feed_forward.intermediate_dense", "fc2": "encoder.layers.*.feed_forward.output_dense", "final_layer_norm": "encoder.layers.*.final_layer_norm", "encoder.layer_norm": "encoder.layer_norm", "adapter_layer": "encoder.layers.*.adapter_layer", "w2v_model.layer_norm": "feature_projection.layer_norm", "quantizer.weight_proj": "quantizer.weight_proj", "quantizer.vars": "quantizer.codevectors", "project_q": "project_q", "final_proj": "project_hid", "w2v_encoder.proj": "lm_head", "mask_emb": "masked_spec_embed", "pooling_layer.linear": "projector", "pooling_layer.projection": "classifier", } _UpperCamelCase = [ "lm_head", "quantizer.weight_proj", "quantizer.codevectors", "project_q", "project_hid", "projector", "classifier", ] def _lowercase ( lowercase__ ): __lowerCAmelCase : List[str] = {} with open(lowercase__ , '''r''' ) as file: for line_number, line in enumerate(lowercase__ ): __lowerCAmelCase : Any = line.strip() if line: __lowerCAmelCase : Dict = line.split() __lowerCAmelCase : str = line_number __lowerCAmelCase : List[str] = words[0] __lowerCAmelCase : Any = value return result def _lowercase ( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): for attribute in key.split('''.''' ): __lowerCAmelCase : List[Any] = getattr(lowercase__ , lowercase__ ) __lowerCAmelCase : Any = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(lowercase__ ): __lowerCAmelCase : Tuple = PARAM_MAPPING[full_name.split('''.''' )[-1]] __lowerCAmelCase : List[Any] = '''param''' if weight_type is not None and weight_type != "param": __lowerCAmelCase : str = getattr(lowercase__ , lowercase__ ).shape elif weight_type is not None and weight_type == "param": __lowerCAmelCase : Dict = hf_pointer for attribute in hf_param_name.split('''.''' ): __lowerCAmelCase : Dict = getattr(lowercase__ , lowercase__ ) __lowerCAmelCase : str = shape_pointer.shape # let's reduce dimension __lowerCAmelCase : Any = value[0] else: __lowerCAmelCase : str = hf_pointer.shape if hf_shape != value.shape: raise ValueError( f"""Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be""" f""" {value.shape} for {full_name}""" ) if weight_type == "weight": __lowerCAmelCase : Union[str, Any] = value elif weight_type == "weight_g": __lowerCAmelCase : List[str] = value elif weight_type == "weight_v": __lowerCAmelCase : int = value elif weight_type == "bias": __lowerCAmelCase : Union[str, Any] = value elif weight_type == "param": for attribute in hf_param_name.split('''.''' ): __lowerCAmelCase : Dict = getattr(lowercase__ , lowercase__ ) __lowerCAmelCase : Tuple = value else: __lowerCAmelCase : Any = value logger.info(f"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def _lowercase ( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): __lowerCAmelCase : Any = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(lowercase__ ): __lowerCAmelCase : str = PARAM_MAPPING[full_name.split('''.''' )[-1]] __lowerCAmelCase : int = '''param''' if weight_type is not None and weight_type != "param": __lowerCAmelCase : Tuple = '''.'''.join([key, weight_type] ) elif weight_type is not None and weight_type == "param": __lowerCAmelCase : List[str] = '''.'''.join([key, hf_param_name] ) else: __lowerCAmelCase : Optional[int] = key __lowerCAmelCase : Union[str, Any] = value if '''lm_head''' in full_key else value[0] _UpperCamelCase = { "W_a": "linear_1.weight", "W_b": "linear_2.weight", "b_a": "linear_1.bias", "b_b": "linear_2.bias", "ln_W": "norm.weight", "ln_b": "norm.bias", } def _lowercase ( lowercase__ , lowercase__ , lowercase__=None , lowercase__=None ): __lowerCAmelCase : Any = False for key, mapped_key in MAPPING.items(): __lowerCAmelCase : Tuple = '''wav2vec2.''' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0]: __lowerCAmelCase : Optional[Any] = True if "*" in mapped_key: __lowerCAmelCase : List[str] = name.split(lowercase__ )[0].split('''.''' )[-2] __lowerCAmelCase : Dict = mapped_key.replace('''*''' , lowercase__ ) if "weight_g" in name: __lowerCAmelCase : List[Any] = '''weight_g''' elif "weight_v" in name: __lowerCAmelCase : List[Any] = '''weight_v''' elif "bias" in name: __lowerCAmelCase : Any = '''bias''' elif "weight" in name: # TODO: don't match quantizer.weight_proj __lowerCAmelCase : int = '''weight''' else: __lowerCAmelCase : Any = None if hf_dict is not None: rename_dict(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) else: set_recursively(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) return is_used return is_used def _lowercase ( lowercase__ , lowercase__ , lowercase__ ): __lowerCAmelCase : List[str] = [] __lowerCAmelCase : Optional[Any] = fairseq_model.state_dict() __lowerCAmelCase : Tuple = hf_model.wavaveca.feature_extractor for name, value in fairseq_dict.items(): __lowerCAmelCase : Any = False if "conv_layers" in name: load_conv_layer( lowercase__ , lowercase__ , lowercase__ , lowercase__ , hf_model.config.feat_extract_norm == '''group''' , ) __lowerCAmelCase : int = True else: __lowerCAmelCase : Dict = load_wavaveca_layer(lowercase__ , lowercase__ , lowercase__ ) if not is_used: unused_weights.append(lowercase__ ) logger.warning(f"""Unused weights: {unused_weights}""" ) def _lowercase ( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): __lowerCAmelCase : Any = full_name.split('''conv_layers.''' )[-1] __lowerCAmelCase : List[str] = name.split('''.''' ) __lowerCAmelCase : Any = int(items[0] ) __lowerCAmelCase : str = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) __lowerCAmelCase : List[str] = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) __lowerCAmelCase : List[str] = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.""" ) __lowerCAmelCase : List[str] = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.""" ) __lowerCAmelCase : Optional[int] = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(lowercase__ ) @torch.no_grad() def _lowercase ( lowercase__ , lowercase__ , lowercase__=None , lowercase__=None , lowercase__=True , lowercase__=False ): if config_path is not None: __lowerCAmelCase : Union[str, Any] = WavaVecaConfig.from_pretrained(lowercase__ ) else: __lowerCAmelCase : Optional[int] = WavaVecaConfig() if is_seq_class: __lowerCAmelCase : Optional[Any] = read_txt_into_dict(lowercase__ ) __lowerCAmelCase : int = idalabel __lowerCAmelCase : Optional[int] = WavaVecaForSequenceClassification(lowercase__ ) __lowerCAmelCase : List[str] = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6_0_0_0 , padding_value=0 , do_normalize=lowercase__ , return_attention_mask=lowercase__ , ) feature_extractor.save_pretrained(lowercase__ ) elif is_finetuned: if dict_path: __lowerCAmelCase : List[str] = Dictionary.load(lowercase__ ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq __lowerCAmelCase : List[Any] = target_dict.pad_index __lowerCAmelCase : List[Any] = target_dict.bos_index __lowerCAmelCase : Optional[int] = target_dict.eos_index __lowerCAmelCase : Any = len(target_dict.symbols ) __lowerCAmelCase : Union[str, Any] = os.path.join(lowercase__ , '''vocab.json''' ) if not os.path.isdir(lowercase__ ): logger.error('''--pytorch_dump_folder_path ({}) should be a directory'''.format(lowercase__ ) ) return os.makedirs(lowercase__ , exist_ok=lowercase__ ) __lowerCAmelCase : Optional[int] = target_dict.indices # fairseq has the <pad> and <s> switched __lowerCAmelCase : List[str] = 0 __lowerCAmelCase : int = 1 with open(lowercase__ , '''w''' , encoding='''utf-8''' ) as vocab_handle: json.dump(lowercase__ , lowercase__ ) __lowerCAmelCase : Dict = WavaVecaCTCTokenizer( lowercase__ , 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=lowercase__ , ) __lowerCAmelCase : List[str] = True if config.feat_extract_norm == '''layer''' else False __lowerCAmelCase : List[str] = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6_0_0_0 , padding_value=0 , do_normalize=lowercase__ , return_attention_mask=lowercase__ , ) __lowerCAmelCase : List[Any] = WavaVecaProcessor(feature_extractor=lowercase__ , tokenizer=lowercase__ ) processor.save_pretrained(lowercase__ ) __lowerCAmelCase : str = WavaVecaForCTC(lowercase__ ) else: __lowerCAmelCase : Any = WavaVecaForPreTraining(lowercase__ ) if is_finetuned or is_seq_class: __lowerCAmelCase, __lowerCAmelCase, __lowerCAmelCase : Optional[int] = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'''data''': '''/'''.join(dict_path.split('''/''' )[:-1] )} ) else: __lowerCAmelCase : Union[str, Any] = argparse.Namespace(task='''audio_pretraining''' ) __lowerCAmelCase : str = fairseq.tasks.setup_task(lowercase__ ) __lowerCAmelCase, __lowerCAmelCase, __lowerCAmelCase : Dict = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] , task=lowercase__ ) __lowerCAmelCase : int = model[0].eval() recursively_load_weights(lowercase__ , lowercase__ , not is_finetuned ) hf_wavavec.save_pretrained(lowercase__ ) if __name__ == "__main__": _UpperCamelCase = 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( "--not_finetuned", action="store_true", help="Whether the model to convert is a fine-tuned model or not" ) parser.add_argument( "--is_seq_class", action="store_true", help="Whether the model to convert is a fine-tuned sequence classification model or not", ) _UpperCamelCase = parser.parse_args() _UpperCamelCase = not args.not_finetuned and not args.is_seq_class convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, is_finetuned, args.is_seq_class, )
275
0
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL UpperCAmelCase = logging.get_logger(__name__) class UpperCAmelCase_ ( _UpperCAmelCase): snake_case__ = ['''pixel_values'''] def __init__( self : Tuple , __UpperCamelCase : Union[str, Any] = True , __UpperCamelCase : Optional[Any] = None , __UpperCamelCase : Dict = 0.9 , __UpperCamelCase : int = PILImageResampling.BICUBIC , __UpperCamelCase : List[Any] = True , __UpperCamelCase : Union[str, Any] = None , __UpperCamelCase : str = 1 / 255 , __UpperCamelCase : str = True , __UpperCamelCase : Tuple = True , __UpperCamelCase : List[str] = None , __UpperCamelCase : Tuple = None , **__UpperCamelCase : Optional[int] , ) -> None: super().__init__(**A_ ) _UpperCamelCase = size if size is not None else {'''shortest_edge''': 224} _UpperCamelCase = get_size_dict(A_ , default_to_square=A_ ) _UpperCamelCase = crop_size if crop_size is not None else {'''height''': 224, '''width''': 224} _UpperCamelCase = get_size_dict(A_ , param_name='''crop_size''' ) _UpperCamelCase = do_resize _UpperCamelCase = size _UpperCamelCase = crop_pct _UpperCamelCase = resample _UpperCamelCase = do_center_crop _UpperCamelCase = crop_size _UpperCamelCase = do_rescale _UpperCamelCase = rescale_factor _UpperCamelCase = do_normalize _UpperCamelCase = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN _UpperCamelCase = image_std if image_std is not None else IMAGENET_DEFAULT_STD def _UpperCamelCase ( self : List[str] , __UpperCamelCase : List[Any] , __UpperCamelCase : str , __UpperCamelCase : List[Any] = None , __UpperCamelCase : List[Any] = PILImageResampling.BICUBIC , __UpperCamelCase : int = None , **__UpperCamelCase : Union[str, Any] , ) -> np.ndarray: _UpperCamelCase = get_size_dict(A_ , default_to_square=A_ ) if "shortest_edge" not in size and ("height" not in size or "width" not in size): raise ValueError(F'''size must contain \'height\' and \'width\' or \'shortest_edge\' as keys. Got {size.keys()}''' ) if crop_pct is not None: if "shortest_edge" in size: _UpperCamelCase = int(size['''shortest_edge'''] / crop_pct ) elif "height" in size and "width" in size: if size["height"] == size["width"]: _UpperCamelCase = int(size['''height'''] / crop_pct ) else: _UpperCamelCase = (int(size['''height'''] / crop_pct ), int(size['''width'''] / crop_pct )) else: raise ValueError('''Invalid size for resize: {}'''.format(A_ ) ) _UpperCamelCase = get_resize_output_image_size(A_ , size=A_ , default_to_square=A_ ) else: if "shortest_edge" in size: _UpperCamelCase = get_resize_output_image_size(A_ , size=size['''shortest_edge'''] , default_to_square=A_ ) elif "height" in size and "width" in size: _UpperCamelCase = (size['''height'''], size['''width''']) else: raise ValueError('''Invalid size for resize: {}'''.format(A_ ) ) return resize(A_ , size=A_ , resample=A_ , data_format=A_ , **A_ ) def _UpperCamelCase ( self : Union[str, Any] , __UpperCamelCase : Dict , __UpperCamelCase : Optional[Any] , __UpperCamelCase : Any = None , **__UpperCamelCase : Tuple , ) -> np.ndarray: _UpperCamelCase = get_size_dict(A_ ) if "height" not in size or "width" not in size: raise ValueError(F'''size must contain \'height\' and \'width\' as keys. Got {size.keys()}''' ) return center_crop(A_ , size=(size['''height'''], size['''width''']) , data_format=A_ , **A_ ) def _UpperCamelCase ( self : int , __UpperCamelCase : List[str] , __UpperCamelCase : Union[str, Any] , __UpperCamelCase : str = None , **__UpperCamelCase : Dict , ) -> Union[str, Any]: return rescale(A_ , scale=A_ , data_format=A_ , **A_ ) def _UpperCamelCase ( self : int , __UpperCamelCase : Union[str, Any] , __UpperCamelCase : Any , __UpperCamelCase : Tuple , __UpperCamelCase : Tuple = None , **__UpperCamelCase : str , ) -> np.ndarray: return normalize(A_ , mean=A_ , std=A_ , data_format=A_ , **A_ ) def _UpperCamelCase ( self : Optional[int] , __UpperCamelCase : str , __UpperCamelCase : str = None , __UpperCamelCase : Optional[int] = None , __UpperCamelCase : Union[str, Any] = None , __UpperCamelCase : str = None , __UpperCamelCase : List[Any] = None , __UpperCamelCase : Union[str, Any] = None , __UpperCamelCase : Optional[Any] = None , __UpperCamelCase : str = None , __UpperCamelCase : int = None , __UpperCamelCase : Union[str, Any] = None , __UpperCamelCase : int = None , __UpperCamelCase : Any = None , __UpperCamelCase : Optional[Any] = ChannelDimension.FIRST , **__UpperCamelCase : int , ) -> PIL.Image.Image: _UpperCamelCase = do_resize if do_resize is not None else self.do_resize _UpperCamelCase = crop_pct if crop_pct is not None else self.crop_pct _UpperCamelCase = resample if resample is not None else self.resample _UpperCamelCase = do_center_crop if do_center_crop is not None else self.do_center_crop _UpperCamelCase = do_rescale if do_rescale is not None else self.do_rescale _UpperCamelCase = rescale_factor if rescale_factor is not None else self.rescale_factor _UpperCamelCase = do_normalize if do_normalize is not None else self.do_normalize _UpperCamelCase = image_mean if image_mean is not None else self.image_mean _UpperCamelCase = image_std if image_std is not None else self.image_std _UpperCamelCase = size if size is not None else self.size _UpperCamelCase = get_size_dict(A_ , default_to_square=A_ ) _UpperCamelCase = crop_size if crop_size is not None else self.crop_size _UpperCamelCase = get_size_dict(A_ , param_name='''crop_size''' ) _UpperCamelCase = make_list_of_images(A_ ) if not valid_images(A_ ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None or resample is None: raise ValueError('''Size and resample must be specified if do_resize is True.''' ) if do_center_crop and crop_pct is None: raise ValueError('''Crop_pct 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. _UpperCamelCase = [to_numpy_array(A_ ) for image in images] if do_resize: _UpperCamelCase = [self.resize(image=A_ , size=A_ , crop_pct=A_ , resample=A_ ) for image in images] if do_center_crop: _UpperCamelCase = [self.center_crop(image=A_ , size=A_ ) for image in images] if do_rescale: _UpperCamelCase = [self.rescale(image=A_ , scale=A_ ) for image in images] if do_normalize: _UpperCamelCase = [self.normalize(image=A_ , mean=A_ , std=A_ ) for image in images] _UpperCamelCase = [to_channel_dimension_format(A_ , A_ ) for image in images] _UpperCamelCase = {'''pixel_values''': images} return BatchFeature(data=A_ , tensor_type=A_ )
256
from ....configuration_utils import PretrainedConfig from ....utils import logging _UpperCamelCase = logging.get_logger(__name__) _UpperCamelCase = { "CarlCochet/trajectory-transformer-halfcheetah-medium-v2": ( "https://huggingface.co/CarlCochet/trajectory-transformer-halfcheetah-medium-v2/resolve/main/config.json" ), # See all TrajectoryTransformer models at https://huggingface.co/models?filter=trajectory_transformer } class __lowercase (_UpperCAmelCase ): _UpperCamelCase = """trajectory_transformer""" _UpperCamelCase = ["""past_key_values"""] _UpperCamelCase = { """hidden_size""": """n_embd""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self , A_=100 , A_=5 , A_=1 , A_=1 , A_=249 , A_=6 , A_=17 , A_=25 , A_=4 , A_=4 , A_=128 , A_=0.1 , A_=0.1 , A_=0.1 , A_=0.0_006 , A_=512 , A_=0.02 , A_=1e-12 , A_=1 , A_=True , A_=1 , A_=5_0256 , A_=5_0256 , **A_ , ) ->int: '''simple docstring''' __lowerCAmelCase : Any = vocab_size __lowerCAmelCase : Tuple = action_weight __lowerCAmelCase : Tuple = reward_weight __lowerCAmelCase : Union[str, Any] = value_weight __lowerCAmelCase : List[str] = max_position_embeddings __lowerCAmelCase : str = block_size __lowerCAmelCase : Optional[Any] = action_dim __lowerCAmelCase : Union[str, Any] = observation_dim __lowerCAmelCase : Union[str, Any] = transition_dim __lowerCAmelCase : Dict = learning_rate __lowerCAmelCase : Any = n_layer __lowerCAmelCase : Any = n_head __lowerCAmelCase : Optional[int] = n_embd __lowerCAmelCase : str = embd_pdrop __lowerCAmelCase : Dict = attn_pdrop __lowerCAmelCase : Optional[int] = resid_pdrop __lowerCAmelCase : Union[str, Any] = initializer_range __lowerCAmelCase : Optional[int] = layer_norm_eps __lowerCAmelCase : Any = kaiming_initializer_range __lowerCAmelCase : List[str] = use_cache super().__init__(pad_token_id=A_ , bos_token_id=A_ , eos_token_id=A_ , **A_ )
275
0
'''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 typing import TYPE_CHECKING from ..models.auto import AutoModelForVisionaSeq from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class __SCREAMING_SNAKE_CASE (_UpperCAmelCase ): """simple docstring""" __a ='Salesforce/blip-image-captioning-base' __a =( 'This is a tool that generates a description of an image. It takes an input named `image` which should be the ' 'image to caption, and returns a text that contains the description in English.' ) __a ='image_captioner' __a =AutoModelForVisionaSeq __a =['image'] __a =['text'] def __init__( self : List[str] , *__a : int , **__a : Optional[int] ): requires_backends(self , ["vision"] ) super().__init__(*A_ , **A_ ) def UpperCamelCase__ ( self : int , __a : Optional[Any] ): return self.pre_processor(images=A_ , return_tensors="pt" ) def UpperCamelCase__ ( self : Union[str, Any] , __a : Any ): return self.model.generate(**A_ ) def UpperCamelCase__ ( self : Optional[Any] , __a : Optional[int] ): return self.pre_processor.batch_decode(A_ , skip_special_tokens=A_ )[0].strip()
63
def _lowercase ( lowercase__ , lowercase__ ): if a < 0 or b < 0: raise ValueError('''the value of both inputs must be positive''' ) __lowerCAmelCase : int = str(bin(lowercase__ ) )[2:] # remove the leading "0b" __lowerCAmelCase : Any = str(bin(lowercase__ ) )[2:] __lowerCAmelCase : List[str] = max(len(lowercase__ ) , len(lowercase__ ) ) return "0b" + "".join( str(int('''1''' in (char_a, char_b) ) ) for char_a, char_b in zip(a_binary.zfill(lowercase__ ) , b_binary.zfill(lowercase__ ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
275
0
import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DeiTImageProcessor, ViTConfig, ViTForImageClassification, ViTImageProcessor, ViTModel from transformers.utils import logging logging.set_verbosity_info() _SCREAMING_SNAKE_CASE = logging.get_logger(__name__) def lowercase( UpperCamelCase_ , UpperCamelCase_=False ) -> List[str]: '''simple docstring''' UpperCamelCase = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f"""blocks.{i}.norm1.weight""", f"""vit.encoder.layer.{i}.layernorm_before.weight""") ) rename_keys.append((f"""blocks.{i}.norm1.bias""", f"""vit.encoder.layer.{i}.layernorm_before.bias""") ) rename_keys.append((f"""blocks.{i}.attn.proj.weight""", f"""vit.encoder.layer.{i}.attention.output.dense.weight""") ) rename_keys.append((f"""blocks.{i}.attn.proj.bias""", f"""vit.encoder.layer.{i}.attention.output.dense.bias""") ) rename_keys.append((f"""blocks.{i}.norm2.weight""", f"""vit.encoder.layer.{i}.layernorm_after.weight""") ) rename_keys.append((f"""blocks.{i}.norm2.bias""", f"""vit.encoder.layer.{i}.layernorm_after.bias""") ) rename_keys.append((f"""blocks.{i}.mlp.fc1.weight""", f"""vit.encoder.layer.{i}.intermediate.dense.weight""") ) rename_keys.append((f"""blocks.{i}.mlp.fc1.bias""", f"""vit.encoder.layer.{i}.intermediate.dense.bias""") ) rename_keys.append((f"""blocks.{i}.mlp.fc2.weight""", f"""vit.encoder.layer.{i}.output.dense.weight""") ) rename_keys.append((f"""blocks.{i}.mlp.fc2.bias""", f"""vit.encoder.layer.{i}.output.dense.bias""") ) # projection layer + position embeddings rename_keys.extend( [ ("""cls_token""", """vit.embeddings.cls_token"""), ("""patch_embed.proj.weight""", """vit.embeddings.patch_embeddings.projection.weight"""), ("""patch_embed.proj.bias""", """vit.embeddings.patch_embeddings.projection.bias"""), ("""pos_embed""", """vit.embeddings.position_embeddings"""), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ("""norm.weight""", """layernorm.weight"""), ("""norm.bias""", """layernorm.bias"""), ("""pre_logits.fc.weight""", """pooler.dense.weight"""), ("""pre_logits.fc.bias""", """pooler.dense.bias"""), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" UpperCamelCase = [(pair[0], pair[1][4:]) if pair[1].startswith("""vit""" ) else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ("""norm.weight""", """vit.layernorm.weight"""), ("""norm.bias""", """vit.layernorm.bias"""), ("""head.weight""", """classifier.weight"""), ("""head.bias""", """classifier.bias"""), ] ) return rename_keys def lowercase( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_=False ) -> str: '''simple docstring''' for i in range(config.num_hidden_layers ): if base_model: UpperCamelCase = '''''' else: UpperCamelCase = '''vit.''' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) UpperCamelCase = state_dict.pop(f"""blocks.{i}.attn.qkv.weight""" ) UpperCamelCase = state_dict.pop(f"""blocks.{i}.attn.qkv.bias""" ) # next, add query, keys and values (in that order) to the state dict UpperCamelCase = in_proj_weight[ : config.hidden_size, : ] UpperCamelCase = in_proj_bias[: config.hidden_size] UpperCamelCase = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] UpperCamelCase = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] UpperCamelCase = in_proj_weight[ -config.hidden_size :, : ] UpperCamelCase = in_proj_bias[-config.hidden_size :] def lowercase( UpperCamelCase_ ) -> List[str]: '''simple docstring''' UpperCamelCase = ['''head.weight''', '''head.bias'''] for k in ignore_keys: state_dict.pop(lowercase__ , lowercase__ ) def lowercase( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> Tuple: '''simple docstring''' UpperCamelCase = dct.pop(lowercase__ ) UpperCamelCase = val def lowercase( ) -> str: '''simple docstring''' UpperCamelCase = '''http://images.cocodataset.org/val2017/000000039769.jpg''' UpperCamelCase = Image.open(requests.get(lowercase__ , stream=lowercase__ ).raw ) return im @torch.no_grad() def lowercase( UpperCamelCase_ , UpperCamelCase_ ) -> List[str]: '''simple docstring''' UpperCamelCase = ViTConfig() UpperCamelCase = False # dataset (ImageNet-21k only or also fine-tuned on ImageNet 2012), patch_size and image_size if vit_name[-5:] == "in21k": UpperCamelCase = True UpperCamelCase = int(vit_name[-12:-10] ) UpperCamelCase = int(vit_name[-9:-6] ) else: UpperCamelCase = 1000 UpperCamelCase = '''huggingface/label-files''' UpperCamelCase = '''imagenet-1k-id2label.json''' UpperCamelCase = json.load(open(hf_hub_download(lowercase__ , lowercase__ , repo_type="""dataset""" ) , """r""" ) ) UpperCamelCase = {int(lowercase__ ): v for k, v in idalabel.items()} UpperCamelCase = idalabel UpperCamelCase = {v: k for k, v in idalabel.items()} UpperCamelCase = int(vit_name[-6:-4] ) UpperCamelCase = int(vit_name[-3:] ) # size of the architecture if "deit" in vit_name: if vit_name[9:].startswith("""tiny""" ): UpperCamelCase = 192 UpperCamelCase = 768 UpperCamelCase = 12 UpperCamelCase = 3 elif vit_name[9:].startswith("""small""" ): UpperCamelCase = 384 UpperCamelCase = 1536 UpperCamelCase = 12 UpperCamelCase = 6 else: pass else: if vit_name[4:].startswith("""small""" ): UpperCamelCase = 768 UpperCamelCase = 2304 UpperCamelCase = 8 UpperCamelCase = 8 elif vit_name[4:].startswith("""base""" ): pass elif vit_name[4:].startswith("""large""" ): UpperCamelCase = 1024 UpperCamelCase = 4096 UpperCamelCase = 24 UpperCamelCase = 16 elif vit_name[4:].startswith("""huge""" ): UpperCamelCase = 1280 UpperCamelCase = 5120 UpperCamelCase = 32 UpperCamelCase = 16 # load original model from timm UpperCamelCase = timm.create_model(lowercase__ , pretrained=lowercase__ ) timm_model.eval() # load state_dict of original model, remove and rename some keys UpperCamelCase = timm_model.state_dict() if base_model: remove_classification_head_(lowercase__ ) UpperCamelCase = create_rename_keys(lowercase__ , lowercase__ ) for src, dest in rename_keys: rename_key(lowercase__ , lowercase__ , lowercase__ ) read_in_q_k_v(lowercase__ , lowercase__ , lowercase__ ) # load HuggingFace model if vit_name[-5:] == "in21k": UpperCamelCase = ViTModel(lowercase__ ).eval() else: UpperCamelCase = ViTForImageClassification(lowercase__ ).eval() model.load_state_dict(lowercase__ ) # Check outputs on an image, prepared by ViTImageProcessor/DeiTImageProcessor if "deit" in vit_name: UpperCamelCase = DeiTImageProcessor(size=config.image_size ) else: UpperCamelCase = ViTImageProcessor(size=config.image_size ) UpperCamelCase = image_processor(images=prepare_img() , return_tensors="""pt""" ) UpperCamelCase = encoding['''pixel_values'''] UpperCamelCase = model(lowercase__ ) if base_model: UpperCamelCase = timm_model.forward_features(lowercase__ ) assert timm_pooled_output.shape == outputs.pooler_output.shape assert torch.allclose(lowercase__ , outputs.pooler_output , atol=1E-3 ) else: UpperCamelCase = timm_model(lowercase__ ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(lowercase__ , outputs.logits , atol=1E-3 ) Path(lowercase__ ).mkdir(exist_ok=lowercase__ ) print(f"""Saving model {vit_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(lowercase__ ) print(f"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(lowercase__ ) if __name__ == "__main__": _SCREAMING_SNAKE_CASE = argparse.ArgumentParser() # Required parameters parser.add_argument( """--vit_name""", default="""vit_base_patch16_224""", type=str, help="""Name of the ViT timm model you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) _SCREAMING_SNAKE_CASE = parser.parse_args() convert_vit_checkpoint(args.vit_name, args.pytorch_dump_folder_path)
343
import math from typing import Dict, Iterable, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, get_image_size, is_torch_available, is_torch_tensor, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_torch_available(): import torch if is_vision_available(): import PIL _UpperCamelCase = logging.get_logger(__name__) def _lowercase ( lowercase__ , lowercase__ , lowercase__ , lowercase__ ): def constraint_to_multiple_of(lowercase__ , lowercase__ , lowercase__=0 , lowercase__=None ): __lowerCAmelCase : int = round(val / multiple ) * multiple if max_val is not None and x > max_val: __lowerCAmelCase : Optional[int] = math.floor(val / multiple ) * multiple if x < min_val: __lowerCAmelCase : Any = math.ceil(val / multiple ) * multiple return x __lowerCAmelCase : Dict = (output_size, output_size) if isinstance(lowercase__ , lowercase__ ) else output_size __lowerCAmelCase, __lowerCAmelCase : Optional[Any] = get_image_size(lowercase__ ) __lowerCAmelCase, __lowerCAmelCase : int = output_size # determine new height and width __lowerCAmelCase : Optional[Any] = output_height / input_height __lowerCAmelCase : List[Any] = output_width / input_width if keep_aspect_ratio: # scale as little as possible if abs(1 - scale_width ) < abs(1 - scale_height ): # fit width __lowerCAmelCase : str = scale_width else: # fit height __lowerCAmelCase : str = scale_height __lowerCAmelCase : Any = constraint_to_multiple_of(scale_height * input_height , multiple=lowercase__ ) __lowerCAmelCase : Union[str, Any] = constraint_to_multiple_of(scale_width * input_width , multiple=lowercase__ ) return (new_height, new_width) class __lowercase (_UpperCAmelCase ): _UpperCamelCase = ["""pixel_values"""] def __init__( self , A_ = True , A_ = None , A_ = PILImageResampling.BILINEAR , A_ = False , A_ = 1 , A_ = True , A_ = 1 / 255 , A_ = True , A_ = None , A_ = None , **A_ , ) ->None: '''simple docstring''' super().__init__(**A_ ) __lowerCAmelCase : Union[str, Any] = size if size is not None else {'''height''': 384, '''width''': 384} __lowerCAmelCase : Dict = get_size_dict(A_ ) __lowerCAmelCase : Optional[Any] = do_resize __lowerCAmelCase : int = size __lowerCAmelCase : Dict = keep_aspect_ratio __lowerCAmelCase : List[Any] = ensure_multiple_of __lowerCAmelCase : Tuple = resample __lowerCAmelCase : Dict = do_rescale __lowerCAmelCase : Any = rescale_factor __lowerCAmelCase : List[Any] = do_normalize __lowerCAmelCase : Optional[int] = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN __lowerCAmelCase : Optional[int] = image_std if image_std is not None else IMAGENET_STANDARD_STD def UpperCamelCase__ ( self , A_ , A_ , A_ = False , A_ = 1 , A_ = PILImageResampling.BICUBIC , A_ = None , **A_ , ) ->np.ndarray: '''simple docstring''' __lowerCAmelCase : int = get_size_dict(A_ ) if "height" not in size or "width" not in size: raise ValueError(f"""The size dictionary must contain the keys 'height' and 'width'. Got {size.keys()}""" ) __lowerCAmelCase : Union[str, Any] = get_resize_output_image_size( A_ , output_size=(size['''height'''], size['''width''']) , keep_aspect_ratio=A_ , multiple=A_ , ) return resize(A_ , size=A_ , resample=A_ , data_format=A_ , **A_ ) def UpperCamelCase__ ( self , A_ , A_ , A_ = None , **A_ , ) ->Dict: '''simple docstring''' return rescale(A_ , scale=A_ , data_format=A_ , **A_ ) def UpperCamelCase__ ( self , A_ , A_ , A_ , A_ = None , **A_ , ) ->np.ndarray: '''simple docstring''' return normalize(A_ , mean=A_ , std=A_ , data_format=A_ , **A_ ) def UpperCamelCase__ ( self , A_ , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = ChannelDimension.FIRST , **A_ , ) ->PIL.Image.Image: '''simple docstring''' __lowerCAmelCase : int = do_resize if do_resize is not None else self.do_resize __lowerCAmelCase : Optional[int] = size if size is not None else self.size __lowerCAmelCase : Union[str, Any] = get_size_dict(A_ ) __lowerCAmelCase : List[Any] = keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio __lowerCAmelCase : Optional[int] = ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of __lowerCAmelCase : Tuple = resample if resample is not None else self.resample __lowerCAmelCase : Optional[int] = do_rescale if do_rescale is not None else self.do_rescale __lowerCAmelCase : Union[str, Any] = rescale_factor if rescale_factor is not None else self.rescale_factor __lowerCAmelCase : Tuple = do_normalize if do_normalize is not None else self.do_normalize __lowerCAmelCase : str = image_mean if image_mean is not None else self.image_mean __lowerCAmelCase : Optional[Any] = image_std if image_std is not None else self.image_std __lowerCAmelCase : Optional[Any] = make_list_of_images(A_ ) if not valid_images(A_ ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None or resample is None: raise ValueError('''Size and resample must be specified if do_resize is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('''Image mean and std must be specified if do_normalize is True.''' ) # All transformations expect numpy arrays. __lowerCAmelCase : Any = [to_numpy_array(A_ ) for image in images] if do_resize: __lowerCAmelCase : Optional[Any] = [self.resize(image=A_ , size=A_ , resample=A_ ) for image in images] if do_rescale: __lowerCAmelCase : Tuple = [self.rescale(image=A_ , scale=A_ ) for image in images] if do_normalize: __lowerCAmelCase : str = [self.normalize(image=A_ , mean=A_ , std=A_ ) for image in images] __lowerCAmelCase : Union[str, Any] = [to_channel_dimension_format(A_ , A_ ) for image in images] __lowerCAmelCase : Dict = {'''pixel_values''': images} return BatchFeature(data=A_ , tensor_type=A_ ) def UpperCamelCase__ ( self , A_ , A_ = None ) ->Any: '''simple docstring''' __lowerCAmelCase : Any = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(A_ ) != len(A_ ): raise ValueError( '''Make sure that you pass in as many target sizes as the batch dimension of the logits''' ) if is_torch_tensor(A_ ): __lowerCAmelCase : Optional[int] = target_sizes.numpy() __lowerCAmelCase : List[str] = [] for idx in range(len(A_ ) ): __lowerCAmelCase : Any = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode='''bilinear''' , align_corners=A_ ) __lowerCAmelCase : str = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(A_ ) else: __lowerCAmelCase : Any = logits.argmax(dim=1 ) __lowerCAmelCase : List[Any] = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
275
0
'''simple docstring''' from __future__ import annotations from math import gcd def __lowerCAmelCase (__lowerCAmelCase , __lowerCAmelCase = 2 , __lowerCAmelCase = 1 , __lowerCAmelCase = 3 , ): # A value less than 2 can cause an infinite loop in the algorithm. if num < 2: raise ValueError("The input value cannot be less than 2" ) # Because of the relationship between ``f(f(x))`` and ``f(x)``, this # algorithm struggles to find factors that are divisible by two. # As a workaround, we specifically check for two and even inputs. # See: https://math.stackexchange.com/a/2856214/165820 if num > 2 and num % 2 == 0: return 2 # Pollard's Rho algorithm requires a function that returns pseudorandom # values between 0 <= X < ``num``. It doesn't need to be random in the # sense that the output value is cryptographically secure or difficult # to calculate, it only needs to be random in the sense that all output # values should be equally likely to appear. # For this reason, Pollard suggested using ``f(x) = (x**2 - 1) % num`` # However, the success of Pollard's algorithm isn't guaranteed and is # determined in part by the initial seed and the chosen random function. # To make retries easier, we will instead use ``f(x) = (x**2 + C) % num`` # where ``C`` is a value that we can modify between each attempt. def rand_fn(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> int: return (pow(lowercase__ , 2 ) + step) % modulus for _ in range(lowercase__ ): # These track the position within the cycle detection logic. _UpperCAmelCase : Optional[int] = seed _UpperCAmelCase : Optional[Any] = seed while True: # At each iteration, the tortoise moves one step and the hare moves two. _UpperCAmelCase : Any = rand_fn(lowercase__ , lowercase__ , lowercase__ ) _UpperCAmelCase : Optional[int] = rand_fn(lowercase__ , lowercase__ , lowercase__ ) _UpperCAmelCase : Union[str, Any] = rand_fn(lowercase__ , lowercase__ , lowercase__ ) # At some point both the tortoise and the hare will enter a cycle whose # length ``p`` is a divisor of ``num``. Once in that cycle, at some point # the tortoise and hare will end up on the same value modulo ``p``. # We can detect when this happens because the position difference between # the tortoise and the hare will share a common divisor with ``num``. _UpperCAmelCase : List[Any] = gcd(hare - tortoise , lowercase__ ) if divisor == 1: # No common divisor yet, just keep searching. continue else: # We found a common divisor! if divisor == num: # Unfortunately, the divisor is ``num`` itself and is useless. break else: # The divisor is a nontrivial factor of ``num``! return divisor # If we made it here, then this attempt failed. # We need to pick a new starting seed for the tortoise and hare # in addition to a new step value for the random function. # To keep this example implementation deterministic, the # new values will be generated based on currently available # values instead of using something like ``random.randint``. # We can use the hare's position as the new seed. # This is actually what Richard Brent's the "optimized" variant does. _UpperCAmelCase : Optional[Any] = hare # The new step value for the random function can just be incremented. # At first the results will be similar to what the old function would # have produced, but the value will quickly diverge after a bit. step += 1 # We haven't found a divisor within the requested number of attempts. # We were unlucky or ``num`` itself is actually prime. return None if __name__ == "__main__": import argparse lowerCamelCase__ = argparse.ArgumentParser() parser.add_argument( 'num', type=int, help='The value to find a divisor of', ) parser.add_argument( '--attempts', type=int, default=3, help='The number of attempts before giving up', ) lowerCamelCase__ = parser.parse_args() lowerCamelCase__ = pollard_rho(args.num, attempts=args.attempts) if divisor is None: print(F'''{args.num} is probably prime''') else: lowerCamelCase__ = args.num // divisor print(F'''{args.num} = {divisor} * {quotient}''')
234
import unittest from .lib import ( Matrix, Vector, axpy, square_zero_matrix, unit_basis_vector, zero_vector, ) class __lowercase (unittest.TestCase ): def UpperCamelCase__ ( self ) ->None: '''simple docstring''' __lowerCAmelCase : List[str] = Vector([1, 2, 3] ) self.assertEqual(x.component(0 ) , 1 ) self.assertEqual(x.component(2 ) , 3 ) __lowerCAmelCase : Dict = Vector() def UpperCamelCase__ ( self ) ->None: '''simple docstring''' __lowerCAmelCase : Any = Vector([0, 0, 0, 0, 0, 1] ) self.assertEqual(str(A_ ) , '''(0,0,0,0,0,1)''' ) def UpperCamelCase__ ( self ) ->None: '''simple docstring''' __lowerCAmelCase : Union[str, Any] = Vector([1, 2, 3, 4] ) self.assertEqual(len(A_ ) , 4 ) def UpperCamelCase__ ( self ) ->None: '''simple docstring''' __lowerCAmelCase : Dict = Vector([1, 2] ) __lowerCAmelCase : Optional[int] = Vector([1, 2, 3, 4, 5] ) __lowerCAmelCase : Optional[Any] = Vector([0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ) __lowerCAmelCase : str = Vector([1, -1, 1, -1, 2, -3, 4, -5] ) self.assertAlmostEqual(x.euclidean_length() , 2.236 , 3 ) self.assertAlmostEqual(y.euclidean_length() , 7.416 , 3 ) self.assertEqual(z.euclidean_length() , 0 ) self.assertAlmostEqual(w.euclidean_length() , 7.616 , 3 ) def UpperCamelCase__ ( self ) ->None: '''simple docstring''' __lowerCAmelCase : Tuple = Vector([1, 2, 3] ) __lowerCAmelCase : List[str] = Vector([1, 1, 1] ) self.assertEqual((x + y).component(0 ) , 2 ) self.assertEqual((x + y).component(1 ) , 3 ) self.assertEqual((x + y).component(2 ) , 4 ) def UpperCamelCase__ ( self ) ->None: '''simple docstring''' __lowerCAmelCase : Any = Vector([1, 2, 3] ) __lowerCAmelCase : List[str] = Vector([1, 1, 1] ) self.assertEqual((x - y).component(0 ) , 0 ) self.assertEqual((x - y).component(1 ) , 1 ) self.assertEqual((x - y).component(2 ) , 2 ) def UpperCamelCase__ ( self ) ->None: '''simple docstring''' __lowerCAmelCase : str = Vector([1, 2, 3] ) __lowerCAmelCase : List[Any] = Vector([2, -1, 4] ) # for test of dot product __lowerCAmelCase : Optional[int] = Vector([1, -2, -1] ) self.assertEqual(str(x * 3.0 ) , '''(3.0,6.0,9.0)''' ) self.assertEqual((a * b) , 0 ) def UpperCamelCase__ ( self ) ->None: '''simple docstring''' self.assertEqual(str(zero_vector(10 ) ).count('''0''' ) , 10 ) def UpperCamelCase__ ( self ) ->None: '''simple docstring''' self.assertEqual(str(unit_basis_vector(3 , 1 ) ) , '''(0,1,0)''' ) def UpperCamelCase__ ( self ) ->None: '''simple docstring''' __lowerCAmelCase : str = Vector([1, 2, 3] ) __lowerCAmelCase : Any = Vector([1, 0, 1] ) self.assertEqual(str(axpy(2 , A_ , A_ ) ) , '''(3,4,7)''' ) def UpperCamelCase__ ( self ) ->None: '''simple docstring''' __lowerCAmelCase : Tuple = Vector([1, 0, 0, 0, 0, 0] ) __lowerCAmelCase : Optional[Any] = x.copy() self.assertEqual(str(A_ ) , str(A_ ) ) def UpperCamelCase__ ( self ) ->None: '''simple docstring''' __lowerCAmelCase : List[str] = Vector([1, 0, 0] ) x.change_component(0 , 0 ) x.change_component(1 , 1 ) self.assertEqual(str(A_ ) , '''(0,1,0)''' ) def UpperCamelCase__ ( self ) ->None: '''simple docstring''' __lowerCAmelCase : Union[str, Any] = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) self.assertEqual('''|1,2,3|\n|2,4,5|\n|6,7,8|\n''' , str(A_ ) ) def UpperCamelCase__ ( self ) ->None: '''simple docstring''' __lowerCAmelCase : List[Any] = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) __lowerCAmelCase : str = [[-3, -14, -10], [-5, -10, -5], [-2, -1, 0]] for x in range(a.height() ): for y in range(a.width() ): self.assertEqual(minors[x][y] , a.minor(A_ , A_ ) ) def UpperCamelCase__ ( self ) ->None: '''simple docstring''' __lowerCAmelCase : Optional[int] = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) __lowerCAmelCase : Tuple = [[-3, 14, -10], [5, -10, 5], [-2, 1, 0]] for x in range(a.height() ): for y in range(a.width() ): self.assertEqual(cofactors[x][y] , a.cofactor(A_ , A_ ) ) def UpperCamelCase__ ( self ) ->None: '''simple docstring''' __lowerCAmelCase : Dict = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) self.assertEqual(-5 , a.determinant() ) def UpperCamelCase__ ( self ) ->None: '''simple docstring''' __lowerCAmelCase : Tuple = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]] , 3 , 3 ) __lowerCAmelCase : Union[str, Any] = Vector([1, 2, 3] ) self.assertEqual('''(14,32,50)''' , str(a * x ) ) self.assertEqual('''|2,4,6|\n|8,10,12|\n|14,16,18|\n''' , str(a * 2 ) ) def UpperCamelCase__ ( self ) ->None: '''simple docstring''' __lowerCAmelCase : Any = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) a.change_component(0 , 2 , 5 ) self.assertEqual('''|1,2,5|\n|2,4,5|\n|6,7,8|\n''' , str(A_ ) ) def UpperCamelCase__ ( self ) ->None: '''simple docstring''' __lowerCAmelCase : Tuple = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) self.assertEqual(7 , a.component(2 , 1 ) , 0.01 ) def UpperCamelCase__ ( self ) ->None: '''simple docstring''' __lowerCAmelCase : Any = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) __lowerCAmelCase : Dict = Matrix([[1, 2, 7], [2, 4, 5], [6, 7, 10]] , 3 , 3 ) self.assertEqual('''|2,4,10|\n|4,8,10|\n|12,14,18|\n''' , str(a + b ) ) def UpperCamelCase__ ( self ) ->None: '''simple docstring''' __lowerCAmelCase : Dict = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) __lowerCAmelCase : str = Matrix([[1, 2, 7], [2, 4, 5], [6, 7, 10]] , 3 , 3 ) self.assertEqual('''|0,0,-4|\n|0,0,0|\n|0,0,-2|\n''' , str(a - b ) ) def UpperCamelCase__ ( self ) ->None: '''simple docstring''' self.assertEqual( '''|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n''' , str(square_zero_matrix(5 ) ) , ) if __name__ == "__main__": unittest.main()
275
0
"""simple docstring""" from typing import Any, Dict, List, Optional, Tuple, Union import torch from torch import nn from torch.utils.data import DistributedSampler, RandomSampler from transformers import PreTrainedModel, Trainer, logging from transformers.integrations import is_fairscale_available from transformers.models.fsmt.configuration_fsmt import FSMTConfig from transformers.optimization import ( Adafactor, AdamW, get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) from transformers.trainer_pt_utils import get_tpu_sampler from transformers.training_args import ParallelMode from transformers.utils import is_torch_tpu_available if is_fairscale_available(): from fairscale.optim import OSS SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = { "linear": get_linear_schedule_with_warmup, "cosine": get_cosine_schedule_with_warmup, "cosine_w_restarts": get_cosine_with_hard_restarts_schedule_with_warmup, "polynomial": get_polynomial_decay_schedule_with_warmup, "constant": get_constant_schedule, "constant_w_warmup": get_constant_schedule_with_warmup, } class lowercase ( _UpperCAmelCase ): def __init__( self , lowercase=None , lowercase=None , *lowercase , **lowercase ) -> Optional[Any]: super().__init__(*A_ , **A_ ) if config is None: assert isinstance(self.model , A_ ), ( "If no `config` is passed the model to be trained has to be of type `PreTrainedModel`, but is" f' {self.model.__class__}' ) lowerCAmelCase = self.model.config else: lowerCAmelCase = config lowerCAmelCase = data_args lowerCAmelCase = self.config.tgt_vocab_size if isinstance(self.config , A_ ) else self.config.vocab_size if self.args.label_smoothing != 0 or (self.data_args is not None and self.data_args.ignore_pad_token_for_loss): assert self.config.pad_token_id is not None, ( "Make sure that `config.pad_token_id` is correcly defined when ignoring `pad_token` for loss" " calculation or doing label smoothing." ) if self.config.pad_token_id is None and self.config.eos_token_id is not None: logger.warning( f'The `config.pad_token_id` is `None`. Using `config.eos_token_id` = {self.config.eos_token_id} for' """ padding..""" ) if self.args.label_smoothing == 0: lowerCAmelCase = torch.nn.CrossEntropyLoss(ignore_index=self.config.pad_token_id ) else: # dynamically import label_smoothed_nll_loss from utils import label_smoothed_nll_loss lowerCAmelCase = label_smoothed_nll_loss def _snake_case ( self , lowercase ) -> str: if self.optimizer is None: lowerCAmelCase = ['''bias''', '''LayerNorm.weight'''] lowerCAmelCase = [ { '''params''': [p for n, p in self.model.named_parameters() if not any(nd in n for nd in no_decay )], '''weight_decay''': self.args.weight_decay, }, { '''params''': [p for n, p in self.model.named_parameters() if any(nd in n for nd in no_decay )], '''weight_decay''': 0.0, }, ] lowerCAmelCase = Adafactor if self.args.adafactor else AdamW if self.args.adafactor: lowerCAmelCase = Adafactor lowerCAmelCase = {'''scale_parameter''': False, '''relative_step''': False} else: lowerCAmelCase = AdamW lowerCAmelCase = { '''betas''': (self.args.adam_betaa, self.args.adam_betaa), '''eps''': self.args.adam_epsilon, } lowerCAmelCase = self.args.learning_rate if self.sharded_ddp: lowerCAmelCase = OSS( params=A_ , optim=A_ , **A_ , ) else: lowerCAmelCase = optimizer_cls(A_ , **A_ ) if self.lr_scheduler is None: lowerCAmelCase = self._get_lr_scheduler(A_ ) else: # ignoring --lr_scheduler logger.warning("""scheduler is passed to `Seq2SeqTrainer`, `--lr_scheduler` arg is ignored.""" ) def _snake_case ( self , lowercase ) -> List[str]: lowerCAmelCase = arg_to_scheduler[self.args.lr_scheduler] if self.args.lr_scheduler == "constant": lowerCAmelCase = schedule_func(self.optimizer ) elif self.args.lr_scheduler == "constant_w_warmup": lowerCAmelCase = schedule_func(self.optimizer , num_warmup_steps=self.args.warmup_steps ) else: lowerCAmelCase = schedule_func( self.optimizer , num_warmup_steps=self.args.warmup_steps , num_training_steps=A_ ) return scheduler def _snake_case ( self ) -> Optional[torch.utils.data.Sampler]: if isinstance(self.train_dataset , torch.utils.data.IterableDataset ): return None elif is_torch_tpu_available(): return get_tpu_sampler(self.train_dataset ) else: if self.args.sortish_sampler: self.train_dataset.make_sortish_sampler( self.args.per_device_train_batch_size , distributed=(self.args.parallel_mode == ParallelMode.DISTRIBUTED) , ) return ( RandomSampler(self.train_dataset ) if self.args.local_rank == -1 else DistributedSampler(self.train_dataset ) ) def _snake_case ( self , lowercase , lowercase , lowercase ) -> str: if self.args.label_smoothing == 0: if self.data_args is not None and self.data_args.ignore_pad_token_for_loss: # force training to ignore pad token lowerCAmelCase = model(**A_ , use_cache=A_ )[0] lowerCAmelCase = self.loss_fn(logits.view(-1 , logits.shape[-1] ) , labels.view(-1 ) ) else: # compute usual loss via models lowerCAmelCase = model(**A_ , labels=A_ , use_cache=A_ )[:2] else: # compute label smoothed loss lowerCAmelCase = model(**A_ , use_cache=A_ )[0] lowerCAmelCase = torch.nn.functional.log_softmax(A_ , dim=-1 ) lowerCAmelCase = self.loss_fn(A_ , A_ , self.args.label_smoothing , ignore_index=self.config.pad_token_id ) return loss, logits def _snake_case ( self , lowercase , lowercase ) -> Union[str, Any]: lowerCAmelCase = inputs.pop("""labels""" ) lowerCAmelCase = self._compute_loss(A_ , A_ , A_ ) return loss def _snake_case ( self , lowercase , lowercase , lowercase , lowercase = None , ) -> Tuple[Optional[float], Optional[torch.Tensor], Optional[torch.Tensor]]: lowerCAmelCase = self._prepare_inputs(A_ ) lowerCAmelCase = { '''max_length''': self.data_args.val_max_target_length if self.data_args is not None else self.config.max_length, '''num_beams''': self.data_args.eval_beams if self.data_args is not None else self.config.num_beams, } if self.args.predict_with_generate and not self.args.prediction_loss_only: lowerCAmelCase = self.model.generate( inputs["""input_ids"""] , attention_mask=inputs["""attention_mask"""] , **A_ , ) # in case the batch is shorter than max length, the output should be padded if generated_tokens.shape[-1] < gen_kwargs["max_length"]: lowerCAmelCase = self._pad_tensors_to_max_len(A_ , gen_kwargs["""max_length"""] ) lowerCAmelCase = inputs.pop("""labels""" ) with torch.no_grad(): # compute loss on predict data lowerCAmelCase = self._compute_loss(A_ , A_ , A_ ) lowerCAmelCase = loss.mean().detach() if self.args.prediction_loss_only: return (loss, None, None) lowerCAmelCase = generated_tokens if self.args.predict_with_generate else logits if labels.shape[-1] < gen_kwargs["max_length"]: lowerCAmelCase = self._pad_tensors_to_max_len(A_ , gen_kwargs["""max_length"""] ) return (loss, logits, labels) def _snake_case ( self , lowercase , lowercase ) -> List[Any]: lowerCAmelCase = self.config.pad_token_id if self.config.pad_token_id is not None else self.config.eos_token_id if pad_token_id is None: raise ValueError( """Make sure that either `config.pad_token_id` or `config.eos_token_id` is defined if tensor has to be""" f' padded to `max_length`={max_length}' ) lowerCAmelCase = pad_token_id * torch.ones( (tensor.shape[0], max_length) , dtype=tensor.dtype , device=tensor.device ) lowerCAmelCase = tensor return padded_tensor
46
def _lowercase ( lowercase__ , lowercase__ ): if density <= 0: raise ValueError('''Impossible fluid density''' ) if bulk_modulus <= 0: raise ValueError('''Impossible bulk modulus''' ) return (bulk_modulus / density) ** 0.5 if __name__ == "__main__": import doctest doctest.testmod()
275
0
import shutil import tempfile import unittest from unittest.mock import patch from transformers import ( DefaultFlowCallback, IntervalStrategy, PrinterCallback, ProgressCallback, Trainer, TrainerCallback, TrainingArguments, is_torch_available, ) from transformers.testing_utils import require_torch if is_torch_available(): from transformers.trainer import DEFAULT_CALLBACKS from .test_trainer import RegressionDataset, RegressionModelConfig, RegressionPreTrainedModel class _SCREAMING_SNAKE_CASE ( _UpperCAmelCase): def __init__( self )-> Dict: lowerCamelCase_ =[] def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> str: self.events.append("""on_init_end""" ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> Any: self.events.append("""on_train_begin""" ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> Any: self.events.append("""on_train_end""" ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> Union[str, Any]: self.events.append("""on_epoch_begin""" ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> Tuple: self.events.append("""on_epoch_end""" ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> Union[str, Any]: self.events.append("""on_step_begin""" ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> Tuple: self.events.append("""on_step_end""" ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> Any: self.events.append("""on_evaluate""" ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> Union[str, Any]: self.events.append("""on_predict""" ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> Optional[int]: self.events.append("""on_save""" ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> Union[str, Any]: self.events.append("""on_log""" ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> Optional[int]: self.events.append("""on_prediction_step""" ) @require_torch class _SCREAMING_SNAKE_CASE ( unittest.TestCase): def _snake_case ( self )-> str: lowerCamelCase_ =tempfile.mkdtemp() def _snake_case ( self )-> List[Any]: shutil.rmtree(self.output_dir ) def _snake_case ( self , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=64 , _SCREAMING_SNAKE_CASE=64 , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=False , **_SCREAMING_SNAKE_CASE )-> List[Any]: lowerCamelCase_ =RegressionDataset(length=A_ ) lowerCamelCase_ =RegressionDataset(length=A_ ) lowerCamelCase_ =RegressionModelConfig(a=A_ , b=A_ ) lowerCamelCase_ =RegressionPreTrainedModel(A_ ) lowerCamelCase_ =TrainingArguments(self.output_dir , disable_tqdm=A_ , report_to=[] , **A_ ) return Trainer( A_ , A_ , train_dataset=A_ , eval_dataset=A_ , callbacks=A_ , ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Dict: self.assertEqual(len(A_ ) , len(A_ ) ) # Order doesn't matter lowerCamelCase_ =sorted(A_ , key=lambda _SCREAMING_SNAKE_CASE : cb.__name__ if isinstance(A_ , A_ ) else cb.__class__.__name__ ) lowerCamelCase_ =sorted(A_ , key=lambda _SCREAMING_SNAKE_CASE : cb.__name__ if isinstance(A_ , A_ ) else cb.__class__.__name__ ) for cba, cba in zip(A_ , A_ ): if isinstance(A_ , A_ ) and isinstance(A_ , A_ ): self.assertEqual(A_ , A_ ) elif isinstance(A_ , A_ ) and not isinstance(A_ , A_ ): self.assertEqual(A_ , cba.__class__ ) elif not isinstance(A_ , A_ ) and isinstance(A_ , A_ ): self.assertEqual(cba.__class__ , A_ ) else: self.assertEqual(A_ , A_ ) def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> int: lowerCamelCase_ =['''on_init_end''', '''on_train_begin'''] lowerCamelCase_ =0 lowerCamelCase_ =len(trainer.get_eval_dataloader() ) lowerCamelCase_ =['''on_prediction_step'''] * len(trainer.get_eval_dataloader() ) + ['''on_log''', '''on_evaluate'''] for _ in range(trainer.state.num_train_epochs ): expected_events.append("""on_epoch_begin""" ) for _ in range(A_ ): step += 1 expected_events += ["on_step_begin", "on_step_end"] if step % trainer.args.logging_steps == 0: expected_events.append("""on_log""" ) if trainer.args.evaluation_strategy == IntervalStrategy.STEPS and step % trainer.args.eval_steps == 0: expected_events += evaluation_events.copy() if step % trainer.args.save_steps == 0: expected_events.append("""on_save""" ) expected_events.append("""on_epoch_end""" ) if trainer.args.evaluation_strategy == IntervalStrategy.EPOCH: expected_events += evaluation_events.copy() expected_events += ["on_log", "on_train_end"] return expected_events def _snake_case ( self )-> str: lowerCamelCase_ =self.get_trainer() lowerCamelCase_ =DEFAULT_CALLBACKS.copy() + [ProgressCallback] self.check_callbacks_equality(trainer.callback_handler.callbacks , A_ ) # Callbacks passed at init are added to the default callbacks lowerCamelCase_ =self.get_trainer(callbacks=[MyTestTrainerCallback] ) expected_callbacks.append(A_ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , A_ ) # TrainingArguments.disable_tqdm controls if use ProgressCallback or PrinterCallback lowerCamelCase_ =self.get_trainer(disable_tqdm=A_ ) lowerCamelCase_ =DEFAULT_CALLBACKS.copy() + [PrinterCallback] self.check_callbacks_equality(trainer.callback_handler.callbacks , A_ ) def _snake_case ( self )-> List[Any]: lowerCamelCase_ =DEFAULT_CALLBACKS.copy() + [ProgressCallback] lowerCamelCase_ =self.get_trainer() # We can add, pop, or remove by class name trainer.remove_callback(A_ ) expected_callbacks.remove(A_ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , A_ ) lowerCamelCase_ =self.get_trainer() lowerCamelCase_ =trainer.pop_callback(A_ ) self.assertEqual(cb.__class__ , A_ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , A_ ) trainer.add_callback(A_ ) expected_callbacks.insert(0 , A_ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , A_ ) # We can also add, pop, or remove by instance lowerCamelCase_ =self.get_trainer() lowerCamelCase_ =trainer.callback_handler.callbacks[0] trainer.remove_callback(A_ ) expected_callbacks.remove(A_ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , A_ ) lowerCamelCase_ =self.get_trainer() lowerCamelCase_ =trainer.callback_handler.callbacks[0] lowerCamelCase_ =trainer.pop_callback(A_ ) self.assertEqual(A_ , A_ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , A_ ) trainer.add_callback(A_ ) expected_callbacks.insert(0 , A_ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , A_ ) def _snake_case ( self )-> Dict: import warnings # XXX: for now ignore scatter_gather warnings in this test since it's not relevant to what's being tested warnings.simplefilter(action="""ignore""" , category=A_ ) lowerCamelCase_ =self.get_trainer(callbacks=[MyTestTrainerCallback] ) trainer.train() lowerCamelCase_ =trainer.callback_handler.callbacks[-2].events self.assertEqual(A_ , self.get_expected_events(A_ ) ) # Independent log/save/eval lowerCamelCase_ =self.get_trainer(callbacks=[MyTestTrainerCallback] , logging_steps=5 ) trainer.train() lowerCamelCase_ =trainer.callback_handler.callbacks[-2].events self.assertEqual(A_ , self.get_expected_events(A_ ) ) lowerCamelCase_ =self.get_trainer(callbacks=[MyTestTrainerCallback] , save_steps=5 ) trainer.train() lowerCamelCase_ =trainer.callback_handler.callbacks[-2].events self.assertEqual(A_ , self.get_expected_events(A_ ) ) lowerCamelCase_ =self.get_trainer(callbacks=[MyTestTrainerCallback] , eval_steps=5 , evaluation_strategy="""steps""" ) trainer.train() lowerCamelCase_ =trainer.callback_handler.callbacks[-2].events self.assertEqual(A_ , self.get_expected_events(A_ ) ) lowerCamelCase_ =self.get_trainer(callbacks=[MyTestTrainerCallback] , evaluation_strategy="""epoch""" ) trainer.train() lowerCamelCase_ =trainer.callback_handler.callbacks[-2].events self.assertEqual(A_ , self.get_expected_events(A_ ) ) # A bit of everything lowerCamelCase_ =self.get_trainer( callbacks=[MyTestTrainerCallback] , logging_steps=3 , save_steps=10 , eval_steps=5 , evaluation_strategy="""steps""" , ) trainer.train() lowerCamelCase_ =trainer.callback_handler.callbacks[-2].events self.assertEqual(A_ , self.get_expected_events(A_ ) ) # warning should be emitted for duplicated callbacks with patch("""transformers.trainer_callback.logger.warning""" ) as warn_mock: lowerCamelCase_ =self.get_trainer( callbacks=[MyTestTrainerCallback, MyTestTrainerCallback] , ) assert str(A_ ) in warn_mock.call_args[0][0]
154
def _lowercase ( lowercase__ , lowercase__ ): return (pointa[0] - pointa[0]) ** 2 + (pointa[1] - pointa[1]) ** 2 def _lowercase ( lowercase__ , lowercase__=0 ): return sorted(lowercase__ , key=lambda lowercase__ : x[column] ) def _lowercase ( lowercase__ , lowercase__ , lowercase__=float('''inf''' ) ): for i in range(points_counts - 1 ): for j in range(i + 1 , lowercase__ ): __lowerCAmelCase : List[str] = euclidean_distance_sqr(points[i] , points[j] ) if current_dis < min_dis: __lowerCAmelCase : Tuple = current_dis return min_dis def _lowercase ( lowercase__ , lowercase__ , lowercase__=float('''inf''' ) ): for i in range(min(6 , points_counts - 1 ) , lowercase__ ): for j in range(max(0 , i - 6 ) , lowercase__ ): __lowerCAmelCase : Union[str, Any] = euclidean_distance_sqr(points[i] , points[j] ) if current_dis < min_dis: __lowerCAmelCase : int = current_dis return min_dis def _lowercase ( lowercase__ , lowercase__ , lowercase__ ): # base case if points_counts <= 3: return dis_between_closest_pair(lowercase__ , lowercase__ ) # recursion __lowerCAmelCase : Optional[Any] = points_counts // 2 __lowerCAmelCase : Optional[Any] = closest_pair_of_points_sqr( lowercase__ , points_sorted_on_y[:mid] , lowercase__ ) __lowerCAmelCase : str = closest_pair_of_points_sqr( lowercase__ , points_sorted_on_y[mid:] , points_counts - mid ) __lowerCAmelCase : Optional[int] = min(lowercase__ , lowercase__ ) __lowerCAmelCase : Tuple = [] for point in points_sorted_on_x: if abs(point[0] - points_sorted_on_x[mid][0] ) < closest_pair_dis: cross_strip.append(lowercase__ ) __lowerCAmelCase : List[Any] = dis_between_closest_in_strip( lowercase__ , len(lowercase__ ) , lowercase__ ) return min(lowercase__ , lowercase__ ) def _lowercase ( lowercase__ , lowercase__ ): __lowerCAmelCase : Union[str, Any] = column_based_sort(lowercase__ , column=0 ) __lowerCAmelCase : Any = column_based_sort(lowercase__ , column=1 ) return ( closest_pair_of_points_sqr( lowercase__ , lowercase__ , lowercase__ ) ) ** 0.5 if __name__ == "__main__": _UpperCamelCase = [(2, 3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4)] print("Distance:", closest_pair_of_points(points, len(points)))
275
0
from ..utils import DummyObject, requires_backends class UpperCamelCase_ ( metaclass=_UpperCAmelCase ): '''simple docstring''' UpperCAmelCase__ = ['''sentencepiece'''] def __init__( self : int , *UpperCAmelCase__ : List[Any] , **UpperCAmelCase__ : Optional[Any]) ->Tuple: '''simple docstring''' requires_backends(self , ['''sentencepiece''']) class UpperCamelCase_ ( metaclass=_UpperCAmelCase ): '''simple docstring''' UpperCAmelCase__ = ['''sentencepiece'''] def __init__( self : List[str] , *UpperCAmelCase__ : Any , **UpperCAmelCase__ : str) ->List[str]: '''simple docstring''' requires_backends(self , ['''sentencepiece''']) class UpperCamelCase_ ( metaclass=_UpperCAmelCase ): '''simple docstring''' UpperCAmelCase__ = ['''sentencepiece'''] def __init__( self : Optional[int] , *UpperCAmelCase__ : Dict , **UpperCAmelCase__ : int) ->str: '''simple docstring''' requires_backends(self , ['''sentencepiece''']) class UpperCamelCase_ ( metaclass=_UpperCAmelCase ): '''simple docstring''' UpperCAmelCase__ = ['''sentencepiece'''] def __init__( self : int , *UpperCAmelCase__ : Tuple , **UpperCAmelCase__ : Dict) ->str: '''simple docstring''' requires_backends(self , ['''sentencepiece''']) class UpperCamelCase_ ( metaclass=_UpperCAmelCase ): '''simple docstring''' UpperCAmelCase__ = ['''sentencepiece'''] def __init__( self : List[str] , *UpperCAmelCase__ : Union[str, Any] , **UpperCAmelCase__ : int) ->Optional[int]: '''simple docstring''' requires_backends(self , ['''sentencepiece''']) class UpperCamelCase_ ( metaclass=_UpperCAmelCase ): '''simple docstring''' UpperCAmelCase__ = ['''sentencepiece'''] def __init__( self : int , *UpperCAmelCase__ : Tuple , **UpperCAmelCase__ : List[str]) ->str: '''simple docstring''' requires_backends(self , ['''sentencepiece''']) class UpperCamelCase_ ( metaclass=_UpperCAmelCase ): '''simple docstring''' UpperCAmelCase__ = ['''sentencepiece'''] def __init__( self : int , *UpperCAmelCase__ : Optional[Any] , **UpperCAmelCase__ : Any) ->Optional[int]: '''simple docstring''' requires_backends(self , ['''sentencepiece''']) class UpperCamelCase_ ( metaclass=_UpperCAmelCase ): '''simple docstring''' UpperCAmelCase__ = ['''sentencepiece'''] def __init__( self : Optional[Any] , *UpperCAmelCase__ : Dict , **UpperCAmelCase__ : Optional[int]) ->Any: '''simple docstring''' requires_backends(self , ['''sentencepiece''']) class UpperCamelCase_ ( metaclass=_UpperCAmelCase ): '''simple docstring''' UpperCAmelCase__ = ['''sentencepiece'''] def __init__( self : int , *UpperCAmelCase__ : int , **UpperCAmelCase__ : str) ->List[str]: '''simple docstring''' requires_backends(self , ['''sentencepiece''']) class UpperCamelCase_ ( metaclass=_UpperCAmelCase ): '''simple docstring''' UpperCAmelCase__ = ['''sentencepiece'''] def __init__( self : Optional[Any] , *UpperCAmelCase__ : Union[str, Any] , **UpperCAmelCase__ : Optional[int]) ->List[Any]: '''simple docstring''' requires_backends(self , ['''sentencepiece''']) class UpperCamelCase_ ( metaclass=_UpperCAmelCase ): '''simple docstring''' UpperCAmelCase__ = ['''sentencepiece'''] def __init__( self : Any , *UpperCAmelCase__ : str , **UpperCAmelCase__ : List[Any]) ->List[str]: '''simple docstring''' requires_backends(self , ['''sentencepiece''']) class UpperCamelCase_ ( metaclass=_UpperCAmelCase ): '''simple docstring''' UpperCAmelCase__ = ['''sentencepiece'''] def __init__( self : Any , *UpperCAmelCase__ : Dict , **UpperCAmelCase__ : Union[str, Any]) ->int: '''simple docstring''' requires_backends(self , ['''sentencepiece''']) class UpperCamelCase_ ( metaclass=_UpperCAmelCase ): '''simple docstring''' UpperCAmelCase__ = ['''sentencepiece'''] def __init__( self : int , *UpperCAmelCase__ : List[str] , **UpperCAmelCase__ : Optional[int]) ->List[str]: '''simple docstring''' requires_backends(self , ['''sentencepiece''']) class UpperCamelCase_ ( metaclass=_UpperCAmelCase ): '''simple docstring''' UpperCAmelCase__ = ['''sentencepiece'''] def __init__( self : str , *UpperCAmelCase__ : str , **UpperCAmelCase__ : Tuple) ->List[Any]: '''simple docstring''' requires_backends(self , ['''sentencepiece''']) class UpperCamelCase_ ( metaclass=_UpperCAmelCase ): '''simple docstring''' UpperCAmelCase__ = ['''sentencepiece'''] def __init__( self : int , *UpperCAmelCase__ : Optional[Any] , **UpperCAmelCase__ : Union[str, Any]) ->int: '''simple docstring''' requires_backends(self , ['''sentencepiece''']) class UpperCamelCase_ ( metaclass=_UpperCAmelCase ): '''simple docstring''' UpperCAmelCase__ = ['''sentencepiece'''] def __init__( self : Union[str, Any] , *UpperCAmelCase__ : str , **UpperCAmelCase__ : Optional[Any]) ->Tuple: '''simple docstring''' requires_backends(self , ['''sentencepiece''']) class UpperCamelCase_ ( metaclass=_UpperCAmelCase ): '''simple docstring''' UpperCAmelCase__ = ['''sentencepiece'''] def __init__( self : List[str] , *UpperCAmelCase__ : List[Any] , **UpperCAmelCase__ : List[str]) ->Any: '''simple docstring''' requires_backends(self , ['''sentencepiece''']) class UpperCamelCase_ ( metaclass=_UpperCAmelCase ): '''simple docstring''' UpperCAmelCase__ = ['''sentencepiece'''] def __init__( self : List[Any] , *UpperCAmelCase__ : int , **UpperCAmelCase__ : Optional[int]) ->Union[str, Any]: '''simple docstring''' requires_backends(self , ['''sentencepiece''']) class UpperCamelCase_ ( metaclass=_UpperCAmelCase ): '''simple docstring''' UpperCAmelCase__ = ['''sentencepiece'''] def __init__( self : Any , *UpperCAmelCase__ : Union[str, Any] , **UpperCAmelCase__ : int) ->int: '''simple docstring''' requires_backends(self , ['''sentencepiece''']) class UpperCamelCase_ ( metaclass=_UpperCAmelCase ): '''simple docstring''' UpperCAmelCase__ = ['''sentencepiece'''] def __init__( self : Dict , *UpperCAmelCase__ : int , **UpperCAmelCase__ : Any) ->Optional[int]: '''simple docstring''' requires_backends(self , ['''sentencepiece''']) class UpperCamelCase_ ( metaclass=_UpperCAmelCase ): '''simple docstring''' UpperCAmelCase__ = ['''sentencepiece'''] def __init__( self : str , *UpperCAmelCase__ : List[Any] , **UpperCAmelCase__ : Dict) ->int: '''simple docstring''' requires_backends(self , ['''sentencepiece''']) class UpperCamelCase_ ( metaclass=_UpperCAmelCase ): '''simple docstring''' UpperCAmelCase__ = ['''sentencepiece'''] def __init__( self : int , *UpperCAmelCase__ : List[str] , **UpperCAmelCase__ : Tuple) ->Any: '''simple docstring''' requires_backends(self , ['''sentencepiece''']) class UpperCamelCase_ ( metaclass=_UpperCAmelCase ): '''simple docstring''' UpperCAmelCase__ = ['''sentencepiece'''] def __init__( self : List[Any] , *UpperCAmelCase__ : str , **UpperCAmelCase__ : List[str]) ->Optional[Any]: '''simple docstring''' requires_backends(self , ['''sentencepiece''']) class UpperCamelCase_ ( metaclass=_UpperCAmelCase ): '''simple docstring''' UpperCAmelCase__ = ['''sentencepiece'''] def __init__( self : Dict , *UpperCAmelCase__ : Optional[Any] , **UpperCAmelCase__ : Optional[int]) ->Dict: '''simple docstring''' requires_backends(self , ['''sentencepiece''']) class UpperCamelCase_ ( metaclass=_UpperCAmelCase ): '''simple docstring''' UpperCAmelCase__ = ['''sentencepiece'''] def __init__( self : Any , *UpperCAmelCase__ : Any , **UpperCAmelCase__ : Optional[Any]) ->int: '''simple docstring''' requires_backends(self , ['''sentencepiece''']) class UpperCamelCase_ ( metaclass=_UpperCAmelCase ): '''simple docstring''' UpperCAmelCase__ = ['''sentencepiece'''] def __init__( self : List[str] , *UpperCAmelCase__ : int , **UpperCAmelCase__ : str) ->str: '''simple docstring''' requires_backends(self , ['''sentencepiece''']) class UpperCamelCase_ ( metaclass=_UpperCAmelCase ): '''simple docstring''' UpperCAmelCase__ = ['''sentencepiece'''] def __init__( self : List[Any] , *UpperCAmelCase__ : Optional[int] , **UpperCAmelCase__ : Optional[int]) ->Optional[int]: '''simple docstring''' requires_backends(self , ['''sentencepiece''']) class UpperCamelCase_ ( metaclass=_UpperCAmelCase ): '''simple docstring''' UpperCAmelCase__ = ['''sentencepiece'''] def __init__( self : Dict , *UpperCAmelCase__ : Union[str, Any] , **UpperCAmelCase__ : int) ->Union[str, Any]: '''simple docstring''' requires_backends(self , ['''sentencepiece''']) class UpperCamelCase_ ( metaclass=_UpperCAmelCase ): '''simple docstring''' UpperCAmelCase__ = ['''sentencepiece'''] def __init__( self : Union[str, Any] , *UpperCAmelCase__ : Tuple , **UpperCAmelCase__ : Dict) ->Optional[Any]: '''simple docstring''' requires_backends(self , ['''sentencepiece''']) class UpperCamelCase_ ( metaclass=_UpperCAmelCase ): '''simple docstring''' UpperCAmelCase__ = ['''sentencepiece'''] def __init__( self : List[str] , *UpperCAmelCase__ : Tuple , **UpperCAmelCase__ : List[str]) ->List[str]: '''simple docstring''' requires_backends(self , ['''sentencepiece''']) class UpperCamelCase_ ( metaclass=_UpperCAmelCase ): '''simple docstring''' UpperCAmelCase__ = ['''sentencepiece'''] def __init__( self : Tuple , *UpperCAmelCase__ : Any , **UpperCAmelCase__ : List[str]) ->int: '''simple docstring''' requires_backends(self , ['''sentencepiece'''])
14
def _lowercase ( lowercase__ = 2_0_0 ): __lowerCAmelCase : Union[str, Any] = [1, 2, 5, 1_0, 2_0, 5_0, 1_0_0, 2_0_0] __lowerCAmelCase : Dict = [0] * (pence + 1) __lowerCAmelCase : Optional[int] = 1 # base case: 1 way to make 0 pence for coin in coins: for i in range(lowercase__ , pence + 1 , 1 ): number_of_ways[i] += number_of_ways[i - coin] return number_of_ways[pence] if __name__ == "__main__": assert solution(200) == 7_3682
275
0
'''simple docstring''' from __future__ import annotations def a__ ( lowercase : Dict, lowercase : Optional[int] ) -> Optional[Any]: """simple docstring""" if len(lowercase__ ) < k or k < 0: raise ValueError('''Invalid Input''' ) _UpperCamelCase = sum(array[:k] ) for i in range(len(lowercase__ ) - k ): _UpperCamelCase = current_sum - array[i] + array[i + k] _UpperCamelCase = max(lowercase__, lowercase__ ) return max_sum if __name__ == "__main__": from doctest import testmod from random import randint testmod() lowercase__ : List[str] = [randint(-10_00, 10_00) for i in range(1_00)] lowercase__ : str = randint(0, 1_10) print(F"""The maximum sum of {k} consecutive elements is {max_sum_in_array(array,k)}""")
324
import gc import unittest import numpy as np import torch from torch.backends.cuda import sdp_kernel from diffusers import ( CMStochasticIterativeScheduler, ConsistencyModelPipeline, UNetaDModel, ) from diffusers.utils import randn_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_a, require_torch_gpu from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class __lowercase (_UpperCAmelCase , unittest.TestCase ): _UpperCamelCase = ConsistencyModelPipeline _UpperCamelCase = UNCONDITIONAL_IMAGE_GENERATION_PARAMS _UpperCamelCase = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS # Override required_optional_params to remove num_images_per_prompt _UpperCamelCase = frozenset( [ """num_inference_steps""", """generator""", """latents""", """output_type""", """return_dict""", """callback""", """callback_steps""", ] ) @property def UpperCamelCase__ ( self ) ->List[str]: '''simple docstring''' __lowerCAmelCase : List[Any] = UNetaDModel.from_pretrained( '''diffusers/consistency-models-test''' , subfolder='''test_unet''' , ) return unet @property def UpperCamelCase__ ( self ) ->Optional[int]: '''simple docstring''' __lowerCAmelCase : List[str] = UNetaDModel.from_pretrained( '''diffusers/consistency-models-test''' , subfolder='''test_unet_class_cond''' , ) return unet def UpperCamelCase__ ( self , A_=False ) ->Dict: '''simple docstring''' if class_cond: __lowerCAmelCase : List[str] = self.dummy_cond_unet else: __lowerCAmelCase : Optional[Any] = self.dummy_uncond_unet # Default to CM multistep sampler __lowerCAmelCase : List[str] = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.002 , sigma_max=80.0 , ) __lowerCAmelCase : Dict = { '''unet''': unet, '''scheduler''': scheduler, } return components def UpperCamelCase__ ( self , A_ , A_=0 ) ->Tuple: '''simple docstring''' if str(A_ ).startswith('''mps''' ): __lowerCAmelCase : str = torch.manual_seed(A_ ) else: __lowerCAmelCase : Dict = torch.Generator(device=A_ ).manual_seed(A_ ) __lowerCAmelCase : Tuple = { '''batch_size''': 1, '''num_inference_steps''': None, '''timesteps''': [22, 0], '''generator''': generator, '''output_type''': '''np''', } return inputs def UpperCamelCase__ ( self ) ->Tuple: '''simple docstring''' __lowerCAmelCase : Union[str, Any] = '''cpu''' # ensure determinism for the device-dependent torch.Generator __lowerCAmelCase : Tuple = self.get_dummy_components() __lowerCAmelCase : Union[str, Any] = ConsistencyModelPipeline(**A_ ) __lowerCAmelCase : List[str] = pipe.to(A_ ) pipe.set_progress_bar_config(disable=A_ ) __lowerCAmelCase : Any = self.get_dummy_inputs(A_ ) __lowerCAmelCase : int = pipe(**A_ ).images assert image.shape == (1, 32, 32, 3) __lowerCAmelCase : Tuple = image[0, -3:, -3:, -1] __lowerCAmelCase : str = np.array([0.3_572, 0.6_273, 0.4_031, 0.3_961, 0.4_321, 0.5_730, 0.5_266, 0.4_780, 0.5_004] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def UpperCamelCase__ ( self ) ->Tuple: '''simple docstring''' __lowerCAmelCase : List[Any] = '''cpu''' # ensure determinism for the device-dependent torch.Generator __lowerCAmelCase : str = self.get_dummy_components(class_cond=A_ ) __lowerCAmelCase : List[str] = ConsistencyModelPipeline(**A_ ) __lowerCAmelCase : List[Any] = pipe.to(A_ ) pipe.set_progress_bar_config(disable=A_ ) __lowerCAmelCase : Optional[Any] = self.get_dummy_inputs(A_ ) __lowerCAmelCase : Optional[int] = 0 __lowerCAmelCase : int = pipe(**A_ ).images assert image.shape == (1, 32, 32, 3) __lowerCAmelCase : Optional[int] = image[0, -3:, -3:, -1] __lowerCAmelCase : List[str] = np.array([0.3_572, 0.6_273, 0.4_031, 0.3_961, 0.4_321, 0.5_730, 0.5_266, 0.4_780, 0.5_004] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def UpperCamelCase__ ( self ) ->Optional[Any]: '''simple docstring''' __lowerCAmelCase : Any = '''cpu''' # ensure determinism for the device-dependent torch.Generator __lowerCAmelCase : Union[str, Any] = self.get_dummy_components() __lowerCAmelCase : List[Any] = ConsistencyModelPipeline(**A_ ) __lowerCAmelCase : int = pipe.to(A_ ) pipe.set_progress_bar_config(disable=A_ ) __lowerCAmelCase : Tuple = self.get_dummy_inputs(A_ ) __lowerCAmelCase : Any = 1 __lowerCAmelCase : List[Any] = None __lowerCAmelCase : Dict = pipe(**A_ ).images assert image.shape == (1, 32, 32, 3) __lowerCAmelCase : Any = image[0, -3:, -3:, -1] __lowerCAmelCase : List[Any] = np.array([0.5_004, 0.5_004, 0.4_994, 0.5_008, 0.4_976, 0.5_018, 0.4_990, 0.4_982, 0.4_987] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def UpperCamelCase__ ( self ) ->Optional[Any]: '''simple docstring''' __lowerCAmelCase : List[Any] = '''cpu''' # ensure determinism for the device-dependent torch.Generator __lowerCAmelCase : Optional[Any] = self.get_dummy_components(class_cond=A_ ) __lowerCAmelCase : List[str] = ConsistencyModelPipeline(**A_ ) __lowerCAmelCase : Union[str, Any] = pipe.to(A_ ) pipe.set_progress_bar_config(disable=A_ ) __lowerCAmelCase : Any = self.get_dummy_inputs(A_ ) __lowerCAmelCase : List[str] = 1 __lowerCAmelCase : Dict = None __lowerCAmelCase : Tuple = 0 __lowerCAmelCase : Dict = pipe(**A_ ).images assert image.shape == (1, 32, 32, 3) __lowerCAmelCase : List[Any] = image[0, -3:, -3:, -1] __lowerCAmelCase : Any = np.array([0.5_004, 0.5_004, 0.4_994, 0.5_008, 0.4_976, 0.5_018, 0.4_990, 0.4_982, 0.4_987] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 @slow @require_torch_gpu class __lowercase (unittest.TestCase ): def UpperCamelCase__ ( self ) ->int: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase__ ( self , A_=0 , A_=False , A_="cpu" , A_=torch.floataa , A_=(1, 3, 64, 64) ) ->str: '''simple docstring''' __lowerCAmelCase : Dict = torch.manual_seed(A_ ) __lowerCAmelCase : Tuple = { '''num_inference_steps''': None, '''timesteps''': [22, 0], '''class_labels''': 0, '''generator''': generator, '''output_type''': '''np''', } if get_fixed_latents: __lowerCAmelCase : List[str] = self.get_fixed_latents(seed=A_ , device=A_ , dtype=A_ , shape=A_ ) __lowerCAmelCase : Union[str, Any] = latents return inputs def UpperCamelCase__ ( self , A_=0 , A_="cpu" , A_=torch.floataa , A_=(1, 3, 64, 64) ) ->Optional[int]: '''simple docstring''' if type(A_ ) == str: __lowerCAmelCase : int = torch.device(A_ ) __lowerCAmelCase : Optional[Any] = torch.Generator(device=A_ ).manual_seed(A_ ) __lowerCAmelCase : Union[str, Any] = randn_tensor(A_ , generator=A_ , device=A_ , dtype=A_ ) return latents def UpperCamelCase__ ( self ) ->Optional[Any]: '''simple docstring''' __lowerCAmelCase : int = UNetaDModel.from_pretrained('''diffusers/consistency_models''' , subfolder='''diffusers_cd_imagenet64_l2''' ) __lowerCAmelCase : List[Any] = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.002 , sigma_max=80.0 , ) __lowerCAmelCase : List[str] = ConsistencyModelPipeline(unet=A_ , scheduler=A_ ) pipe.to(torch_device=A_ ) pipe.set_progress_bar_config(disable=A_ ) __lowerCAmelCase : str = self.get_inputs() __lowerCAmelCase : Any = pipe(**A_ ).images assert image.shape == (1, 64, 64, 3) __lowerCAmelCase : Dict = image[0, -3:, -3:, -1] __lowerCAmelCase : Optional[int] = np.array([0.0_888, 0.0_881, 0.0_666, 0.0_479, 0.0_292, 0.0_195, 0.0_201, 0.0_163, 0.0_254] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 def UpperCamelCase__ ( self ) ->Any: '''simple docstring''' __lowerCAmelCase : int = UNetaDModel.from_pretrained('''diffusers/consistency_models''' , subfolder='''diffusers_cd_imagenet64_l2''' ) __lowerCAmelCase : Optional[Any] = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.002 , sigma_max=80.0 , ) __lowerCAmelCase : List[str] = ConsistencyModelPipeline(unet=A_ , scheduler=A_ ) pipe.to(torch_device=A_ ) pipe.set_progress_bar_config(disable=A_ ) __lowerCAmelCase : List[Any] = self.get_inputs() __lowerCAmelCase : Tuple = 1 __lowerCAmelCase : Optional[Any] = None __lowerCAmelCase : str = pipe(**A_ ).images assert image.shape == (1, 64, 64, 3) __lowerCAmelCase : Optional[int] = image[0, -3:, -3:, -1] __lowerCAmelCase : List[Any] = np.array([0.0_340, 0.0_152, 0.0_063, 0.0_267, 0.0_221, 0.0_107, 0.0_416, 0.0_186, 0.0_217] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 @require_torch_a def UpperCamelCase__ ( self ) ->Optional[Any]: '''simple docstring''' __lowerCAmelCase : Tuple = UNetaDModel.from_pretrained('''diffusers/consistency_models''' , subfolder='''diffusers_cd_imagenet64_l2''' ) __lowerCAmelCase : List[str] = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.002 , sigma_max=80.0 , ) __lowerCAmelCase : Union[str, Any] = ConsistencyModelPipeline(unet=A_ , scheduler=A_ ) pipe.to(torch_device=A_ , torch_dtype=torch.floataa ) pipe.set_progress_bar_config(disable=A_ ) __lowerCAmelCase : Any = self.get_inputs(get_fixed_latents=A_ , device=A_ ) # Ensure usage of flash attention in torch 2.0 with sdp_kernel(enable_flash=A_ , enable_math=A_ , enable_mem_efficient=A_ ): __lowerCAmelCase : Dict = pipe(**A_ ).images assert image.shape == (1, 64, 64, 3) __lowerCAmelCase : Dict = image[0, -3:, -3:, -1] __lowerCAmelCase : Optional[int] = np.array([0.1_875, 0.1_428, 0.1_289, 0.2_151, 0.2_092, 0.1_477, 0.1_877, 0.1_641, 0.1_353] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 @require_torch_a def UpperCamelCase__ ( self ) ->List[str]: '''simple docstring''' __lowerCAmelCase : Optional[Any] = UNetaDModel.from_pretrained('''diffusers/consistency_models''' , subfolder='''diffusers_cd_imagenet64_l2''' ) __lowerCAmelCase : List[Any] = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.002 , sigma_max=80.0 , ) __lowerCAmelCase : Union[str, Any] = ConsistencyModelPipeline(unet=A_ , scheduler=A_ ) pipe.to(torch_device=A_ , torch_dtype=torch.floataa ) pipe.set_progress_bar_config(disable=A_ ) __lowerCAmelCase : Union[str, Any] = self.get_inputs(get_fixed_latents=A_ , device=A_ ) __lowerCAmelCase : Any = 1 __lowerCAmelCase : int = None # Ensure usage of flash attention in torch 2.0 with sdp_kernel(enable_flash=A_ , enable_math=A_ , enable_mem_efficient=A_ ): __lowerCAmelCase : int = pipe(**A_ ).images assert image.shape == (1, 64, 64, 3) __lowerCAmelCase : str = image[0, -3:, -3:, -1] __lowerCAmelCase : Any = np.array([0.1_663, 0.1_948, 0.2_275, 0.1_680, 0.1_204, 0.1_245, 0.1_858, 0.1_338, 0.2_095] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3
275
0
'''simple docstring''' # Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torch from accelerate import PartialState from accelerate.utils.operations import broadcast, gather, gather_object, pad_across_processes, reduce def _UpperCAmelCase ( _lowerCamelCase : str ) -> List[str]: return (torch.arange(state.num_processes ) + 1.0 + (state.num_processes * state.process_index)).to(state.device ) def _UpperCAmelCase ( _lowerCamelCase : Dict ) -> Optional[int]: _lowerCAmelCase : Optional[int] = create_tensor(lowercase__ ) _lowerCAmelCase : Tuple = gather(lowercase__ ) assert gathered_tensor.tolist() == list(range(1 , state.num_processes**2 + 1 ) ) def _UpperCAmelCase ( _lowerCamelCase : Optional[int] ) -> Optional[Any]: _lowerCAmelCase : List[Any] = [state.process_index] _lowerCAmelCase : str = gather_object(lowercase__ ) assert len(lowercase__ ) == state.num_processes, f'{gathered_obj}, {len(lowercase__ )} != {state.num_processes}' assert gathered_obj == list(range(state.num_processes ) ), f'{gathered_obj} != {list(range(state.num_processes ) )}' def _UpperCAmelCase ( _lowerCamelCase : str ) -> Tuple: _lowerCAmelCase : Tuple = create_tensor(lowercase__ ) _lowerCAmelCase : List[Any] = broadcast(lowercase__ ) assert broadcasted_tensor.shape == torch.Size([state.num_processes] ) assert broadcasted_tensor.tolist() == list(range(1 , state.num_processes + 1 ) ) def _UpperCAmelCase ( _lowerCamelCase : List[str] ) -> str: # We need to pad the tensor with one more element if we are the main process # to ensure that we can pad if state.is_main_process: _lowerCAmelCase : int = torch.arange(state.num_processes + 1 ).to(state.device ) else: _lowerCAmelCase : str = torch.arange(state.num_processes ).to(state.device ) _lowerCAmelCase : List[str] = pad_across_processes(lowercase__ ) assert padded_tensor.shape == torch.Size([state.num_processes + 1] ) if not state.is_main_process: assert padded_tensor.tolist() == list(range(0 , state.num_processes ) ) + [0] def _UpperCAmelCase ( _lowerCamelCase : List[Any] ) -> List[str]: # For now runs on only two processes if state.num_processes != 2: return _lowerCAmelCase : Optional[int] = create_tensor(lowercase__ ) _lowerCAmelCase : str = reduce(lowercase__ , """sum""" ) _lowerCAmelCase : int = torch.tensor([4.0, 6] ).to(state.device ) assert torch.allclose(lowercase__ , lowercase__ ), f'{reduced_tensor} != {truth_tensor}' def _UpperCAmelCase ( _lowerCamelCase : int ) -> List[str]: # For now runs on only two processes if state.num_processes != 2: return _lowerCAmelCase : str = create_tensor(lowercase__ ) _lowerCAmelCase : Dict = reduce(lowercase__ , """mean""" ) _lowerCAmelCase : List[str] = torch.tensor([2.0, 3] ).to(state.device ) assert torch.allclose(lowercase__ , lowercase__ ), f'{reduced_tensor} != {truth_tensor}' def _UpperCAmelCase ( _lowerCamelCase : List[Any] ) -> Tuple: # For xla_spawn (TPUs) main() def _UpperCAmelCase ( ) -> Any: _lowerCAmelCase : Union[str, Any] = PartialState() state.print(f'State: {state}' ) state.print("""testing gather""" ) test_gather(lowercase__ ) state.print("""testing gather_object""" ) test_gather_object(lowercase__ ) state.print("""testing broadcast""" ) test_broadcast(lowercase__ ) state.print("""testing pad_across_processes""" ) test_pad_across_processes(lowercase__ ) state.print("""testing reduce_sum""" ) test_reduce_sum(lowercase__ ) state.print("""testing reduce_mean""" ) test_reduce_mean(lowercase__ ) if __name__ == "__main__": main()
309
from collections import deque from .hash_table import HashTable class __lowercase (_UpperCAmelCase ): def __init__( self , *A_ , **A_ ) ->int: '''simple docstring''' super().__init__(*A_ , **A_ ) def UpperCamelCase__ ( self , A_ , A_ ) ->Optional[int]: '''simple docstring''' __lowerCAmelCase : Dict = deque([] ) if self.values[key] is None else self.values[key] self.values[key].appendleft(A_ ) __lowerCAmelCase : int = self.values[key] def UpperCamelCase__ ( self ) ->Tuple: '''simple docstring''' return ( sum(self.charge_factor - len(A_ ) for slot in self.values ) / self.size_table * self.charge_factor ) def UpperCamelCase__ ( self , A_ , A_=None ) ->str: '''simple docstring''' if not ( len(self.values[key] ) == self.charge_factor and self.values.count(A_ ) == 0 ): return key return super()._collision_resolution(A_ , A_ )
275
0
import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionInstructPixaPixPipeline, UNetaDConditionModel, ) from diffusers.image_processor import VaeImageProcessor from diffusers.utils import floats_tensor, load_image, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class a__ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Dict =StableDiffusionInstructPixaPixPipeline UpperCAmelCase__ : List[Any] =TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"""height""", """width""", """cross_attention_kwargs"""} UpperCAmelCase__ : Optional[Any] =TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS UpperCAmelCase__ : List[str] =IMAGE_TO_IMAGE_IMAGE_PARAMS UpperCAmelCase__ : str =IMAGE_TO_IMAGE_IMAGE_PARAMS def _lowercase ( self : Tuple ) ->Tuple: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Tuple = UNetaDConditionModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=8 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=3_2 , ) SCREAMING_SNAKE_CASE : List[Any] = PNDMScheduler(skip_prk_steps=A_ ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Tuple = AutoencoderKL( block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Any = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , intermediate_size=3_7 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , ) SCREAMING_SNAKE_CASE : Optional[Any] = CLIPTextModel(A_ ) SCREAMING_SNAKE_CASE : Optional[Any] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) SCREAMING_SNAKE_CASE : Dict = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''safety_checker''': None, '''feature_extractor''': None, } return components def _lowercase ( self : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[Any]=0 ) ->List[str]: """simple docstring""" SCREAMING_SNAKE_CASE : Any = floats_tensor((1, 3, 3_2, 3_2) , rng=random.Random(A_ ) ).to(A_ ) SCREAMING_SNAKE_CASE : Optional[int] = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE : Any = Image.fromarray(np.uinta(A_ ) ).convert("""RGB""" ) if str(A_ ).startswith("""mps""" ): SCREAMING_SNAKE_CASE : Dict = torch.manual_seed(A_ ) else: SCREAMING_SNAKE_CASE : int = torch.Generator(device=A_ ).manual_seed(A_ ) SCREAMING_SNAKE_CASE : List[Any] = { '''prompt''': '''A painting of a squirrel eating a burger''', '''image''': image, '''generator''': generator, '''num_inference_steps''': 2, '''guidance_scale''': 6.0, '''image_guidance_scale''': 1, '''output_type''': '''numpy''', } return inputs def _lowercase ( self : int ) ->str: """simple docstring""" SCREAMING_SNAKE_CASE : int = '''cpu''' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE : Dict = self.get_dummy_components() SCREAMING_SNAKE_CASE : List[str] = StableDiffusionInstructPixaPixPipeline(**A_ ) SCREAMING_SNAKE_CASE : int = sd_pipe.to(A_ ) sd_pipe.set_progress_bar_config(disable=A_ ) SCREAMING_SNAKE_CASE : List[str] = self.get_dummy_inputs(A_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = sd_pipe(**A_ ).images SCREAMING_SNAKE_CASE : Dict = image[0, -3:, -3:, -1] assert image.shape == (1, 3_2, 3_2, 3) SCREAMING_SNAKE_CASE : List[Any] = np.array([0.75_26, 0.37_50, 0.45_47, 0.61_17, 0.58_66, 0.50_16, 0.43_27, 0.56_42, 0.48_15] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def _lowercase ( self : List[Any] ) ->List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = '''cpu''' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE : str = self.get_dummy_components() SCREAMING_SNAKE_CASE : List[str] = StableDiffusionInstructPixaPixPipeline(**A_ ) SCREAMING_SNAKE_CASE : List[str] = sd_pipe.to(A_ ) sd_pipe.set_progress_bar_config(disable=A_ ) SCREAMING_SNAKE_CASE : int = self.get_dummy_inputs(A_ ) SCREAMING_SNAKE_CASE : int = '''french fries''' SCREAMING_SNAKE_CASE : str = sd_pipe(**A_ , negative_prompt=A_ ) SCREAMING_SNAKE_CASE : List[Any] = output.images SCREAMING_SNAKE_CASE : Union[str, Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 3_2, 3_2, 3) SCREAMING_SNAKE_CASE : int = np.array([0.75_11, 0.36_42, 0.45_53, 0.62_36, 0.57_97, 0.50_13, 0.43_43, 0.56_11, 0.48_31] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def _lowercase ( self : List[Any] ) ->Any: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = '''cpu''' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE : Any = self.get_dummy_components() SCREAMING_SNAKE_CASE : int = StableDiffusionInstructPixaPixPipeline(**A_ ) SCREAMING_SNAKE_CASE : Optional[int] = sd_pipe.to(A_ ) sd_pipe.set_progress_bar_config(disable=A_ ) SCREAMING_SNAKE_CASE : List[Any] = self.get_dummy_inputs(A_ ) SCREAMING_SNAKE_CASE : Tuple = [inputs['''prompt''']] * 2 SCREAMING_SNAKE_CASE : List[Any] = np.array(inputs["""image"""] ).astype(np.floataa ) / 2_55.0 SCREAMING_SNAKE_CASE : Tuple = torch.from_numpy(A_ ).unsqueeze(0 ).to(A_ ) SCREAMING_SNAKE_CASE : int = image / 2 + 0.5 SCREAMING_SNAKE_CASE : int = image.permute(0 , 3 , 1 , 2 ) SCREAMING_SNAKE_CASE : Optional[int] = image.repeat(2 , 1 , 1 , 1 ) SCREAMING_SNAKE_CASE : int = sd_pipe(**A_ ).images SCREAMING_SNAKE_CASE : List[Any] = image[-1, -3:, -3:, -1] assert image.shape == (2, 3_2, 3_2, 3) SCREAMING_SNAKE_CASE : Any = np.array([0.58_12, 0.57_48, 0.52_22, 0.59_08, 0.56_95, 0.71_74, 0.68_04, 0.55_23, 0.55_79] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def _lowercase ( self : int ) ->List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = '''cpu''' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE : List[Any] = self.get_dummy_components() SCREAMING_SNAKE_CASE : Any = EulerAncestralDiscreteScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule="""scaled_linear""" ) SCREAMING_SNAKE_CASE : int = StableDiffusionInstructPixaPixPipeline(**A_ ) SCREAMING_SNAKE_CASE : Dict = sd_pipe.to(A_ ) sd_pipe.set_progress_bar_config(disable=A_ ) SCREAMING_SNAKE_CASE : Optional[int] = self.get_dummy_inputs(A_ ) SCREAMING_SNAKE_CASE : Optional[Any] = sd_pipe(**A_ ).images SCREAMING_SNAKE_CASE : Optional[Any] = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE : List[str] = [round(A_ , 4 ) for x in image_slice.flatten().tolist()] print(""",""".join([str(A_ ) for x in slice] ) ) assert image.shape == (1, 3_2, 3_2, 3) SCREAMING_SNAKE_CASE : List[str] = np.array([0.74_17, 0.38_42, 0.47_32, 0.57_76, 0.58_91, 0.51_39, 0.40_52, 0.56_73, 0.49_86] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def _lowercase ( self : Optional[Any] ) ->str: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) def _lowercase ( self : List[str] ) ->Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = self.get_dummy_components() SCREAMING_SNAKE_CASE : Any = StableDiffusionInstructPixaPixPipeline(**A_ ) SCREAMING_SNAKE_CASE : Dict = VaeImageProcessor(do_resize=A_ , do_normalize=A_ ) SCREAMING_SNAKE_CASE : List[str] = pipe.to(A_ ) pipe.set_progress_bar_config(disable=A_ ) SCREAMING_SNAKE_CASE : List[str] = pipe(**self.get_dummy_inputs_by_type(A_ , input_image_type="""pt""" ) )[0] SCREAMING_SNAKE_CASE : Any = components['''vae'''] SCREAMING_SNAKE_CASE : Optional[Any] = self.get_dummy_inputs_by_type(A_ , input_image_type="""pt""" ) for image_param in self.image_latents_params: if image_param in inputs.keys(): SCREAMING_SNAKE_CASE : Any = vae.encode(inputs[image_param] ).latent_dist.mode() SCREAMING_SNAKE_CASE : Optional[int] = pipe(**A_ )[0] SCREAMING_SNAKE_CASE : Optional[Any] = np.abs(out - out_latents_inputs ).max() self.assertLess(A_ , 1e-4 , """passing latents as image input generate different result from passing image""" ) @slow @require_torch_gpu class a__ ( unittest.TestCase ): """simple docstring""" def _lowercase ( self : Tuple ) ->Dict: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _lowercase ( self : str , UpperCAmelCase__ : Union[str, Any]=0 ) ->List[str]: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = torch.manual_seed(A_ ) SCREAMING_SNAKE_CASE : Optional[int] = load_image( """https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_pix2pix/example.jpg""" ) SCREAMING_SNAKE_CASE : Optional[int] = { '''prompt''': '''turn him into a cyborg''', '''image''': image, '''generator''': generator, '''num_inference_steps''': 3, '''guidance_scale''': 7.5, '''image_guidance_scale''': 1.0, '''output_type''': '''numpy''', } return inputs def _lowercase ( self : Dict ) ->List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : str = StableDiffusionInstructPixaPixPipeline.from_pretrained( """timbrooks/instruct-pix2pix""" , safety_checker=A_ ) pipe.to(A_ ) pipe.set_progress_bar_config(disable=A_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE : int = self.get_inputs() SCREAMING_SNAKE_CASE : Union[str, Any] = pipe(**A_ ).images SCREAMING_SNAKE_CASE : str = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_1_2, 5_1_2, 3) SCREAMING_SNAKE_CASE : Optional[Any] = np.array([0.59_02, 0.60_15, 0.60_27, 0.59_83, 0.60_92, 0.60_61, 0.57_65, 0.57_85, 0.55_55] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def _lowercase ( self : int ) ->List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : str = StableDiffusionInstructPixaPixPipeline.from_pretrained( """timbrooks/instruct-pix2pix""" , safety_checker=A_ ) SCREAMING_SNAKE_CASE : Tuple = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.to(A_ ) pipe.set_progress_bar_config(disable=A_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE : Optional[Any] = self.get_inputs() SCREAMING_SNAKE_CASE : Dict = pipe(**A_ ).images SCREAMING_SNAKE_CASE : Tuple = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_1_2, 5_1_2, 3) SCREAMING_SNAKE_CASE : Optional[Any] = np.array([0.65_78, 0.68_17, 0.69_72, 0.67_61, 0.68_56, 0.69_16, 0.64_28, 0.65_16, 0.63_01] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def _lowercase ( self : Tuple ) ->Dict: """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = StableDiffusionInstructPixaPixPipeline.from_pretrained( """timbrooks/instruct-pix2pix""" , safety_checker=A_ ) SCREAMING_SNAKE_CASE : List[Any] = DDIMScheduler.from_config(pipe.scheduler.config ) pipe.to(A_ ) pipe.set_progress_bar_config(disable=A_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE : Optional[Any] = self.get_inputs() SCREAMING_SNAKE_CASE : Union[str, Any] = pipe(**A_ ).images SCREAMING_SNAKE_CASE : Union[str, Any] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_1_2, 5_1_2, 3) SCREAMING_SNAKE_CASE : Optional[Any] = np.array([0.38_28, 0.38_34, 0.38_18, 0.37_92, 0.38_65, 0.37_52, 0.37_92, 0.38_47, 0.37_53] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def _lowercase ( self : int ) ->Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = 0 def callback_fn(UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : Union[str, Any] ) -> None: SCREAMING_SNAKE_CASE : Union[str, Any] = True nonlocal number_of_steps number_of_steps += 1 if step == 1: SCREAMING_SNAKE_CASE : Any = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 6_4, 6_4) SCREAMING_SNAKE_CASE : List[str] = latents[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE : Any = np.array([-0.24_63, -0.46_44, -0.97_56, 1.51_76, 1.44_14, 0.78_66, 0.98_97, 0.85_21, 0.79_83] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 elif step == 2: SCREAMING_SNAKE_CASE : int = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 6_4, 6_4) SCREAMING_SNAKE_CASE : List[str] = latents[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE : Any = np.array([-0.26_44, -0.46_26, -0.96_53, 1.51_76, 1.45_51, 0.76_86, 0.98_05, 0.84_52, 0.81_15] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 SCREAMING_SNAKE_CASE : List[str] = False SCREAMING_SNAKE_CASE : Union[str, Any] = StableDiffusionInstructPixaPixPipeline.from_pretrained( """timbrooks/instruct-pix2pix""" , safety_checker=A_ , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE : List[Any] = pipe.to(A_ ) pipe.set_progress_bar_config(disable=A_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE : Optional[int] = self.get_inputs() pipe(**A_ , callback=A_ , callback_steps=1 ) assert callback_fn.has_been_called assert number_of_steps == 3 def _lowercase ( self : List[str] ) ->List[str]: """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() SCREAMING_SNAKE_CASE : Dict = StableDiffusionInstructPixaPixPipeline.from_pretrained( """timbrooks/instruct-pix2pix""" , safety_checker=A_ , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE : str = pipe.to(A_ ) pipe.set_progress_bar_config(disable=A_ ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_inputs() SCREAMING_SNAKE_CASE : int = pipe(**A_ ) SCREAMING_SNAKE_CASE : Dict = torch.cuda.max_memory_allocated() # make sure that less than 2.2 GB is allocated assert mem_bytes < 2.2 * 1_0**9 def _lowercase ( self : Optional[int] ) ->Any: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = self.get_inputs() # resize to resolution that is divisible by 8 but not 16 or 32 SCREAMING_SNAKE_CASE : List[str] = inputs['''image'''].resize((5_0_4, 5_0_4) ) SCREAMING_SNAKE_CASE : Tuple = '''timbrooks/instruct-pix2pix''' SCREAMING_SNAKE_CASE : List[str] = StableDiffusionInstructPixaPixPipeline.from_pretrained( A_ , safety_checker=A_ , ) pipe.to(A_ ) pipe.set_progress_bar_config(disable=A_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE : List[Any] = pipe(**A_ ) SCREAMING_SNAKE_CASE : Optional[int] = output.images[0] SCREAMING_SNAKE_CASE : Any = image[2_5_5:2_5_8, 3_8_3:3_8_6, -1] assert image.shape == (5_0_4, 5_0_4, 3) SCREAMING_SNAKE_CASE : int = np.array([0.27_26, 0.25_29, 0.26_64, 0.26_55, 0.26_41, 0.26_42, 0.25_91, 0.26_49, 0.25_90] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-3
245
import itertools import random import unittest import numpy as np from transformers import WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, WavaVecaConfig, WavaVecaFeatureExtractor from transformers.testing_utils import require_torch, slow from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin _UpperCamelCase = random.Random() def _lowercase ( lowercase__ , lowercase__=1.0 , lowercase__=None , lowercase__=None ): if rng is None: __lowerCAmelCase : Optional[Any] = global_rng __lowerCAmelCase : Tuple = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class __lowercase (unittest.TestCase ): def __init__( self , A_ , A_=7 , A_=400 , A_=2000 , A_=1 , A_=0.0 , A_=1_6000 , A_=True , A_=True , ) ->List[Any]: '''simple docstring''' __lowerCAmelCase : List[Any] = parent __lowerCAmelCase : Optional[int] = batch_size __lowerCAmelCase : Any = min_seq_length __lowerCAmelCase : Tuple = max_seq_length __lowerCAmelCase : Tuple = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) __lowerCAmelCase : Dict = feature_size __lowerCAmelCase : Optional[int] = padding_value __lowerCAmelCase : Tuple = sampling_rate __lowerCAmelCase : Union[str, Any] = return_attention_mask __lowerCAmelCase : Dict = do_normalize def UpperCamelCase__ ( self ) ->Optional[Any]: '''simple docstring''' return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def UpperCamelCase__ ( self , A_=False , A_=False ) ->Union[str, Any]: '''simple docstring''' def _flatten(A_ ): return list(itertools.chain(*A_ ) ) if equal_length: __lowerCAmelCase : Dict = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size __lowerCAmelCase : Tuple = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: __lowerCAmelCase : Tuple = [np.asarray(A_ ) for x in speech_inputs] return speech_inputs class __lowercase (_UpperCAmelCase , unittest.TestCase ): _UpperCamelCase = WavaVecaFeatureExtractor def UpperCamelCase__ ( self ) ->Dict: '''simple docstring''' __lowerCAmelCase : List[Any] = WavaVecaFeatureExtractionTester(self ) def UpperCamelCase__ ( self , A_ ) ->Optional[Any]: '''simple docstring''' self.assertTrue(np.all(np.mean(A_ , axis=0 ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(A_ , axis=0 ) - 1 ) < 1e-3 ) ) def UpperCamelCase__ ( self ) ->Tuple: '''simple docstring''' __lowerCAmelCase : List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 __lowerCAmelCase : Optional[Any] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] __lowerCAmelCase : Any = [np.asarray(A_ ) for speech_input in speech_inputs] # Test not batched input __lowerCAmelCase : Optional[Any] = feat_extract(speech_inputs[0] , return_tensors='''np''' ).input_values __lowerCAmelCase : Dict = feat_extract(np_speech_inputs[0] , return_tensors='''np''' ).input_values self.assertTrue(np.allclose(A_ , A_ , atol=1e-3 ) ) # Test batched __lowerCAmelCase : Dict = feat_extract(A_ , return_tensors='''np''' ).input_values __lowerCAmelCase : Dict = feat_extract(A_ , return_tensors='''np''' ).input_values for enc_seq_a, enc_seq_a in zip(A_ , A_ ): self.assertTrue(np.allclose(A_ , A_ , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. __lowerCAmelCase : int = [floats_list((1, x) )[0] for x in (800, 800, 800)] __lowerCAmelCase : List[Any] = np.asarray(A_ ) __lowerCAmelCase : Any = feat_extract(A_ , return_tensors='''np''' ).input_values __lowerCAmelCase : Union[str, Any] = feat_extract(A_ , return_tensors='''np''' ).input_values for enc_seq_a, enc_seq_a in zip(A_ , A_ ): self.assertTrue(np.allclose(A_ , A_ , atol=1e-3 ) ) def UpperCamelCase__ ( self ) ->Union[str, Any]: '''simple docstring''' __lowerCAmelCase : Optional[int] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __lowerCAmelCase : str = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] __lowerCAmelCase : str = ['''longest''', '''max_length''', '''do_not_pad'''] __lowerCAmelCase : str = [None, 1600, None] for max_length, padding in zip(A_ , A_ ): __lowerCAmelCase : Optional[int] = feat_extract(A_ , padding=A_ , max_length=A_ , return_tensors='''np''' ) __lowerCAmelCase : Optional[Any] = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800] ) self.assertTrue(input_values[0][800:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[1][:1000] ) self.assertTrue(input_values[0][1000:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[2][:1200] ) def UpperCamelCase__ ( self ) ->Dict: '''simple docstring''' __lowerCAmelCase : List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __lowerCAmelCase : Optional[int] = range(800 , 1400 , 200 ) __lowerCAmelCase : Union[str, Any] = [floats_list((1, x) )[0] for x in lengths] __lowerCAmelCase : int = ['''longest''', '''max_length''', '''do_not_pad'''] __lowerCAmelCase : List[str] = [None, 1600, None] for max_length, padding in zip(A_ , A_ ): __lowerCAmelCase : Union[str, Any] = feat_extract(A_ , max_length=A_ , padding=A_ ) __lowerCAmelCase : Union[str, Any] = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800] ) self._check_zero_mean_unit_variance(input_values[1][:1000] ) self._check_zero_mean_unit_variance(input_values[2][:1200] ) def UpperCamelCase__ ( self ) ->Tuple: '''simple docstring''' __lowerCAmelCase : Dict = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __lowerCAmelCase : Optional[Any] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] __lowerCAmelCase : List[str] = feat_extract( A_ , truncation=A_ , max_length=1000 , padding='''max_length''' , return_tensors='''np''' ) __lowerCAmelCase : int = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1] ) self._check_zero_mean_unit_variance(input_values[2] ) def UpperCamelCase__ ( self ) ->List[str]: '''simple docstring''' __lowerCAmelCase : Dict = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __lowerCAmelCase : int = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] __lowerCAmelCase : int = feat_extract( A_ , truncation=A_ , max_length=1000 , padding='''longest''' , return_tensors='''np''' ) __lowerCAmelCase : Optional[Any] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1, :1000] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertTrue(input_values.shape == (3, 1000) ) __lowerCAmelCase : Any = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] __lowerCAmelCase : Optional[int] = feat_extract( A_ , truncation=A_ , max_length=2000 , padding='''longest''' , return_tensors='''np''' ) __lowerCAmelCase : List[str] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1, :1000] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length > longest -> then pad to longest self.assertTrue(input_values.shape == (3, 1200) ) @require_torch def UpperCamelCase__ ( self ) ->Any: '''simple docstring''' import torch __lowerCAmelCase : Union[str, Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __lowerCAmelCase : Any = np.random.rand(100 ).astype(np.floataa ) __lowerCAmelCase : List[Any] = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: __lowerCAmelCase : Any = feature_extractor.pad([{'''input_values''': inputs}] , return_tensors='''np''' ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) __lowerCAmelCase : List[str] = feature_extractor.pad([{'''input_values''': inputs}] , return_tensors='''pt''' ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) @slow @require_torch def UpperCamelCase__ ( self ) ->int: '''simple docstring''' for model_id in WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST: __lowerCAmelCase : Any = WavaVecaConfig.from_pretrained(A_ ) __lowerCAmelCase : Tuple = WavaVecaFeatureExtractor.from_pretrained(A_ ) # only "layer" feature extraction norm should make use of # attention_mask self.assertEqual(feat_extract.return_attention_mask , config.feat_extract_norm == '''layer''' )
275
0
from __future__ import annotations from cmath import sqrt def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): if a == 0: raise ValueError("Coefficient \'a\' must not be zero." ) __snake_case : Optional[Any] = b * b - 4 * a * c __snake_case : List[str] = (-b + sqrt(lowercase__ )) / (2 * a) __snake_case : List[str] = (-b - sqrt(lowercase__ )) / (2 * a) return ( root_a.real if not root_a.imag else root_a, root_a.real if not root_a.imag else root_a, ) def lowerCAmelCase_ ( ): __snake_case : int = quadratic_roots(a=5 , b=6 , c=1 ) print(F'The solutions are: {solutiona} and {solutiona}' ) if __name__ == "__main__": main()
123
import unittest from transformers import DebertaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DebertaForMaskedLM, DebertaForQuestionAnswering, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaModel, ) from transformers.models.deberta.modeling_deberta import DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST class __lowercase (_UpperCAmelCase ): def __init__( self , A_ , A_=13 , A_=7 , A_=True , A_=True , A_=True , A_=True , A_=99 , A_=32 , A_=5 , A_=4 , A_=37 , A_="gelu" , A_=0.1 , A_=0.1 , A_=512 , A_=16 , A_=2 , A_=0.02 , A_=False , A_=True , A_="None" , A_=3 , A_=4 , A_=None , ) ->List[Any]: '''simple docstring''' __lowerCAmelCase : Union[str, Any] = parent __lowerCAmelCase : List[str] = batch_size __lowerCAmelCase : Dict = seq_length __lowerCAmelCase : List[Any] = is_training __lowerCAmelCase : List[Any] = use_input_mask __lowerCAmelCase : Optional[int] = use_token_type_ids __lowerCAmelCase : Tuple = use_labels __lowerCAmelCase : str = vocab_size __lowerCAmelCase : int = hidden_size __lowerCAmelCase : Any = num_hidden_layers __lowerCAmelCase : Any = num_attention_heads __lowerCAmelCase : Dict = intermediate_size __lowerCAmelCase : int = hidden_act __lowerCAmelCase : int = hidden_dropout_prob __lowerCAmelCase : Any = attention_probs_dropout_prob __lowerCAmelCase : List[str] = max_position_embeddings __lowerCAmelCase : Union[str, Any] = type_vocab_size __lowerCAmelCase : Union[str, Any] = type_sequence_label_size __lowerCAmelCase : Optional[int] = initializer_range __lowerCAmelCase : int = num_labels __lowerCAmelCase : int = num_choices __lowerCAmelCase : List[str] = relative_attention __lowerCAmelCase : Union[str, Any] = position_biased_input __lowerCAmelCase : int = pos_att_type __lowerCAmelCase : List[Any] = scope def UpperCamelCase__ ( self ) ->Dict: '''simple docstring''' __lowerCAmelCase : Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __lowerCAmelCase : int = None if self.use_input_mask: __lowerCAmelCase : List[Any] = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) __lowerCAmelCase : List[str] = None if self.use_token_type_ids: __lowerCAmelCase : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __lowerCAmelCase : Union[str, Any] = None __lowerCAmelCase : int = None __lowerCAmelCase : List[str] = None if self.use_labels: __lowerCAmelCase : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCAmelCase : Dict = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __lowerCAmelCase : Union[str, Any] = ids_tensor([self.batch_size] , self.num_choices ) __lowerCAmelCase : Tuple = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCamelCase__ ( self ) ->List[Any]: '''simple docstring''' return DebertaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , pos_att_type=self.pos_att_type , ) def UpperCamelCase__ ( self ) ->str: '''simple docstring''' __lowerCAmelCase : str = self.get_config() __lowerCAmelCase : Dict = 300 return config def UpperCamelCase__ ( self , A_ ) ->Union[str, Any]: '''simple docstring''' self.parent.assertListEqual(list(result.loss.size() ) , [] ) def UpperCamelCase__ ( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ) ->Any: '''simple docstring''' __lowerCAmelCase : Optional[Any] = DebertaModel(config=A_ ) model.to(A_ ) model.eval() __lowerCAmelCase : str = model(A_ , attention_mask=A_ , token_type_ids=A_ )[0] __lowerCAmelCase : Any = model(A_ , token_type_ids=A_ )[0] __lowerCAmelCase : List[str] = model(A_ )[0] self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] ) def UpperCamelCase__ ( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ) ->int: '''simple docstring''' __lowerCAmelCase : Tuple = DebertaForMaskedLM(config=A_ ) model.to(A_ ) model.eval() __lowerCAmelCase : Union[str, Any] = model(A_ , attention_mask=A_ , token_type_ids=A_ , labels=A_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCamelCase__ ( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ) ->Any: '''simple docstring''' __lowerCAmelCase : Any = self.num_labels __lowerCAmelCase : Tuple = DebertaForSequenceClassification(A_ ) model.to(A_ ) model.eval() __lowerCAmelCase : Union[str, Any] = model(A_ , attention_mask=A_ , token_type_ids=A_ , labels=A_ ) self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] ) self.check_loss_output(A_ ) def UpperCamelCase__ ( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ) ->Dict: '''simple docstring''' __lowerCAmelCase : List[Any] = self.num_labels __lowerCAmelCase : Optional[int] = DebertaForTokenClassification(config=A_ ) model.to(A_ ) model.eval() __lowerCAmelCase : Tuple = model(A_ , attention_mask=A_ , token_type_ids=A_ , labels=A_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCamelCase__ ( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ) ->str: '''simple docstring''' __lowerCAmelCase : List[str] = DebertaForQuestionAnswering(config=A_ ) model.to(A_ ) model.eval() __lowerCAmelCase : int = model( A_ , attention_mask=A_ , token_type_ids=A_ , start_positions=A_ , end_positions=A_ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def UpperCamelCase__ ( self ) ->List[str]: '''simple docstring''' __lowerCAmelCase : Any = self.prepare_config_and_inputs() ( ( __lowerCAmelCase ), ( __lowerCAmelCase ), ( __lowerCAmelCase ), ( __lowerCAmelCase ), ( __lowerCAmelCase ), ( __lowerCAmelCase ), ( __lowerCAmelCase ), ) : Tuple = config_and_inputs __lowerCAmelCase : Tuple = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class __lowercase (_UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): _UpperCamelCase = ( ( DebertaModel, DebertaForMaskedLM, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaForQuestionAnswering, ) if is_torch_available() else () ) _UpperCamelCase = ( { """feature-extraction""": DebertaModel, """fill-mask""": DebertaForMaskedLM, """question-answering""": DebertaForQuestionAnswering, """text-classification""": DebertaForSequenceClassification, """token-classification""": DebertaForTokenClassification, """zero-shot""": DebertaForSequenceClassification, } if is_torch_available() else {} ) _UpperCamelCase = True _UpperCamelCase = False _UpperCamelCase = False _UpperCamelCase = False _UpperCamelCase = False def UpperCamelCase__ ( self ) ->int: '''simple docstring''' __lowerCAmelCase : int = DebertaModelTester(self ) __lowerCAmelCase : List[Any] = ConfigTester(self , config_class=A_ , hidden_size=37 ) def UpperCamelCase__ ( self ) ->Optional[Any]: '''simple docstring''' self.config_tester.run_common_tests() def UpperCamelCase__ ( self ) ->List[Any]: '''simple docstring''' __lowerCAmelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*A_ ) def UpperCamelCase__ ( self ) ->int: '''simple docstring''' __lowerCAmelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*A_ ) def UpperCamelCase__ ( self ) ->int: '''simple docstring''' __lowerCAmelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*A_ ) def UpperCamelCase__ ( self ) ->Optional[int]: '''simple docstring''' __lowerCAmelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*A_ ) def UpperCamelCase__ ( self ) ->List[Any]: '''simple docstring''' __lowerCAmelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*A_ ) @slow def UpperCamelCase__ ( self ) ->Tuple: '''simple docstring''' for model_name in DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCAmelCase : Optional[int] = DebertaModel.from_pretrained(A_ ) self.assertIsNotNone(A_ ) @require_torch @require_sentencepiece @require_tokenizers class __lowercase (unittest.TestCase ): @unittest.skip(reason='''Model not available yet''' ) def UpperCamelCase__ ( self ) ->Dict: '''simple docstring''' pass @slow def UpperCamelCase__ ( self ) ->Tuple: '''simple docstring''' __lowerCAmelCase : str = DebertaModel.from_pretrained('''microsoft/deberta-base''' ) __lowerCAmelCase : Tuple = torch.tensor([[0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2]] ) __lowerCAmelCase : Union[str, Any] = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __lowerCAmelCase : Optional[int] = model(A_ , attention_mask=A_ )[0] # compare the actual values for a slice. __lowerCAmelCase : Optional[Any] = torch.tensor( [[[-0.5_986, -0.8_055, -0.8_462], [1.4_484, -0.9_348, -0.8_059], [0.3_123, 0.0_032, -1.4_131]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , A_ , atol=1e-4 ) , f"""{output[:, 1:4, 1:4]}""" )
275
0
"""simple docstring""" import sacrebleu as scb from packaging import version from sacrebleu import TER import datasets UpperCAmelCase = """\\n@inproceedings{snover-etal-2006-study,\n title = \"A Study of Translation Edit Rate with Targeted Human Annotation\",\n author = \"Snover, Matthew and\n Dorr, Bonnie and\n Schwartz, Rich and\n Micciulla, Linnea and\n Makhoul, John\",\n booktitle = \"Proceedings of the 7th Conference of the Association for Machine Translation in the Americas: Technical Papers\",\n month = aug # \" 8-12\",\n year = \"2006\",\n address = \"Cambridge, Massachusetts, USA\",\n publisher = \"Association for Machine Translation in the Americas\",\n url = \"https://aclanthology.org/2006.amta-papers.25\",\n pages = \"223--231\",\n}\n@inproceedings{post-2018-call,\n title = \"A Call for Clarity in Reporting {BLEU} Scores\",\n author = \"Post, Matt\",\n booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\",\n month = oct,\n year = \"2018\",\n address = \"Belgium, Brussels\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://www.aclweb.org/anthology/W18-6319\",\n pages = \"186--191\",\n}\n""" UpperCAmelCase = """\\nTER (Translation Edit Rate, also called Translation Error Rate) is a metric to quantify the edit operations that a\nhypothesis requires to match a reference translation. We use the implementation that is already present in sacrebleu\n(https://github.com/mjpost/sacreBLEU#ter), which in turn is inspired by the TERCOM implementation, which can be found\nhere: https://github.com/jhclark/tercom.\n\nThe implementation here is slightly different from sacrebleu in terms of the required input format. The length of\nthe references and hypotheses lists need to be the same, so you may need to transpose your references compared to\nsacrebleu's required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534\n\nSee the README.md file at https://github.com/mjpost/sacreBLEU#ter for more information.\n""" UpperCAmelCase = """\nProduces TER scores alongside the number of edits and reference length.\n\nArgs:\n predictions (list of str): The system stream (a sequence of segments).\n references (list of list of str): A list of one or more reference streams (each a sequence of segments).\n normalized (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.\n ignore_punct (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.\n support_zh_ja_chars (boolean): If `True`, tokenization/normalization supports processing of Chinese characters,\n as well as Japanese Kanji, Hiragana, Katakana, and Phonetic Extensions of Katakana.\n Only applies if `normalized = True`. Defaults to `False`.\n case_sensitive (boolean): If `False`, makes all predictions and references lowercase to ignore differences in case. Defaults to `False`.\n\nReturns:\n 'score' (float): TER score (num_edits / sum_ref_lengths * 100)\n 'num_edits' (int): The cumulative number of edits\n 'ref_length' (float): The cumulative average reference length\n\nExamples:\n Example 1:\n >>> predictions = [\"does this sentence match??\",\n ... \"what about this sentence?\",\n ... \"What did the TER metric user say to the developer?\"]\n >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],\n ... [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"],\n ... [\"Your jokes are...\", \"...TERrible\"]]\n >>> ter = datasets.load_metric(\"ter\")\n >>> results = ter.compute(predictions=predictions,\n ... references=references,\n ... case_sensitive=True)\n >>> print(results)\n {'score': 150.0, 'num_edits': 15, 'ref_length': 10.0}\n\n Example 2:\n >>> predictions = [\"does this sentence match??\",\n ... \"what about this sentence?\"]\n >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],\n ... [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]]\n >>> ter = datasets.load_metric(\"ter\")\n >>> results = ter.compute(predictions=predictions,\n ... references=references,\n ... case_sensitive=True)\n >>> print(results)\n {'score': 62.5, 'num_edits': 5, 'ref_length': 8.0}\n\n Example 3:\n >>> predictions = [\"does this sentence match??\",\n ... \"what about this sentence?\"]\n >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],\n ... [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]]\n >>> ter = datasets.load_metric(\"ter\")\n >>> results = ter.compute(predictions=predictions,\n ... references=references,\n ... normalized=True,\n ... case_sensitive=True)\n >>> print(results)\n {'score': 57.14285714285714, 'num_edits': 6, 'ref_length': 10.5}\n\n Example 4:\n >>> predictions = [\"does this sentence match??\",\n ... \"what about this sentence?\"]\n >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],\n ... [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]]\n >>> ter = datasets.load_metric(\"ter\")\n >>> results = ter.compute(predictions=predictions,\n ... references=references,\n ... ignore_punct=True,\n ... case_sensitive=False)\n >>> print(results)\n {'score': 0.0, 'num_edits': 0, 'ref_length': 8.0}\n\n Example 5:\n >>> predictions = [\"does this sentence match??\",\n ... \"what about this sentence?\",\n ... \"What did the TER metric user say to the developer?\"]\n >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],\n ... [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"],\n ... [\"Your jokes are...\", \"...TERrible\"]]\n >>> ter = datasets.load_metric(\"ter\")\n >>> results = ter.compute(predictions=predictions,\n ... references=references,\n ... ignore_punct=True,\n ... case_sensitive=False)\n >>> print(results)\n {'score': 100.0, 'num_edits': 10, 'ref_length': 10.0}\n""" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class UpperCAmelCase_ ( datasets.Metric): def _UpperCamelCase ( self : Tuple ) -> str: if version.parse(scb.__version__ ) < version.parse('''1.4.12''' ): raise ImportWarning( '''To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn\'t match this condition.\n''' '''You can install it with `pip install "sacrebleu>=1.4.12"`.''' ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage='''http://www.cs.umd.edu/~snover/tercom/''' , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''string''' , id='''sequence''' ), '''references''': datasets.Sequence(datasets.Value('''string''' , id='''sequence''' ) , id='''references''' ), } ) , codebase_urls=['''https://github.com/mjpost/sacreBLEU#ter'''] , reference_urls=[ '''https://github.com/jhclark/tercom''', ] , ) def _UpperCamelCase ( self : Any , __UpperCamelCase : List[Any] , __UpperCamelCase : str , __UpperCamelCase : Tuple = False , __UpperCamelCase : Optional[int] = False , __UpperCamelCase : List[Any] = False , __UpperCamelCase : int = False , ) -> Optional[Any]: _UpperCamelCase = len(references[0] ) if any(len(A_ ) != references_per_prediction for refs in references ): raise ValueError('''Sacrebleu requires the same number of references for each prediction''' ) _UpperCamelCase = [[refs[i] for refs in references] for i in range(A_ )] _UpperCamelCase = TER( normalized=A_ , no_punct=A_ , asian_support=A_ , case_sensitive=A_ , ) _UpperCamelCase = sb_ter.corpus_score(A_ , A_ ) return {"score": output.score, "num_edits": output.num_edits, "ref_length": output.ref_length}
256
from typing import Dict import numpy as np import torch from . import residue_constants as rc from .tensor_utils import tensor_tree_map, tree_map def _lowercase ( lowercase__ ): __lowerCAmelCase : str = [] __lowerCAmelCase : List[Any] = [] __lowerCAmelCase : str = [] for rt in rc.restypes: __lowerCAmelCase : List[Any] = rc.restype_name_to_atomaa_names[rc.restype_atoa[rt]] restype_atomaa_to_atomaa_list.append([(rc.atom_order[name] if name else 0) for name in atom_names] ) __lowerCAmelCase : List[str] = {name: i for i, name in enumerate(lowercase__ )} restype_atomaa_to_atomaa_list.append( [(atom_name_to_idxaa[name] if name in atom_name_to_idxaa else 0) for name in rc.atom_types] ) restype_atomaa_mask_list.append([(1.0 if name else 0.0) for name in atom_names] ) # Add dummy mapping for restype 'UNK' restype_atomaa_to_atomaa_list.append([0] * 1_4 ) restype_atomaa_to_atomaa_list.append([0] * 3_7 ) restype_atomaa_mask_list.append([0.0] * 1_4 ) __lowerCAmelCase : List[Any] = torch.tensor( lowercase__ , dtype=torch.intaa , device=protein['''aatype'''].device , ) __lowerCAmelCase : Optional[Any] = torch.tensor( lowercase__ , dtype=torch.intaa , device=protein['''aatype'''].device , ) __lowerCAmelCase : Tuple = torch.tensor( lowercase__ , dtype=torch.floataa , device=protein['''aatype'''].device , ) __lowerCAmelCase : List[Any] = protein['''aatype'''].to(torch.long ) # create the mapping for (residx, atom14) --> atom37, i.e. an array # with shape (num_res, 14) containing the atom37 indices for this protein __lowerCAmelCase : Any = restype_atomaa_to_atomaa[protein_aatype] __lowerCAmelCase : Union[str, Any] = restype_atomaa_mask[protein_aatype] __lowerCAmelCase : int = residx_atomaa_mask __lowerCAmelCase : List[str] = residx_atomaa_to_atomaa.long() # create the gather indices for mapping back __lowerCAmelCase : int = restype_atomaa_to_atomaa[protein_aatype] __lowerCAmelCase : Union[str, Any] = residx_atomaa_to_atomaa.long() # create the corresponding mask __lowerCAmelCase : str = torch.zeros([2_1, 3_7] , dtype=torch.floataa , device=protein['''aatype'''].device ) for restype, restype_letter in enumerate(rc.restypes ): __lowerCAmelCase : Optional[int] = rc.restype_atoa[restype_letter] __lowerCAmelCase : Optional[Any] = rc.residue_atoms[restype_name] for atom_name in atom_names: __lowerCAmelCase : str = rc.atom_order[atom_name] __lowerCAmelCase : List[Any] = 1 __lowerCAmelCase : Union[str, Any] = restype_atomaa_mask[protein_aatype] __lowerCAmelCase : Any = residx_atomaa_mask return protein def _lowercase ( lowercase__ ): __lowerCAmelCase : Dict = tree_map(lambda lowercase__ : torch.tensor(lowercase__ , device=batch['''aatype'''].device ) , lowercase__ , np.ndarray ) __lowerCAmelCase : Tuple = tensor_tree_map(lambda lowercase__ : np.array(lowercase__ ) , make_atomaa_masks(lowercase__ ) ) return out
275
0
'''simple docstring''' import argparse import re from pathlib import Path import requests import torch from PIL import Image from torchvision.transforms import CenterCrop, Compose, Normalize, Resize, ToTensor from transformers import ( EfficientFormerConfig, EfficientFormerForImageClassificationWithTeacher, EfficientFormerImageProcessor, ) from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, PILImageResampling def _lowerCamelCase ( lowercase : Optional[Any] , lowercase : Dict ) -> List[Any]: _a = old_name if "patch_embed" in old_name: _a = old_name.split("." ) if layer == "0": _a = old_name.replace("0" , "convolution1" ) elif layer == "1": _a = old_name.replace("1" , "batchnorm_before" ) elif layer == "3": _a = old_name.replace("3" , "convolution2" ) else: _a = old_name.replace("4" , "batchnorm_after" ) if "network" in old_name and re.search(r"\d\.\d" , lowercase__ ): _a = r'''\b\d{2}\b''' if bool(re.search(lowercase__ , lowercase__ ) ): _a = re.search(r"\d\.\d\d." , lowercase__ ).group() else: _a = re.search(r"\d\.\d." , lowercase__ ).group() if int(match[0] ) < 6: _a = old_name.replace(lowercase__ , "" ) _a = trimmed_name.replace("network" , match[0] + ".meta4D_layers.blocks." + match[2:-1] ) _a = '''intermediate_stages.''' + trimmed_name else: _a = old_name.replace(lowercase__ , "" ) if int(match[2] ) < num_meta4D_last_stage: _a = trimmed_name.replace("network" , "meta4D_layers.blocks." + match[2] ) else: _a = str(int(match[2] ) - num_meta4D_last_stage ) _a = trimmed_name.replace("network" , "meta3D_layers.blocks." + layer_index ) if "norm1" in old_name: _a = trimmed_name.replace("norm1" , "layernorm1" ) elif "norm2" in old_name: _a = trimmed_name.replace("norm2" , "layernorm2" ) elif "fc1" in old_name: _a = trimmed_name.replace("fc1" , "linear_in" ) elif "fc2" in old_name: _a = trimmed_name.replace("fc2" , "linear_out" ) _a = '''last_stage.''' + trimmed_name elif "network" in old_name and re.search(r".\d." , lowercase__ ): _a = old_name.replace("network" , "intermediate_stages" ) if "fc" in new_name: _a = new_name.replace("fc" , "convolution" ) elif ("norm1" in new_name) and ("layernorm1" not in new_name): _a = new_name.replace("norm1" , "batchnorm_before" ) elif ("norm2" in new_name) and ("layernorm2" not in new_name): _a = new_name.replace("norm2" , "batchnorm_after" ) if "proj" in new_name: _a = new_name.replace("proj" , "projection" ) if "dist_head" in new_name: _a = new_name.replace("dist_head" , "distillation_classifier" ) elif "head" in new_name: _a = new_name.replace("head" , "classifier" ) elif "patch_embed" in new_name: _a = '''efficientformer.''' + new_name elif new_name == "norm.weight" or new_name == "norm.bias": _a = new_name.replace("norm" , "layernorm" ) _a = '''efficientformer.''' + new_name else: _a = '''efficientformer.encoder.''' + new_name return new_name def _lowerCamelCase ( lowercase : List[str] , lowercase : Optional[int] ) -> int: for key in checkpoint.copy().keys(): _a = checkpoint.pop(lowercase__ ) _a = val return checkpoint def _lowerCamelCase ( ) -> List[Any]: _a = '''http://images.cocodataset.org/val2017/000000039769.jpg''' _a = Image.open(requests.get(lowercase__ , stream=lowercase__ ).raw ) return image def _lowerCamelCase ( lowercase : Optional[int] , lowercase : Dict , lowercase : List[Any] , lowercase : Dict ) -> str: _a = torch.load(lowercase__ , map_location="cpu" )['''model'''] _a = EfficientFormerConfig.from_json_file(lowercase__ ) _a = EfficientFormerForImageClassificationWithTeacher(lowercase__ ) _a = '''_'''.join(checkpoint_path.split("/" )[-1].split("." )[0].split("_" )[:-1] ) _a = config.depths[-1] - config.num_metaad_blocks + 1 _a = convert_torch_checkpoint(lowercase__ , lowercase__ ) model.load_state_dict(lowercase__ ) model.eval() _a = { '''bilinear''': PILImageResampling.BILINEAR, '''bicubic''': PILImageResampling.BICUBIC, '''nearest''': PILImageResampling.NEAREST, } # prepare image _a = prepare_img() _a = 256 _a = 224 _a = EfficientFormerImageProcessor( size={"shortest_edge": image_size} , crop_size={"height": crop_size, "width": crop_size} , resample=pillow_resamplings["bicubic"] , ) _a = processor(images=lowercase__ , return_tensors="pt" ).pixel_values # original processing pipeline _a = Compose( [ Resize(lowercase__ , interpolation=pillow_resamplings["bicubic"] ), CenterCrop(lowercase__ ), ToTensor(), Normalize(lowercase__ , lowercase__ ), ] ) _a = image_transforms(lowercase__ ).unsqueeze(0 ) assert torch.allclose(lowercase__ , lowercase__ ) _a = model(lowercase__ ) _a = outputs.logits _a = (1, 1000) if "l1" in model_name: _a = torch.Tensor( [-0.13_12, 0.43_53, -1.04_99, -0.51_24, 0.41_83, -0.67_93, -1.37_77, -0.08_93, -0.73_58, -2.43_28] ) assert torch.allclose(logits[0, :10] , lowercase__ , atol=1E-3 ) assert logits.shape == expected_shape elif "l3" in model_name: _a = torch.Tensor( [-1.31_50, -1.54_56, -1.25_56, -0.84_96, -0.71_27, -0.78_97, -0.97_28, -0.30_52, 0.37_51, -0.31_27] ) assert torch.allclose(logits[0, :10] , lowercase__ , atol=1E-3 ) assert logits.shape == expected_shape elif "l7" in model_name: _a = torch.Tensor( [-1.02_83, -1.41_31, -0.56_44, -1.31_15, -0.57_85, -1.20_49, -0.75_28, 0.19_92, -0.38_22, -0.08_78] ) assert logits.shape == expected_shape else: raise ValueError( F'Unknown model checkpoint: {checkpoint_path}. Supported version of efficientformer are l1, l3 and l7' ) # Save Checkpoints Path(lowercase__ ).mkdir(exist_ok=lowercase__ ) model.save_pretrained(lowercase__ ) print(F'Checkpoint successfuly converted. Model saved at {pytorch_dump_path}' ) processor.save_pretrained(lowercase__ ) print(F'Processor successfuly saved at {pytorch_dump_path}' ) if push_to_hub: print("Pushing model to the hub..." ) model.push_to_hub( repo_id=F'Bearnardd/{pytorch_dump_path}' , commit_message="Add model" , use_temp_dir=lowercase__ , ) processor.push_to_hub( repo_id=F'Bearnardd/{pytorch_dump_path}' , commit_message="Add image processor" , use_temp_dir=lowercase__ , ) if __name__ == "__main__": lowerCAmelCase_ : Dict = argparse.ArgumentParser() # Required parameters parser.add_argument( '--pytorch_model_path', default=None, type=str, required=True, help='Path to EfficientFormer pytorch checkpoint.', ) parser.add_argument( '--config_file', default=None, type=str, required=True, help='The json file for EfficientFormer model config.', ) parser.add_argument( '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) parser.add_argument('--push_to_hub', action='store_true', help='Push model and image processor to the hub') parser.add_argument( '--no-push_to_hub', dest='push_to_hub', action='store_false', help='Do not push model and image processor to the hub', ) parser.set_defaults(push_to_hub=True) lowerCAmelCase_ : Any = parser.parse_args() convert_efficientformer_checkpoint( checkpoint_path=args.pytorch_model_path, efficientformer_config_file=args.config_file, pytorch_dump_path=args.pytorch_dump_path, push_to_hub=args.push_to_hub, )
63
def _lowercase ( lowercase__ ): if not all(x.isalpha() for x in string ): raise ValueError('''String must only contain alphabetic characters.''' ) __lowerCAmelCase : int = sorted(string.lower() ) return len(lowercase__ ) == len(set(lowercase__ ) ) if __name__ == "__main__": _UpperCamelCase = input("Enter a string ").strip() _UpperCamelCase = is_isogram(input_str) print(F"{input_str} is {'an' if isogram else 'not an'} isogram.")
275
0
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING _SCREAMING_SNAKE_CASE = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE = { """microsoft/table-transformer-detection""": ( """https://huggingface.co/microsoft/table-transformer-detection/resolve/main/config.json""" ), } class SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase ): __lowerCAmelCase = """table-transformer""" __lowerCAmelCase = ["""past_key_values"""] __lowerCAmelCase = { """hidden_size""": """d_model""", """num_attention_heads""": """encoder_attention_heads""", } def __init__( self : List[Any] , lowerCamelCase_ : Dict=True , lowerCamelCase_ : Tuple=None , lowerCamelCase_ : Tuple=3 , lowerCamelCase_ : int=100 , lowerCamelCase_ : List[Any]=6 , lowerCamelCase_ : Any=2048 , lowerCamelCase_ : int=8 , lowerCamelCase_ : Optional[int]=6 , lowerCamelCase_ : Optional[int]=2048 , lowerCamelCase_ : Dict=8 , lowerCamelCase_ : int=0.0 , lowerCamelCase_ : List[str]=0.0 , lowerCamelCase_ : int=True , lowerCamelCase_ : Optional[int]="relu" , lowerCamelCase_ : List[str]=256 , lowerCamelCase_ : int=0.1 , lowerCamelCase_ : Optional[int]=0.0 , lowerCamelCase_ : Dict=0.0 , lowerCamelCase_ : List[str]=0.0_2 , lowerCamelCase_ : Optional[int]=1.0 , lowerCamelCase_ : List[str]=False , lowerCamelCase_ : Optional[int]="sine" , lowerCamelCase_ : Any="resnet50" , lowerCamelCase_ : Any=True , lowerCamelCase_ : Any=False , lowerCamelCase_ : List[str]=1 , lowerCamelCase_ : Optional[Any]=5 , lowerCamelCase_ : int=2 , lowerCamelCase_ : str=1 , lowerCamelCase_ : List[Any]=1 , lowerCamelCase_ : Tuple=5 , lowerCamelCase_ : Optional[Any]=2 , lowerCamelCase_ : Any=0.1 , **lowerCamelCase_ : List[str] , ): """simple docstring""" if backbone_config is not None and use_timm_backbone: raise ValueError("""You can\'t specify both `backbone_config` and `use_timm_backbone`.""" ) if not use_timm_backbone: if backbone_config is None: logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.""" ) UpperCamelCase = CONFIG_MAPPING['''resnet'''](out_features=["""stage4"""] ) elif isinstance(A_ , A_ ): UpperCamelCase = backbone_config.get("""model_type""" ) UpperCamelCase = CONFIG_MAPPING[backbone_model_type] UpperCamelCase = config_class.from_dict(A_ ) # set timm attributes to None UpperCamelCase = None, None, None UpperCamelCase = use_timm_backbone UpperCamelCase = backbone_config UpperCamelCase = num_channels UpperCamelCase = num_queries UpperCamelCase = d_model UpperCamelCase = encoder_ffn_dim UpperCamelCase = encoder_layers UpperCamelCase = encoder_attention_heads UpperCamelCase = decoder_ffn_dim UpperCamelCase = decoder_layers UpperCamelCase = decoder_attention_heads UpperCamelCase = dropout UpperCamelCase = attention_dropout UpperCamelCase = activation_dropout UpperCamelCase = activation_function UpperCamelCase = init_std UpperCamelCase = init_xavier_std UpperCamelCase = encoder_layerdrop UpperCamelCase = decoder_layerdrop UpperCamelCase = encoder_layers UpperCamelCase = auxiliary_loss UpperCamelCase = position_embedding_type UpperCamelCase = backbone UpperCamelCase = use_pretrained_backbone UpperCamelCase = dilation # Hungarian matcher UpperCamelCase = class_cost UpperCamelCase = bbox_cost UpperCamelCase = giou_cost # Loss coefficients UpperCamelCase = mask_loss_coefficient UpperCamelCase = dice_loss_coefficient UpperCamelCase = bbox_loss_coefficient UpperCamelCase = giou_loss_coefficient UpperCamelCase = eos_coefficient super().__init__(is_encoder_decoder=A_ , **A_ ) @property def lowerCamelCase_ ( self : List[Any] ): """simple docstring""" return self.encoder_attention_heads @property def lowerCamelCase_ ( self : Optional[Any] ): """simple docstring""" return self.d_model class SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase ): __lowerCAmelCase = version.parse("""1.11""" ) @property def lowerCamelCase_ ( self : Union[str, Any] ): """simple docstring""" return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ("""pixel_mask""", {0: """batch"""}), ] ) @property def lowerCamelCase_ ( self : Union[str, Any] ): """simple docstring""" return 1E-5 @property def lowerCamelCase_ ( self : List[Any] ): """simple docstring""" return 12
343
from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin @dataclass class __lowercase (_UpperCAmelCase ): _UpperCamelCase = 42 _UpperCamelCase = 42 _UpperCamelCase = None class __lowercase (_UpperCAmelCase , _UpperCAmelCase ): _UpperCamelCase = 2 @register_to_config def __init__( self , A_ = 0.02 , A_ = 100 , A_ = 1.007 , A_ = 80 , A_ = 0.05 , A_ = 50 , ) ->int: '''simple docstring''' __lowerCAmelCase : Optional[int] = sigma_max # setable values __lowerCAmelCase : int = None __lowerCAmelCase : np.IntTensor = None __lowerCAmelCase : torch.FloatTensor = None # sigma(t_i) def UpperCamelCase__ ( self , A_ , A_ = None ) ->torch.FloatTensor: '''simple docstring''' return sample def UpperCamelCase__ ( self , A_ , A_ = None ) ->List[str]: '''simple docstring''' __lowerCAmelCase : str = num_inference_steps __lowerCAmelCase : Dict = np.arange(0 , self.num_inference_steps )[::-1].copy() __lowerCAmelCase : Optional[Any] = torch.from_numpy(A_ ).to(A_ ) __lowerCAmelCase : Tuple = [ ( self.config.sigma_max**2 * (self.config.sigma_min**2 / self.config.sigma_max**2) ** (i / (num_inference_steps - 1)) ) for i in self.timesteps ] __lowerCAmelCase : Optional[int] = torch.tensor(A_ , dtype=torch.floataa , device=A_ ) def UpperCamelCase__ ( self , A_ , A_ , A_ = None ) ->Tuple[torch.FloatTensor, float]: '''simple docstring''' if self.config.s_min <= sigma <= self.config.s_max: __lowerCAmelCase : List[str] = min(self.config.s_churn / self.num_inference_steps , 2**0.5 - 1 ) else: __lowerCAmelCase : List[str] = 0 # sample eps ~ N(0, S_noise^2 * I) __lowerCAmelCase : int = self.config.s_noise * randn_tensor(sample.shape , generator=A_ ).to(sample.device ) __lowerCAmelCase : str = sigma + gamma * sigma __lowerCAmelCase : Any = sample + ((sigma_hat**2 - sigma**2) ** 0.5 * eps) return sample_hat, sigma_hat def UpperCamelCase__ ( self , A_ , A_ , A_ , A_ , A_ = True , ) ->Union[KarrasVeOutput, Tuple]: '''simple docstring''' __lowerCAmelCase : Union[str, Any] = sample_hat + sigma_hat * model_output __lowerCAmelCase : int = (sample_hat - pred_original_sample) / sigma_hat __lowerCAmelCase : Tuple = sample_hat + (sigma_prev - sigma_hat) * derivative if not return_dict: return (sample_prev, derivative) return KarrasVeOutput( prev_sample=A_ , derivative=A_ , pred_original_sample=A_ ) def UpperCamelCase__ ( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ = True , ) ->Union[KarrasVeOutput, Tuple]: '''simple docstring''' __lowerCAmelCase : str = sample_prev + sigma_prev * model_output __lowerCAmelCase : List[Any] = (sample_prev - pred_original_sample) / sigma_prev __lowerCAmelCase : Any = sample_hat + (sigma_prev - sigma_hat) * (0.5 * derivative + 0.5 * derivative_corr) if not return_dict: return (sample_prev, derivative) return KarrasVeOutput( prev_sample=A_ , derivative=A_ , pred_original_sample=A_ ) def UpperCamelCase__ ( self , A_ , A_ , A_ ) ->Any: '''simple docstring''' raise NotImplementedError()
275
0
'''simple docstring''' import math def __lowerCAmelCase (__lowerCAmelCase , __lowerCAmelCase ): return math.pow(lowercase__ , 2 ) - a def __lowerCAmelCase (__lowerCAmelCase ): return 2 * x def __lowerCAmelCase (__lowerCAmelCase ): _UpperCAmelCase : str = 2.0 while start <= a: _UpperCAmelCase : Dict = math.pow(lowercase__ , 2 ) return start def __lowerCAmelCase (__lowerCAmelCase , __lowerCAmelCase = 9_999 , __lowerCAmelCase = 0.0_0_0_0_0_0_0_0_0_0_0_0_0_1 ): if a < 0: raise ValueError("math domain error" ) _UpperCAmelCase : List[Any] = get_initial_point(lowercase__ ) for _ in range(lowercase__ ): _UpperCAmelCase : List[Any] = value _UpperCAmelCase : Any = value - fx(lowercase__ , lowercase__ ) / fx_derivative(lowercase__ ) if abs(prev_value - value ) < tolerance: return value return value if __name__ == "__main__": from doctest import testmod testmod()
234
import unicodedata from dataclasses import dataclass from typing import Optional, Union import numpy as np from transformers.data.data_collator import DataCollatorMixin from transformers.file_utils import PaddingStrategy from transformers.tokenization_utils_base import PreTrainedTokenizerBase def _lowercase ( lowercase__ , lowercase__ , lowercase__ , lowercase__ ): if isinstance(lowercase__ , lowercase__ ): __lowerCAmelCase : Dict = np.full((len(lowercase__ ), sequence_length, 2) , lowercase__ ) else: __lowerCAmelCase : Optional[int] = np.full((len(lowercase__ ), sequence_length) , lowercase__ ) for i, tensor in enumerate(lowercase__ ): if padding_side == "right": if isinstance(lowercase__ , lowercase__ ): __lowerCAmelCase : Union[str, Any] = tensor[:sequence_length] else: __lowerCAmelCase : int = tensor[:sequence_length] else: if isinstance(lowercase__ , lowercase__ ): __lowerCAmelCase : Union[str, Any] = tensor[:sequence_length] else: __lowerCAmelCase : Optional[Any] = tensor[:sequence_length] return out_tensor.tolist() def _lowercase ( lowercase__ ): __lowerCAmelCase : Union[str, Any] = ord(lowercase__ ) if (cp >= 3_3 and cp <= 4_7) or (cp >= 5_8 and cp <= 6_4) or (cp >= 9_1 and cp <= 9_6) or (cp >= 1_2_3 and cp <= 1_2_6): return True __lowerCAmelCase : int = unicodedata.category(lowercase__ ) if cat.startswith('''P''' ): return True return False @dataclass class __lowercase (_UpperCAmelCase ): _UpperCamelCase = 42 _UpperCamelCase = True _UpperCamelCase = None _UpperCamelCase = None _UpperCamelCase = -100 _UpperCamelCase = "pt" def UpperCamelCase__ ( self , A_ ) ->Optional[int]: '''simple docstring''' import torch __lowerCAmelCase : List[str] = '''label''' if '''label''' in features[0].keys() else '''labels''' __lowerCAmelCase : Union[str, Any] = [feature[label_name] for feature in features] if label_name in features[0].keys() else None __lowerCAmelCase : List[Any] = self.tokenizer.pad( A_ , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors='''pt''' if labels is None else None , ) if labels is None: return batch __lowerCAmelCase : Dict = torch.tensor(batch['''entity_ids'''] ).shape[1] __lowerCAmelCase : Optional[int] = self.tokenizer.padding_side if padding_side == "right": __lowerCAmelCase : Any = [ list(A_ ) + [self.label_pad_token_id] * (sequence_length - len(A_ )) for label in labels ] else: __lowerCAmelCase : Optional[int] = [ [self.label_pad_token_id] * (sequence_length - len(A_ )) + list(A_ ) for label in labels ] __lowerCAmelCase : Tuple = [feature['''ner_tags'''] for feature in features] __lowerCAmelCase : List[Any] = padding_tensor(A_ , -1 , A_ , A_ ) __lowerCAmelCase : Optional[int] = [feature['''original_entity_spans'''] for feature in features] __lowerCAmelCase : Any = padding_tensor(A_ , (-1, -1) , A_ , A_ ) __lowerCAmelCase : Optional[Any] = {k: torch.tensor(A_ , dtype=torch.intaa ) for k, v in batch.items()} return batch
275
0
"""simple docstring""" import inspect import unittest import numpy as np from transformers import ViTConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor if is_flax_available(): import jax from transformers.models.vit.modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel class lowercase ( unittest.TestCase ): def __init__( self , lowercase , lowercase=13 , lowercase=30 , lowercase=2 , lowercase=3 , lowercase=True , lowercase=True , lowercase=32 , lowercase=5 , lowercase=4 , lowercase=37 , lowercase="gelu" , lowercase=0.1 , lowercase=0.1 , lowercase=10 , lowercase=0.02 , ) -> int: lowerCAmelCase = parent lowerCAmelCase = batch_size lowerCAmelCase = image_size lowerCAmelCase = patch_size lowerCAmelCase = num_channels lowerCAmelCase = is_training lowerCAmelCase = use_labels lowerCAmelCase = hidden_size lowerCAmelCase = num_hidden_layers lowerCAmelCase = num_attention_heads lowerCAmelCase = intermediate_size lowerCAmelCase = hidden_act lowerCAmelCase = hidden_dropout_prob lowerCAmelCase = attention_probs_dropout_prob lowerCAmelCase = type_sequence_label_size lowerCAmelCase = initializer_range # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) lowerCAmelCase = (image_size // patch_size) ** 2 lowerCAmelCase = num_patches + 1 def _snake_case ( self ) -> List[Any]: lowerCAmelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCAmelCase = ViTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=A_ , initializer_range=self.initializer_range , ) return config, pixel_values def _snake_case ( self , lowercase , lowercase ) -> List[str]: lowerCAmelCase = FlaxViTModel(config=A_ ) lowerCAmelCase = model(A_ ) # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token) lowerCAmelCase = (self.image_size, self.image_size) lowerCAmelCase = (self.patch_size, self.patch_size) lowerCAmelCase = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, num_patches + 1, self.hidden_size) ) def _snake_case ( self , lowercase , lowercase ) -> Dict: lowerCAmelCase = self.type_sequence_label_size lowerCAmelCase = FlaxViTForImageClassification(config=A_ ) lowerCAmelCase = model(A_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images lowerCAmelCase = 1 lowerCAmelCase = FlaxViTForImageClassification(A_ ) lowerCAmelCase = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) lowerCAmelCase = model(A_ ) def _snake_case ( self ) -> Optional[int]: lowerCAmelCase = self.prepare_config_and_inputs() ( lowerCAmelCase ) = config_and_inputs lowerCAmelCase = {'''pixel_values''': pixel_values} return config, inputs_dict @require_flax class lowercase ( _UpperCAmelCase , unittest.TestCase ): _SCREAMING_SNAKE_CASE = (FlaxViTModel, FlaxViTForImageClassification) if is_flax_available() else () def _snake_case ( self ) -> None: lowerCAmelCase = FlaxViTModelTester(self ) lowerCAmelCase = ConfigTester(self , config_class=A_ , has_text_modality=A_ , hidden_size=37 ) def _snake_case ( self ) -> Dict: self.config_tester.run_common_tests() def _snake_case ( self ) -> Any: lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A_ ) def _snake_case ( self ) -> Any: lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*A_ ) def _snake_case ( self ) -> List[Any]: lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase = model_class(A_ ) lowerCAmelCase = inspect.signature(model.__call__ ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCAmelCase = [*signature.parameters.keys()] lowerCAmelCase = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , A_ ) def _snake_case ( self ) -> Any: lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): lowerCAmelCase = self._prepare_for_class(A_ , A_ ) lowerCAmelCase = model_class(A_ ) @jax.jit def model_jitted(lowercase , **lowercase ): return model(pixel_values=A_ , **A_ ) with self.subTest("""JIT Enabled""" ): lowerCAmelCase = model_jitted(**A_ ).to_tuple() with self.subTest("""JIT Disabled""" ): with jax.disable_jit(): lowerCAmelCase = model_jitted(**A_ ).to_tuple() self.assertEqual(len(A_ ) , len(A_ ) ) for jitted_output, output in zip(A_ , A_ ): self.assertEqual(jitted_output.shape , output.shape ) @slow def _snake_case ( self ) -> int: for model_class_name in self.all_model_classes: lowerCAmelCase = model_class_name.from_pretrained("""google/vit-base-patch16-224""" ) lowerCAmelCase = model(np.ones((1, 3, 224, 224) ) ) self.assertIsNotNone(A_ )
46
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import MgpstrTokenizer from transformers.models.mgp_str.tokenization_mgp_str import VOCAB_FILES_NAMES from transformers.testing_utils import require_torch, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_torch_available, is_vision_available if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import MgpstrProcessor, ViTImageProcessor @require_torch @require_vision class __lowercase (unittest.TestCase ): _UpperCamelCase = ViTImageProcessor if is_vision_available() else None @property def UpperCamelCase__ ( self ) ->str: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def UpperCamelCase__ ( self ) ->str: '''simple docstring''' __lowerCAmelCase : Tuple = (3, 32, 128) __lowerCAmelCase : List[str] = tempfile.mkdtemp() # fmt: off __lowerCAmelCase : List[str] = ['''[GO]''', '''[s]''', '''0''', '''1''', '''2''', '''3''', '''4''', '''5''', '''6''', '''7''', '''8''', '''9''', '''a''', '''b''', '''c''', '''d''', '''e''', '''f''', '''g''', '''h''', '''i''', '''j''', '''k''', '''l''', '''m''', '''n''', '''o''', '''p''', '''q''', '''r''', '''s''', '''t''', '''u''', '''v''', '''w''', '''x''', '''y''', '''z'''] # fmt: on __lowerCAmelCase : Optional[int] = dict(zip(A_ , range(len(A_ ) ) ) ) __lowerCAmelCase : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(A_ ) + '''\n''' ) __lowerCAmelCase : Union[str, Any] = { '''do_normalize''': False, '''do_resize''': True, '''image_processor_type''': '''ViTImageProcessor''', '''resample''': 3, '''size''': {'''height''': 32, '''width''': 128}, } __lowerCAmelCase : Optional[Any] = os.path.join(self.tmpdirname , A_ ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(A_ , A_ ) def UpperCamelCase__ ( self , **A_ ) ->Tuple: '''simple docstring''' return MgpstrTokenizer.from_pretrained(self.tmpdirname , **A_ ) def UpperCamelCase__ ( self , **A_ ) ->Tuple: '''simple docstring''' return ViTImageProcessor.from_pretrained(self.tmpdirname , **A_ ) def UpperCamelCase__ ( self ) ->Optional[int]: '''simple docstring''' shutil.rmtree(self.tmpdirname ) def UpperCamelCase__ ( self ) ->Optional[Any]: '''simple docstring''' __lowerCAmelCase : Tuple = np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta ) __lowerCAmelCase : str = Image.fromarray(np.moveaxis(A_ , 0 , -1 ) ) return image_input def UpperCamelCase__ ( self ) ->Any: '''simple docstring''' __lowerCAmelCase : Dict = self.get_tokenizer() __lowerCAmelCase : List[Any] = self.get_image_processor() __lowerCAmelCase : List[Any] = MgpstrProcessor(tokenizer=A_ , image_processor=A_ ) processor.save_pretrained(self.tmpdirname ) __lowerCAmelCase : Union[str, Any] = MgpstrProcessor.from_pretrained(self.tmpdirname , use_fast=A_ ) self.assertEqual(processor.char_tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.char_tokenizer , A_ ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , A_ ) def UpperCamelCase__ ( self ) ->Optional[int]: '''simple docstring''' __lowerCAmelCase : Any = self.get_tokenizer() __lowerCAmelCase : Union[str, Any] = self.get_image_processor() __lowerCAmelCase : List[Any] = MgpstrProcessor(tokenizer=A_ , image_processor=A_ ) processor.save_pretrained(self.tmpdirname ) __lowerCAmelCase : List[Any] = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) __lowerCAmelCase : int = self.get_image_processor(do_normalize=A_ , padding_value=1.0 ) __lowerCAmelCase : int = MgpstrProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=A_ , padding_value=1.0 ) self.assertEqual(processor.char_tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.char_tokenizer , A_ ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , A_ ) def UpperCamelCase__ ( self ) ->List[str]: '''simple docstring''' __lowerCAmelCase : Any = self.get_image_processor() __lowerCAmelCase : Optional[Any] = self.get_tokenizer() __lowerCAmelCase : int = MgpstrProcessor(tokenizer=A_ , image_processor=A_ ) __lowerCAmelCase : Optional[int] = self.prepare_image_inputs() __lowerCAmelCase : Optional[Any] = image_processor(A_ , return_tensors='''np''' ) __lowerCAmelCase : Tuple = processor(images=A_ , return_tensors='''np''' ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1e-2 ) def UpperCamelCase__ ( self ) ->str: '''simple docstring''' __lowerCAmelCase : str = self.get_image_processor() __lowerCAmelCase : Union[str, Any] = self.get_tokenizer() __lowerCAmelCase : Optional[Any] = MgpstrProcessor(tokenizer=A_ , image_processor=A_ ) __lowerCAmelCase : Any = '''test''' __lowerCAmelCase : Dict = processor(text=A_ ) __lowerCAmelCase : str = tokenizer(A_ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def UpperCamelCase__ ( self ) ->Optional[int]: '''simple docstring''' __lowerCAmelCase : Dict = self.get_image_processor() __lowerCAmelCase : Any = self.get_tokenizer() __lowerCAmelCase : str = MgpstrProcessor(tokenizer=A_ , image_processor=A_ ) __lowerCAmelCase : List[Any] = '''test''' __lowerCAmelCase : int = self.prepare_image_inputs() __lowerCAmelCase : int = processor(text=A_ , images=A_ ) self.assertListEqual(list(inputs.keys() ) , ['''pixel_values''', '''labels'''] ) # test if it raises when no input is passed with pytest.raises(A_ ): processor() def UpperCamelCase__ ( self ) ->Union[str, Any]: '''simple docstring''' __lowerCAmelCase : List[Any] = self.get_image_processor() __lowerCAmelCase : int = self.get_tokenizer() __lowerCAmelCase : Any = MgpstrProcessor(tokenizer=A_ , image_processor=A_ ) __lowerCAmelCase : List[str] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9], [3, 4, 3, 1, 1, 8, 9]] __lowerCAmelCase : Optional[int] = processor.char_decode(A_ ) __lowerCAmelCase : Tuple = tokenizer.batch_decode(A_ ) __lowerCAmelCase : Any = [seq.replace(''' ''' , '''''' ) for seq in decoded_tok] self.assertListEqual(A_ , A_ ) def UpperCamelCase__ ( self ) ->Any: '''simple docstring''' __lowerCAmelCase : str = self.get_image_processor() __lowerCAmelCase : Any = self.get_tokenizer() __lowerCAmelCase : int = MgpstrProcessor(tokenizer=A_ , image_processor=A_ ) __lowerCAmelCase : Union[str, Any] = None __lowerCAmelCase : Optional[Any] = self.prepare_image_inputs() __lowerCAmelCase : List[Any] = processor(text=A_ , images=A_ ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names ) def UpperCamelCase__ ( self ) ->List[str]: '''simple docstring''' __lowerCAmelCase : List[str] = self.get_image_processor() __lowerCAmelCase : List[str] = self.get_tokenizer() __lowerCAmelCase : Any = MgpstrProcessor(tokenizer=A_ , image_processor=A_ ) __lowerCAmelCase : List[Any] = torch.randn(1 , 27 , 38 ) __lowerCAmelCase : Optional[int] = torch.randn(1 , 27 , 5_0257 ) __lowerCAmelCase : Optional[Any] = torch.randn(1 , 27 , 3_0522 ) __lowerCAmelCase : List[str] = processor.batch_decode([char_input, bpe_input, wp_input] ) self.assertListEqual(list(results.keys() ) , ['''generated_text''', '''scores''', '''char_preds''', '''bpe_preds''', '''wp_preds'''] )
275
0
import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, MBartTokenizer, MBartTokenizerFast, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin __A : List[str] = get_tests_dir('fixtures/test_sentencepiece.model') if is_torch_available(): from transformers.models.mbart.modeling_mbart import shift_tokens_right __A : int = 25_00_04 __A : Optional[Any] = 25_00_20 @require_sentencepiece @require_tokenizers class _SCREAMING_SNAKE_CASE ( _UpperCAmelCase , unittest.TestCase): _UpperCamelCase:List[Any] = MBartTokenizer _UpperCamelCase:Any = MBartTokenizerFast _UpperCamelCase:Optional[int] = True _UpperCamelCase:Optional[int] = True def _snake_case ( self )-> str: super().setUp() # We have a SentencePiece fixture for testing lowerCamelCase_ =MBartTokenizer(A_ , keep_accents=A_ ) tokenizer.save_pretrained(self.tmpdirname ) def _snake_case ( self )-> Optional[Any]: lowerCamelCase_ =MBartTokenizer(A_ , keep_accents=A_ ) lowerCamelCase_ =tokenizer.tokenize("""This is a test""" ) self.assertListEqual(A_ , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(A_ ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) lowerCamelCase_ =tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( A_ , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """9""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """é""", """.""", ] , ) lowerCamelCase_ =tokenizer.convert_tokens_to_ids(A_ ) self.assertListEqual( A_ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] # ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^ ] , ) lowerCamelCase_ =tokenizer.convert_ids_to_tokens(A_ ) self.assertListEqual( A_ , [ 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>""", """.""", ] , ) def _snake_case ( self )-> Dict: if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return lowerCamelCase_ =(self.rust_tokenizer_class, '''hf-internal-testing/tiny-random-mbart''', {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): lowerCamelCase_ =self.rust_tokenizer_class.from_pretrained(A_ , **A_ ) lowerCamelCase_ =self.tokenizer_class.from_pretrained(A_ , **A_ ) lowerCamelCase_ =tempfile.mkdtemp() lowerCamelCase_ =tokenizer_r.save_pretrained(A_ ) lowerCamelCase_ =tokenizer_p.save_pretrained(A_ ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) lowerCamelCase_ =tuple(f for f in tokenizer_r_files if """tokenizer.json""" not in f ) self.assertSequenceEqual(A_ , A_ ) # Checks everything loads correctly in the same way lowerCamelCase_ =tokenizer_r.from_pretrained(A_ ) lowerCamelCase_ =tokenizer_p.from_pretrained(A_ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(A_ , A_ ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(A_ ) # Save tokenizer rust, legacy_format=True lowerCamelCase_ =tempfile.mkdtemp() lowerCamelCase_ =tokenizer_r.save_pretrained(A_ , legacy_format=A_ ) lowerCamelCase_ =tokenizer_p.save_pretrained(A_ ) # Checks it save with the same files self.assertSequenceEqual(A_ , A_ ) # Checks everything loads correctly in the same way lowerCamelCase_ =tokenizer_r.from_pretrained(A_ ) lowerCamelCase_ =tokenizer_p.from_pretrained(A_ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(A_ , A_ ) ) shutil.rmtree(A_ ) # Save tokenizer rust, legacy_format=False lowerCamelCase_ =tempfile.mkdtemp() lowerCamelCase_ =tokenizer_r.save_pretrained(A_ , legacy_format=A_ ) lowerCamelCase_ =tokenizer_p.save_pretrained(A_ ) # Checks it saved the tokenizer.json file self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way lowerCamelCase_ =tokenizer_r.from_pretrained(A_ ) lowerCamelCase_ =tokenizer_p.from_pretrained(A_ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(A_ , A_ ) ) shutil.rmtree(A_ ) @require_torch @require_sentencepiece @require_tokenizers class _SCREAMING_SNAKE_CASE ( unittest.TestCase): _UpperCamelCase:Optional[int] = "facebook/mbart-large-en-ro" _UpperCamelCase:List[str] = [ " UN Chief Says There Is No Military Solution in Syria", " Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for Syria is that \"there is no military solution\" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.", ] _UpperCamelCase:Union[str, Any] = [ "Şeful ONU declară că nu există o soluţie militară în Siria", "Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei" " pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi că noi arme nu vor" " face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.", ] _UpperCamelCase:Optional[int] = [82_74, 12_78_73, 2_59_16, 7, 86_22, 20_71, 4_38, 6_74_85, 53, 18_78_95, 23, 5_17_12, 2, EN_CODE] @classmethod def _snake_case ( cls )-> Tuple: lowerCamelCase_ =MBartTokenizer.from_pretrained( cls.checkpoint_name , src_lang="""en_XX""" , tgt_lang="""ro_RO""" ) lowerCamelCase_ =1 return cls def _snake_case ( self )-> List[Any]: self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ar_AR"""] , 25_0001 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""en_EN"""] , 25_0004 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ro_RO"""] , 25_0020 ) def _snake_case ( self )-> Any: lowerCamelCase_ =self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , A_ ) def _snake_case ( self )-> List[Any]: self.assertIn(A_ , self.tokenizer.all_special_ids ) lowerCamelCase_ =[RO_CODE, 884, 9019, 96, 9, 916, 8_6792, 36, 1_8743, 1_5596, 5, 2] lowerCamelCase_ =self.tokenizer.decode(A_ , skip_special_tokens=A_ ) lowerCamelCase_ =self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=A_ ) self.assertEqual(A_ , A_ ) self.assertNotIn(self.tokenizer.eos_token , A_ ) def _snake_case ( self )-> str: lowerCamelCase_ =['''this is gunna be a long sentence ''' * 20] assert isinstance(src_text[0] , A_ ) lowerCamelCase_ =10 lowerCamelCase_ =self.tokenizer(A_ , max_length=A_ , truncation=A_ ).input_ids[0] self.assertEqual(ids[-2] , 2 ) self.assertEqual(ids[-1] , A_ ) self.assertEqual(len(A_ ) , A_ ) def _snake_case ( self )-> str: self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["""<mask>""", """ar_AR"""] ) , [25_0026, 25_0001] ) def _snake_case ( self )-> Tuple: lowerCamelCase_ =tempfile.mkdtemp() lowerCamelCase_ =self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(A_ ) lowerCamelCase_ =MBartTokenizer.from_pretrained(A_ ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , A_ ) @require_torch def _snake_case ( self )-> Dict: lowerCamelCase_ =self.tokenizer(self.src_text , text_target=self.tgt_text , padding=A_ , return_tensors="""pt""" ) lowerCamelCase_ =shift_tokens_right(batch["""labels"""] , self.tokenizer.pad_token_id ) # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 assert batch.input_ids[1][-2:].tolist() == [2, EN_CODE] assert batch.decoder_input_ids[1][0].tolist() == RO_CODE assert batch.decoder_input_ids[1][-1] == 2 assert batch.labels[1][-2:].tolist() == [2, RO_CODE] @require_torch def _snake_case ( self )-> Dict: lowerCamelCase_ =self.tokenizer( self.src_text , text_target=self.tgt_text , padding=A_ , truncation=A_ , max_length=len(self.expected_src_tokens ) , return_tensors="""pt""" , ) lowerCamelCase_ =shift_tokens_right(batch["""labels"""] , self.tokenizer.pad_token_id ) self.assertIsInstance(A_ , A_ ) self.assertEqual((2, 14) , batch.input_ids.shape ) self.assertEqual((2, 14) , batch.attention_mask.shape ) lowerCamelCase_ =batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , A_ ) self.assertEqual(2 , batch.decoder_input_ids[0, -1] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id, EN_CODE] ) def _snake_case ( self )-> Dict: lowerCamelCase_ =self.tokenizer(self.src_text , padding=A_ , truncation=A_ , max_length=3 , return_tensors="""pt""" ) lowerCamelCase_ =self.tokenizer( text_target=self.tgt_text , padding=A_ , truncation=A_ , max_length=10 , return_tensors="""pt""" ) lowerCamelCase_ =targets['''input_ids'''] lowerCamelCase_ =shift_tokens_right(A_ , self.tokenizer.pad_token_id ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def _snake_case ( self )-> List[str]: lowerCamelCase_ =self.tokenizer._build_translation_inputs( """A test""" , return_tensors="""pt""" , src_lang="""en_XX""" , tgt_lang="""ar_AR""" ) self.assertEqual( nested_simplify(A_ ) , { # A, test, EOS, en_XX """input_ids""": [[62, 3034, 2, 25_0004]], """attention_mask""": [[1, 1, 1, 1]], # ar_AR """forced_bos_token_id""": 25_0001, } , )
154
import unittest import numpy as np import torch from diffusers import PNDMPipeline, PNDMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class __lowercase (unittest.TestCase ): @property def UpperCamelCase__ ( self ) ->Tuple: '''simple docstring''' torch.manual_seed(0 ) __lowerCAmelCase : List[Any] = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''') , up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''') , ) return model def UpperCamelCase__ ( self ) ->int: '''simple docstring''' __lowerCAmelCase : List[str] = self.dummy_uncond_unet __lowerCAmelCase : Any = PNDMScheduler() __lowerCAmelCase : Dict = PNDMPipeline(unet=A_ , scheduler=A_ ) pndm.to(A_ ) pndm.set_progress_bar_config(disable=A_ ) __lowerCAmelCase : Optional[Any] = torch.manual_seed(0 ) __lowerCAmelCase : Any = pndm(generator=A_ , num_inference_steps=20 , output_type='''numpy''' ).images __lowerCAmelCase : Optional[Any] = torch.manual_seed(0 ) __lowerCAmelCase : List[Any] = pndm(generator=A_ , num_inference_steps=20 , output_type='''numpy''' , return_dict=A_ )[0] __lowerCAmelCase : Tuple = image[0, -3:, -3:, -1] __lowerCAmelCase : Optional[Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __lowerCAmelCase : int = np.array([1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch class __lowercase (unittest.TestCase ): def UpperCamelCase__ ( self ) ->Optional[Any]: '''simple docstring''' __lowerCAmelCase : Optional[int] = '''google/ddpm-cifar10-32''' __lowerCAmelCase : Union[str, Any] = UNetaDModel.from_pretrained(A_ ) __lowerCAmelCase : int = PNDMScheduler() __lowerCAmelCase : Any = PNDMPipeline(unet=A_ , scheduler=A_ ) pndm.to(A_ ) pndm.set_progress_bar_config(disable=A_ ) __lowerCAmelCase : Tuple = torch.manual_seed(0 ) __lowerCAmelCase : Any = pndm(generator=A_ , output_type='''numpy''' ).images __lowerCAmelCase : Optional[int] = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __lowerCAmelCase : List[Any] = np.array([0.1_564, 0.14_645, 0.1_406, 0.14_715, 0.12_425, 0.14_045, 0.13_115, 0.12_175, 0.125] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
275
0
import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_camembert import CamembertTokenizer else: _lowerCamelCase : Any = None _lowerCamelCase : str = logging.get_logger(__name__) _lowerCamelCase : Tuple = {"""vocab_file""": """sentencepiece.bpe.model""", """tokenizer_file""": """tokenizer.json"""} _lowerCamelCase : List[str] = { """vocab_file""": { """camembert-base""": """https://huggingface.co/camembert-base/resolve/main/sentencepiece.bpe.model""", }, """tokenizer_file""": { """camembert-base""": """https://huggingface.co/camembert-base/resolve/main/tokenizer.json""", }, } _lowerCamelCase : Any = { """camembert-base""": 512, } _lowerCamelCase : Any = """▁""" class UpperCamelCase_ ( _UpperCAmelCase ): '''simple docstring''' UpperCAmelCase__ = VOCAB_FILES_NAMES UpperCAmelCase__ = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase__ = ['''input_ids''', '''attention_mask'''] UpperCAmelCase__ = CamembertTokenizer def __init__( self : List[Any] , UpperCAmelCase__ : str=None , UpperCAmelCase__ : Optional[int]=None , UpperCAmelCase__ : Dict="<s>" , UpperCAmelCase__ : Optional[int]="</s>" , UpperCAmelCase__ : Dict="</s>" , UpperCAmelCase__ : int="<s>" , UpperCAmelCase__ : List[str]="<unk>" , UpperCAmelCase__ : List[str]="<pad>" , UpperCAmelCase__ : List[Any]="<mask>" , UpperCAmelCase__ : str=["<s>NOTUSED", "</s>NOTUSED"] , **UpperCAmelCase__ : Optional[Any] , ) ->Union[str, Any]: '''simple docstring''' A__ = AddedToken(A_ , lstrip=A_ , rstrip=A_) if isinstance(A_ , A_) else mask_token super().__init__( A_ , tokenizer_file=A_ , bos_token=A_ , eos_token=A_ , sep_token=A_ , cls_token=A_ , unk_token=A_ , pad_token=A_ , mask_token=A_ , additional_special_tokens=A_ , **A_ , ) A__ = vocab_file A__ = False if not self.vocab_file else True def SCREAMING_SNAKE_CASE ( self : Optional[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Tuple = None) ->List[int]: '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] A__ = [self.cls_token_id] A__ = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE ( self : Any , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : int = None) ->List[int]: '''simple docstring''' A__ = [self.sep_token_id] A__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep) * [0] def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : str = None) ->Tuple[str]: '''simple docstring''' if not self.can_save_slow_tokenizer: raise ValueError( '''Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ''' '''tokenizer.''') if not os.path.isdir(A_): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""") return A__ = os.path.join( A_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']) if os.path.abspath(self.vocab_file) != os.path.abspath(A_): copyfile(self.vocab_file , A_) return (out_vocab_file,)
14
from __future__ import annotations import random # Maximum size of the population. Bigger could be faster but is more memory expensive. _UpperCamelCase = 200 # Number of elements selected in every generation of evolution. The selection takes # place from best to worst of that generation and must be smaller than N_POPULATION. _UpperCamelCase = 50 # Probability that an element of a generation can mutate, changing one of its genes. # This will guarantee that all genes will be used during evolution. _UpperCamelCase = 0.4 # Just a seed to improve randomness required by the algorithm. random.seed(random.randint(0, 1000)) def _lowercase ( lowercase__ , lowercase__ ): __lowerCAmelCase : List[str] = len([g for position, g in enumerate(lowercase__ ) if g == main_target[position]] ) return (item, float(lowercase__ )) def _lowercase ( lowercase__ , lowercase__ ): __lowerCAmelCase : str = random.randint(0 , len(lowercase__ ) - 1 ) __lowerCAmelCase : int = parent_a[:random_slice] + parent_a[random_slice:] __lowerCAmelCase : Dict = parent_a[:random_slice] + parent_a[random_slice:] return (child_a, child_a) def _lowercase ( lowercase__ , lowercase__ ): __lowerCAmelCase : List[str] = list(lowercase__ ) if random.uniform(0 , 1 ) < MUTATION_PROBABILITY: __lowerCAmelCase : int = random.choice(lowercase__ ) return "".join(lowercase__ ) def _lowercase ( lowercase__ , lowercase__ , lowercase__ , ): __lowerCAmelCase : str = [] # Generate more children proportionally to the fitness score. __lowerCAmelCase : str = int(parent_a[1] * 1_0_0 ) + 1 __lowerCAmelCase : Optional[Any] = 1_0 if child_n >= 1_0 else child_n for _ in range(lowercase__ ): __lowerCAmelCase : List[Any] = population_score[random.randint(0 , lowercase__ )][0] __lowerCAmelCase, __lowerCAmelCase : Dict = crossover(parent_a[0] , lowercase__ ) # Append new string to the population list. pop.append(mutate(lowercase__ , lowercase__ ) ) pop.append(mutate(lowercase__ , lowercase__ ) ) return pop def _lowercase ( lowercase__ , lowercase__ , lowercase__ = True ): # Verify if N_POPULATION is bigger than N_SELECTED if N_POPULATION < N_SELECTED: __lowerCAmelCase : int = f"""{N_POPULATION} must be bigger than {N_SELECTED}""" raise ValueError(lowercase__ ) # Verify that the target contains no genes besides the ones inside genes variable. __lowerCAmelCase : Any = sorted({c for c in target if c not in genes} ) if not_in_genes_list: __lowerCAmelCase : List[str] = f"""{not_in_genes_list} is not in genes list, evolution cannot converge""" raise ValueError(lowercase__ ) # Generate random starting population. __lowerCAmelCase : List[Any] = [] for _ in range(lowercase__ ): population.append(''''''.join([random.choice(lowercase__ ) for i in range(len(lowercase__ ) )] ) ) # Just some logs to know what the algorithms is doing. __lowerCAmelCase, __lowerCAmelCase : Tuple = 0, 0 # This loop will end when we find a perfect match for our target. while True: generation += 1 total_population += len(lowercase__ ) # Random population created. Now it's time to evaluate. # Adding a bit of concurrency can make everything faster, # # import concurrent.futures # population_score: list[tuple[str, float]] = [] # with concurrent.futures.ThreadPoolExecutor( # max_workers=NUM_WORKERS) as executor: # futures = {executor.submit(evaluate, item) for item in population} # concurrent.futures.wait(futures) # population_score = [item.result() for item in futures] # # but with a simple algorithm like this, it will probably be slower. # We just need to call evaluate for every item inside the population. __lowerCAmelCase : Any = [evaluate(lowercase__ , lowercase__ ) for item in population] # Check if there is a matching evolution. __lowerCAmelCase : Union[str, Any] = sorted(lowercase__ , key=lambda lowercase__ : x[1] , reverse=lowercase__ ) if population_score[0][0] == target: return (generation, total_population, population_score[0][0]) # Print the best result every 10 generation. # Just to know that the algorithm is working. if debug and generation % 1_0 == 0: print( f"""\nGeneration: {generation}""" f"""\nTotal Population:{total_population}""" f"""\nBest score: {population_score[0][1]}""" f"""\nBest string: {population_score[0][0]}""" ) # Flush the old population, keeping some of the best evolutions. # Keeping this avoid regression of evolution. __lowerCAmelCase : Tuple = population[: int(N_POPULATION / 3 )] population.clear() population.extend(lowercase__ ) # Normalize population score to be between 0 and 1. __lowerCAmelCase : List[Any] = [ (item, score / len(lowercase__ )) for item, score in population_score ] # This is selection for i in range(lowercase__ ): population.extend(select(population_score[int(lowercase__ )] , lowercase__ , lowercase__ ) ) # Check if the population has already reached the maximum value and if so, # break the cycle. If this check is disabled, the algorithm will take # forever to compute large strings, but will also calculate small strings in # a far fewer generations. if len(lowercase__ ) > N_POPULATION: break if __name__ == "__main__": _UpperCamelCase = ( "This is a genetic algorithm to evaluate, combine, evolve, and mutate a string!" ) _UpperCamelCase = list( " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm" "nopqrstuvwxyz.,;!?+-*#@^'èéòà€ù=)(&%$£/\\" ) _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = basic(target_str, genes_list) print( F"\nGeneration: {generation}\nTotal Population: {population}\nTarget: {target}" )
275
0
'''simple docstring''' def a__ ( lowercase : Any, lowercase : str ) -> Optional[Any]: """simple docstring""" if density <= 0: raise ValueError('''Impossible fluid density''' ) if bulk_modulus <= 0: raise ValueError('''Impossible bulk modulus''' ) return (bulk_modulus / density) ** 0.5 if __name__ == "__main__": import doctest doctest.testmod()
324
import os import re import unicodedata from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import is_torch_available, logging if is_torch_available(): import torch if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation _UpperCamelCase = logging.get_logger(__name__) _UpperCamelCase = {"vocab_file": "spiece.model"} _UpperCamelCase = { "vocab_file": { "AI-Sweden/gpt-sw3-126m": "https://huggingface.co/AI-Sweden/gpt-sw3-126m/resolve/main/spiece.model", "AI-Sweden/gpt-sw3-350m": "https://huggingface.co/AI-Sweden/gpt-sw3-350m/resolve/main/spiece.model", "AI-Sweden/gpt-sw3-1.6b": "https://huggingface.co/AI-Sweden/gpt-sw3-1.6b/resolve/main/spiece.model", "AI-Sweden/gpt-sw3-6.7b": "https://huggingface.co/AI-Sweden/gpt-sw3-6.7b/resolve/main/spiece.model", "AI-Sweden/gpt-sw3-20b": "https://huggingface.co/AI-Sweden/gpt-sw3-20b/resolve/main/spiece.model", } } _UpperCamelCase = { "AI-Sweden/gpt-sw3-126m": 2048, "AI-Sweden/gpt-sw3-350m": 2048, "AI-Sweden/gpt-sw3-1.6b": 2048, "AI-Sweden/gpt-sw3-6.7b": 2048, "AI-Sweden/gpt-sw3-20b": 2048, } class __lowercase (_UpperCAmelCase ): _UpperCamelCase = VOCAB_FILES_NAMES _UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP _UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCamelCase = ["""input_ids""", """attention_mask"""] def __init__( self , A_ , A_=False , A_=False , A_=False , A_=None , A_=None , A_=None , A_=None , A_ = None , **A_ , ) ->None: '''simple docstring''' __lowerCAmelCase : Optional[int] = {} if sp_model_kwargs is None else sp_model_kwargs __lowerCAmelCase : int = kwargs.get('''name_or_path''' ) if name_or_path is None: logger.warning( '''name_or_path not provided, will work for all GPTSw3 models except gpt-sw3-7b,''' ''' you are testing the model, this can safely be ignored''' ) __lowerCAmelCase : Union[str, Any] = '''None''' # Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing __lowerCAmelCase : str = '''<|endoftext|>''' if eos_token is None else eos_token __lowerCAmelCase : Any = '''<unk>''' if unk_token is None else unk_token if "gpt-sw3-7b" in name_or_path: __lowerCAmelCase : Dict = unk_token if pad_token is None else pad_token __lowerCAmelCase : int = eos_token if bos_token is None else bos_token else: __lowerCAmelCase : Optional[int] = '''<pad>''' if pad_token is None else pad_token __lowerCAmelCase : List[str] = '''<s>''' if bos_token is None else bos_token super().__init__( do_lower_case=A_ , remove_space=A_ , keep_accents=A_ , bos_token=A_ , eos_token=A_ , unk_token=A_ , pad_token=A_ , sp_model_kwargs=self.sp_model_kwargs , **A_ , ) __lowerCAmelCase : Union[str, Any] = do_lower_case __lowerCAmelCase : Union[str, Any] = remove_space __lowerCAmelCase : int = keep_accents __lowerCAmelCase : Union[str, Any] = vocab_file __lowerCAmelCase : int = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(A_ ) # Used for whitespace normalization in input texts # fmt : off __lowerCAmelCase : List[Any] = {''' ''', ''' ''', ''' ''', ''' ''', ''' ''', ''' ''', ''' ''', ''' ''', ''' ''', ''' ''', '''''', '''„'''} # fmt : on # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing __lowerCAmelCase : int = re.compile( f"""[{"".join(map(A_ , list(range(0 , 9 ) ) + list(range(11 , 32 ) ) + list(range(127 , 160 ) ) + [160, 173, 8203] ) )}]""" ) def __getstate__( self ) ->Dict: '''simple docstring''' __lowerCAmelCase : Union[str, Any] = self.__dict__.copy() __lowerCAmelCase : List[Any] = None return state def __setstate__( self , A_ ) ->Tuple: '''simple docstring''' __lowerCAmelCase : int = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): __lowerCAmelCase : List[Any] = {} __lowerCAmelCase : List[str] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) @property # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.vocab_size def UpperCamelCase__ ( self ) ->int: '''simple docstring''' return len(self.sp_model ) def UpperCamelCase__ ( self , A_ ) ->str: '''simple docstring''' __lowerCAmelCase : int = self.non_printing_characters_re.sub('''''' , A_ ) # Normalize whitespaces __lowerCAmelCase : List[str] = ''''''.join([char if char not in self.whitespaces else ''' ''' for char in text] ) # NFC Unicode normalization __lowerCAmelCase : Tuple = unicodedata.normalize('''NFC''' , A_ ) return text def UpperCamelCase__ ( self , A_ , **A_ ) ->List[str]: '''simple docstring''' __lowerCAmelCase : int = self.preprocess_text(A_ ) return self.sp_model.encode(A_ , out_type=A_ ) def UpperCamelCase__ ( self , A_ ) ->int: '''simple docstring''' return self.sp_model.PieceToId(A_ ) def UpperCamelCase__ ( self , A_ ) ->str: '''simple docstring''' return self.sp_model.IdToPiece(A_ ) @staticmethod def UpperCamelCase__ ( A_ ) ->str: '''simple docstring''' return out_string def UpperCamelCase__ ( self , A_ ) ->str: '''simple docstring''' __lowerCAmelCase : str = [] __lowerCAmelCase : Tuple = '''''' __lowerCAmelCase : int = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: # TODO: Check if this is needed, as it ensures that decode(encode(doc)) != doc by adding extra whitespace in the decoded document if not prev_is_special: out_string += " " out_string += self.sp_model.decode(A_ ) + token __lowerCAmelCase : Optional[Any] = True __lowerCAmelCase : Optional[int] = [] else: current_sub_tokens.append(A_ ) __lowerCAmelCase : str = False out_string += self.sp_model.decode(A_ ) return out_string def UpperCamelCase__ ( self ) ->Dict[str, int]: '''simple docstring''' __lowerCAmelCase : str = {self.convert_ids_to_tokens(A_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def UpperCamelCase__ ( self , A_ , A_ = None ) ->Tuple[str]: '''simple docstring''' if not os.path.isdir(A_ ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return __lowerCAmelCase : Any = os.path.join( A_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , A_ ) elif not os.path.isfile(self.vocab_file ): with open(A_ , '''wb''' ) as fi: __lowerCAmelCase : Dict = self.sp_model.serialized_model_proto() fi.write(A_ ) return (out_vocab_file,) def UpperCamelCase__ ( self , A_ , A_ = False ) ->Union[List[int], List[List[int]], "torch.Tensor"]: '''simple docstring''' if isinstance(A_ , A_ ): __lowerCAmelCase : Optional[Any] = self.preprocess_text(A_ ) __lowerCAmelCase : Dict = self.sp_model.encode(A_ ) else: __lowerCAmelCase : Dict = [self.preprocess_text(A_ ) for t in text] __lowerCAmelCase : Optional[int] = self.sp_model.encode(A_ ) if return_tensors is True or return_tensors == "pt": __lowerCAmelCase : Tuple = torch.tensor(A_ ) return token_ids def UpperCamelCase__ ( self , A_ ) ->str: '''simple docstring''' return self.sp_model.decode(A_ ) def UpperCamelCase__ ( self , A_ ) ->List[int]: '''simple docstring''' __lowerCAmelCase : int = [f"""User: {text}""" if is_user else f"""Bot: {text}""" for is_user, text in conversation.iter_texts()] __lowerCAmelCase : Any = ( f"""{self.eos_token}{self.bos_token}""" + f"""{self.bos_token}""".join(A_ ) + f"""{self.bos_token}Bot:""" ) return self.encode(text=A_ )
275
0
'''simple docstring''' from pathlib import Path from typing import List from transformers import is_torch_available, is_vision_available from transformers.testing_utils import get_tests_dir, is_tool_test from transformers.tools.agent_types import AGENT_TYPE_MAPPING, AgentAudio, AgentImage, AgentText if is_torch_available(): import torch if is_vision_available(): from PIL import Image UpperCamelCase_ = ["""text""", """image""", """audio"""] def _UpperCAmelCase ( _lowerCamelCase : Dict ) -> List[str]: _lowerCAmelCase : str = [] for input_type in input_types: if input_type == "text": inputs.append("""Text input""" ) elif input_type == "image": inputs.append( Image.open(Path(get_tests_dir("""fixtures/tests_samples/COCO""" ) ) / """000000039769.png""" ).resize((5_12, 5_12) ) ) elif input_type == "audio": inputs.append(torch.ones(30_00 ) ) elif isinstance(lowercase__ , lowercase__ ): inputs.append(create_inputs(lowercase__ ) ) else: raise ValueError(f'Invalid type requested: {input_type}' ) return inputs def _UpperCAmelCase ( _lowerCamelCase : str ) -> int: _lowerCAmelCase : Any = [] for output in outputs: if isinstance(lowercase__ , (str, AgentText) ): output_types.append("""text""" ) elif isinstance(lowercase__ , (Image.Image, AgentImage) ): output_types.append("""image""" ) elif isinstance(lowercase__ , (torch.Tensor, AgentAudio) ): output_types.append("""audio""" ) else: raise ValueError(f'Invalid output: {output}' ) return output_types @is_tool_test class a_ : def __UpperCamelCase ( self ): self.assertTrue(hasattr(self.tool , """inputs""" ) ) self.assertTrue(hasattr(self.tool , """outputs""" ) ) _lowerCAmelCase : str = self.tool.inputs for _input in inputs: if isinstance(_input , A_ ): for __input in _input: self.assertTrue(__input in authorized_types ) else: self.assertTrue(_input in authorized_types ) _lowerCAmelCase : Optional[Any] = self.tool.outputs for _output in outputs: self.assertTrue(_output in authorized_types ) def __UpperCamelCase ( self ): _lowerCAmelCase : Dict = create_inputs(self.tool.inputs ) _lowerCAmelCase : Dict = self.tool(*A_ ) # There is a single output if len(self.tool.outputs ) == 1: _lowerCAmelCase : str = [outputs] self.assertListEqual(output_types(A_ ) , self.tool.outputs ) def __UpperCamelCase ( self ): self.assertTrue(hasattr(self.tool , """description""" ) ) self.assertTrue(hasattr(self.tool , """default_checkpoint""" ) ) self.assertTrue(self.tool.description.startswith("""This is a tool that""" ) ) def __UpperCamelCase ( self ): _lowerCAmelCase : List[Any] = create_inputs(self.tool.inputs ) _lowerCAmelCase : Dict = self.tool(*A_ ) if not isinstance(A_ , A_ ): _lowerCAmelCase : List[Any] = [outputs] self.assertEqual(len(A_ ) , len(self.tool.outputs ) ) for output, output_type in zip(A_ , self.tool.outputs ): _lowerCAmelCase : Union[str, Any] = AGENT_TYPE_MAPPING[output_type] self.assertTrue(isinstance(A_ , A_ ) ) def __UpperCamelCase ( self ): _lowerCAmelCase : Any = create_inputs(self.tool.inputs ) _lowerCAmelCase : List[str] = [] for _input, input_type in zip(A_ , self.tool.inputs ): if isinstance(A_ , A_ ): _inputs.append([AGENT_TYPE_MAPPING[_input_type](_input ) for _input_type in input_type] ) else: _inputs.append(AGENT_TYPE_MAPPING[input_type](_input ) ) # Should not raise an error _lowerCAmelCase : Dict = self.tool(*A_ ) if not isinstance(A_ , A_ ): _lowerCAmelCase : Any = [outputs] self.assertEqual(len(A_ ) , len(self.tool.outputs ) )
309
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING _UpperCamelCase = logging.get_logger(__name__) _UpperCamelCase = { "microsoft/table-transformer-detection": ( "https://huggingface.co/microsoft/table-transformer-detection/resolve/main/config.json" ), } class __lowercase (_UpperCAmelCase ): _UpperCamelCase = """table-transformer""" _UpperCamelCase = ["""past_key_values"""] _UpperCamelCase = { """hidden_size""": """d_model""", """num_attention_heads""": """encoder_attention_heads""", } def __init__( self , A_=True , A_=None , A_=3 , A_=100 , A_=6 , A_=2048 , A_=8 , A_=6 , A_=2048 , A_=8 , A_=0.0 , A_=0.0 , A_=True , A_="relu" , A_=256 , A_=0.1 , A_=0.0 , A_=0.0 , A_=0.02 , A_=1.0 , A_=False , A_="sine" , A_="resnet50" , A_=True , A_=False , A_=1 , A_=5 , A_=2 , A_=1 , A_=1 , A_=5 , A_=2 , A_=0.1 , **A_ , ) ->Any: '''simple docstring''' if backbone_config is not None and use_timm_backbone: raise ValueError('''You can\'t specify both `backbone_config` and `use_timm_backbone`.''' ) if not use_timm_backbone: if backbone_config is None: logger.info('''`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.''' ) __lowerCAmelCase : Optional[Any] = CONFIG_MAPPING['''resnet'''](out_features=['''stage4'''] ) elif isinstance(A_ , A_ ): __lowerCAmelCase : int = backbone_config.get('''model_type''' ) __lowerCAmelCase : List[str] = CONFIG_MAPPING[backbone_model_type] __lowerCAmelCase : Any = config_class.from_dict(A_ ) # set timm attributes to None __lowerCAmelCase, __lowerCAmelCase, __lowerCAmelCase : List[str] = None, None, None __lowerCAmelCase : Tuple = use_timm_backbone __lowerCAmelCase : Optional[Any] = backbone_config __lowerCAmelCase : List[str] = num_channels __lowerCAmelCase : Tuple = num_queries __lowerCAmelCase : int = d_model __lowerCAmelCase : List[Any] = encoder_ffn_dim __lowerCAmelCase : Optional[int] = encoder_layers __lowerCAmelCase : List[str] = encoder_attention_heads __lowerCAmelCase : str = decoder_ffn_dim __lowerCAmelCase : Union[str, Any] = decoder_layers __lowerCAmelCase : Any = decoder_attention_heads __lowerCAmelCase : Optional[int] = dropout __lowerCAmelCase : Any = attention_dropout __lowerCAmelCase : Tuple = activation_dropout __lowerCAmelCase : Optional[Any] = activation_function __lowerCAmelCase : List[str] = init_std __lowerCAmelCase : Tuple = init_xavier_std __lowerCAmelCase : Any = encoder_layerdrop __lowerCAmelCase : List[Any] = decoder_layerdrop __lowerCAmelCase : Optional[Any] = encoder_layers __lowerCAmelCase : Optional[Any] = auxiliary_loss __lowerCAmelCase : Optional[Any] = position_embedding_type __lowerCAmelCase : Tuple = backbone __lowerCAmelCase : Any = use_pretrained_backbone __lowerCAmelCase : int = dilation # Hungarian matcher __lowerCAmelCase : Dict = class_cost __lowerCAmelCase : List[str] = bbox_cost __lowerCAmelCase : int = giou_cost # Loss coefficients __lowerCAmelCase : Optional[Any] = mask_loss_coefficient __lowerCAmelCase : Tuple = dice_loss_coefficient __lowerCAmelCase : int = bbox_loss_coefficient __lowerCAmelCase : List[Any] = giou_loss_coefficient __lowerCAmelCase : int = eos_coefficient super().__init__(is_encoder_decoder=A_ , **A_ ) @property def UpperCamelCase__ ( self ) ->int: '''simple docstring''' return self.encoder_attention_heads @property def UpperCamelCase__ ( self ) ->int: '''simple docstring''' return self.d_model class __lowercase (_UpperCAmelCase ): _UpperCamelCase = version.parse("""1.11""" ) @property def UpperCamelCase__ ( self ) ->Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ('''pixel_mask''', {0: '''batch'''}), ] ) @property def UpperCamelCase__ ( self ) ->float: '''simple docstring''' return 1e-5 @property def UpperCamelCase__ ( self ) ->int: '''simple docstring''' return 12
275
0
import unittest from transformers import EsmConfig, is_torch_available from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers.models.esm.modeling_esmfold import EsmForProteinFolding class a__ : """simple docstring""" def __init__( self : Dict , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Any=1_3 , UpperCAmelCase__ : Dict=7 , UpperCAmelCase__ : str=False , UpperCAmelCase__ : Any=True , UpperCAmelCase__ : List[Any]=False , UpperCAmelCase__ : List[str]=False , UpperCAmelCase__ : List[Any]=1_9 , UpperCAmelCase__ : Tuple=3_2 , UpperCAmelCase__ : Any=5 , UpperCAmelCase__ : Dict=4 , UpperCAmelCase__ : List[str]=3_7 , UpperCAmelCase__ : Tuple="gelu" , UpperCAmelCase__ : Union[str, Any]=0.1 , UpperCAmelCase__ : int=0.1 , UpperCAmelCase__ : str=5_1_2 , UpperCAmelCase__ : Any=1_6 , UpperCAmelCase__ : Any=2 , UpperCAmelCase__ : Optional[Any]=0.02 , UpperCAmelCase__ : str=3 , UpperCAmelCase__ : Tuple=4 , UpperCAmelCase__ : str=None , ) ->Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = parent SCREAMING_SNAKE_CASE : Optional[int] = batch_size SCREAMING_SNAKE_CASE : Any = seq_length SCREAMING_SNAKE_CASE : Tuple = is_training SCREAMING_SNAKE_CASE : int = use_input_mask SCREAMING_SNAKE_CASE : Optional[Any] = use_token_type_ids SCREAMING_SNAKE_CASE : List[str] = use_labels SCREAMING_SNAKE_CASE : Optional[int] = vocab_size SCREAMING_SNAKE_CASE : Optional[int] = hidden_size SCREAMING_SNAKE_CASE : Any = num_hidden_layers SCREAMING_SNAKE_CASE : Optional[Any] = num_attention_heads SCREAMING_SNAKE_CASE : Union[str, Any] = intermediate_size SCREAMING_SNAKE_CASE : Tuple = hidden_act SCREAMING_SNAKE_CASE : Optional[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE : Tuple = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE : List[Any] = type_vocab_size SCREAMING_SNAKE_CASE : Tuple = type_sequence_label_size SCREAMING_SNAKE_CASE : int = initializer_range SCREAMING_SNAKE_CASE : Dict = num_labels SCREAMING_SNAKE_CASE : List[str] = num_choices SCREAMING_SNAKE_CASE : str = scope def _lowercase ( self : Tuple ) ->str: """simple docstring""" SCREAMING_SNAKE_CASE : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE : str = None if self.use_input_mask: SCREAMING_SNAKE_CASE : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE : Optional[int] = None SCREAMING_SNAKE_CASE : int = None SCREAMING_SNAKE_CASE : Tuple = None if self.use_labels: SCREAMING_SNAKE_CASE : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE : Any = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE : str = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def _lowercase ( self : Any ) ->str: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = EsmConfig( vocab_size=3_3 , hidden_size=self.hidden_size , pad_token_id=1 , 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 , is_folding_model=A_ , esmfold_config={"""trunk""": {"""num_blocks""": 2}, """fp16_esm""": False} , ) return config def _lowercase ( self : Optional[int] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[Any] ) ->str: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = EsmForProteinFolding(config=A_ ).float() model.to(A_ ) model.eval() SCREAMING_SNAKE_CASE : Union[str, Any] = model(A_ , attention_mask=A_ ) SCREAMING_SNAKE_CASE : Any = model(A_ ) SCREAMING_SNAKE_CASE : Optional[Any] = model(A_ ) self.parent.assertEqual(result.positions.shape , (8, self.batch_size, self.seq_length, 1_4, 3) ) self.parent.assertEqual(result.angles.shape , (8, self.batch_size, self.seq_length, 7, 2) ) def _lowercase ( self : Any ) ->str: """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = self.prepare_config_and_inputs() ( SCREAMING_SNAKE_CASE ) : Union[str, Any] = config_and_inputs SCREAMING_SNAKE_CASE : List[Any] = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class a__ ( _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Any =False UpperCAmelCase__ : Union[str, Any] =(EsmForProteinFolding,) if is_torch_available() else () UpperCAmelCase__ : List[str] =() UpperCAmelCase__ : Union[str, Any] ={} if is_torch_available() else {} UpperCAmelCase__ : str =False def _lowercase ( self : int ) ->Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = EsmFoldModelTester(self ) SCREAMING_SNAKE_CASE : int = ConfigTester(self , config_class=A_ , hidden_size=3_7 ) def _lowercase ( self : Optional[Any] ) ->List[str]: """simple docstring""" self.config_tester.run_common_tests() def _lowercase ( self : str ) ->int: """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A_ ) @unittest.skip("""Does not support attention outputs""" ) def _lowercase ( self : Optional[int] ) ->Optional[Any]: """simple docstring""" pass @unittest.skip def _lowercase ( self : Tuple ) ->Dict: """simple docstring""" pass @unittest.skip("""Esm does not support embedding resizing""" ) def _lowercase ( self : str ) ->int: """simple docstring""" pass @unittest.skip("""Esm does not support embedding resizing""" ) def _lowercase ( self : str ) ->Optional[Any]: """simple docstring""" pass @unittest.skip("""ESMFold does not support passing input embeds!""" ) def _lowercase ( self : Tuple ) ->Optional[Any]: """simple docstring""" pass @unittest.skip("""ESMFold does not support head pruning.""" ) def _lowercase ( self : Any ) ->Union[str, Any]: """simple docstring""" pass @unittest.skip("""ESMFold does not support head pruning.""" ) def _lowercase ( self : List[Any] ) ->Optional[int]: """simple docstring""" pass @unittest.skip("""ESMFold does not support head pruning.""" ) def _lowercase ( self : Optional[int] ) ->Optional[Any]: """simple docstring""" pass @unittest.skip("""ESMFold does not support head pruning.""" ) def _lowercase ( self : List[Any] ) ->Optional[Any]: """simple docstring""" pass @unittest.skip("""ESMFold does not support head pruning.""" ) def _lowercase ( self : Dict ) ->List[Any]: """simple docstring""" pass @unittest.skip("""ESMFold does not output hidden states in the normal way.""" ) def _lowercase ( self : Any ) ->Any: """simple docstring""" pass @unittest.skip("""ESMfold does not output hidden states in the normal way.""" ) def _lowercase ( self : Dict ) ->str: """simple docstring""" pass @unittest.skip("""ESMFold only has one output format.""" ) def _lowercase ( self : List[Any] ) ->Dict: """simple docstring""" pass @unittest.skip("""This test doesn\'t work for ESMFold and doesn\'t test core functionality""" ) def _lowercase ( self : str ) ->Optional[Any]: """simple docstring""" pass @unittest.skip("""ESMFold does not support input chunking.""" ) def _lowercase ( self : Union[str, Any] ) ->List[str]: """simple docstring""" pass @unittest.skip("""ESMFold doesn\'t respect you and it certainly doesn\'t respect your initialization arguments.""" ) def _lowercase ( self : Any ) ->Optional[int]: """simple docstring""" pass @unittest.skip("""ESMFold doesn\'t support torchscript compilation.""" ) def _lowercase ( self : int ) ->Any: """simple docstring""" pass @unittest.skip("""ESMFold doesn\'t support torchscript compilation.""" ) def _lowercase ( self : Union[str, Any] ) ->Union[str, Any]: """simple docstring""" pass @unittest.skip("""ESMFold doesn\'t support torchscript compilation.""" ) def _lowercase ( self : Union[str, Any] ) ->Dict: """simple docstring""" pass @unittest.skip("""ESMFold doesn\'t support data parallel.""" ) def _lowercase ( self : Tuple ) ->Tuple: """simple docstring""" pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def _lowercase ( self : Any ) ->List[str]: """simple docstring""" pass @require_torch class a__ ( _UpperCAmelCase ): """simple docstring""" @slow def _lowercase ( self : Optional[Any] ) ->List[str]: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = EsmForProteinFolding.from_pretrained("""facebook/esmfold_v1""" ).float() model.eval() SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([[0, 6, 4, 1_3, 5, 4, 1_6, 1_2, 1_1, 7, 2]] ) SCREAMING_SNAKE_CASE : List[str] = model(A_ )['''positions'''] SCREAMING_SNAKE_CASE : Any = torch.tensor([2.58_28, 0.79_93, -10.93_34] , dtype=torch.floataa ) self.assertTrue(torch.allclose(position_outputs[0, 0, 0, 0] , A_ , atol=1e-4 ) )
245
import itertools import os import random import tempfile import unittest import numpy as np from datasets import load_dataset from transformers import is_speech_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import WhisperFeatureExtractor if is_torch_available(): import torch _UpperCamelCase = random.Random() def _lowercase ( lowercase__ , lowercase__=1.0 , lowercase__=None , lowercase__=None ): if rng is None: __lowerCAmelCase : Any = global_rng __lowerCAmelCase : str = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch @require_torchaudio class __lowercase (unittest.TestCase ): def __init__( self , A_ , A_=7 , A_=400 , A_=2000 , A_=10 , A_=160 , A_=8 , A_=0.0 , A_=4000 , A_=False , A_=True , ) ->List[str]: '''simple docstring''' __lowerCAmelCase : Optional[int] = parent __lowerCAmelCase : Dict = batch_size __lowerCAmelCase : str = min_seq_length __lowerCAmelCase : int = max_seq_length __lowerCAmelCase : Any = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) __lowerCAmelCase : Any = padding_value __lowerCAmelCase : str = sampling_rate __lowerCAmelCase : Optional[Any] = return_attention_mask __lowerCAmelCase : Optional[Any] = do_normalize __lowerCAmelCase : Optional[Any] = feature_size __lowerCAmelCase : Optional[int] = chunk_length __lowerCAmelCase : Optional[Any] = hop_length def UpperCamelCase__ ( self ) ->Optional[Any]: '''simple docstring''' return { "feature_size": self.feature_size, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def UpperCamelCase__ ( self , A_=False , A_=False ) ->Optional[Any]: '''simple docstring''' def _flatten(A_ ): return list(itertools.chain(*A_ ) ) if equal_length: __lowerCAmelCase : str = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size __lowerCAmelCase : Any = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: __lowerCAmelCase : Optional[Any] = [np.asarray(A_ ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class __lowercase (_UpperCAmelCase , unittest.TestCase ): _UpperCamelCase = WhisperFeatureExtractor if is_speech_available() else None def UpperCamelCase__ ( self ) ->Optional[int]: '''simple docstring''' __lowerCAmelCase : Tuple = WhisperFeatureExtractionTester(self ) def UpperCamelCase__ ( self ) ->int: '''simple docstring''' __lowerCAmelCase : str = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __lowerCAmelCase : List[str] = feat_extract_first.save_pretrained(A_ )[0] check_json_file_has_correct_format(A_ ) __lowerCAmelCase : int = self.feature_extraction_class.from_pretrained(A_ ) __lowerCAmelCase : Dict = feat_extract_first.to_dict() __lowerCAmelCase : Union[str, Any] = feat_extract_second.to_dict() __lowerCAmelCase : Union[str, Any] = feat_extract_first.mel_filters __lowerCAmelCase : Dict = feat_extract_second.mel_filters self.assertTrue(np.allclose(A_ , A_ ) ) self.assertEqual(A_ , A_ ) def UpperCamelCase__ ( self ) ->str: '''simple docstring''' __lowerCAmelCase : str = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __lowerCAmelCase : Union[str, Any] = os.path.join(A_ , '''feat_extract.json''' ) feat_extract_first.to_json_file(A_ ) __lowerCAmelCase : List[str] = self.feature_extraction_class.from_json_file(A_ ) __lowerCAmelCase : List[str] = feat_extract_first.to_dict() __lowerCAmelCase : Tuple = feat_extract_second.to_dict() __lowerCAmelCase : Any = feat_extract_first.mel_filters __lowerCAmelCase : List[str] = feat_extract_second.mel_filters self.assertTrue(np.allclose(A_ , A_ ) ) self.assertEqual(A_ , A_ ) def UpperCamelCase__ ( self ) ->List[Any]: '''simple docstring''' __lowerCAmelCase : List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 __lowerCAmelCase : Dict = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] __lowerCAmelCase : Dict = [np.asarray(A_ ) for speech_input in speech_inputs] # Test feature size __lowerCAmelCase : Tuple = feature_extractor(A_ , padding='''max_length''' , return_tensors='''np''' ).input_features self.assertTrue(input_features.ndim == 3 ) self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames ) self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size ) # Test not batched input __lowerCAmelCase : Dict = feature_extractor(speech_inputs[0] , return_tensors='''np''' ).input_features __lowerCAmelCase : List[str] = feature_extractor(np_speech_inputs[0] , return_tensors='''np''' ).input_features self.assertTrue(np.allclose(A_ , A_ , atol=1e-3 ) ) # Test batched __lowerCAmelCase : Union[str, Any] = feature_extractor(A_ , return_tensors='''np''' ).input_features __lowerCAmelCase : List[Any] = feature_extractor(A_ , return_tensors='''np''' ).input_features for enc_seq_a, enc_seq_a in zip(A_ , A_ ): self.assertTrue(np.allclose(A_ , A_ , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. __lowerCAmelCase : int = [floats_list((1, x) )[0] for x in (800, 800, 800)] __lowerCAmelCase : Optional[int] = np.asarray(A_ ) __lowerCAmelCase : Dict = feature_extractor(A_ , return_tensors='''np''' ).input_features __lowerCAmelCase : Any = feature_extractor(A_ , return_tensors='''np''' ).input_features for enc_seq_a, enc_seq_a in zip(A_ , A_ ): self.assertTrue(np.allclose(A_ , A_ , atol=1e-3 ) ) # Test truncation required __lowerCAmelCase : Optional[int] = [floats_list((1, x) )[0] for x in range(200 , (feature_extractor.n_samples + 500) , 200 )] __lowerCAmelCase : Dict = [np.asarray(A_ ) for speech_input in speech_inputs] __lowerCAmelCase : Tuple = [x[: feature_extractor.n_samples] for x in speech_inputs] __lowerCAmelCase : Optional[int] = [np.asarray(A_ ) for speech_input in speech_inputs_truncated] __lowerCAmelCase : Any = feature_extractor(A_ , return_tensors='''np''' ).input_features __lowerCAmelCase : List[str] = feature_extractor(A_ , return_tensors='''np''' ).input_features for enc_seq_a, enc_seq_a in zip(A_ , A_ ): self.assertTrue(np.allclose(A_ , A_ , atol=1e-3 ) ) def UpperCamelCase__ ( self ) ->Dict: '''simple docstring''' import torch __lowerCAmelCase : Tuple = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __lowerCAmelCase : List[Any] = np.random.rand(100 , 32 ).astype(np.floataa ) __lowerCAmelCase : Any = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: __lowerCAmelCase : Tuple = feature_extractor.pad([{'''input_features''': inputs}] , return_tensors='''np''' ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) __lowerCAmelCase : int = feature_extractor.pad([{'''input_features''': inputs}] , return_tensors='''pt''' ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def UpperCamelCase__ ( self , A_ ) ->str: '''simple docstring''' __lowerCAmelCase : Any = load_dataset('''hf-internal-testing/librispeech_asr_dummy''' , '''clean''' , split='''validation''' ) # automatic decoding with librispeech __lowerCAmelCase : Union[str, Any] = ds.sort('''id''' ).select(range(A_ ) )[:num_samples]['''audio'''] return [x["array"] for x in speech_samples] def UpperCamelCase__ ( self ) ->int: '''simple docstring''' __lowerCAmelCase : Optional[int] = torch.tensor( [ 0.1_193, -0.0_946, -0.1_098, -0.0_196, 0.0_225, -0.0_690, -0.1_736, 0.0_951, 0.0_971, -0.0_817, -0.0_702, 0.0_162, 0.0_260, 0.0_017, -0.0_192, -0.1_678, 0.0_709, -0.1_867, -0.0_655, -0.0_274, -0.0_234, -0.1_884, -0.0_516, -0.0_554, -0.0_274, -0.1_425, -0.1_423, 0.0_837, 0.0_377, -0.0_854 ] ) # fmt: on __lowerCAmelCase : int = self._load_datasamples(1 ) __lowerCAmelCase : Any = WhisperFeatureExtractor() __lowerCAmelCase : Optional[Any] = feature_extractor(A_ , return_tensors='''pt''' ).input_features self.assertEqual(input_features.shape , (1, 80, 3000) ) self.assertTrue(torch.allclose(input_features[0, 0, :30] , A_ , atol=1e-4 ) ) def UpperCamelCase__ ( self ) ->Any: '''simple docstring''' __lowerCAmelCase : Tuple = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __lowerCAmelCase : str = self._load_datasamples(1 )[0] __lowerCAmelCase : Optional[Any] = ((audio - audio.min()) / (audio.max() - audio.min())) * 6_5535 # Rescale to [0, 65535] to show issue __lowerCAmelCase : Union[str, Any] = feat_extract.zero_mean_unit_var_norm([audio] , attention_mask=A_ )[0] self.assertTrue(np.all(np.mean(A_ ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(A_ ) - 1 ) < 1e-3 ) )
275
0
from __future__ import annotations def lowerCAmelCase_ ( __lowerCamelCase ): # This function is recursive __snake_case : str = len(lowercase__ ) # If the array contains only one element, we return it (it's the stop condition of # recursion) if array_length <= 1: return array # Else __snake_case : List[Any] = array[0] __snake_case : List[Any] = False __snake_case : int = 1 __snake_case : list[int] = [] while not is_found and i < array_length: if array[i] < pivot: __snake_case : str = True __snake_case : Union[str, Any] = [element for element in array[i:] if element >= array[i]] __snake_case : List[str] = longest_subsequence(lowercase__ ) if len(lowercase__ ) > len(lowercase__ ): __snake_case : Optional[int] = temp_array else: i += 1 __snake_case : Union[str, Any] = [element for element in array[1:] if element >= pivot] __snake_case : List[str] = [pivot, *longest_subsequence(lowercase__ )] if len(lowercase__ ) > len(lowercase__ ): return temp_array else: return longest_subseq if __name__ == "__main__": import doctest doctest.testmod()
123
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConfig, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaForCTC, WavaVecaForPreTraining, WavaVecaProcessor, logging, ) from transformers.models.wavaveca.modeling_wavaveca import WavaVecaForSequenceClassification logging.set_verbosity_info() _UpperCamelCase = logging.get_logger(__name__) _UpperCamelCase = { "post_extract_proj": "feature_projection.projection", "encoder.pos_conv.0": "encoder.pos_conv_embed.conv", "self_attn.k_proj": "encoder.layers.*.attention.k_proj", "self_attn.v_proj": "encoder.layers.*.attention.v_proj", "self_attn.q_proj": "encoder.layers.*.attention.q_proj", "self_attn.out_proj": "encoder.layers.*.attention.out_proj", "self_attn_layer_norm": "encoder.layers.*.layer_norm", "fc1": "encoder.layers.*.feed_forward.intermediate_dense", "fc2": "encoder.layers.*.feed_forward.output_dense", "final_layer_norm": "encoder.layers.*.final_layer_norm", "encoder.layer_norm": "encoder.layer_norm", "adapter_layer": "encoder.layers.*.adapter_layer", "w2v_model.layer_norm": "feature_projection.layer_norm", "quantizer.weight_proj": "quantizer.weight_proj", "quantizer.vars": "quantizer.codevectors", "project_q": "project_q", "final_proj": "project_hid", "w2v_encoder.proj": "lm_head", "mask_emb": "masked_spec_embed", "pooling_layer.linear": "projector", "pooling_layer.projection": "classifier", } _UpperCamelCase = [ "lm_head", "quantizer.weight_proj", "quantizer.codevectors", "project_q", "project_hid", "projector", "classifier", ] def _lowercase ( lowercase__ ): __lowerCAmelCase : List[str] = {} with open(lowercase__ , '''r''' ) as file: for line_number, line in enumerate(lowercase__ ): __lowerCAmelCase : Any = line.strip() if line: __lowerCAmelCase : Dict = line.split() __lowerCAmelCase : str = line_number __lowerCAmelCase : List[str] = words[0] __lowerCAmelCase : Any = value return result def _lowercase ( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): for attribute in key.split('''.''' ): __lowerCAmelCase : List[Any] = getattr(lowercase__ , lowercase__ ) __lowerCAmelCase : Any = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(lowercase__ ): __lowerCAmelCase : Tuple = PARAM_MAPPING[full_name.split('''.''' )[-1]] __lowerCAmelCase : List[Any] = '''param''' if weight_type is not None and weight_type != "param": __lowerCAmelCase : str = getattr(lowercase__ , lowercase__ ).shape elif weight_type is not None and weight_type == "param": __lowerCAmelCase : Dict = hf_pointer for attribute in hf_param_name.split('''.''' ): __lowerCAmelCase : Dict = getattr(lowercase__ , lowercase__ ) __lowerCAmelCase : str = shape_pointer.shape # let's reduce dimension __lowerCAmelCase : Any = value[0] else: __lowerCAmelCase : str = hf_pointer.shape if hf_shape != value.shape: raise ValueError( f"""Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be""" f""" {value.shape} for {full_name}""" ) if weight_type == "weight": __lowerCAmelCase : Union[str, Any] = value elif weight_type == "weight_g": __lowerCAmelCase : List[str] = value elif weight_type == "weight_v": __lowerCAmelCase : int = value elif weight_type == "bias": __lowerCAmelCase : Union[str, Any] = value elif weight_type == "param": for attribute in hf_param_name.split('''.''' ): __lowerCAmelCase : Dict = getattr(lowercase__ , lowercase__ ) __lowerCAmelCase : Tuple = value else: __lowerCAmelCase : Any = value logger.info(f"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def _lowercase ( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): __lowerCAmelCase : Any = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(lowercase__ ): __lowerCAmelCase : str = PARAM_MAPPING[full_name.split('''.''' )[-1]] __lowerCAmelCase : int = '''param''' if weight_type is not None and weight_type != "param": __lowerCAmelCase : Tuple = '''.'''.join([key, weight_type] ) elif weight_type is not None and weight_type == "param": __lowerCAmelCase : List[str] = '''.'''.join([key, hf_param_name] ) else: __lowerCAmelCase : Optional[int] = key __lowerCAmelCase : Union[str, Any] = value if '''lm_head''' in full_key else value[0] _UpperCamelCase = { "W_a": "linear_1.weight", "W_b": "linear_2.weight", "b_a": "linear_1.bias", "b_b": "linear_2.bias", "ln_W": "norm.weight", "ln_b": "norm.bias", } def _lowercase ( lowercase__ , lowercase__ , lowercase__=None , lowercase__=None ): __lowerCAmelCase : Any = False for key, mapped_key in MAPPING.items(): __lowerCAmelCase : Tuple = '''wav2vec2.''' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0]: __lowerCAmelCase : Optional[Any] = True if "*" in mapped_key: __lowerCAmelCase : List[str] = name.split(lowercase__ )[0].split('''.''' )[-2] __lowerCAmelCase : Dict = mapped_key.replace('''*''' , lowercase__ ) if "weight_g" in name: __lowerCAmelCase : List[Any] = '''weight_g''' elif "weight_v" in name: __lowerCAmelCase : List[Any] = '''weight_v''' elif "bias" in name: __lowerCAmelCase : Any = '''bias''' elif "weight" in name: # TODO: don't match quantizer.weight_proj __lowerCAmelCase : int = '''weight''' else: __lowerCAmelCase : Any = None if hf_dict is not None: rename_dict(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) else: set_recursively(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) return is_used return is_used def _lowercase ( lowercase__ , lowercase__ , lowercase__ ): __lowerCAmelCase : List[str] = [] __lowerCAmelCase : Optional[Any] = fairseq_model.state_dict() __lowerCAmelCase : Tuple = hf_model.wavaveca.feature_extractor for name, value in fairseq_dict.items(): __lowerCAmelCase : Any = False if "conv_layers" in name: load_conv_layer( lowercase__ , lowercase__ , lowercase__ , lowercase__ , hf_model.config.feat_extract_norm == '''group''' , ) __lowerCAmelCase : int = True else: __lowerCAmelCase : Dict = load_wavaveca_layer(lowercase__ , lowercase__ , lowercase__ ) if not is_used: unused_weights.append(lowercase__ ) logger.warning(f"""Unused weights: {unused_weights}""" ) def _lowercase ( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): __lowerCAmelCase : Any = full_name.split('''conv_layers.''' )[-1] __lowerCAmelCase : List[str] = name.split('''.''' ) __lowerCAmelCase : Any = int(items[0] ) __lowerCAmelCase : str = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) __lowerCAmelCase : List[str] = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) __lowerCAmelCase : List[str] = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.""" ) __lowerCAmelCase : List[str] = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.""" ) __lowerCAmelCase : Optional[int] = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(lowercase__ ) @torch.no_grad() def _lowercase ( lowercase__ , lowercase__ , lowercase__=None , lowercase__=None , lowercase__=True , lowercase__=False ): if config_path is not None: __lowerCAmelCase : Union[str, Any] = WavaVecaConfig.from_pretrained(lowercase__ ) else: __lowerCAmelCase : Optional[int] = WavaVecaConfig() if is_seq_class: __lowerCAmelCase : Optional[Any] = read_txt_into_dict(lowercase__ ) __lowerCAmelCase : int = idalabel __lowerCAmelCase : Optional[int] = WavaVecaForSequenceClassification(lowercase__ ) __lowerCAmelCase : List[str] = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6_0_0_0 , padding_value=0 , do_normalize=lowercase__ , return_attention_mask=lowercase__ , ) feature_extractor.save_pretrained(lowercase__ ) elif is_finetuned: if dict_path: __lowerCAmelCase : List[str] = Dictionary.load(lowercase__ ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq __lowerCAmelCase : List[Any] = target_dict.pad_index __lowerCAmelCase : List[Any] = target_dict.bos_index __lowerCAmelCase : Optional[int] = target_dict.eos_index __lowerCAmelCase : Any = len(target_dict.symbols ) __lowerCAmelCase : Union[str, Any] = os.path.join(lowercase__ , '''vocab.json''' ) if not os.path.isdir(lowercase__ ): logger.error('''--pytorch_dump_folder_path ({}) should be a directory'''.format(lowercase__ ) ) return os.makedirs(lowercase__ , exist_ok=lowercase__ ) __lowerCAmelCase : Optional[int] = target_dict.indices # fairseq has the <pad> and <s> switched __lowerCAmelCase : List[str] = 0 __lowerCAmelCase : int = 1 with open(lowercase__ , '''w''' , encoding='''utf-8''' ) as vocab_handle: json.dump(lowercase__ , lowercase__ ) __lowerCAmelCase : Dict = WavaVecaCTCTokenizer( lowercase__ , 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=lowercase__ , ) __lowerCAmelCase : List[str] = True if config.feat_extract_norm == '''layer''' else False __lowerCAmelCase : List[str] = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6_0_0_0 , padding_value=0 , do_normalize=lowercase__ , return_attention_mask=lowercase__ , ) __lowerCAmelCase : List[Any] = WavaVecaProcessor(feature_extractor=lowercase__ , tokenizer=lowercase__ ) processor.save_pretrained(lowercase__ ) __lowerCAmelCase : str = WavaVecaForCTC(lowercase__ ) else: __lowerCAmelCase : Any = WavaVecaForPreTraining(lowercase__ ) if is_finetuned or is_seq_class: __lowerCAmelCase, __lowerCAmelCase, __lowerCAmelCase : Optional[int] = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'''data''': '''/'''.join(dict_path.split('''/''' )[:-1] )} ) else: __lowerCAmelCase : Union[str, Any] = argparse.Namespace(task='''audio_pretraining''' ) __lowerCAmelCase : str = fairseq.tasks.setup_task(lowercase__ ) __lowerCAmelCase, __lowerCAmelCase, __lowerCAmelCase : Dict = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] , task=lowercase__ ) __lowerCAmelCase : int = model[0].eval() recursively_load_weights(lowercase__ , lowercase__ , not is_finetuned ) hf_wavavec.save_pretrained(lowercase__ ) if __name__ == "__main__": _UpperCamelCase = 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( "--not_finetuned", action="store_true", help="Whether the model to convert is a fine-tuned model or not" ) parser.add_argument( "--is_seq_class", action="store_true", help="Whether the model to convert is a fine-tuned sequence classification model or not", ) _UpperCamelCase = parser.parse_args() _UpperCamelCase = not args.not_finetuned and not args.is_seq_class convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, is_finetuned, args.is_seq_class, )
275
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available UpperCAmelCase = {"""configuration_yolos""": ["""YOLOS_PRETRAINED_CONFIG_ARCHIVE_MAP""", """YolosConfig""", """YolosOnnxConfig"""]} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = ["""YolosFeatureExtractor"""] UpperCAmelCase = ["""YolosImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = [ """YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST""", """YolosForObjectDetection""", """YolosModel""", """YolosPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_yolos import YOLOS_PRETRAINED_CONFIG_ARCHIVE_MAP, YolosConfig, YolosOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_yolos import YolosFeatureExtractor from .image_processing_yolos import YolosImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_yolos import ( YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST, YolosForObjectDetection, YolosModel, YolosPreTrainedModel, ) else: import sys UpperCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
256
from ....configuration_utils import PretrainedConfig from ....utils import logging _UpperCamelCase = logging.get_logger(__name__) _UpperCamelCase = { "CarlCochet/trajectory-transformer-halfcheetah-medium-v2": ( "https://huggingface.co/CarlCochet/trajectory-transformer-halfcheetah-medium-v2/resolve/main/config.json" ), # See all TrajectoryTransformer models at https://huggingface.co/models?filter=trajectory_transformer } class __lowercase (_UpperCAmelCase ): _UpperCamelCase = """trajectory_transformer""" _UpperCamelCase = ["""past_key_values"""] _UpperCamelCase = { """hidden_size""": """n_embd""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self , A_=100 , A_=5 , A_=1 , A_=1 , A_=249 , A_=6 , A_=17 , A_=25 , A_=4 , A_=4 , A_=128 , A_=0.1 , A_=0.1 , A_=0.1 , A_=0.0_006 , A_=512 , A_=0.02 , A_=1e-12 , A_=1 , A_=True , A_=1 , A_=5_0256 , A_=5_0256 , **A_ , ) ->int: '''simple docstring''' __lowerCAmelCase : Any = vocab_size __lowerCAmelCase : Tuple = action_weight __lowerCAmelCase : Tuple = reward_weight __lowerCAmelCase : Union[str, Any] = value_weight __lowerCAmelCase : List[str] = max_position_embeddings __lowerCAmelCase : str = block_size __lowerCAmelCase : Optional[Any] = action_dim __lowerCAmelCase : Union[str, Any] = observation_dim __lowerCAmelCase : Union[str, Any] = transition_dim __lowerCAmelCase : Dict = learning_rate __lowerCAmelCase : Any = n_layer __lowerCAmelCase : Any = n_head __lowerCAmelCase : Optional[int] = n_embd __lowerCAmelCase : str = embd_pdrop __lowerCAmelCase : Dict = attn_pdrop __lowerCAmelCase : Optional[int] = resid_pdrop __lowerCAmelCase : Union[str, Any] = initializer_range __lowerCAmelCase : Optional[int] = layer_norm_eps __lowerCAmelCase : Any = kaiming_initializer_range __lowerCAmelCase : List[str] = use_cache super().__init__(pad_token_id=A_ , bos_token_id=A_ , eos_token_id=A_ , **A_ )
275
0
'''simple docstring''' import argparse from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_controlnet_from_original_ckpt if __name__ == "__main__": lowerCAmelCase_ : 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=5_12, type=int, help=( 'The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2' ' Base. Use 768 for Stable Diffusion v2.' ), ) parser.add_argument( '--extract_ema', action='store_true', help=( 'Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights' ' or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield' ' higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning.' ), ) parser.add_argument( '--upcast_attention', action='store_true', help=( 'Whether the attention computation should always be upcasted. This is necessary when running stable' ' diffusion 2.1.' ), ) parser.add_argument( '--from_safetensors', action='store_true', help='If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.', ) parser.add_argument( '--to_safetensors', action='store_true', help='Whether to store pipeline in safetensors format or not.', ) parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') parser.add_argument('--device', type=str, help='Device to use (e.g. cpu, cuda:0, cuda:1, etc.)') def _lowerCamelCase ( lowercase : List[str] ) -> Optional[int]: 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) lowerCAmelCase_ : Union[str, Any] = parser.parse_args() lowerCAmelCase_ : str = 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)
63
def _lowercase ( lowercase__ , lowercase__ ): if a < 0 or b < 0: raise ValueError('''the value of both inputs must be positive''' ) __lowerCAmelCase : int = str(bin(lowercase__ ) )[2:] # remove the leading "0b" __lowerCAmelCase : Any = str(bin(lowercase__ ) )[2:] __lowerCAmelCase : List[str] = max(len(lowercase__ ) , len(lowercase__ ) ) return "0b" + "".join( str(int('''1''' in (char_a, char_b) ) ) for char_a, char_b in zip(a_binary.zfill(lowercase__ ) , b_binary.zfill(lowercase__ ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
275
0
import os import unittest from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import ( VOCAB_FILES_NAMES, BasicTokenizer, BertTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase , unittest.TestCase ): __lowerCAmelCase = BertTokenizer __lowerCAmelCase = BertTokenizerFast __lowerCAmelCase = True __lowerCAmelCase = True __lowerCAmelCase = filter_non_english def lowerCamelCase_ ( self : List[str] ): """simple docstring""" super().setUp() UpperCamelCase = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] UpperCamelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) def lowerCamelCase_ ( self : Optional[int] , lowerCamelCase_ : Tuple ): """simple docstring""" UpperCamelCase = '''UNwant\u00E9d,running''' UpperCamelCase = '''unwanted, running''' return input_text, output_text def lowerCamelCase_ ( self : Union[str, Any] ): """simple docstring""" UpperCamelCase = self.tokenizer_class(self.vocab_file ) UpperCamelCase = tokenizer.tokenize("""UNwant\u00E9d,running""" ) self.assertListEqual(A_ , ["""un""", """##want""", """##ed""", """,""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(A_ ) , [9, 6, 7, 12, 10, 11] ) def lowerCamelCase_ ( self : Optional[Any] ): """simple docstring""" if not self.test_rust_tokenizer: return UpperCamelCase = self.get_tokenizer() UpperCamelCase = self.get_rust_tokenizer() UpperCamelCase = '''UNwant\u00E9d,running''' UpperCamelCase = tokenizer.tokenize(A_ ) UpperCamelCase = rust_tokenizer.tokenize(A_ ) self.assertListEqual(A_ , A_ ) UpperCamelCase = tokenizer.encode(A_ , add_special_tokens=A_ ) UpperCamelCase = rust_tokenizer.encode(A_ , add_special_tokens=A_ ) self.assertListEqual(A_ , A_ ) UpperCamelCase = self.get_rust_tokenizer() UpperCamelCase = tokenizer.encode(A_ ) UpperCamelCase = rust_tokenizer.encode(A_ ) self.assertListEqual(A_ , A_ ) # With lower casing UpperCamelCase = self.get_tokenizer(do_lower_case=A_ ) UpperCamelCase = self.get_rust_tokenizer(do_lower_case=A_ ) UpperCamelCase = '''UNwant\u00E9d,running''' UpperCamelCase = tokenizer.tokenize(A_ ) UpperCamelCase = rust_tokenizer.tokenize(A_ ) self.assertListEqual(A_ , A_ ) UpperCamelCase = tokenizer.encode(A_ , add_special_tokens=A_ ) UpperCamelCase = rust_tokenizer.encode(A_ , add_special_tokens=A_ ) self.assertListEqual(A_ , A_ ) UpperCamelCase = self.get_rust_tokenizer() UpperCamelCase = tokenizer.encode(A_ ) UpperCamelCase = rust_tokenizer.encode(A_ ) self.assertListEqual(A_ , A_ ) def lowerCamelCase_ ( self : Union[str, Any] ): """simple docstring""" UpperCamelCase = BasicTokenizer() self.assertListEqual(tokenizer.tokenize("""ah\u535A\u63A8zz""" ) , ["""ah""", """\u535A""", """\u63A8""", """zz"""] ) def lowerCamelCase_ ( self : Optional[int] ): """simple docstring""" UpperCamelCase = BasicTokenizer(do_lower_case=A_ ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? """ ) , ["""hello""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def lowerCamelCase_ ( self : Dict ): """simple docstring""" UpperCamelCase = BasicTokenizer(do_lower_case=A_ , strip_accents=A_ ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hällo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""h\u00E9llo"""] ) def lowerCamelCase_ ( self : List[str] ): """simple docstring""" UpperCamelCase = BasicTokenizer(do_lower_case=A_ , strip_accents=A_ ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hallo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def lowerCamelCase_ ( self : str ): """simple docstring""" UpperCamelCase = BasicTokenizer(do_lower_case=A_ ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hallo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def lowerCamelCase_ ( self : str ): """simple docstring""" UpperCamelCase = BasicTokenizer(do_lower_case=A_ ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? """ ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def lowerCamelCase_ ( self : Union[str, Any] ): """simple docstring""" UpperCamelCase = BasicTokenizer(do_lower_case=A_ , strip_accents=A_ ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""HäLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def lowerCamelCase_ ( self : List[str] ): """simple docstring""" UpperCamelCase = BasicTokenizer(do_lower_case=A_ , strip_accents=A_ ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""HaLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def lowerCamelCase_ ( self : Dict ): """simple docstring""" UpperCamelCase = BasicTokenizer(do_lower_case=A_ , never_split=["""[UNK]"""] ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? [UNK]""" ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?""", """[UNK]"""] ) def lowerCamelCase_ ( self : Tuple ): """simple docstring""" UpperCamelCase = BasicTokenizer() UpperCamelCase = '''a\n\'ll !!to?\'d of, can\'t.''' UpperCamelCase = ['''a''', '''\'''', '''ll''', '''!''', '''!''', '''to''', '''?''', '''\'''', '''d''', '''of''', ''',''', '''can''', '''\'''', '''t''', '''.'''] self.assertListEqual(tokenizer.tokenize(A_ ) , A_ ) def lowerCamelCase_ ( self : Optional[int] ): """simple docstring""" UpperCamelCase = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing'''] UpperCamelCase = {} for i, token in enumerate(A_ ): UpperCamelCase = i UpperCamelCase = WordpieceTokenizer(vocab=A_ , unk_token="""[UNK]""" ) self.assertListEqual(tokenizer.tokenize("""""" ) , [] ) self.assertListEqual(tokenizer.tokenize("""unwanted running""" ) , ["""un""", """##want""", """##ed""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.tokenize("""unwantedX running""" ) , ["""[UNK]""", """runn""", """##ing"""] ) def lowerCamelCase_ ( self : Union[str, Any] ): """simple docstring""" self.assertTrue(_is_whitespace(""" """ ) ) self.assertTrue(_is_whitespace("""\t""" ) ) self.assertTrue(_is_whitespace("""\r""" ) ) self.assertTrue(_is_whitespace("""\n""" ) ) self.assertTrue(_is_whitespace("""\u00A0""" ) ) self.assertFalse(_is_whitespace("""A""" ) ) self.assertFalse(_is_whitespace("""-""" ) ) def lowerCamelCase_ ( self : Optional[int] ): """simple docstring""" self.assertTrue(_is_control("""\u0005""" ) ) self.assertFalse(_is_control("""A""" ) ) self.assertFalse(_is_control(""" """ ) ) self.assertFalse(_is_control("""\t""" ) ) self.assertFalse(_is_control("""\r""" ) ) def lowerCamelCase_ ( self : Any ): """simple docstring""" self.assertTrue(_is_punctuation("""-""" ) ) self.assertTrue(_is_punctuation("""$""" ) ) self.assertTrue(_is_punctuation("""`""" ) ) self.assertTrue(_is_punctuation(""".""" ) ) self.assertFalse(_is_punctuation("""A""" ) ) self.assertFalse(_is_punctuation(""" """ ) ) def lowerCamelCase_ ( self : int ): """simple docstring""" UpperCamelCase = self.get_tokenizer() UpperCamelCase = self.get_rust_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(A_ ) for t in ["""Test""", """\xad""", """test"""]] , [["""[UNK]"""], [], ["""[UNK]"""]] ) self.assertListEqual( [rust_tokenizer.tokenize(A_ ) for t in ["""Test""", """\xad""", """test"""]] , [["""[UNK]"""], [], ["""[UNK]"""]] ) @slow def lowerCamelCase_ ( self : int ): """simple docstring""" UpperCamelCase = self.tokenizer_class.from_pretrained("""bert-base-uncased""" ) UpperCamelCase = tokenizer.encode("""sequence builders""" , add_special_tokens=A_ ) UpperCamelCase = tokenizer.encode("""multi-sequence build""" , add_special_tokens=A_ ) UpperCamelCase = tokenizer.build_inputs_with_special_tokens(A_ ) UpperCamelCase = tokenizer.build_inputs_with_special_tokens(A_ , A_ ) assert encoded_sentence == [101] + text + [102] assert encoded_pair == [101] + text + [102] + text_a + [102] def lowerCamelCase_ ( self : List[Any] ): """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): UpperCamelCase = self.rust_tokenizer_class.from_pretrained(A_ , **A_ ) UpperCamelCase = f"""A, naïve {tokenizer_r.mask_token} AllenNLP sentence.""" UpperCamelCase = tokenizer_r.encode_plus( A_ , return_attention_mask=A_ , return_token_type_ids=A_ , return_offsets_mapping=A_ , add_special_tokens=A_ , ) UpperCamelCase = tokenizer_r.do_lower_case if hasattr(A_ , """do_lower_case""" ) else False UpperCamelCase = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), '''A'''), ((1, 2), ''','''), ((3, 5), '''na'''), ((5, 6), '''##ï'''), ((6, 8), '''##ve'''), ((9, 15), tokenizer_r.mask_token), ((16, 21), '''Allen'''), ((21, 23), '''##NL'''), ((23, 24), '''##P'''), ((25, 33), '''sentence'''), ((33, 34), '''.'''), ((0, 0), tokenizer_r.sep_token), ] if not do_lower_case else [ ((0, 0), tokenizer_r.cls_token), ((0, 1), '''a'''), ((1, 2), ''','''), ((3, 8), '''naive'''), ((9, 15), tokenizer_r.mask_token), ((16, 21), '''allen'''), ((21, 23), '''##nl'''), ((23, 24), '''##p'''), ((25, 33), '''sentence'''), ((33, 34), '''.'''), ((0, 0), tokenizer_r.sep_token), ] ) self.assertEqual( [e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens["""input_ids"""] ) ) self.assertEqual([e[0] for e in expected_results] , tokens["""offset_mapping"""] ) def lowerCamelCase_ ( self : List[str] ): """simple docstring""" UpperCamelCase = ['''的''', '''人''', '''有'''] UpperCamelCase = ''''''.join(A_ ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): UpperCamelCase = True UpperCamelCase = self.tokenizer_class.from_pretrained(A_ , **A_ ) UpperCamelCase = self.rust_tokenizer_class.from_pretrained(A_ , **A_ ) UpperCamelCase = tokenizer_p.encode(A_ , add_special_tokens=A_ ) UpperCamelCase = tokenizer_r.encode(A_ , add_special_tokens=A_ ) UpperCamelCase = tokenizer_r.convert_ids_to_tokens(A_ ) UpperCamelCase = tokenizer_p.convert_ids_to_tokens(A_ ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(A_ , A_ ) self.assertListEqual(A_ , A_ ) UpperCamelCase = False UpperCamelCase = self.rust_tokenizer_class.from_pretrained(A_ , **A_ ) UpperCamelCase = self.tokenizer_class.from_pretrained(A_ , **A_ ) UpperCamelCase = tokenizer_r.encode(A_ , add_special_tokens=A_ ) UpperCamelCase = tokenizer_p.encode(A_ , add_special_tokens=A_ ) UpperCamelCase = tokenizer_r.convert_ids_to_tokens(A_ ) UpperCamelCase = tokenizer_p.convert_ids_to_tokens(A_ ) # it is expected that only the first Chinese character is not preceded by "##". UpperCamelCase = [ f"""##{token}""" if idx != 0 else token for idx, token in enumerate(A_ ) ] self.assertListEqual(A_ , A_ ) self.assertListEqual(A_ , A_ )
343
import math from typing import Dict, Iterable, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, get_image_size, is_torch_available, is_torch_tensor, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_torch_available(): import torch if is_vision_available(): import PIL _UpperCamelCase = logging.get_logger(__name__) def _lowercase ( lowercase__ , lowercase__ , lowercase__ , lowercase__ ): def constraint_to_multiple_of(lowercase__ , lowercase__ , lowercase__=0 , lowercase__=None ): __lowerCAmelCase : int = round(val / multiple ) * multiple if max_val is not None and x > max_val: __lowerCAmelCase : Optional[int] = math.floor(val / multiple ) * multiple if x < min_val: __lowerCAmelCase : Any = math.ceil(val / multiple ) * multiple return x __lowerCAmelCase : Dict = (output_size, output_size) if isinstance(lowercase__ , lowercase__ ) else output_size __lowerCAmelCase, __lowerCAmelCase : Optional[Any] = get_image_size(lowercase__ ) __lowerCAmelCase, __lowerCAmelCase : int = output_size # determine new height and width __lowerCAmelCase : Optional[Any] = output_height / input_height __lowerCAmelCase : List[Any] = output_width / input_width if keep_aspect_ratio: # scale as little as possible if abs(1 - scale_width ) < abs(1 - scale_height ): # fit width __lowerCAmelCase : str = scale_width else: # fit height __lowerCAmelCase : str = scale_height __lowerCAmelCase : Any = constraint_to_multiple_of(scale_height * input_height , multiple=lowercase__ ) __lowerCAmelCase : Union[str, Any] = constraint_to_multiple_of(scale_width * input_width , multiple=lowercase__ ) return (new_height, new_width) class __lowercase (_UpperCAmelCase ): _UpperCamelCase = ["""pixel_values"""] def __init__( self , A_ = True , A_ = None , A_ = PILImageResampling.BILINEAR , A_ = False , A_ = 1 , A_ = True , A_ = 1 / 255 , A_ = True , A_ = None , A_ = None , **A_ , ) ->None: '''simple docstring''' super().__init__(**A_ ) __lowerCAmelCase : Union[str, Any] = size if size is not None else {'''height''': 384, '''width''': 384} __lowerCAmelCase : Dict = get_size_dict(A_ ) __lowerCAmelCase : Optional[Any] = do_resize __lowerCAmelCase : int = size __lowerCAmelCase : Dict = keep_aspect_ratio __lowerCAmelCase : List[Any] = ensure_multiple_of __lowerCAmelCase : Tuple = resample __lowerCAmelCase : Dict = do_rescale __lowerCAmelCase : Any = rescale_factor __lowerCAmelCase : List[Any] = do_normalize __lowerCAmelCase : Optional[int] = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN __lowerCAmelCase : Optional[int] = image_std if image_std is not None else IMAGENET_STANDARD_STD def UpperCamelCase__ ( self , A_ , A_ , A_ = False , A_ = 1 , A_ = PILImageResampling.BICUBIC , A_ = None , **A_ , ) ->np.ndarray: '''simple docstring''' __lowerCAmelCase : int = get_size_dict(A_ ) if "height" not in size or "width" not in size: raise ValueError(f"""The size dictionary must contain the keys 'height' and 'width'. Got {size.keys()}""" ) __lowerCAmelCase : Union[str, Any] = get_resize_output_image_size( A_ , output_size=(size['''height'''], size['''width''']) , keep_aspect_ratio=A_ , multiple=A_ , ) return resize(A_ , size=A_ , resample=A_ , data_format=A_ , **A_ ) def UpperCamelCase__ ( self , A_ , A_ , A_ = None , **A_ , ) ->Dict: '''simple docstring''' return rescale(A_ , scale=A_ , data_format=A_ , **A_ ) def UpperCamelCase__ ( self , A_ , A_ , A_ , A_ = None , **A_ , ) ->np.ndarray: '''simple docstring''' return normalize(A_ , mean=A_ , std=A_ , data_format=A_ , **A_ ) def UpperCamelCase__ ( self , A_ , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = ChannelDimension.FIRST , **A_ , ) ->PIL.Image.Image: '''simple docstring''' __lowerCAmelCase : int = do_resize if do_resize is not None else self.do_resize __lowerCAmelCase : Optional[int] = size if size is not None else self.size __lowerCAmelCase : Union[str, Any] = get_size_dict(A_ ) __lowerCAmelCase : List[Any] = keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio __lowerCAmelCase : Optional[int] = ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of __lowerCAmelCase : Tuple = resample if resample is not None else self.resample __lowerCAmelCase : Optional[int] = do_rescale if do_rescale is not None else self.do_rescale __lowerCAmelCase : Union[str, Any] = rescale_factor if rescale_factor is not None else self.rescale_factor __lowerCAmelCase : Tuple = do_normalize if do_normalize is not None else self.do_normalize __lowerCAmelCase : str = image_mean if image_mean is not None else self.image_mean __lowerCAmelCase : Optional[Any] = image_std if image_std is not None else self.image_std __lowerCAmelCase : Optional[Any] = make_list_of_images(A_ ) if not valid_images(A_ ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None or resample is None: raise ValueError('''Size and resample must be specified if do_resize is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('''Image mean and std must be specified if do_normalize is True.''' ) # All transformations expect numpy arrays. __lowerCAmelCase : Any = [to_numpy_array(A_ ) for image in images] if do_resize: __lowerCAmelCase : Optional[Any] = [self.resize(image=A_ , size=A_ , resample=A_ ) for image in images] if do_rescale: __lowerCAmelCase : Tuple = [self.rescale(image=A_ , scale=A_ ) for image in images] if do_normalize: __lowerCAmelCase : str = [self.normalize(image=A_ , mean=A_ , std=A_ ) for image in images] __lowerCAmelCase : Union[str, Any] = [to_channel_dimension_format(A_ , A_ ) for image in images] __lowerCAmelCase : Dict = {'''pixel_values''': images} return BatchFeature(data=A_ , tensor_type=A_ ) def UpperCamelCase__ ( self , A_ , A_ = None ) ->Any: '''simple docstring''' __lowerCAmelCase : Any = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(A_ ) != len(A_ ): raise ValueError( '''Make sure that you pass in as many target sizes as the batch dimension of the logits''' ) if is_torch_tensor(A_ ): __lowerCAmelCase : Optional[int] = target_sizes.numpy() __lowerCAmelCase : List[str] = [] for idx in range(len(A_ ) ): __lowerCAmelCase : Any = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode='''bilinear''' , align_corners=A_ ) __lowerCAmelCase : str = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(A_ ) else: __lowerCAmelCase : Any = logits.argmax(dim=1 ) __lowerCAmelCase : List[Any] = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
275
0
'''simple docstring''' from argparse import ArgumentParser from ..pipelines import Pipeline, PipelineDataFormat, get_supported_tasks, pipeline from ..utils import logging from . import BaseTransformersCLICommand lowerCamelCase__ = logging.get_logger(__name__) # pylint: disable=invalid-name def __lowerCAmelCase (__lowerCAmelCase ): if not path: return "pipe" for ext in PipelineDataFormat.SUPPORTED_FORMATS: if path.endswith(lowercase__ ): return ext raise Exception( F"""Unable to determine file format from file extension {path}. """ F"""Please provide the format through --format {PipelineDataFormat.SUPPORTED_FORMATS}""" ) def __lowerCAmelCase (__lowerCAmelCase ): _UpperCAmelCase : Any = pipeline( task=args.task , model=args.model if args.model else None , config=args.config , tokenizer=args.tokenizer , device=args.device , ) _UpperCAmelCase : Dict = try_infer_format_from_ext(args.input ) if args.format == '''infer''' else args.format _UpperCAmelCase : Dict = PipelineDataFormat.from_str( format=lowercase__ , output_path=args.output , input_path=args.input , column=args.column if args.column else nlp.default_input_names , overwrite=args.overwrite , ) return RunCommand(lowercase__ , lowercase__ ) class lowerCAmelCase__ ( _UpperCAmelCase ): def __init__( self : Union[str, Any] , lowerCamelCase__ : str , lowerCamelCase__ : Any ) ->Any: '''simple docstring''' _UpperCAmelCase : Optional[Any] = nlp _UpperCAmelCase : Tuple = reader @staticmethod def lowerCAmelCase__ ( lowerCamelCase__ : Tuple ) ->Dict: '''simple docstring''' _UpperCAmelCase : str = parser.add_parser("run" , help="Run a pipeline through the CLI" ) run_parser.add_argument("--task" , choices=get_supported_tasks() , help="Task to run" ) run_parser.add_argument("--input" , type=A_ , help="Path to the file to use for inference" ) run_parser.add_argument("--output" , type=A_ , help="Path to the file that will be used post to write results." ) run_parser.add_argument("--model" , type=A_ , help="Name or path to the model to instantiate." ) run_parser.add_argument("--config" , type=A_ , help="Name or path to the model\'s config to instantiate." ) run_parser.add_argument( "--tokenizer" , type=A_ , help="Name of the tokenizer to use. (default: same as the model name)" ) run_parser.add_argument( "--column" , type=A_ , help="Name of the column to use as input. (For multi columns input as QA use column1,columns2)" , ) run_parser.add_argument( "--format" , type=A_ , default="infer" , choices=PipelineDataFormat.SUPPORTED_FORMATS , help="Input format to read from" , ) run_parser.add_argument( "--device" , type=A_ , default=-1 , help="Indicate the device to run onto, -1 indicates CPU, >= 0 indicates GPU (default: -1)" , ) run_parser.add_argument("--overwrite" , action="store_true" , help="Allow overwriting the output file." ) run_parser.set_defaults(func=A_ ) def lowerCAmelCase__ ( self : List[Any] ) ->Tuple: '''simple docstring''' _UpperCAmelCase : Any = self._nlp, [] for entry in self._reader: _UpperCAmelCase : Optional[int] = nlp(**A_ ) if self._reader.is_multi_columns else nlp(A_ ) if isinstance(A_ , A_ ): outputs.append(A_ ) else: outputs += output # Saving data if self._nlp.binary_output: _UpperCAmelCase : Union[str, Any] = self._reader.save_binary(A_ ) logger.warning(F"""Current pipeline requires output to be in binary format, saving at {binary_path}""" ) else: self._reader.save(A_ )
234
import unittest from .lib import ( Matrix, Vector, axpy, square_zero_matrix, unit_basis_vector, zero_vector, ) class __lowercase (unittest.TestCase ): def UpperCamelCase__ ( self ) ->None: '''simple docstring''' __lowerCAmelCase : List[str] = Vector([1, 2, 3] ) self.assertEqual(x.component(0 ) , 1 ) self.assertEqual(x.component(2 ) , 3 ) __lowerCAmelCase : Dict = Vector() def UpperCamelCase__ ( self ) ->None: '''simple docstring''' __lowerCAmelCase : Any = Vector([0, 0, 0, 0, 0, 1] ) self.assertEqual(str(A_ ) , '''(0,0,0,0,0,1)''' ) def UpperCamelCase__ ( self ) ->None: '''simple docstring''' __lowerCAmelCase : Union[str, Any] = Vector([1, 2, 3, 4] ) self.assertEqual(len(A_ ) , 4 ) def UpperCamelCase__ ( self ) ->None: '''simple docstring''' __lowerCAmelCase : Dict = Vector([1, 2] ) __lowerCAmelCase : Optional[int] = Vector([1, 2, 3, 4, 5] ) __lowerCAmelCase : Optional[Any] = Vector([0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ) __lowerCAmelCase : str = Vector([1, -1, 1, -1, 2, -3, 4, -5] ) self.assertAlmostEqual(x.euclidean_length() , 2.236 , 3 ) self.assertAlmostEqual(y.euclidean_length() , 7.416 , 3 ) self.assertEqual(z.euclidean_length() , 0 ) self.assertAlmostEqual(w.euclidean_length() , 7.616 , 3 ) def UpperCamelCase__ ( self ) ->None: '''simple docstring''' __lowerCAmelCase : Tuple = Vector([1, 2, 3] ) __lowerCAmelCase : List[str] = Vector([1, 1, 1] ) self.assertEqual((x + y).component(0 ) , 2 ) self.assertEqual((x + y).component(1 ) , 3 ) self.assertEqual((x + y).component(2 ) , 4 ) def UpperCamelCase__ ( self ) ->None: '''simple docstring''' __lowerCAmelCase : Any = Vector([1, 2, 3] ) __lowerCAmelCase : List[str] = Vector([1, 1, 1] ) self.assertEqual((x - y).component(0 ) , 0 ) self.assertEqual((x - y).component(1 ) , 1 ) self.assertEqual((x - y).component(2 ) , 2 ) def UpperCamelCase__ ( self ) ->None: '''simple docstring''' __lowerCAmelCase : str = Vector([1, 2, 3] ) __lowerCAmelCase : List[Any] = Vector([2, -1, 4] ) # for test of dot product __lowerCAmelCase : Optional[int] = Vector([1, -2, -1] ) self.assertEqual(str(x * 3.0 ) , '''(3.0,6.0,9.0)''' ) self.assertEqual((a * b) , 0 ) def UpperCamelCase__ ( self ) ->None: '''simple docstring''' self.assertEqual(str(zero_vector(10 ) ).count('''0''' ) , 10 ) def UpperCamelCase__ ( self ) ->None: '''simple docstring''' self.assertEqual(str(unit_basis_vector(3 , 1 ) ) , '''(0,1,0)''' ) def UpperCamelCase__ ( self ) ->None: '''simple docstring''' __lowerCAmelCase : str = Vector([1, 2, 3] ) __lowerCAmelCase : Any = Vector([1, 0, 1] ) self.assertEqual(str(axpy(2 , A_ , A_ ) ) , '''(3,4,7)''' ) def UpperCamelCase__ ( self ) ->None: '''simple docstring''' __lowerCAmelCase : Tuple = Vector([1, 0, 0, 0, 0, 0] ) __lowerCAmelCase : Optional[Any] = x.copy() self.assertEqual(str(A_ ) , str(A_ ) ) def UpperCamelCase__ ( self ) ->None: '''simple docstring''' __lowerCAmelCase : List[str] = Vector([1, 0, 0] ) x.change_component(0 , 0 ) x.change_component(1 , 1 ) self.assertEqual(str(A_ ) , '''(0,1,0)''' ) def UpperCamelCase__ ( self ) ->None: '''simple docstring''' __lowerCAmelCase : Union[str, Any] = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) self.assertEqual('''|1,2,3|\n|2,4,5|\n|6,7,8|\n''' , str(A_ ) ) def UpperCamelCase__ ( self ) ->None: '''simple docstring''' __lowerCAmelCase : List[Any] = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) __lowerCAmelCase : str = [[-3, -14, -10], [-5, -10, -5], [-2, -1, 0]] for x in range(a.height() ): for y in range(a.width() ): self.assertEqual(minors[x][y] , a.minor(A_ , A_ ) ) def UpperCamelCase__ ( self ) ->None: '''simple docstring''' __lowerCAmelCase : Optional[int] = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) __lowerCAmelCase : Tuple = [[-3, 14, -10], [5, -10, 5], [-2, 1, 0]] for x in range(a.height() ): for y in range(a.width() ): self.assertEqual(cofactors[x][y] , a.cofactor(A_ , A_ ) ) def UpperCamelCase__ ( self ) ->None: '''simple docstring''' __lowerCAmelCase : Dict = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) self.assertEqual(-5 , a.determinant() ) def UpperCamelCase__ ( self ) ->None: '''simple docstring''' __lowerCAmelCase : Tuple = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]] , 3 , 3 ) __lowerCAmelCase : Union[str, Any] = Vector([1, 2, 3] ) self.assertEqual('''(14,32,50)''' , str(a * x ) ) self.assertEqual('''|2,4,6|\n|8,10,12|\n|14,16,18|\n''' , str(a * 2 ) ) def UpperCamelCase__ ( self ) ->None: '''simple docstring''' __lowerCAmelCase : Any = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) a.change_component(0 , 2 , 5 ) self.assertEqual('''|1,2,5|\n|2,4,5|\n|6,7,8|\n''' , str(A_ ) ) def UpperCamelCase__ ( self ) ->None: '''simple docstring''' __lowerCAmelCase : Tuple = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) self.assertEqual(7 , a.component(2 , 1 ) , 0.01 ) def UpperCamelCase__ ( self ) ->None: '''simple docstring''' __lowerCAmelCase : Any = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) __lowerCAmelCase : Dict = Matrix([[1, 2, 7], [2, 4, 5], [6, 7, 10]] , 3 , 3 ) self.assertEqual('''|2,4,10|\n|4,8,10|\n|12,14,18|\n''' , str(a + b ) ) def UpperCamelCase__ ( self ) ->None: '''simple docstring''' __lowerCAmelCase : Dict = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) __lowerCAmelCase : str = Matrix([[1, 2, 7], [2, 4, 5], [6, 7, 10]] , 3 , 3 ) self.assertEqual('''|0,0,-4|\n|0,0,0|\n|0,0,-2|\n''' , str(a - b ) ) def UpperCamelCase__ ( self ) ->None: '''simple docstring''' self.assertEqual( '''|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n''' , str(square_zero_matrix(5 ) ) , ) if __name__ == "__main__": unittest.main()
275
0
"""simple docstring""" import copy import inspect import unittest from transformers import AutoBackbone from transformers.configuration_utils import PretrainedConfig from transformers.testing_utils import require_timm, require_torch, torch_device from transformers.utils.import_utils import is_torch_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor if is_torch_available(): import torch from transformers import TimmBackbone, TimmBackboneConfig from ...test_pipeline_mixin import PipelineTesterMixin class lowercase : def __init__( self , lowercase , lowercase=None , lowercase=None , lowercase=None , lowercase="resnet50" , lowercase=3 , lowercase=32 , lowercase=3 , lowercase=True , lowercase=True , ) -> Any: lowerCAmelCase = parent lowerCAmelCase = out_indices if out_indices is not None else [4] lowerCAmelCase = stage_names lowerCAmelCase = out_features lowerCAmelCase = backbone lowerCAmelCase = batch_size lowerCAmelCase = image_size lowerCAmelCase = num_channels lowerCAmelCase = use_pretrained_backbone lowerCAmelCase = is_training def _snake_case ( self ) -> List[Any]: lowerCAmelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCAmelCase = self.get_config() return config, pixel_values def _snake_case ( self ) -> Tuple: return TimmBackboneConfig( image_size=self.image_size , num_channels=self.num_channels , out_features=self.out_features , out_indices=self.out_indices , stage_names=self.stage_names , use_pretrained_backbone=self.use_pretrained_backbone , backbone=self.backbone , ) def _snake_case ( self , lowercase , lowercase ) -> str: lowerCAmelCase = TimmBackbone(config=A_ ) model.to(A_ ) model.eval() with torch.no_grad(): lowerCAmelCase = model(A_ ) self.parent.assertEqual( result.feature_map[-1].shape , (self.batch_size, model.channels[-1], 14, 14) , ) def _snake_case ( self ) -> Union[str, Any]: lowerCAmelCase = self.prepare_config_and_inputs() lowerCAmelCase = config_and_inputs lowerCAmelCase = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch @require_timm class lowercase ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): _SCREAMING_SNAKE_CASE = (TimmBackbone,) if is_torch_available() else () _SCREAMING_SNAKE_CASE = {'feature-extraction': TimmBackbone} if is_torch_available() else {} _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = False def _snake_case ( self ) -> Any: lowerCAmelCase = TimmBackboneModelTester(self ) lowerCAmelCase = ConfigTester(self , config_class=A_ , has_text_modality=A_ ) def _snake_case ( self ) -> Optional[Any]: self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _snake_case ( self ) -> Optional[Any]: lowerCAmelCase = '''resnet18''' lowerCAmelCase = '''microsoft/resnet-18''' lowerCAmelCase = AutoBackbone.from_pretrained(A_ , use_timm_backbone=A_ ) lowerCAmelCase = AutoBackbone.from_pretrained(A_ ) self.assertEqual(len(timm_model.out_features ) , len(transformers_model.out_features ) ) self.assertEqual(len(timm_model.stage_names ) , len(transformers_model.stage_names ) ) self.assertEqual(timm_model.channels , transformers_model.channels ) # Out indices are set to the last layer by default. For timm models, we don't know # the number of layers in advance, so we set it to (-1,), whereas for transformers # models, we set it to [len(stage_names) - 1] (kept for backward compatibility). self.assertEqual(timm_model.out_indices , (-1,) ) self.assertEqual(transformers_model.out_indices , [len(timm_model.stage_names ) - 1] ) lowerCAmelCase = AutoBackbone.from_pretrained(A_ , use_timm_backbone=A_ , out_indices=[1, 2, 3] ) lowerCAmelCase = AutoBackbone.from_pretrained(A_ , out_indices=[1, 2, 3] ) self.assertEqual(timm_model.out_indices , transformers_model.out_indices ) self.assertEqual(len(timm_model.out_features ) , len(transformers_model.out_features ) ) self.assertEqual(timm_model.channels , transformers_model.channels ) @unittest.skip("""TimmBackbone doesn\'t support feed forward chunking""" ) def _snake_case ( self ) -> Optional[int]: pass @unittest.skip("""TimmBackbone doesn\'t have num_hidden_layers attribute""" ) def _snake_case ( self ) -> Dict: pass @unittest.skip("""TimmBackbone initialization is managed on the timm side""" ) def _snake_case ( self ) -> Any: pass @unittest.skip("""TimmBackbone models doesn\'t have inputs_embeds""" ) def _snake_case ( self ) -> Optional[Any]: pass @unittest.skip("""TimmBackbone models doesn\'t have inputs_embeds""" ) def _snake_case ( self ) -> List[Any]: pass @unittest.skip("""TimmBackbone model cannot be created without specifying a backbone checkpoint""" ) def _snake_case ( self ) -> Optional[int]: pass @unittest.skip("""Only checkpoints on timm can be loaded into TimmBackbone""" ) def _snake_case ( self ) -> Tuple: pass @unittest.skip("""model weights aren\'t tied in TimmBackbone.""" ) def _snake_case ( self ) -> str: pass @unittest.skip("""model weights aren\'t tied in TimmBackbone.""" ) def _snake_case ( self ) -> List[Any]: pass @unittest.skip("""Only checkpoints on timm can be loaded into TimmBackbone""" ) def _snake_case ( self ) -> Optional[int]: pass @unittest.skip("""Only checkpoints on timm can be loaded into TimmBackbone""" ) def _snake_case ( self ) -> List[str]: pass @unittest.skip("""TimmBackbone doesn\'t have hidden size info in its configuration.""" ) def _snake_case ( self ) -> str: pass @unittest.skip("""TimmBackbone doesn\'t support output_attentions.""" ) def _snake_case ( self ) -> str: pass @unittest.skip("""Safetensors is not supported by timm.""" ) def _snake_case ( self ) -> Tuple: pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def _snake_case ( self ) -> Any: pass def _snake_case ( self ) -> str: lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase = model_class(A_ ) lowerCAmelCase = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCAmelCase = [*signature.parameters.keys()] lowerCAmelCase = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , A_ ) def _snake_case ( self ) -> Union[str, Any]: lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase = True lowerCAmelCase = self.has_attentions # no need to test all models as different heads yield the same functionality lowerCAmelCase = self.all_model_classes[0] lowerCAmelCase = model_class(A_ ) model.to(A_ ) lowerCAmelCase = self._prepare_for_class(A_ , A_ ) lowerCAmelCase = model(**A_ ) lowerCAmelCase = outputs[0][-1] # Encoder-/Decoder-only models lowerCAmelCase = outputs.hidden_states[0] hidden_states.retain_grad() if self.has_attentions: lowerCAmelCase = outputs.attentions[0] attentions.retain_grad() output.flatten()[0].backward(retain_graph=A_ ) self.assertIsNotNone(hidden_states.grad ) if self.has_attentions: self.assertIsNotNone(attentions.grad ) def _snake_case ( self ) -> int: lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase = model_class(A_ ) model.to(A_ ) model.eval() lowerCAmelCase = model(**A_ ) self.assertEqual(len(result.feature_maps ) , len(config.out_indices ) ) self.assertEqual(len(model.channels ) , len(config.out_indices ) ) # Check output of last stage is taken if out_features=None, out_indices=None lowerCAmelCase = copy.deepcopy(A_ ) lowerCAmelCase = None lowerCAmelCase = model_class(A_ ) model.to(A_ ) model.eval() lowerCAmelCase = model(**A_ ) self.assertEqual(len(result.feature_maps ) , 1 ) self.assertEqual(len(model.channels ) , 1 ) # Check backbone can be initialized with fresh weights lowerCAmelCase = copy.deepcopy(A_ ) lowerCAmelCase = False lowerCAmelCase = model_class(A_ ) model.to(A_ ) model.eval() lowerCAmelCase = model(**A_ )
46
def _lowercase ( lowercase__ , lowercase__ ): if density <= 0: raise ValueError('''Impossible fluid density''' ) if bulk_modulus <= 0: raise ValueError('''Impossible bulk modulus''' ) return (bulk_modulus / density) ** 0.5 if __name__ == "__main__": import doctest doctest.testmod()
275
0
from graphs.minimum_spanning_tree_kruskal import kruskal def __UpperCamelCase ( ) ->int: """simple docstring""" lowerCamelCase_ =9 lowerCamelCase_ =[ [0, 1, 4], [0, 7, 8], [1, 2, 8], [7, 8, 7], [7, 6, 1], [2, 8, 2], [8, 6, 6], [2, 3, 7], [2, 5, 4], [6, 5, 2], [3, 5, 14], [3, 4, 9], [5, 4, 10], [1, 7, 11], ] lowerCamelCase_ =kruskal(lowercase__ , lowercase__ ) lowerCamelCase_ =[ [7, 6, 1], [2, 8, 2], [6, 5, 2], [0, 1, 4], [2, 5, 4], [2, 3, 7], [0, 7, 8], [3, 4, 9], ] assert sorted(lowercase__ ) == sorted(lowercase__ )
154
def _lowercase ( lowercase__ , lowercase__ ): return (pointa[0] - pointa[0]) ** 2 + (pointa[1] - pointa[1]) ** 2 def _lowercase ( lowercase__ , lowercase__=0 ): return sorted(lowercase__ , key=lambda lowercase__ : x[column] ) def _lowercase ( lowercase__ , lowercase__ , lowercase__=float('''inf''' ) ): for i in range(points_counts - 1 ): for j in range(i + 1 , lowercase__ ): __lowerCAmelCase : List[str] = euclidean_distance_sqr(points[i] , points[j] ) if current_dis < min_dis: __lowerCAmelCase : Tuple = current_dis return min_dis def _lowercase ( lowercase__ , lowercase__ , lowercase__=float('''inf''' ) ): for i in range(min(6 , points_counts - 1 ) , lowercase__ ): for j in range(max(0 , i - 6 ) , lowercase__ ): __lowerCAmelCase : Union[str, Any] = euclidean_distance_sqr(points[i] , points[j] ) if current_dis < min_dis: __lowerCAmelCase : int = current_dis return min_dis def _lowercase ( lowercase__ , lowercase__ , lowercase__ ): # base case if points_counts <= 3: return dis_between_closest_pair(lowercase__ , lowercase__ ) # recursion __lowerCAmelCase : Optional[Any] = points_counts // 2 __lowerCAmelCase : Optional[Any] = closest_pair_of_points_sqr( lowercase__ , points_sorted_on_y[:mid] , lowercase__ ) __lowerCAmelCase : str = closest_pair_of_points_sqr( lowercase__ , points_sorted_on_y[mid:] , points_counts - mid ) __lowerCAmelCase : Optional[int] = min(lowercase__ , lowercase__ ) __lowerCAmelCase : Tuple = [] for point in points_sorted_on_x: if abs(point[0] - points_sorted_on_x[mid][0] ) < closest_pair_dis: cross_strip.append(lowercase__ ) __lowerCAmelCase : List[Any] = dis_between_closest_in_strip( lowercase__ , len(lowercase__ ) , lowercase__ ) return min(lowercase__ , lowercase__ ) def _lowercase ( lowercase__ , lowercase__ ): __lowerCAmelCase : Union[str, Any] = column_based_sort(lowercase__ , column=0 ) __lowerCAmelCase : Any = column_based_sort(lowercase__ , column=1 ) return ( closest_pair_of_points_sqr( lowercase__ , lowercase__ , lowercase__ ) ) ** 0.5 if __name__ == "__main__": _UpperCamelCase = [(2, 3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4)] print("Distance:", closest_pair_of_points(points, len(points)))
275
0
import warnings from ...utils import logging from .image_processing_beit import BeitImageProcessor _lowerCamelCase : Optional[Any] = logging.get_logger(__name__) class UpperCamelCase_ ( _UpperCAmelCase ): '''simple docstring''' def __init__( self : int , *UpperCAmelCase__ : Optional[int] , **UpperCAmelCase__ : Optional[Any]) ->None: '''simple docstring''' warnings.warn( '''The class BeitFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please''' ''' use BeitImageProcessor instead.''' , A_ , ) super().__init__(*A_ , **A_)
14
def _lowercase ( lowercase__ = 2_0_0 ): __lowerCAmelCase : Union[str, Any] = [1, 2, 5, 1_0, 2_0, 5_0, 1_0_0, 2_0_0] __lowerCAmelCase : Dict = [0] * (pence + 1) __lowerCAmelCase : Optional[int] = 1 # base case: 1 way to make 0 pence for coin in coins: for i in range(lowercase__ , pence + 1 , 1 ): number_of_ways[i] += number_of_ways[i - coin] return number_of_ways[pence] if __name__ == "__main__": assert solution(200) == 7_3682
275
0
'''simple docstring''' import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XGLMTokenizer, XGLMTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin lowercase__ : Any = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece @require_tokenizers class __lowerCAmelCase ( _UpperCAmelCase , unittest.TestCase ): """simple docstring""" _snake_case : Union[str, Any] = XGLMTokenizer _snake_case : Dict = XGLMTokenizerFast _snake_case : Union[str, Any] = True _snake_case : List[str] = True def snake_case__ ( self : str ) -> List[str]: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing _UpperCamelCase = XGLMTokenizer(A_ , keep_accents=A_ ) tokenizer.save_pretrained(self.tmpdirname ) def snake_case__ ( self : Any ) -> Union[str, Any]: '''simple docstring''' _UpperCamelCase = '''<pad>''' _UpperCamelCase = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(A_ ) , A_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(A_ ) , A_ ) def snake_case__ ( self : Any ) -> List[Any]: '''simple docstring''' _UpperCamelCase = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<s>''' ) self.assertEqual(vocab_keys[1] , '''<pad>''' ) self.assertEqual(len(A_ ) , 1008 ) def snake_case__ ( self : List[str] ) -> Optional[int]: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1008 ) def snake_case__ ( self : Optional[int] ) -> List[str]: '''simple docstring''' _UpperCamelCase = XGLMTokenizer(A_ , keep_accents=A_ ) _UpperCamelCase = tokenizer.tokenize('''This is a test''' ) self.assertListEqual(A_ , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(A_ ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) _UpperCamelCase = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( A_ , [ 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''', '''é''', '''.''', ] , ) _UpperCamelCase = tokenizer.convert_tokens_to_ids(A_ ) self.assertListEqual( A_ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) _UpperCamelCase = tokenizer.convert_ids_to_tokens(A_ ) self.assertListEqual( A_ , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''<unk>''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''<unk>''', '''.''', ] , ) @cached_property def snake_case__ ( self : Any ) -> Union[str, Any]: '''simple docstring''' return XGLMTokenizer.from_pretrained('''facebook/xglm-564M''' ) def snake_case__ ( self : List[Any] ) -> List[str]: '''simple docstring''' with tempfile.NamedTemporaryFile() as f: shutil.copyfile(A_ , f.name ) _UpperCamelCase = XGLMTokenizer(f.name , keep_accents=A_ ) _UpperCamelCase = pickle.dumps(A_ ) pickle.loads(A_ ) def snake_case__ ( self : int ) -> List[Any]: '''simple docstring''' if not self.test_rust_tokenizer: return _UpperCamelCase = self.get_tokenizer() _UpperCamelCase = self.get_rust_tokenizer() _UpperCamelCase = '''I was born in 92000, and this is falsé.''' _UpperCamelCase = tokenizer.tokenize(A_ ) _UpperCamelCase = rust_tokenizer.tokenize(A_ ) self.assertListEqual(A_ , A_ ) _UpperCamelCase = tokenizer.encode(A_ , add_special_tokens=A_ ) _UpperCamelCase = rust_tokenizer.encode(A_ , add_special_tokens=A_ ) self.assertListEqual(A_ , A_ ) _UpperCamelCase = self.get_rust_tokenizer() _UpperCamelCase = tokenizer.encode(A_ ) _UpperCamelCase = rust_tokenizer.encode(A_ ) self.assertListEqual(A_ , A_ ) @slow def snake_case__ ( self : Optional[int] ) -> List[str]: '''simple docstring''' _UpperCamelCase = '''Hello World!''' _UpperCamelCase = [2, 31227, 4447, 35] self.assertListEqual(A_ , self.big_tokenizer.encode(A_ ) ) @slow def snake_case__ ( self : List[Any] ) -> Tuple: '''simple docstring''' _UpperCamelCase = ( '''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 _UpperCamelCase = [2, 1018, 67, 11, 1988, 2617, 5631, 278, 11, 3407, 48, 71630, 28085, 4, 3234, 157, 13, 6, 5, 6, 4, 3526, 768, 15, 659, 57, 298, 3983, 864, 129, 21, 6, 5, 13675, 377, 652, 7580, 10341, 155, 2817, 422, 1666, 7, 1674, 53, 113, 202277, 17892, 33, 60, 87, 4, 3234, 157, 61, 2667, 52376, 19, 88, 23, 735] # fmt: on self.assertListEqual(A_ , self.big_tokenizer.encode(A_ ) ) @slow def snake_case__ ( self : Any ) -> List[Any]: '''simple docstring''' _UpperCamelCase = { '''input_ids''': [[2, 108825, 1163, 15, 88010, 473, 15898, 157, 13672, 1857, 312, 8, 238021, 1163, 53, 13672, 1857, 312, 8, 53283, 182396, 8, 18566, 16, 36733, 4101, 8, 230, 244017, 122553, 7, 15, 132597, 4, 293, 12511, 7610, 4, 3414, 132597, 9, 4, 32361, 362, 4, 734, 28512, 32569, 18, 4, 32361, 26096, 14982, 73, 18715, 21433, 235261, 15, 492, 12427, 16, 53, 18715, 21433, 65454, 15, 23659, 563, 16, 278, 597, 2843, 595, 7931, 182396, 64186, 22, 886, 595, 132981, 53, 25540, 3449, 43982, 39901, 5951, 878, 330, 4, 27694, 80269, 312, 53, 6517, 11780, 611, 20408, 5], [2, 6, 132597, 67, 42897, 33, 592, 8, 163729, 25540, 361, 136997, 109514, 173230, 7, 501, 60, 102913, 196, 5631, 235, 63243, 473, 6, 231757, 74, 5277, 7905, 53, 3095, 37317, 22, 454, 183874, 5], [2, 268, 31298, 46530, 6, 132935, 43831, 7, 597, 32, 24, 3688, 9865, 5]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] } # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=A_ , model_name='''facebook/xglm-564M''' , padding=A_ , )
324
import gc import unittest import numpy as np import torch from torch.backends.cuda import sdp_kernel from diffusers import ( CMStochasticIterativeScheduler, ConsistencyModelPipeline, UNetaDModel, ) from diffusers.utils import randn_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_a, require_torch_gpu from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class __lowercase (_UpperCAmelCase , unittest.TestCase ): _UpperCamelCase = ConsistencyModelPipeline _UpperCamelCase = UNCONDITIONAL_IMAGE_GENERATION_PARAMS _UpperCamelCase = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS # Override required_optional_params to remove num_images_per_prompt _UpperCamelCase = frozenset( [ """num_inference_steps""", """generator""", """latents""", """output_type""", """return_dict""", """callback""", """callback_steps""", ] ) @property def UpperCamelCase__ ( self ) ->List[str]: '''simple docstring''' __lowerCAmelCase : List[Any] = UNetaDModel.from_pretrained( '''diffusers/consistency-models-test''' , subfolder='''test_unet''' , ) return unet @property def UpperCamelCase__ ( self ) ->Optional[int]: '''simple docstring''' __lowerCAmelCase : List[str] = UNetaDModel.from_pretrained( '''diffusers/consistency-models-test''' , subfolder='''test_unet_class_cond''' , ) return unet def UpperCamelCase__ ( self , A_=False ) ->Dict: '''simple docstring''' if class_cond: __lowerCAmelCase : List[str] = self.dummy_cond_unet else: __lowerCAmelCase : Optional[Any] = self.dummy_uncond_unet # Default to CM multistep sampler __lowerCAmelCase : List[str] = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.002 , sigma_max=80.0 , ) __lowerCAmelCase : Dict = { '''unet''': unet, '''scheduler''': scheduler, } return components def UpperCamelCase__ ( self , A_ , A_=0 ) ->Tuple: '''simple docstring''' if str(A_ ).startswith('''mps''' ): __lowerCAmelCase : str = torch.manual_seed(A_ ) else: __lowerCAmelCase : Dict = torch.Generator(device=A_ ).manual_seed(A_ ) __lowerCAmelCase : Tuple = { '''batch_size''': 1, '''num_inference_steps''': None, '''timesteps''': [22, 0], '''generator''': generator, '''output_type''': '''np''', } return inputs def UpperCamelCase__ ( self ) ->Tuple: '''simple docstring''' __lowerCAmelCase : Union[str, Any] = '''cpu''' # ensure determinism for the device-dependent torch.Generator __lowerCAmelCase : Tuple = self.get_dummy_components() __lowerCAmelCase : Union[str, Any] = ConsistencyModelPipeline(**A_ ) __lowerCAmelCase : List[str] = pipe.to(A_ ) pipe.set_progress_bar_config(disable=A_ ) __lowerCAmelCase : Any = self.get_dummy_inputs(A_ ) __lowerCAmelCase : int = pipe(**A_ ).images assert image.shape == (1, 32, 32, 3) __lowerCAmelCase : Tuple = image[0, -3:, -3:, -1] __lowerCAmelCase : str = np.array([0.3_572, 0.6_273, 0.4_031, 0.3_961, 0.4_321, 0.5_730, 0.5_266, 0.4_780, 0.5_004] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def UpperCamelCase__ ( self ) ->Tuple: '''simple docstring''' __lowerCAmelCase : List[Any] = '''cpu''' # ensure determinism for the device-dependent torch.Generator __lowerCAmelCase : str = self.get_dummy_components(class_cond=A_ ) __lowerCAmelCase : List[str] = ConsistencyModelPipeline(**A_ ) __lowerCAmelCase : List[Any] = pipe.to(A_ ) pipe.set_progress_bar_config(disable=A_ ) __lowerCAmelCase : Optional[Any] = self.get_dummy_inputs(A_ ) __lowerCAmelCase : Optional[int] = 0 __lowerCAmelCase : int = pipe(**A_ ).images assert image.shape == (1, 32, 32, 3) __lowerCAmelCase : Optional[int] = image[0, -3:, -3:, -1] __lowerCAmelCase : List[str] = np.array([0.3_572, 0.6_273, 0.4_031, 0.3_961, 0.4_321, 0.5_730, 0.5_266, 0.4_780, 0.5_004] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def UpperCamelCase__ ( self ) ->Optional[Any]: '''simple docstring''' __lowerCAmelCase : Any = '''cpu''' # ensure determinism for the device-dependent torch.Generator __lowerCAmelCase : Union[str, Any] = self.get_dummy_components() __lowerCAmelCase : List[Any] = ConsistencyModelPipeline(**A_ ) __lowerCAmelCase : int = pipe.to(A_ ) pipe.set_progress_bar_config(disable=A_ ) __lowerCAmelCase : Tuple = self.get_dummy_inputs(A_ ) __lowerCAmelCase : Any = 1 __lowerCAmelCase : List[Any] = None __lowerCAmelCase : Dict = pipe(**A_ ).images assert image.shape == (1, 32, 32, 3) __lowerCAmelCase : Any = image[0, -3:, -3:, -1] __lowerCAmelCase : List[Any] = np.array([0.5_004, 0.5_004, 0.4_994, 0.5_008, 0.4_976, 0.5_018, 0.4_990, 0.4_982, 0.4_987] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def UpperCamelCase__ ( self ) ->Optional[Any]: '''simple docstring''' __lowerCAmelCase : List[Any] = '''cpu''' # ensure determinism for the device-dependent torch.Generator __lowerCAmelCase : Optional[Any] = self.get_dummy_components(class_cond=A_ ) __lowerCAmelCase : List[str] = ConsistencyModelPipeline(**A_ ) __lowerCAmelCase : Union[str, Any] = pipe.to(A_ ) pipe.set_progress_bar_config(disable=A_ ) __lowerCAmelCase : Any = self.get_dummy_inputs(A_ ) __lowerCAmelCase : List[str] = 1 __lowerCAmelCase : Dict = None __lowerCAmelCase : Tuple = 0 __lowerCAmelCase : Dict = pipe(**A_ ).images assert image.shape == (1, 32, 32, 3) __lowerCAmelCase : List[Any] = image[0, -3:, -3:, -1] __lowerCAmelCase : Any = np.array([0.5_004, 0.5_004, 0.4_994, 0.5_008, 0.4_976, 0.5_018, 0.4_990, 0.4_982, 0.4_987] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 @slow @require_torch_gpu class __lowercase (unittest.TestCase ): def UpperCamelCase__ ( self ) ->int: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase__ ( self , A_=0 , A_=False , A_="cpu" , A_=torch.floataa , A_=(1, 3, 64, 64) ) ->str: '''simple docstring''' __lowerCAmelCase : Dict = torch.manual_seed(A_ ) __lowerCAmelCase : Tuple = { '''num_inference_steps''': None, '''timesteps''': [22, 0], '''class_labels''': 0, '''generator''': generator, '''output_type''': '''np''', } if get_fixed_latents: __lowerCAmelCase : List[str] = self.get_fixed_latents(seed=A_ , device=A_ , dtype=A_ , shape=A_ ) __lowerCAmelCase : Union[str, Any] = latents return inputs def UpperCamelCase__ ( self , A_=0 , A_="cpu" , A_=torch.floataa , A_=(1, 3, 64, 64) ) ->Optional[int]: '''simple docstring''' if type(A_ ) == str: __lowerCAmelCase : int = torch.device(A_ ) __lowerCAmelCase : Optional[Any] = torch.Generator(device=A_ ).manual_seed(A_ ) __lowerCAmelCase : Union[str, Any] = randn_tensor(A_ , generator=A_ , device=A_ , dtype=A_ ) return latents def UpperCamelCase__ ( self ) ->Optional[Any]: '''simple docstring''' __lowerCAmelCase : int = UNetaDModel.from_pretrained('''diffusers/consistency_models''' , subfolder='''diffusers_cd_imagenet64_l2''' ) __lowerCAmelCase : List[Any] = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.002 , sigma_max=80.0 , ) __lowerCAmelCase : List[str] = ConsistencyModelPipeline(unet=A_ , scheduler=A_ ) pipe.to(torch_device=A_ ) pipe.set_progress_bar_config(disable=A_ ) __lowerCAmelCase : str = self.get_inputs() __lowerCAmelCase : Any = pipe(**A_ ).images assert image.shape == (1, 64, 64, 3) __lowerCAmelCase : Dict = image[0, -3:, -3:, -1] __lowerCAmelCase : Optional[int] = np.array([0.0_888, 0.0_881, 0.0_666, 0.0_479, 0.0_292, 0.0_195, 0.0_201, 0.0_163, 0.0_254] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 def UpperCamelCase__ ( self ) ->Any: '''simple docstring''' __lowerCAmelCase : int = UNetaDModel.from_pretrained('''diffusers/consistency_models''' , subfolder='''diffusers_cd_imagenet64_l2''' ) __lowerCAmelCase : Optional[Any] = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.002 , sigma_max=80.0 , ) __lowerCAmelCase : List[str] = ConsistencyModelPipeline(unet=A_ , scheduler=A_ ) pipe.to(torch_device=A_ ) pipe.set_progress_bar_config(disable=A_ ) __lowerCAmelCase : List[Any] = self.get_inputs() __lowerCAmelCase : Tuple = 1 __lowerCAmelCase : Optional[Any] = None __lowerCAmelCase : str = pipe(**A_ ).images assert image.shape == (1, 64, 64, 3) __lowerCAmelCase : Optional[int] = image[0, -3:, -3:, -1] __lowerCAmelCase : List[Any] = np.array([0.0_340, 0.0_152, 0.0_063, 0.0_267, 0.0_221, 0.0_107, 0.0_416, 0.0_186, 0.0_217] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 @require_torch_a def UpperCamelCase__ ( self ) ->Optional[Any]: '''simple docstring''' __lowerCAmelCase : Tuple = UNetaDModel.from_pretrained('''diffusers/consistency_models''' , subfolder='''diffusers_cd_imagenet64_l2''' ) __lowerCAmelCase : List[str] = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.002 , sigma_max=80.0 , ) __lowerCAmelCase : Union[str, Any] = ConsistencyModelPipeline(unet=A_ , scheduler=A_ ) pipe.to(torch_device=A_ , torch_dtype=torch.floataa ) pipe.set_progress_bar_config(disable=A_ ) __lowerCAmelCase : Any = self.get_inputs(get_fixed_latents=A_ , device=A_ ) # Ensure usage of flash attention in torch 2.0 with sdp_kernel(enable_flash=A_ , enable_math=A_ , enable_mem_efficient=A_ ): __lowerCAmelCase : Dict = pipe(**A_ ).images assert image.shape == (1, 64, 64, 3) __lowerCAmelCase : Dict = image[0, -3:, -3:, -1] __lowerCAmelCase : Optional[int] = np.array([0.1_875, 0.1_428, 0.1_289, 0.2_151, 0.2_092, 0.1_477, 0.1_877, 0.1_641, 0.1_353] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 @require_torch_a def UpperCamelCase__ ( self ) ->List[str]: '''simple docstring''' __lowerCAmelCase : Optional[Any] = UNetaDModel.from_pretrained('''diffusers/consistency_models''' , subfolder='''diffusers_cd_imagenet64_l2''' ) __lowerCAmelCase : List[Any] = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.002 , sigma_max=80.0 , ) __lowerCAmelCase : Union[str, Any] = ConsistencyModelPipeline(unet=A_ , scheduler=A_ ) pipe.to(torch_device=A_ , torch_dtype=torch.floataa ) pipe.set_progress_bar_config(disable=A_ ) __lowerCAmelCase : Union[str, Any] = self.get_inputs(get_fixed_latents=A_ , device=A_ ) __lowerCAmelCase : Any = 1 __lowerCAmelCase : int = None # Ensure usage of flash attention in torch 2.0 with sdp_kernel(enable_flash=A_ , enable_math=A_ , enable_mem_efficient=A_ ): __lowerCAmelCase : int = pipe(**A_ ).images assert image.shape == (1, 64, 64, 3) __lowerCAmelCase : str = image[0, -3:, -3:, -1] __lowerCAmelCase : Any = np.array([0.1_663, 0.1_948, 0.2_275, 0.1_680, 0.1_204, 0.1_245, 0.1_858, 0.1_338, 0.2_095] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3
275
0
'''simple docstring''' import numpy as np def _UpperCAmelCase ( _lowerCamelCase : Dict ) -> Dict: return 1 / (1 + np.exp(-vector )) if __name__ == "__main__": import doctest doctest.testmod()
309
from collections import deque from .hash_table import HashTable class __lowercase (_UpperCAmelCase ): def __init__( self , *A_ , **A_ ) ->int: '''simple docstring''' super().__init__(*A_ , **A_ ) def UpperCamelCase__ ( self , A_ , A_ ) ->Optional[int]: '''simple docstring''' __lowerCAmelCase : Dict = deque([] ) if self.values[key] is None else self.values[key] self.values[key].appendleft(A_ ) __lowerCAmelCase : int = self.values[key] def UpperCamelCase__ ( self ) ->Tuple: '''simple docstring''' return ( sum(self.charge_factor - len(A_ ) for slot in self.values ) / self.size_table * self.charge_factor ) def UpperCamelCase__ ( self , A_ , A_=None ) ->str: '''simple docstring''' if not ( len(self.values[key] ) == self.charge_factor and self.values.count(A_ ) == 0 ): return key return super()._collision_resolution(A_ , A_ )
275
0
import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ConvNextConfig, SegformerImageProcessor, UperNetConfig, UperNetForSemanticSegmentation def __lowercase ( _A ) -> Optional[int]: SCREAMING_SNAKE_CASE : Union[str, Any] = 384 if "tiny" in model_name: SCREAMING_SNAKE_CASE : Optional[Any] = [3, 3, 9, 3] SCREAMING_SNAKE_CASE : Tuple = [96, 192, 384, 768] if "small" in model_name: SCREAMING_SNAKE_CASE : str = [3, 3, 27, 3] SCREAMING_SNAKE_CASE : str = [96, 192, 384, 768] if "base" in model_name: SCREAMING_SNAKE_CASE : str = [3, 3, 27, 3] SCREAMING_SNAKE_CASE : List[str] = [128, 256, 512, 1024] SCREAMING_SNAKE_CASE : Dict = 512 if "large" in model_name: SCREAMING_SNAKE_CASE : List[str] = [3, 3, 27, 3] SCREAMING_SNAKE_CASE : Dict = [192, 384, 768, 1536] SCREAMING_SNAKE_CASE : Union[str, Any] = 768 if "xlarge" in model_name: SCREAMING_SNAKE_CASE : Any = [3, 3, 27, 3] SCREAMING_SNAKE_CASE : str = [256, 512, 1024, 2048] SCREAMING_SNAKE_CASE : str = 1024 # set label information SCREAMING_SNAKE_CASE : Optional[Any] = 150 SCREAMING_SNAKE_CASE : int = '''huggingface/label-files''' SCREAMING_SNAKE_CASE : str = '''ade20k-id2label.json''' SCREAMING_SNAKE_CASE : Tuple = json.load(open(hf_hub_download(lowercase__ , lowercase__ , repo_type="""dataset""" ) , """r""" ) ) SCREAMING_SNAKE_CASE : str = {int(lowercase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE : List[Any] = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE : str = ConvNextConfig( depths=lowercase__ , hidden_sizes=lowercase__ , out_features=["""stage1""", """stage2""", """stage3""", """stage4"""] ) SCREAMING_SNAKE_CASE : List[Any] = UperNetConfig( backbone_config=lowercase__ , auxiliary_in_channels=lowercase__ , num_labels=lowercase__ , idalabel=lowercase__ , labelaid=lowercase__ , ) return config def __lowercase ( _A ) -> int: SCREAMING_SNAKE_CASE : Optional[Any] = [] # fmt: off # stem rename_keys.append(("""backbone.downsample_layers.0.0.weight""", """backbone.embeddings.patch_embeddings.weight""") ) rename_keys.append(("""backbone.downsample_layers.0.0.bias""", """backbone.embeddings.patch_embeddings.bias""") ) rename_keys.append(("""backbone.downsample_layers.0.1.weight""", """backbone.embeddings.layernorm.weight""") ) rename_keys.append(("""backbone.downsample_layers.0.1.bias""", """backbone.embeddings.layernorm.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.stages.{i}.{j}.gamma", F"backbone.encoder.stages.{i}.layers.{j}.layer_scale_parameter") ) rename_keys.append((F"backbone.stages.{i}.{j}.depthwise_conv.weight", F"backbone.encoder.stages.{i}.layers.{j}.dwconv.weight") ) rename_keys.append((F"backbone.stages.{i}.{j}.depthwise_conv.bias", F"backbone.encoder.stages.{i}.layers.{j}.dwconv.bias") ) rename_keys.append((F"backbone.stages.{i}.{j}.norm.weight", F"backbone.encoder.stages.{i}.layers.{j}.layernorm.weight") ) rename_keys.append((F"backbone.stages.{i}.{j}.norm.bias", F"backbone.encoder.stages.{i}.layers.{j}.layernorm.bias") ) rename_keys.append((F"backbone.stages.{i}.{j}.pointwise_conv1.weight", F"backbone.encoder.stages.{i}.layers.{j}.pwconv1.weight") ) rename_keys.append((F"backbone.stages.{i}.{j}.pointwise_conv1.bias", F"backbone.encoder.stages.{i}.layers.{j}.pwconv1.bias") ) rename_keys.append((F"backbone.stages.{i}.{j}.pointwise_conv2.weight", F"backbone.encoder.stages.{i}.layers.{j}.pwconv2.weight") ) rename_keys.append((F"backbone.stages.{i}.{j}.pointwise_conv2.bias", F"backbone.encoder.stages.{i}.layers.{j}.pwconv2.bias") ) if i > 0: rename_keys.append((F"backbone.downsample_layers.{i}.0.weight", F"backbone.encoder.stages.{i}.downsampling_layer.0.weight") ) rename_keys.append((F"backbone.downsample_layers.{i}.0.bias", F"backbone.encoder.stages.{i}.downsampling_layer.0.bias") ) rename_keys.append((F"backbone.downsample_layers.{i}.1.weight", F"backbone.encoder.stages.{i}.downsampling_layer.1.weight") ) rename_keys.append((F"backbone.downsample_layers.{i}.1.bias", F"backbone.encoder.stages.{i}.downsampling_layer.1.bias") ) rename_keys.append((F"backbone.norm{i}.weight", F"backbone.hidden_states_norms.stage{i+1}.weight") ) rename_keys.append((F"backbone.norm{i}.bias", F"backbone.hidden_states_norms.stage{i+1}.bias") ) # decode head rename_keys.extend( [ ("""decode_head.conv_seg.weight""", """decode_head.classifier.weight"""), ("""decode_head.conv_seg.bias""", """decode_head.classifier.bias"""), ("""auxiliary_head.conv_seg.weight""", """auxiliary_head.classifier.weight"""), ("""auxiliary_head.conv_seg.bias""", """auxiliary_head.classifier.bias"""), ] ) # fmt: on return rename_keys def __lowercase ( _A , _A , _A ) -> Optional[int]: SCREAMING_SNAKE_CASE : Optional[Any] = dct.pop(lowercase__ ) SCREAMING_SNAKE_CASE : List[str] = val def __lowercase ( _A , _A , _A ) -> int: SCREAMING_SNAKE_CASE : Dict = { '''upernet-convnext-tiny''': '''https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_tiny_fp16_512x512_160k_ade20k/upernet_convnext_tiny_fp16_512x512_160k_ade20k_20220227_124553-cad485de.pth''', '''upernet-convnext-small''': '''https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_small_fp16_512x512_160k_ade20k/upernet_convnext_small_fp16_512x512_160k_ade20k_20220227_131208-1b1e394f.pth''', '''upernet-convnext-base''': '''https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_base_fp16_512x512_160k_ade20k/upernet_convnext_base_fp16_512x512_160k_ade20k_20220227_181227-02a24fc6.pth''', '''upernet-convnext-large''': '''https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_large_fp16_640x640_160k_ade20k/upernet_convnext_large_fp16_640x640_160k_ade20k_20220226_040532-e57aa54d.pth''', '''upernet-convnext-xlarge''': '''https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_xlarge_fp16_640x640_160k_ade20k/upernet_convnext_xlarge_fp16_640x640_160k_ade20k_20220226_080344-95fc38c2.pth''', } SCREAMING_SNAKE_CASE : str = model_name_to_url[model_name] SCREAMING_SNAKE_CASE : Tuple = torch.hub.load_state_dict_from_url(lowercase__ , map_location="""cpu""" )['''state_dict'''] SCREAMING_SNAKE_CASE : Optional[int] = get_upernet_config(lowercase__ ) SCREAMING_SNAKE_CASE : List[Any] = UperNetForSemanticSegmentation(lowercase__ ) model.eval() # replace "bn" => "batch_norm" for key in state_dict.copy().keys(): SCREAMING_SNAKE_CASE : str = state_dict.pop(lowercase__ ) if "bn" in key: SCREAMING_SNAKE_CASE : Tuple = key.replace("""bn""" , """batch_norm""" ) SCREAMING_SNAKE_CASE : Dict = val # rename keys SCREAMING_SNAKE_CASE : Tuple = create_rename_keys(lowercase__ ) for src, dest in rename_keys: rename_key(lowercase__ , lowercase__ , lowercase__ ) model.load_state_dict(lowercase__ ) # verify on image SCREAMING_SNAKE_CASE : Dict = '''https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg''' SCREAMING_SNAKE_CASE : Optional[int] = Image.open(requests.get(lowercase__ , stream=lowercase__ ).raw ).convert("""RGB""" ) SCREAMING_SNAKE_CASE : Optional[int] = SegformerImageProcessor() SCREAMING_SNAKE_CASE : List[str] = processor(lowercase__ , return_tensors="""pt""" ).pixel_values with torch.no_grad(): SCREAMING_SNAKE_CASE : int = model(lowercase__ ) if model_name == "upernet-convnext-tiny": SCREAMING_SNAKE_CASE : str = torch.tensor( [[-8.8110, -8.8110, -8.6521], [-8.8110, -8.8110, -8.6521], [-8.7746, -8.7746, -8.6130]] ) elif model_name == "upernet-convnext-small": SCREAMING_SNAKE_CASE : List[str] = torch.tensor( [[-8.8236, -8.8236, -8.6771], [-8.8236, -8.8236, -8.6771], [-8.7638, -8.7638, -8.6240]] ) elif model_name == "upernet-convnext-base": SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor( [[-8.8558, -8.8558, -8.6905], [-8.8558, -8.8558, -8.6905], [-8.7669, -8.7669, -8.6021]] ) elif model_name == "upernet-convnext-large": SCREAMING_SNAKE_CASE : int = torch.tensor( [[-8.6660, -8.6660, -8.6210], [-8.6660, -8.6660, -8.6210], [-8.6310, -8.6310, -8.5964]] ) elif model_name == "upernet-convnext-xlarge": SCREAMING_SNAKE_CASE : List[Any] = torch.tensor( [[-8.4980, -8.4980, -8.3977], [-8.4980, -8.4980, -8.3977], [-8.4379, -8.4379, -8.3412]] ) print("""Logits:""" , outputs.logits[0, 0, :3, :3] ) assert torch.allclose(outputs.logits[0, 0, :3, :3] , lowercase__ , atol=1e-4 ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: print(F"Saving model {model_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(lowercase__ ) print(F"Saving processor to {pytorch_dump_folder_path}" ) processor.save_pretrained(lowercase__ ) if push_to_hub: print(F"Pushing model and processor for {model_name} to hub" ) model.push_to_hub(F"openmmlab/{model_name}" ) processor.push_to_hub(F"openmmlab/{model_name}" ) if __name__ == "__main__": UpperCAmelCase__ : int = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default="""upernet-convnext-tiny""", type=str, choices=[F"""upernet-convnext-{size}""" for size in ["""tiny""", """small""", """base""", """large""", """xlarge"""]], help="""Name of the ConvNext UperNet model you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) parser.add_argument( """--push_to_hub""", action="""store_true""", help="""Whether or not to push the converted model to the 🤗 hub.""" ) UpperCAmelCase__ : int = parser.parse_args() convert_upernet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
245
import itertools import random import unittest import numpy as np from transformers import WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, WavaVecaConfig, WavaVecaFeatureExtractor from transformers.testing_utils import require_torch, slow from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin _UpperCamelCase = random.Random() def _lowercase ( lowercase__ , lowercase__=1.0 , lowercase__=None , lowercase__=None ): if rng is None: __lowerCAmelCase : Optional[Any] = global_rng __lowerCAmelCase : Tuple = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class __lowercase (unittest.TestCase ): def __init__( self , A_ , A_=7 , A_=400 , A_=2000 , A_=1 , A_=0.0 , A_=1_6000 , A_=True , A_=True , ) ->List[Any]: '''simple docstring''' __lowerCAmelCase : List[Any] = parent __lowerCAmelCase : Optional[int] = batch_size __lowerCAmelCase : Any = min_seq_length __lowerCAmelCase : Tuple = max_seq_length __lowerCAmelCase : Tuple = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) __lowerCAmelCase : Dict = feature_size __lowerCAmelCase : Optional[int] = padding_value __lowerCAmelCase : Tuple = sampling_rate __lowerCAmelCase : Union[str, Any] = return_attention_mask __lowerCAmelCase : Dict = do_normalize def UpperCamelCase__ ( self ) ->Optional[Any]: '''simple docstring''' return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def UpperCamelCase__ ( self , A_=False , A_=False ) ->Union[str, Any]: '''simple docstring''' def _flatten(A_ ): return list(itertools.chain(*A_ ) ) if equal_length: __lowerCAmelCase : Dict = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size __lowerCAmelCase : Tuple = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: __lowerCAmelCase : Tuple = [np.asarray(A_ ) for x in speech_inputs] return speech_inputs class __lowercase (_UpperCAmelCase , unittest.TestCase ): _UpperCamelCase = WavaVecaFeatureExtractor def UpperCamelCase__ ( self ) ->Dict: '''simple docstring''' __lowerCAmelCase : List[Any] = WavaVecaFeatureExtractionTester(self ) def UpperCamelCase__ ( self , A_ ) ->Optional[Any]: '''simple docstring''' self.assertTrue(np.all(np.mean(A_ , axis=0 ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(A_ , axis=0 ) - 1 ) < 1e-3 ) ) def UpperCamelCase__ ( self ) ->Tuple: '''simple docstring''' __lowerCAmelCase : List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 __lowerCAmelCase : Optional[Any] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] __lowerCAmelCase : Any = [np.asarray(A_ ) for speech_input in speech_inputs] # Test not batched input __lowerCAmelCase : Optional[Any] = feat_extract(speech_inputs[0] , return_tensors='''np''' ).input_values __lowerCAmelCase : Dict = feat_extract(np_speech_inputs[0] , return_tensors='''np''' ).input_values self.assertTrue(np.allclose(A_ , A_ , atol=1e-3 ) ) # Test batched __lowerCAmelCase : Dict = feat_extract(A_ , return_tensors='''np''' ).input_values __lowerCAmelCase : Dict = feat_extract(A_ , return_tensors='''np''' ).input_values for enc_seq_a, enc_seq_a in zip(A_ , A_ ): self.assertTrue(np.allclose(A_ , A_ , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. __lowerCAmelCase : int = [floats_list((1, x) )[0] for x in (800, 800, 800)] __lowerCAmelCase : List[Any] = np.asarray(A_ ) __lowerCAmelCase : Any = feat_extract(A_ , return_tensors='''np''' ).input_values __lowerCAmelCase : Union[str, Any] = feat_extract(A_ , return_tensors='''np''' ).input_values for enc_seq_a, enc_seq_a in zip(A_ , A_ ): self.assertTrue(np.allclose(A_ , A_ , atol=1e-3 ) ) def UpperCamelCase__ ( self ) ->Union[str, Any]: '''simple docstring''' __lowerCAmelCase : Optional[int] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __lowerCAmelCase : str = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] __lowerCAmelCase : str = ['''longest''', '''max_length''', '''do_not_pad'''] __lowerCAmelCase : str = [None, 1600, None] for max_length, padding in zip(A_ , A_ ): __lowerCAmelCase : Optional[int] = feat_extract(A_ , padding=A_ , max_length=A_ , return_tensors='''np''' ) __lowerCAmelCase : Optional[Any] = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800] ) self.assertTrue(input_values[0][800:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[1][:1000] ) self.assertTrue(input_values[0][1000:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[2][:1200] ) def UpperCamelCase__ ( self ) ->Dict: '''simple docstring''' __lowerCAmelCase : List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __lowerCAmelCase : Optional[int] = range(800 , 1400 , 200 ) __lowerCAmelCase : Union[str, Any] = [floats_list((1, x) )[0] for x in lengths] __lowerCAmelCase : int = ['''longest''', '''max_length''', '''do_not_pad'''] __lowerCAmelCase : List[str] = [None, 1600, None] for max_length, padding in zip(A_ , A_ ): __lowerCAmelCase : Union[str, Any] = feat_extract(A_ , max_length=A_ , padding=A_ ) __lowerCAmelCase : Union[str, Any] = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800] ) self._check_zero_mean_unit_variance(input_values[1][:1000] ) self._check_zero_mean_unit_variance(input_values[2][:1200] ) def UpperCamelCase__ ( self ) ->Tuple: '''simple docstring''' __lowerCAmelCase : Dict = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __lowerCAmelCase : Optional[Any] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] __lowerCAmelCase : List[str] = feat_extract( A_ , truncation=A_ , max_length=1000 , padding='''max_length''' , return_tensors='''np''' ) __lowerCAmelCase : int = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1] ) self._check_zero_mean_unit_variance(input_values[2] ) def UpperCamelCase__ ( self ) ->List[str]: '''simple docstring''' __lowerCAmelCase : Dict = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __lowerCAmelCase : int = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] __lowerCAmelCase : int = feat_extract( A_ , truncation=A_ , max_length=1000 , padding='''longest''' , return_tensors='''np''' ) __lowerCAmelCase : Optional[Any] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1, :1000] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertTrue(input_values.shape == (3, 1000) ) __lowerCAmelCase : Any = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] __lowerCAmelCase : Optional[int] = feat_extract( A_ , truncation=A_ , max_length=2000 , padding='''longest''' , return_tensors='''np''' ) __lowerCAmelCase : List[str] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1, :1000] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length > longest -> then pad to longest self.assertTrue(input_values.shape == (3, 1200) ) @require_torch def UpperCamelCase__ ( self ) ->Any: '''simple docstring''' import torch __lowerCAmelCase : Union[str, Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __lowerCAmelCase : Any = np.random.rand(100 ).astype(np.floataa ) __lowerCAmelCase : List[Any] = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: __lowerCAmelCase : Any = feature_extractor.pad([{'''input_values''': inputs}] , return_tensors='''np''' ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) __lowerCAmelCase : List[str] = feature_extractor.pad([{'''input_values''': inputs}] , return_tensors='''pt''' ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) @slow @require_torch def UpperCamelCase__ ( self ) ->int: '''simple docstring''' for model_id in WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST: __lowerCAmelCase : Any = WavaVecaConfig.from_pretrained(A_ ) __lowerCAmelCase : Tuple = WavaVecaFeatureExtractor.from_pretrained(A_ ) # only "layer" feature extraction norm should make use of # attention_mask self.assertEqual(feat_extract.return_attention_mask , config.feat_extract_norm == '''layer''' )
275
0
import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_pegasus import PegasusTokenizer else: _snake_case : Optional[Any] = None _snake_case : int = logging.get_logger(__name__) _snake_case : Union[str, Any] = "▁" _snake_case : Union[str, Any] = {"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"} _snake_case : Dict = { "vocab_file": {"google/pegasus-xsum": "https://huggingface.co/google/pegasus-xsum/resolve/main/spiece.model"}, "tokenizer_file": { "google/pegasus-xsum": "https://huggingface.co/google/pegasus-xsum/resolve/main/tokenizer.json" }, } _snake_case : Tuple = { "google/pegasus-xsum": 512, } class a (_UpperCAmelCase ): """simple docstring""" __UpperCAmelCase : List[Any] = VOCAB_FILES_NAMES __UpperCAmelCase : Optional[int] = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase : Optional[int] = PegasusTokenizer __UpperCAmelCase : str = ["input_ids", "attention_mask"] def __init__( self : Optional[int] , lowerCamelCase : Optional[Any]=None , lowerCamelCase : List[str]=None , lowerCamelCase : Optional[Any]="<pad>" , lowerCamelCase : Dict="</s>" , lowerCamelCase : Optional[int]="<unk>" , lowerCamelCase : Dict="<mask_2>" , lowerCamelCase : Tuple="<mask_1>" , lowerCamelCase : List[Any]=None , lowerCamelCase : Union[str, Any]=103 , **lowerCamelCase : Dict , ) -> List[str]: __snake_case : Any = offset if additional_special_tokens is not None: if not isinstance(A_ , A_ ): raise TypeError( F'additional_special_tokens should be of type {type(A_ )}, but is' F' {type(A_ )}' ) __snake_case : Union[str, Any] = ( ([mask_token_sent] + additional_special_tokens) if mask_token_sent not in additional_special_tokens and mask_token_sent is not None else additional_special_tokens ) # fill additional tokens with ..., <unk_token_102> in case not all additional tokens are already taken additional_special_tokens_extended += [ F'<unk_{i}>' for i in range(len(A_ ) , self.offset - 1 ) ] if len(set(A_ ) ) != len(A_ ): raise ValueError( "Please make sure that the provided additional_special_tokens do not contain an incorrectly" F' shifted list of <unk_x> tokens. Found {additional_special_tokens_extended}.' ) __snake_case : Union[str, Any] = additional_special_tokens_extended else: __snake_case : Any = [mask_token_sent] if mask_token_sent is not None else [] additional_special_tokens += [F'<unk_{i}>' for i in range(2 , self.offset )] super().__init__( A_ , tokenizer_file=A_ , pad_token=A_ , eos_token=A_ , unk_token=A_ , mask_token=A_ , mask_token_sent=A_ , offset=A_ , additional_special_tokens=A_ , **A_ , ) __snake_case : List[str] = vocab_file __snake_case : List[Any] = False if not self.vocab_file else True def __snake_case ( self : Union[str, Any] , lowerCamelCase : List[str] ) -> str: __snake_case : int = set(self.all_special_ids ) # call it once instead of inside list comp all_special_ids.remove(self.unk_token_id ) # <unk> is only sometimes special if all_special_ids != set(range(len(self.additional_special_tokens ) + 3 ) ): raise ValueError( "There should be 3 special tokens: mask_token, pad_token, and eos_token +" F' {len(self.additional_special_tokens )} additional_special_tokens, but got {all_special_ids}' ) return [1 if x in all_special_ids else 0 for x in seq] def __snake_case ( self : Union[str, Any] , lowerCamelCase : int , lowerCamelCase : str = None , lowerCamelCase : Optional[int] = False ) -> List[int]: if already_has_special_tokens: return self._special_token_mask(A_ ) elif token_ids_a is None: return self._special_token_mask(A_ ) + [1] else: return self._special_token_mask(token_ids_a + token_ids_a ) + [1] def __snake_case ( self : str , lowerCamelCase : Optional[Any] , lowerCamelCase : Tuple=None ) -> List[int]: if token_ids_a is None: return token_ids_a + [self.eos_token_id] # We don't expect to process pairs, but leave the pair logic for API consistency return token_ids_a + token_ids_a + [self.eos_token_id] def __snake_case ( self : Union[str, Any] , lowerCamelCase : Dict , lowerCamelCase : int = None ) -> Tuple[str]: if not self.can_save_slow_tokenizer: raise ValueError( "Your fast tokenizer does not have the necessary information to save the vocabulary for a slow " "tokenizer." ) if not os.path.isdir(A_ ): logger.error(F'Vocabulary path ({save_directory}) should be a directory' ) return __snake_case : Dict = os.path.join( A_ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A_ ): copyfile(self.vocab_file , A_ ) return (out_vocab_file,)
123
import unittest from transformers import DebertaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DebertaForMaskedLM, DebertaForQuestionAnswering, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaModel, ) from transformers.models.deberta.modeling_deberta import DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST class __lowercase (_UpperCAmelCase ): def __init__( self , A_ , A_=13 , A_=7 , A_=True , A_=True , A_=True , A_=True , A_=99 , A_=32 , A_=5 , A_=4 , A_=37 , A_="gelu" , A_=0.1 , A_=0.1 , A_=512 , A_=16 , A_=2 , A_=0.02 , A_=False , A_=True , A_="None" , A_=3 , A_=4 , A_=None , ) ->List[Any]: '''simple docstring''' __lowerCAmelCase : Union[str, Any] = parent __lowerCAmelCase : List[str] = batch_size __lowerCAmelCase : Dict = seq_length __lowerCAmelCase : List[Any] = is_training __lowerCAmelCase : List[Any] = use_input_mask __lowerCAmelCase : Optional[int] = use_token_type_ids __lowerCAmelCase : Tuple = use_labels __lowerCAmelCase : str = vocab_size __lowerCAmelCase : int = hidden_size __lowerCAmelCase : Any = num_hidden_layers __lowerCAmelCase : Any = num_attention_heads __lowerCAmelCase : Dict = intermediate_size __lowerCAmelCase : int = hidden_act __lowerCAmelCase : int = hidden_dropout_prob __lowerCAmelCase : Any = attention_probs_dropout_prob __lowerCAmelCase : List[str] = max_position_embeddings __lowerCAmelCase : Union[str, Any] = type_vocab_size __lowerCAmelCase : Union[str, Any] = type_sequence_label_size __lowerCAmelCase : Optional[int] = initializer_range __lowerCAmelCase : int = num_labels __lowerCAmelCase : int = num_choices __lowerCAmelCase : List[str] = relative_attention __lowerCAmelCase : Union[str, Any] = position_biased_input __lowerCAmelCase : int = pos_att_type __lowerCAmelCase : List[Any] = scope def UpperCamelCase__ ( self ) ->Dict: '''simple docstring''' __lowerCAmelCase : Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __lowerCAmelCase : int = None if self.use_input_mask: __lowerCAmelCase : List[Any] = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) __lowerCAmelCase : List[str] = None if self.use_token_type_ids: __lowerCAmelCase : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __lowerCAmelCase : Union[str, Any] = None __lowerCAmelCase : int = None __lowerCAmelCase : List[str] = None if self.use_labels: __lowerCAmelCase : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCAmelCase : Dict = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __lowerCAmelCase : Union[str, Any] = ids_tensor([self.batch_size] , self.num_choices ) __lowerCAmelCase : Tuple = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCamelCase__ ( self ) ->List[Any]: '''simple docstring''' return DebertaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , pos_att_type=self.pos_att_type , ) def UpperCamelCase__ ( self ) ->str: '''simple docstring''' __lowerCAmelCase : str = self.get_config() __lowerCAmelCase : Dict = 300 return config def UpperCamelCase__ ( self , A_ ) ->Union[str, Any]: '''simple docstring''' self.parent.assertListEqual(list(result.loss.size() ) , [] ) def UpperCamelCase__ ( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ) ->Any: '''simple docstring''' __lowerCAmelCase : Optional[Any] = DebertaModel(config=A_ ) model.to(A_ ) model.eval() __lowerCAmelCase : str = model(A_ , attention_mask=A_ , token_type_ids=A_ )[0] __lowerCAmelCase : Any = model(A_ , token_type_ids=A_ )[0] __lowerCAmelCase : List[str] = model(A_ )[0] self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] ) def UpperCamelCase__ ( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ) ->int: '''simple docstring''' __lowerCAmelCase : Tuple = DebertaForMaskedLM(config=A_ ) model.to(A_ ) model.eval() __lowerCAmelCase : Union[str, Any] = model(A_ , attention_mask=A_ , token_type_ids=A_ , labels=A_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCamelCase__ ( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ) ->Any: '''simple docstring''' __lowerCAmelCase : Any = self.num_labels __lowerCAmelCase : Tuple = DebertaForSequenceClassification(A_ ) model.to(A_ ) model.eval() __lowerCAmelCase : Union[str, Any] = model(A_ , attention_mask=A_ , token_type_ids=A_ , labels=A_ ) self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] ) self.check_loss_output(A_ ) def UpperCamelCase__ ( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ) ->Dict: '''simple docstring''' __lowerCAmelCase : List[Any] = self.num_labels __lowerCAmelCase : Optional[int] = DebertaForTokenClassification(config=A_ ) model.to(A_ ) model.eval() __lowerCAmelCase : Tuple = model(A_ , attention_mask=A_ , token_type_ids=A_ , labels=A_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCamelCase__ ( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ) ->str: '''simple docstring''' __lowerCAmelCase : List[str] = DebertaForQuestionAnswering(config=A_ ) model.to(A_ ) model.eval() __lowerCAmelCase : int = model( A_ , attention_mask=A_ , token_type_ids=A_ , start_positions=A_ , end_positions=A_ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def UpperCamelCase__ ( self ) ->List[str]: '''simple docstring''' __lowerCAmelCase : Any = self.prepare_config_and_inputs() ( ( __lowerCAmelCase ), ( __lowerCAmelCase ), ( __lowerCAmelCase ), ( __lowerCAmelCase ), ( __lowerCAmelCase ), ( __lowerCAmelCase ), ( __lowerCAmelCase ), ) : Tuple = config_and_inputs __lowerCAmelCase : Tuple = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class __lowercase (_UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): _UpperCamelCase = ( ( DebertaModel, DebertaForMaskedLM, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaForQuestionAnswering, ) if is_torch_available() else () ) _UpperCamelCase = ( { """feature-extraction""": DebertaModel, """fill-mask""": DebertaForMaskedLM, """question-answering""": DebertaForQuestionAnswering, """text-classification""": DebertaForSequenceClassification, """token-classification""": DebertaForTokenClassification, """zero-shot""": DebertaForSequenceClassification, } if is_torch_available() else {} ) _UpperCamelCase = True _UpperCamelCase = False _UpperCamelCase = False _UpperCamelCase = False _UpperCamelCase = False def UpperCamelCase__ ( self ) ->int: '''simple docstring''' __lowerCAmelCase : int = DebertaModelTester(self ) __lowerCAmelCase : List[Any] = ConfigTester(self , config_class=A_ , hidden_size=37 ) def UpperCamelCase__ ( self ) ->Optional[Any]: '''simple docstring''' self.config_tester.run_common_tests() def UpperCamelCase__ ( self ) ->List[Any]: '''simple docstring''' __lowerCAmelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*A_ ) def UpperCamelCase__ ( self ) ->int: '''simple docstring''' __lowerCAmelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*A_ ) def UpperCamelCase__ ( self ) ->int: '''simple docstring''' __lowerCAmelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*A_ ) def UpperCamelCase__ ( self ) ->Optional[int]: '''simple docstring''' __lowerCAmelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*A_ ) def UpperCamelCase__ ( self ) ->List[Any]: '''simple docstring''' __lowerCAmelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*A_ ) @slow def UpperCamelCase__ ( self ) ->Tuple: '''simple docstring''' for model_name in DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCAmelCase : Optional[int] = DebertaModel.from_pretrained(A_ ) self.assertIsNotNone(A_ ) @require_torch @require_sentencepiece @require_tokenizers class __lowercase (unittest.TestCase ): @unittest.skip(reason='''Model not available yet''' ) def UpperCamelCase__ ( self ) ->Dict: '''simple docstring''' pass @slow def UpperCamelCase__ ( self ) ->Tuple: '''simple docstring''' __lowerCAmelCase : str = DebertaModel.from_pretrained('''microsoft/deberta-base''' ) __lowerCAmelCase : Tuple = torch.tensor([[0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2]] ) __lowerCAmelCase : Union[str, Any] = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __lowerCAmelCase : Optional[int] = model(A_ , attention_mask=A_ )[0] # compare the actual values for a slice. __lowerCAmelCase : Optional[Any] = torch.tensor( [[[-0.5_986, -0.8_055, -0.8_462], [1.4_484, -0.9_348, -0.8_059], [0.3_123, 0.0_032, -1.4_131]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , A_ , atol=1e-4 ) , f"""{output[:, 1:4, 1:4]}""" )
275
0
"""simple docstring""" from __future__ import annotations from decimal import Decimal from math import * # noqa: F403 from sympy import diff def lowercase ( a__ : Optional[int] , a__ : List[str] , a__ : str = 10**-10 ) -> Optional[Any]: _UpperCamelCase = a while True: _UpperCamelCase = Decimal(lowercase__ ) - ( Decimal(eval(lowercase__ ) ) / Decimal(eval(str(diff(lowercase__ ) ) ) ) # noqa: S307 ) # This number dictates the accuracy of the answer if abs(eval(lowercase__ ) ) < precision: # noqa: S307 return float(lowercase__ ) # Let's Execute if __name__ == "__main__": # Find root of trigonometric function # Find value of pi print(F'''The root of sin(x) = 0 is {newton_raphson('sin(x)', 2)}''') # Find root of polynomial print(F'''The root of x**2 - 5*x + 2 = 0 is {newton_raphson('x**2 - 5*x + 2', 0.4)}''') # Find Square Root of 5 print(F'''The root of log(x) - 1 = 0 is {newton_raphson('log(x) - 1', 2)}''') # Exponential Roots print(F'''The root of exp(x) - 1 = 0 is {newton_raphson('exp(x) - 1', 0)}''')
256
from typing import Dict import numpy as np import torch from . import residue_constants as rc from .tensor_utils import tensor_tree_map, tree_map def _lowercase ( lowercase__ ): __lowerCAmelCase : str = [] __lowerCAmelCase : List[Any] = [] __lowerCAmelCase : str = [] for rt in rc.restypes: __lowerCAmelCase : List[Any] = rc.restype_name_to_atomaa_names[rc.restype_atoa[rt]] restype_atomaa_to_atomaa_list.append([(rc.atom_order[name] if name else 0) for name in atom_names] ) __lowerCAmelCase : List[str] = {name: i for i, name in enumerate(lowercase__ )} restype_atomaa_to_atomaa_list.append( [(atom_name_to_idxaa[name] if name in atom_name_to_idxaa else 0) for name in rc.atom_types] ) restype_atomaa_mask_list.append([(1.0 if name else 0.0) for name in atom_names] ) # Add dummy mapping for restype 'UNK' restype_atomaa_to_atomaa_list.append([0] * 1_4 ) restype_atomaa_to_atomaa_list.append([0] * 3_7 ) restype_atomaa_mask_list.append([0.0] * 1_4 ) __lowerCAmelCase : List[Any] = torch.tensor( lowercase__ , dtype=torch.intaa , device=protein['''aatype'''].device , ) __lowerCAmelCase : Optional[Any] = torch.tensor( lowercase__ , dtype=torch.intaa , device=protein['''aatype'''].device , ) __lowerCAmelCase : Tuple = torch.tensor( lowercase__ , dtype=torch.floataa , device=protein['''aatype'''].device , ) __lowerCAmelCase : List[Any] = protein['''aatype'''].to(torch.long ) # create the mapping for (residx, atom14) --> atom37, i.e. an array # with shape (num_res, 14) containing the atom37 indices for this protein __lowerCAmelCase : Any = restype_atomaa_to_atomaa[protein_aatype] __lowerCAmelCase : Union[str, Any] = restype_atomaa_mask[protein_aatype] __lowerCAmelCase : int = residx_atomaa_mask __lowerCAmelCase : List[str] = residx_atomaa_to_atomaa.long() # create the gather indices for mapping back __lowerCAmelCase : int = restype_atomaa_to_atomaa[protein_aatype] __lowerCAmelCase : Union[str, Any] = residx_atomaa_to_atomaa.long() # create the corresponding mask __lowerCAmelCase : str = torch.zeros([2_1, 3_7] , dtype=torch.floataa , device=protein['''aatype'''].device ) for restype, restype_letter in enumerate(rc.restypes ): __lowerCAmelCase : Optional[int] = rc.restype_atoa[restype_letter] __lowerCAmelCase : Optional[Any] = rc.residue_atoms[restype_name] for atom_name in atom_names: __lowerCAmelCase : str = rc.atom_order[atom_name] __lowerCAmelCase : List[Any] = 1 __lowerCAmelCase : Union[str, Any] = restype_atomaa_mask[protein_aatype] __lowerCAmelCase : Any = residx_atomaa_mask return protein def _lowercase ( lowercase__ ): __lowerCAmelCase : Dict = tree_map(lambda lowercase__ : torch.tensor(lowercase__ , device=batch['''aatype'''].device ) , lowercase__ , np.ndarray ) __lowerCAmelCase : Tuple = tensor_tree_map(lambda lowercase__ : np.array(lowercase__ ) , make_atomaa_masks(lowercase__ ) ) return out
275
0
'''simple docstring''' import gc import importlib.metadata import tempfile import unittest from packaging import version from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoTokenizer, BitsAndBytesConfig, pipeline, ) from transformers.testing_utils import ( is_torch_available, require_accelerate, require_bitsandbytes, require_torch, require_torch_gpu, require_torch_multi_gpu, slow, ) def _lowerCamelCase ( lowercase : Union[str, Any] ) -> List[Any]: if model.config.model_type == "gpt2": return model.transformer.h[0].mlp.c_fc return model.transformer.h[0].mlp.dense_ah_to_h if is_torch_available(): import torch import torch.nn as nn class __SCREAMING_SNAKE_CASE (nn.Module ): """simple docstring""" def __init__( self : str , __a : List[Any] , __a : List[Any] ): super().__init__() _a = module _a = nn.Sequential( nn.Linear(module.in_features , A_ , bias=A_ ) , nn.Linear(A_ , module.out_features , bias=A_ ) , ) _a = (2.0 / (5 * min(module.in_features , module.out_features ))) ** 0.5 nn.init.normal_(self.adapter[0].weight , std=A_ ) nn.init.zeros_(self.adapter[1].weight ) self.adapter.to(module.weight.device ) def UpperCamelCase__ ( self : Tuple , __a : List[Any] , *__a : List[Any] , **__a : str ): return self.module(A_ , *A_ , **A_ ) + self.adapter(A_ ) @require_bitsandbytes @require_accelerate @require_torch @require_torch_gpu @slow class __SCREAMING_SNAKE_CASE (unittest.TestCase ): """simple docstring""" __a ='bigscience/bloom-1b7' # Constant values __a =2.1_09_65_95_52_69_25_74 __a ='Hello my name is' __a =set() EXPECTED_OUTPUTS.add('Hello my name is John and I am a professional photographer. I' ) EXPECTED_OUTPUTS.add('Hello my name is John.\nI am a friend of your father.\n' ) EXPECTED_OUTPUTS.add('Hello my name is John Doe, I am a student at the University' ) __a =10 def UpperCamelCase__ ( self : Tuple ): _a = AutoTokenizer.from_pretrained(self.model_name ) class __SCREAMING_SNAKE_CASE (_UpperCAmelCase ): """simple docstring""" def UpperCamelCase__ ( self : Tuple ): super().setUp() # Models and tokenizer _a = AutoModelForCausalLM.from_pretrained( self.model_name , torch_dtype=torch.floataa , device_map="auto" ) _a = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=A_ , device_map="auto" ) def UpperCamelCase__ ( self : int ): del self.model_fpaa del self.model_abit gc.collect() torch.cuda.empty_cache() def UpperCamelCase__ ( self : Any ): _a = self.model_abit.config self.assertTrue(hasattr(A_ , "quantization_config" ) ) _a = config.to_dict() _a = config.to_diff_dict() _a = config.to_json_string() def UpperCamelCase__ ( self : Union[str, Any] ): from bitsandbytes.nn import Paramsabit _a = self.model_fpaa.get_memory_footprint() _a = self.model_abit.get_memory_footprint() self.assertAlmostEqual(mem_fpaa / mem_abit , self.EXPECTED_RELATIVE_DIFFERENCE ) _a = get_some_linear_layer(self.model_abit ) self.assertTrue(linear.weight.__class__ == Paramsabit ) def UpperCamelCase__ ( self : str ): from transformers import TaPreTrainedModel self.model_fpaa.get_memory_footprint() self.model_abit.get_memory_footprint() for name, module in self.model_abit.named_modules(): if isinstance(A_ , torch.nn.Linear ): if name not in ["lm_head"] + TaPreTrainedModel._keep_in_fpaa_modules: # 4-bit parameters are packed in uint8 variables self.assertTrue(module.weight.dtype == torch.uinta ) def UpperCamelCase__ ( self : Dict ): _a = self.tokenizer(self.input_text , return_tensors="pt" ) _a = self.model_abit.generate(input_ids=encoded_input["input_ids"].to(0 ) , max_new_tokens=10 ) self.assertIn(self.tokenizer.decode(output_sequences[0] , skip_special_tokens=A_ ) , self.EXPECTED_OUTPUTS ) def UpperCamelCase__ ( self : str ): _a = BitsAndBytesConfig() _a = True _a = AutoModelForCausalLM.from_pretrained( self.model_name , quantization_config=A_ , device_map="auto" ) _a = self.tokenizer(self.input_text , return_tensors="pt" ) _a = model_abit_from_config.generate( input_ids=encoded_input["input_ids"].to(0 ) , max_new_tokens=10 ) self.assertIn(self.tokenizer.decode(output_sequences[0] , skip_special_tokens=A_ ) , self.EXPECTED_OUTPUTS ) def UpperCamelCase__ ( self : Tuple ): with self.assertRaises(A_ ), tempfile.TemporaryDirectory() as tmpdirname: self.model_abit.save_pretrained(A_ ) def UpperCamelCase__ ( self : Tuple ): _a = BitsAndBytesConfig() with self.assertRaises(A_ ): _a = AutoModelForCausalLM.from_pretrained( self.model_name , quantization_config=A_ , load_in_abit=A_ , device_map="auto" , bnb_abit_quant_type="nf4" , ) def UpperCamelCase__ ( self : List[Any] ): with self.assertRaises(A_ ): # Tries with `str` self.model_abit.to("cpu" ) with self.assertRaises(A_ ): # Tries with a `dtype`` self.model_abit.to(torch.floataa ) with self.assertRaises(A_ ): # Tries with a `device` self.model_abit.to(torch.device("cuda:0" ) ) with self.assertRaises(A_ ): # Tries with a `device` self.model_abit.float() with self.assertRaises(A_ ): # Tries with a `device` self.model_abit.half() # Test if we did not break anything _a = self.tokenizer(self.input_text , return_tensors="pt" ) _a = self.model_fpaa.to(torch.floataa ) _a = self.model_fpaa.generate(input_ids=encoded_input["input_ids"].to(0 ) , max_new_tokens=10 ) # Check this does not throw an error _a = self.model_fpaa.to("cpu" ) # Check this does not throw an error _a = self.model_fpaa.half() # Check this does not throw an error _a = self.model_fpaa.float() def UpperCamelCase__ ( self : List[str] ): _a = AutoModelForSeqaSeqLM.from_pretrained("t5-small" , load_in_abit=A_ , device_map="auto" ) self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.floataa ) @require_bitsandbytes @require_accelerate @require_torch @require_torch_gpu @slow class __SCREAMING_SNAKE_CASE (unittest.TestCase ): """simple docstring""" @classmethod def UpperCamelCase__ ( cls : List[str] ): _a = '''t5-small''' _a = '''google/flan-t5-small''' # flan-t5 uses dense-act instead of dense-relu-dense _a = AutoTokenizer.from_pretrained(cls.model_name ) _a = '''Translate in German: Hello, my dog is cute''' def UpperCamelCase__ ( self : List[Any] ): gc.collect() torch.cuda.empty_cache() def UpperCamelCase__ ( self : List[str] ): from transformers import TaForConditionalGeneration _a = TaForConditionalGeneration._keep_in_fpaa_modules _a = None # test with `t5-small` _a = TaForConditionalGeneration.from_pretrained(self.model_name , load_in_abit=A_ , device_map="auto" ) _a = self.tokenizer(self.input_text , return_tensors="pt" ).to(0 ) _a = model.generate(**A_ ) # test with `flan-t5-small` _a = TaForConditionalGeneration.from_pretrained( self.dense_act_model_name , load_in_abit=A_ , device_map="auto" ) _a = self.tokenizer(self.input_text , return_tensors="pt" ).to(0 ) _a = model.generate(**A_ ) _a = modules def UpperCamelCase__ ( self : Any ): import bitsandbytes as bnb from transformers import TaForConditionalGeneration # test with `t5-small` _a = TaForConditionalGeneration.from_pretrained(self.model_name , load_in_abit=A_ , device_map="auto" ) # there was a bug with decoders - this test checks that it is fixed self.assertTrue(isinstance(model.decoder.block[0].layer[0].SelfAttention.q , bnb.nn.Linearabit ) ) _a = self.tokenizer(self.input_text , return_tensors="pt" ).to(0 ) _a = model.generate(**A_ ) # test with `flan-t5-small` _a = TaForConditionalGeneration.from_pretrained( self.dense_act_model_name , load_in_abit=A_ , device_map="auto" ) _a = self.tokenizer(self.input_text , return_tensors="pt" ).to(0 ) _a = model.generate(**A_ ) class __SCREAMING_SNAKE_CASE (_UpperCAmelCase ): """simple docstring""" def UpperCamelCase__ ( self : Tuple ): super().setUp() # model_name _a = '''bigscience/bloom-560m''' _a = '''t5-small''' # Different types of model _a = AutoModel.from_pretrained(self.model_name , load_in_abit=A_ , device_map="auto" ) # Sequence classification model _a = AutoModelForSequenceClassification.from_pretrained( self.model_name , load_in_abit=A_ , device_map="auto" ) # CausalLM model _a = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=A_ , device_map="auto" ) # Seq2seq model _a = AutoModelForSeqaSeqLM.from_pretrained( self.seq_to_seq_name , load_in_abit=A_ , device_map="auto" ) def UpperCamelCase__ ( self : Tuple ): del self.base_model del self.sequence_model del self.model_abit del self.seq_to_seq_model gc.collect() torch.cuda.empty_cache() def UpperCamelCase__ ( self : List[Any] ): from bitsandbytes.nn import Paramsabit self.assertTrue(self.base_model.h[-1].mlp.dense_ah_to_h.weight.__class__ == Paramsabit ) # Other heads should be nn.Parameter self.assertTrue(self.model_abit.lm_head.weight.__class__ == torch.nn.Parameter ) self.assertTrue(self.sequence_model.score.weight.__class__ == torch.nn.Parameter ) self.assertTrue(self.seq_to_seq_model.lm_head.weight.__class__ == torch.nn.Parameter ) class __SCREAMING_SNAKE_CASE (_UpperCAmelCase ): """simple docstring""" def UpperCamelCase__ ( self : Optional[Any] ): super().setUp() def UpperCamelCase__ ( self : int ): del self.pipe gc.collect() torch.cuda.empty_cache() def UpperCamelCase__ ( self : Optional[int] ): _a = pipeline( "text-generation" , model=self.model_name , model_kwargs={"device_map": "auto", "load_in_4bit": True, "torch_dtype": torch.floataa} , max_new_tokens=self.MAX_NEW_TOKENS , ) # Real second forward pass _a = self.pipe(self.input_text ) self.assertIn(pipeline_output[0]["generated_text"] , self.EXPECTED_OUTPUTS ) @require_torch_multi_gpu class __SCREAMING_SNAKE_CASE (_UpperCAmelCase ): """simple docstring""" def UpperCamelCase__ ( self : Tuple ): super().setUp() def UpperCamelCase__ ( self : Tuple ): _a = AutoModelForCausalLM.from_pretrained( self.model_name , load_in_abit=A_ , device_map="balanced" ) # Check correct device map self.assertEqual(set(model_parallel.hf_device_map.values() ) , {0, 1} ) # Check that inference pass works on the model _a = self.tokenizer(self.input_text , return_tensors="pt" ) # Second real batch _a = model_parallel.generate(input_ids=encoded_input["input_ids"].to(0 ) , max_new_tokens=10 ) self.assertIn(self.tokenizer.decode(output_parallel[0] , skip_special_tokens=A_ ) , self.EXPECTED_OUTPUTS ) class __SCREAMING_SNAKE_CASE (_UpperCAmelCase ): """simple docstring""" def UpperCamelCase__ ( self : Tuple ): _a = '''facebook/opt-350m''' super().setUp() def UpperCamelCase__ ( self : int ): if version.parse(importlib.metadata.version("bitsandbytes" ) ) < version.parse("0.37.0" ): return # Step 1: freeze all parameters _a = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=A_ ) self.assertEqual(set(model.hf_device_map.values() ) , {torch.cuda.current_device()} ) for param in model.parameters(): _a = False # freeze the model - train adapters later if param.ndim == 1: # cast the small parameters (e.g. layernorm) to fp32 for stability _a = param.data.to(torch.floataa ) # Step 2: add adapters for _, module in model.named_modules(): if "OPTAttention" in repr(type(A_ ) ): _a = LoRALayer(module.q_proj , rank=16 ) _a = LoRALayer(module.k_proj , rank=16 ) _a = LoRALayer(module.v_proj , rank=16 ) # Step 3: dummy batch _a = self.tokenizer("Test batch " , return_tensors="pt" ).to(0 ) # Step 4: Check if the gradient is not None with torch.cuda.amp.autocast(): _a = model.forward(**A_ ) out.logits.norm().backward() for module in model.modules(): if isinstance(A_ , A_ ): self.assertTrue(module.adapter[1].weight.grad is not None ) self.assertTrue(module.adapter[1].weight.grad.norm().item() > 0 ) elif isinstance(A_ , nn.Embedding ): self.assertTrue(module.weight.grad is None ) class __SCREAMING_SNAKE_CASE (_UpperCAmelCase ): """simple docstring""" __a ='gpt2-xl' __a =3.31_91_85_48_54_15_21_87
63
def _lowercase ( lowercase__ ): if not all(x.isalpha() for x in string ): raise ValueError('''String must only contain alphabetic characters.''' ) __lowerCAmelCase : int = sorted(string.lower() ) return len(lowercase__ ) == len(set(lowercase__ ) ) if __name__ == "__main__": _UpperCamelCase = input("Enter a string ").strip() _UpperCamelCase = is_isogram(input_str) print(F"{input_str} is {'an' if isogram else 'not an'} isogram.")
275
0
import os import jsonlines import numpy as np from tqdm import tqdm _SCREAMING_SNAKE_CASE = 2_0_4_8 _SCREAMING_SNAKE_CASE = 4_0_9_6 _SCREAMING_SNAKE_CASE = 4_2 _SCREAMING_SNAKE_CASE = os.environ.pop("""PROCESS_TRAIN""", """false""") _SCREAMING_SNAKE_CASE = {"""null""": 0, """short""": 1, """long""": 2, """yes""": 3, """no""": 4} def lowercase( UpperCamelCase_ ) -> int: '''simple docstring''' def choose_first(UpperCamelCase_ , UpperCamelCase_=False ): assert isinstance(lowercase__ , lowercase__ ) if len(lowercase__ ) == 1: UpperCamelCase = answer[0] return {k: [answer[k]] for k in answer} if is_long_answer else answer for a in answer: if is_long_answer: UpperCamelCase = {k: [a[k]] for k in a} if len(a["""start_token"""] ) > 0: break return a UpperCamelCase = {'''id''': example['''id''']} UpperCamelCase = example['''annotations'''] UpperCamelCase = annotation['''yes_no_answer'''] if 0 in yes_no_answer or 1 in yes_no_answer: UpperCamelCase = ['''yes'''] if 1 in yes_no_answer else ['''no'''] UpperCamelCase = [] UpperCamelCase = [] UpperCamelCase = ['''<cls>'''] else: UpperCamelCase = ['''short'''] UpperCamelCase = choose_first(annotation["""short_answers"""] ) if len(out["""start_token"""] ) == 0: # answer will be long if short is not available UpperCamelCase = ['''long'''] UpperCamelCase = choose_first(annotation["""long_answer"""] , is_long_answer=lowercase__ ) UpperCamelCase = [] answer.update(lowercase__ ) # disregard some samples if len(answer["""start_token"""] ) > 1 or answer["start_token"] == answer["end_token"]: UpperCamelCase = True else: UpperCamelCase = False UpperCamelCase = ['''start_token''', '''end_token''', '''start_byte''', '''end_byte''', '''text'''] if not all(isinstance(answer[k] , lowercase__ ) for k in cols ): raise ValueError("""Issue in ID""" , example["""id"""] ) return answer def lowercase( UpperCamelCase_ , UpperCamelCase_=False ) -> Optional[int]: '''simple docstring''' UpperCamelCase = _get_single_answer(lowercase__ ) # bytes are of no use del answer["start_byte"] del answer["end_byte"] # handle yes_no answers explicitly if answer["category"][0] in ["yes", "no"]: # category is list with one element UpperCamelCase = example['''document''']['''tokens'''] UpperCamelCase = [] for i in range(len(doc["""token"""] ) ): if not doc["is_html"][i]: context.append(doc["""token"""][i] ) return { "context": " ".join(lowercase__ ), "answer": { "start_token": -100, # ignore index in cross-entropy "end_token": -100, # ignore index in cross-entropy "category": answer["category"], "span": answer["category"], # extra }, } # later, help in removing all no answers if answer["start_token"] == [-1]: return { "context": "None", "answer": { "start_token": -1, "end_token": -1, "category": "null", "span": "None", # extra }, } # handling normal samples UpperCamelCase = ['''start_token''', '''end_token'''] answer.update({k: answer[k][0] if len(answer[k] ) > 0 else answer[k] for k in cols} ) # e.g. [10] == 10 UpperCamelCase = example['''document''']['''tokens'''] UpperCamelCase = answer['''start_token'''] UpperCamelCase = answer['''end_token'''] UpperCamelCase = [] for i in range(len(doc["""token"""] ) ): if not doc["is_html"][i]: context.append(doc["""token"""][i] ) else: if answer["start_token"] > i: start_token -= 1 if answer["end_token"] > i: end_token -= 1 UpperCamelCase = ''' '''.join(context[start_token:end_token] ) # checking above code if assertion: UpperCamelCase = doc['''is_html'''][answer['''start_token'''] : answer['''end_token''']] UpperCamelCase = doc['''token'''][answer['''start_token'''] : answer['''end_token''']] UpperCamelCase = ''' '''.join([old[i] for i in range(len(lowercase__ ) ) if not is_html[i]] ) if new != old: print("""ID:""" , example["""id"""] ) print("""New:""" , lowercase__ , end="""\n""" ) print("""Old:""" , lowercase__ , end="""\n\n""" ) return { "context": " ".join(lowercase__ ), "answer": { "start_token": start_token, "end_token": end_token - 1, # this makes it inclusive "category": answer["category"], # either long or short "span": new, # extra }, } def lowercase( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_=2048 , UpperCamelCase_=4096 , UpperCamelCase_=True ) -> Dict: '''simple docstring''' # overlap will be of doc_stride - q_len UpperCamelCase = get_context_and_ans(lowercase__ , assertion=lowercase__ ) UpperCamelCase = out['''answer'''] # later, removing these samples if answer["start_token"] == -1: return { "example_id": example["id"], "input_ids": [[-1]], "labels": { "start_token": [-1], "end_token": [-1], "category": ["null"], }, } UpperCamelCase = tokenizer(example["""question"""]["""text"""] , out["""context"""] ).input_ids UpperCamelCase = input_ids.index(tokenizer.sep_token_id ) + 1 # return yes/no if answer["category"][0] in ["yes", "no"]: # category is list with one element UpperCamelCase = [] UpperCamelCase = [] UpperCamelCase = input_ids[:q_len] UpperCamelCase = range(lowercase__ , len(lowercase__ ) , max_length - doc_stride ) for i in doc_start_indices: UpperCamelCase = i + max_length - q_len UpperCamelCase = input_ids[i:end_index] inputs.append(q_indices + slice ) category.append(answer["""category"""][0] ) if slice[-1] == tokenizer.sep_token_id: break return { "example_id": example["id"], "input_ids": inputs, "labels": { "start_token": [-100] * len(lowercase__ ), "end_token": [-100] * len(lowercase__ ), "category": category, }, } UpperCamelCase = out['''context'''].split() UpperCamelCase = splitted_context[answer['''end_token''']] UpperCamelCase = len( tokenizer( """ """.join(splitted_context[: answer["""start_token"""]] ) , add_special_tokens=lowercase__ , ).input_ids ) UpperCamelCase = len( tokenizer(""" """.join(splitted_context[: answer["""end_token"""]] ) , add_special_tokens=lowercase__ ).input_ids ) answer["start_token"] += q_len answer["end_token"] += q_len # fixing end token UpperCamelCase = len(tokenizer(lowercase__ , add_special_tokens=lowercase__ ).input_ids ) if num_sub_tokens > 1: answer["end_token"] += num_sub_tokens - 1 UpperCamelCase = input_ids[answer['''start_token'''] : answer['''end_token'''] + 1] # right & left are inclusive UpperCamelCase = answer['''start_token'''] UpperCamelCase = answer['''end_token'''] if assertion: UpperCamelCase = tokenizer.decode(lowercase__ ) if answer["span"] != new: print("""ISSUE IN TOKENIZATION""" ) print("""OLD:""" , answer["""span"""] ) print("""NEW:""" , lowercase__ , end="""\n\n""" ) if len(lowercase__ ) <= max_length: return { "example_id": example["id"], "input_ids": [input_ids], "labels": { "start_token": [answer["start_token"]], "end_token": [answer["end_token"]], "category": answer["category"], }, } UpperCamelCase = input_ids[:q_len] UpperCamelCase = range(lowercase__ , len(lowercase__ ) , max_length - doc_stride ) UpperCamelCase = [] UpperCamelCase = [] UpperCamelCase = [] UpperCamelCase = [] # null, yes, no, long, short for i in doc_start_indices: UpperCamelCase = i + max_length - q_len UpperCamelCase = input_ids[i:end_index] inputs.append(q_indices + slice ) assert len(inputs[-1] ) <= max_length, "Issue in truncating length" if start_token >= i and end_token <= end_index - 1: UpperCamelCase = start_token - i + q_len UpperCamelCase = end_token - i + q_len answers_category.append(answer["""category"""][0] ) # ["short"] -> "short" else: UpperCamelCase = -100 UpperCamelCase = -100 answers_category.append("""null""" ) UpperCamelCase = inputs[-1][start_token : end_token + 1] answers_start_token.append(lowercase__ ) answers_end_token.append(lowercase__ ) if assertion: if new != old and new != [tokenizer.cls_token_id]: print("""ISSUE in strided for ID:""" , example["""id"""] ) print("""New:""" , tokenizer.decode(lowercase__ ) ) print("""Old:""" , tokenizer.decode(lowercase__ ) , end="""\n\n""" ) if slice[-1] == tokenizer.sep_token_id: break return { "example_id": example["id"], "input_ids": inputs, "labels": { "start_token": answers_start_token, "end_token": answers_end_token, "category": answers_category, }, } def lowercase( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_=2048 , UpperCamelCase_=4096 , UpperCamelCase_=False ) -> List[Any]: '''simple docstring''' UpperCamelCase = get_strided_contexts_and_ans( lowercase__ , lowercase__ , doc_stride=lowercase__ , max_length=lowercase__ , assertion=lowercase__ , ) return example def lowercase( UpperCamelCase_ , UpperCamelCase_ ) -> str: '''simple docstring''' with jsonlines.open(lowercase__ , """a""" ) as writer: for example in tqdm(lowercase__ , total=len(lowercase__ ) , desc="""Saving samples ... """ ): UpperCamelCase = example['''labels'''] for ids, start, end, cat in zip( example["""input_ids"""] , labels["""start_token"""] , labels["""end_token"""] , labels["""category"""] , ): if start == -1 and end == -1: continue # leave waste samples with no answer if cat == "null" and np.random.rand() < 0.6: continue # removing 50 % samples writer.write( { """input_ids""": ids, """start_token""": start, """end_token""": end, """category""": CATEGORY_MAPPING[cat], } ) if __name__ == "__main__": from datasets import load_dataset from transformers import BigBirdTokenizer _SCREAMING_SNAKE_CASE = load_dataset("""natural_questions""") _SCREAMING_SNAKE_CASE = BigBirdTokenizer.from_pretrained("""google/bigbird-roberta-base""") _SCREAMING_SNAKE_CASE = data["""train""" if PROCESS_TRAIN == """true""" else """validation"""] _SCREAMING_SNAKE_CASE = { """tokenizer""": tokenizer, """doc_stride""": DOC_STRIDE, """max_length""": MAX_LENGTH, """assertion""": False, } _SCREAMING_SNAKE_CASE = data.map(prepare_inputs, fn_kwargs=fn_kwargs) _SCREAMING_SNAKE_CASE = data.remove_columns(["""annotations""", """document""", """id""", """question"""]) print(data) np.random.seed(SEED) _SCREAMING_SNAKE_CASE = """nq-training.jsonl""" if PROCESS_TRAIN == """true""" else """nq-validation.jsonl""" save_to_disk(data, file_name=cache_file_name)
343
from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin @dataclass class __lowercase (_UpperCAmelCase ): _UpperCamelCase = 42 _UpperCamelCase = 42 _UpperCamelCase = None class __lowercase (_UpperCAmelCase , _UpperCAmelCase ): _UpperCamelCase = 2 @register_to_config def __init__( self , A_ = 0.02 , A_ = 100 , A_ = 1.007 , A_ = 80 , A_ = 0.05 , A_ = 50 , ) ->int: '''simple docstring''' __lowerCAmelCase : Optional[int] = sigma_max # setable values __lowerCAmelCase : int = None __lowerCAmelCase : np.IntTensor = None __lowerCAmelCase : torch.FloatTensor = None # sigma(t_i) def UpperCamelCase__ ( self , A_ , A_ = None ) ->torch.FloatTensor: '''simple docstring''' return sample def UpperCamelCase__ ( self , A_ , A_ = None ) ->List[str]: '''simple docstring''' __lowerCAmelCase : str = num_inference_steps __lowerCAmelCase : Dict = np.arange(0 , self.num_inference_steps )[::-1].copy() __lowerCAmelCase : Optional[Any] = torch.from_numpy(A_ ).to(A_ ) __lowerCAmelCase : Tuple = [ ( self.config.sigma_max**2 * (self.config.sigma_min**2 / self.config.sigma_max**2) ** (i / (num_inference_steps - 1)) ) for i in self.timesteps ] __lowerCAmelCase : Optional[int] = torch.tensor(A_ , dtype=torch.floataa , device=A_ ) def UpperCamelCase__ ( self , A_ , A_ , A_ = None ) ->Tuple[torch.FloatTensor, float]: '''simple docstring''' if self.config.s_min <= sigma <= self.config.s_max: __lowerCAmelCase : List[str] = min(self.config.s_churn / self.num_inference_steps , 2**0.5 - 1 ) else: __lowerCAmelCase : List[str] = 0 # sample eps ~ N(0, S_noise^2 * I) __lowerCAmelCase : int = self.config.s_noise * randn_tensor(sample.shape , generator=A_ ).to(sample.device ) __lowerCAmelCase : str = sigma + gamma * sigma __lowerCAmelCase : Any = sample + ((sigma_hat**2 - sigma**2) ** 0.5 * eps) return sample_hat, sigma_hat def UpperCamelCase__ ( self , A_ , A_ , A_ , A_ , A_ = True , ) ->Union[KarrasVeOutput, Tuple]: '''simple docstring''' __lowerCAmelCase : Union[str, Any] = sample_hat + sigma_hat * model_output __lowerCAmelCase : int = (sample_hat - pred_original_sample) / sigma_hat __lowerCAmelCase : Tuple = sample_hat + (sigma_prev - sigma_hat) * derivative if not return_dict: return (sample_prev, derivative) return KarrasVeOutput( prev_sample=A_ , derivative=A_ , pred_original_sample=A_ ) def UpperCamelCase__ ( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ = True , ) ->Union[KarrasVeOutput, Tuple]: '''simple docstring''' __lowerCAmelCase : str = sample_prev + sigma_prev * model_output __lowerCAmelCase : List[Any] = (sample_prev - pred_original_sample) / sigma_prev __lowerCAmelCase : Any = sample_hat + (sigma_prev - sigma_hat) * (0.5 * derivative + 0.5 * derivative_corr) if not return_dict: return (sample_prev, derivative) return KarrasVeOutput( prev_sample=A_ , derivative=A_ , pred_original_sample=A_ ) def UpperCamelCase__ ( self , A_ , A_ , A_ ) ->Any: '''simple docstring''' raise NotImplementedError()
275
0
'''simple docstring''' import argparse import json import os import torch from torch import nn from transformers import NllbMoeConfig, NllbMoeModel from transformers.modeling_utils import dtype_byte_size from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME def __lowerCAmelCase (__lowerCAmelCase ): _UpperCAmelCase : List[str] = [ '''encoder.version''', '''decoder.version''', '''model.encoder.version''', '''model.decoder.version''', '''decoder.output_projection.weight''', '''_float_tensor''', '''encoder.embed_positions._float_tensor''', '''decoder.embed_positions._float_tensor''', ] for k in ignore_keys: state_dict.pop(lowercase__ , lowercase__ ) def __lowerCAmelCase (__lowerCAmelCase ): _UpperCAmelCase : Dict = emb.weight.shape _UpperCAmelCase : int = nn.Linear(lowercase__ , lowercase__ , bias=lowercase__ ) _UpperCAmelCase : Tuple = emb.weight.data return lin_layer def __lowerCAmelCase (__lowerCAmelCase , __lowerCAmelCase=None ): _UpperCAmelCase : Union[str, Any] = {} for old_key in state_dict.keys(): _UpperCAmelCase : Any = old_key if "moe_layer.experts." in key: if expert_idx is not None: _UpperCAmelCase : int = key.replace("moe_layer.experts.0" , F"""ffn.experts.expert_{expert_idx}""" ) else: _UpperCAmelCase : Tuple = key.replace("moe_layer.experts." , "ffn.experts.expert_" ) if "gate" in key: _UpperCAmelCase : List[Any] = key.replace(".moe_layer.gate.wg" , ".ffn.router.classifier" ) if "fc2" and "experts" not in key: _UpperCAmelCase : int = key.replace(".fc2." , ".ffn.fc2." ) if "fc1" and "experts" not in key: _UpperCAmelCase : Tuple = key.replace(".fc1." , ".ffn.fc1." ) if ".encoder_attn." in key: _UpperCAmelCase : Tuple = key.replace(".encoder_attn." , ".cross_attention." ) if "encoder_attn_layer_norm" in key: _UpperCAmelCase : Optional[int] = key.replace("encoder_attn_layer_norm" , "cross_attention_layer_norm" ) if "final_layer_norm" in key: _UpperCAmelCase : Optional[Any] = key.replace("final_layer_norm" , "ff_layer_norm" ) _UpperCAmelCase : Optional[Any] = state_dict[old_key] return new_dict def __lowerCAmelCase (__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = WEIGHTS_NAME ): _UpperCAmelCase : Tuple = [] _UpperCAmelCase : Optional[Any] = 0 os.makedirs(lowercase__ , exist_ok=lowercase__ ) for expert in range(lowercase__ ): _UpperCAmelCase : Optional[Any] = switch_checkpoint_path + F"""-rank-{expert}.pt""" if os.path.isfile(lowercase__ ): _UpperCAmelCase : List[str] = torch.load(lowercase__ )['''model'''] remove_ignore_keys_(lowercase__ ) _UpperCAmelCase : int = rename_fairseq_keys(lowercase__ , lowercase__ ) _UpperCAmelCase : Tuple = os.path.join( lowercase__ , weights_name.replace(".bin" , F"""-{len(lowercase__ )+1:05d}-of-???.bin""" ) ) torch.save(lowercase__ , lowercase__ ) sharded_state_dicts.append(expert_state.keys() ) total_size += sum([value.numel() for key, value in expert_state.items()] ) * dtype_byte_size( expert_state[list(lowercase__ )[0]].dtype ) # Add the last block _UpperCAmelCase : List[Any] = os.path.join(lowercase__ , weights_name.replace(".bin" , F"""-{len(lowercase__ )+1:05d}-of-???.bin""" ) ) _UpperCAmelCase : Optional[int] = torch.load(switch_checkpoint_path + "-shared.pt" )['''model'''] remove_ignore_keys_(lowercase__ ) _UpperCAmelCase : Optional[int] = rename_fairseq_keys(lowercase__ , lowercase__ ) _UpperCAmelCase : int = shared_weights['''decoder.embed_tokens.weight'''] sharded_state_dicts.append(shared_weights.keys() ) # If we only have the shared weights (dummy model/experts saved on the same file) if len(lowercase__ ) == 1: _UpperCAmelCase : str = os.path.join(lowercase__ , lowercase__ ) torch.save(lowercase__ , lowercase__ ) return {weights_name: sharded_state_dicts[0]}, None else: torch.save(lowercase__ , lowercase__ ) # Otherwise, let's build the index _UpperCAmelCase : str = {} for idx, shard in enumerate(lowercase__ ): _UpperCAmelCase : Any = weights_name.replace(".bin" , F"""-{idx+1:05d}-of-{len(lowercase__ ):05d}.bin""" ) _UpperCAmelCase : str = os.path.join(lowercase__ , weights_name.replace(".bin" , F"""-{idx+1:05d}-of-???.bin""" ) ) os.rename(lowercase__ , os.path.join(lowercase__ , lowercase__ ) ) for key in shard: _UpperCAmelCase : Optional[int] = shard_file # Add the metadata _UpperCAmelCase : List[Any] = {'''total_size''': total_size} _UpperCAmelCase : Union[str, Any] = {'''metadata''': metadata, '''weight_map''': weight_map} with open(os.path.join(lowercase__ , lowercase__ ) , "w" , encoding="utf-8" ) as f: _UpperCAmelCase : List[Any] = json.dumps(lowercase__ , indent=2 , sort_keys=lowercase__ ) + '''\n''' f.write(lowercase__ ) return metadata, index if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--nllb_moe_checkpoint_path', default='/home/arthur_huggingface_co/fairseq/weights/checkpoints/model_moe_54b/checkpoint_2_300000', type=str, required=False, help='Path to a directory containing a folder per layer. Follows the original Google format.', ) parser.add_argument('--dtype', default='float32', type=str, required=False, help='dtype of the saved model') parser.add_argument( '--pytorch_dump_folder_path', default='/home/arthur_huggingface_co/fairseq/weights/checkpoints/hf-converted-moe-54b', type=str, required=False, help='Path to the output pytorch model.', ) lowerCamelCase__ = parser.parse_args() lowerCamelCase__ ,lowerCamelCase__ = shard_on_the_fly( args.nllb_moe_checkpoint_path, args.pytorch_dump_folder_path, 128, args.dtype, ) lowerCamelCase__ = NllbMoeConfig.from_pretrained( 'facebook/nllb-200-3.3B', encoder_sparse_step=4, decoder_sparse_step=4, num_experts=128 ) config.save_pretrained(args.pytorch_dump_folder_path) lowerCamelCase__ = NllbMoeModel.from_pretrained(args.pytorch_dump_folder_path) print('Done') model.save_pretrained(args.pytorch_dump_folder_path)
234
import unicodedata from dataclasses import dataclass from typing import Optional, Union import numpy as np from transformers.data.data_collator import DataCollatorMixin from transformers.file_utils import PaddingStrategy from transformers.tokenization_utils_base import PreTrainedTokenizerBase def _lowercase ( lowercase__ , lowercase__ , lowercase__ , lowercase__ ): if isinstance(lowercase__ , lowercase__ ): __lowerCAmelCase : Dict = np.full((len(lowercase__ ), sequence_length, 2) , lowercase__ ) else: __lowerCAmelCase : Optional[int] = np.full((len(lowercase__ ), sequence_length) , lowercase__ ) for i, tensor in enumerate(lowercase__ ): if padding_side == "right": if isinstance(lowercase__ , lowercase__ ): __lowerCAmelCase : Union[str, Any] = tensor[:sequence_length] else: __lowerCAmelCase : int = tensor[:sequence_length] else: if isinstance(lowercase__ , lowercase__ ): __lowerCAmelCase : Union[str, Any] = tensor[:sequence_length] else: __lowerCAmelCase : Optional[Any] = tensor[:sequence_length] return out_tensor.tolist() def _lowercase ( lowercase__ ): __lowerCAmelCase : Union[str, Any] = ord(lowercase__ ) if (cp >= 3_3 and cp <= 4_7) or (cp >= 5_8 and cp <= 6_4) or (cp >= 9_1 and cp <= 9_6) or (cp >= 1_2_3 and cp <= 1_2_6): return True __lowerCAmelCase : int = unicodedata.category(lowercase__ ) if cat.startswith('''P''' ): return True return False @dataclass class __lowercase (_UpperCAmelCase ): _UpperCamelCase = 42 _UpperCamelCase = True _UpperCamelCase = None _UpperCamelCase = None _UpperCamelCase = -100 _UpperCamelCase = "pt" def UpperCamelCase__ ( self , A_ ) ->Optional[int]: '''simple docstring''' import torch __lowerCAmelCase : List[str] = '''label''' if '''label''' in features[0].keys() else '''labels''' __lowerCAmelCase : Union[str, Any] = [feature[label_name] for feature in features] if label_name in features[0].keys() else None __lowerCAmelCase : List[Any] = self.tokenizer.pad( A_ , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors='''pt''' if labels is None else None , ) if labels is None: return batch __lowerCAmelCase : Dict = torch.tensor(batch['''entity_ids'''] ).shape[1] __lowerCAmelCase : Optional[int] = self.tokenizer.padding_side if padding_side == "right": __lowerCAmelCase : Any = [ list(A_ ) + [self.label_pad_token_id] * (sequence_length - len(A_ )) for label in labels ] else: __lowerCAmelCase : Optional[int] = [ [self.label_pad_token_id] * (sequence_length - len(A_ )) + list(A_ ) for label in labels ] __lowerCAmelCase : Tuple = [feature['''ner_tags'''] for feature in features] __lowerCAmelCase : List[Any] = padding_tensor(A_ , -1 , A_ , A_ ) __lowerCAmelCase : Optional[int] = [feature['''original_entity_spans'''] for feature in features] __lowerCAmelCase : Any = padding_tensor(A_ , (-1, -1) , A_ , A_ ) __lowerCAmelCase : Optional[Any] = {k: torch.tensor(A_ , dtype=torch.intaa ) for k, v in batch.items()} return batch
275
0
"""simple docstring""" import unittest import numpy as np from transformers.file_utils import is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision 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 DPTImageProcessor class lowercase ( unittest.TestCase ): def __init__( self , lowercase , lowercase=7 , lowercase=3 , lowercase=18 , lowercase=30 , lowercase=400 , lowercase=True , lowercase=None , lowercase=True , lowercase=[0.5, 0.5, 0.5] , lowercase=[0.5, 0.5, 0.5] , ) -> int: lowerCAmelCase = size if size is not None else {'''height''': 18, '''width''': 18} lowerCAmelCase = parent lowerCAmelCase = batch_size lowerCAmelCase = num_channels lowerCAmelCase = image_size lowerCAmelCase = min_resolution lowerCAmelCase = max_resolution lowerCAmelCase = do_resize lowerCAmelCase = size lowerCAmelCase = do_normalize lowerCAmelCase = image_mean lowerCAmelCase = image_std def _snake_case ( self ) -> List[Any]: return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class lowercase ( _UpperCAmelCase , unittest.TestCase ): _SCREAMING_SNAKE_CASE = DPTImageProcessor if is_vision_available() else None def _snake_case ( self ) -> Any: lowerCAmelCase = DPTImageProcessingTester(self ) @property def _snake_case ( self ) -> Union[str, Any]: return self.image_processor_tester.prepare_image_processor_dict() def _snake_case ( self ) -> Tuple: lowerCAmelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(A_ , """image_mean""" ) ) self.assertTrue(hasattr(A_ , """image_std""" ) ) self.assertTrue(hasattr(A_ , """do_normalize""" ) ) self.assertTrue(hasattr(A_ , """do_resize""" ) ) self.assertTrue(hasattr(A_ , """size""" ) ) def _snake_case ( self ) -> Optional[Any]: lowerCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""height""": 18, """width""": 18} ) lowerCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {"""height""": 42, """width""": 42} ) def _snake_case ( self ) -> int: lowerCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowerCAmelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=A_ ) for image in image_inputs: self.assertIsInstance(A_ , Image.Image ) # Test not batched input lowerCAmelCase = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) # Test batched lowerCAmelCase = image_processing(A_ , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) def _snake_case ( self ) -> Optional[int]: lowerCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowerCAmelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=A_ , numpify=A_ ) for image in image_inputs: self.assertIsInstance(A_ , np.ndarray ) # Test not batched input lowerCAmelCase = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) # Test batched lowerCAmelCase = image_processing(A_ , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) def _snake_case ( self ) -> Union[str, Any]: lowerCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowerCAmelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=A_ , torchify=A_ ) for image in image_inputs: self.assertIsInstance(A_ , torch.Tensor ) # Test not batched input lowerCAmelCase = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) # Test batched lowerCAmelCase = image_processing(A_ , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , )
46
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import MgpstrTokenizer from transformers.models.mgp_str.tokenization_mgp_str import VOCAB_FILES_NAMES from transformers.testing_utils import require_torch, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_torch_available, is_vision_available if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import MgpstrProcessor, ViTImageProcessor @require_torch @require_vision class __lowercase (unittest.TestCase ): _UpperCamelCase = ViTImageProcessor if is_vision_available() else None @property def UpperCamelCase__ ( self ) ->str: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def UpperCamelCase__ ( self ) ->str: '''simple docstring''' __lowerCAmelCase : Tuple = (3, 32, 128) __lowerCAmelCase : List[str] = tempfile.mkdtemp() # fmt: off __lowerCAmelCase : List[str] = ['''[GO]''', '''[s]''', '''0''', '''1''', '''2''', '''3''', '''4''', '''5''', '''6''', '''7''', '''8''', '''9''', '''a''', '''b''', '''c''', '''d''', '''e''', '''f''', '''g''', '''h''', '''i''', '''j''', '''k''', '''l''', '''m''', '''n''', '''o''', '''p''', '''q''', '''r''', '''s''', '''t''', '''u''', '''v''', '''w''', '''x''', '''y''', '''z'''] # fmt: on __lowerCAmelCase : Optional[int] = dict(zip(A_ , range(len(A_ ) ) ) ) __lowerCAmelCase : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(A_ ) + '''\n''' ) __lowerCAmelCase : Union[str, Any] = { '''do_normalize''': False, '''do_resize''': True, '''image_processor_type''': '''ViTImageProcessor''', '''resample''': 3, '''size''': {'''height''': 32, '''width''': 128}, } __lowerCAmelCase : Optional[Any] = os.path.join(self.tmpdirname , A_ ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(A_ , A_ ) def UpperCamelCase__ ( self , **A_ ) ->Tuple: '''simple docstring''' return MgpstrTokenizer.from_pretrained(self.tmpdirname , **A_ ) def UpperCamelCase__ ( self , **A_ ) ->Tuple: '''simple docstring''' return ViTImageProcessor.from_pretrained(self.tmpdirname , **A_ ) def UpperCamelCase__ ( self ) ->Optional[int]: '''simple docstring''' shutil.rmtree(self.tmpdirname ) def UpperCamelCase__ ( self ) ->Optional[Any]: '''simple docstring''' __lowerCAmelCase : Tuple = np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta ) __lowerCAmelCase : str = Image.fromarray(np.moveaxis(A_ , 0 , -1 ) ) return image_input def UpperCamelCase__ ( self ) ->Any: '''simple docstring''' __lowerCAmelCase : Dict = self.get_tokenizer() __lowerCAmelCase : List[Any] = self.get_image_processor() __lowerCAmelCase : List[Any] = MgpstrProcessor(tokenizer=A_ , image_processor=A_ ) processor.save_pretrained(self.tmpdirname ) __lowerCAmelCase : Union[str, Any] = MgpstrProcessor.from_pretrained(self.tmpdirname , use_fast=A_ ) self.assertEqual(processor.char_tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.char_tokenizer , A_ ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , A_ ) def UpperCamelCase__ ( self ) ->Optional[int]: '''simple docstring''' __lowerCAmelCase : Any = self.get_tokenizer() __lowerCAmelCase : Union[str, Any] = self.get_image_processor() __lowerCAmelCase : List[Any] = MgpstrProcessor(tokenizer=A_ , image_processor=A_ ) processor.save_pretrained(self.tmpdirname ) __lowerCAmelCase : List[Any] = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) __lowerCAmelCase : int = self.get_image_processor(do_normalize=A_ , padding_value=1.0 ) __lowerCAmelCase : int = MgpstrProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=A_ , padding_value=1.0 ) self.assertEqual(processor.char_tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.char_tokenizer , A_ ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , A_ ) def UpperCamelCase__ ( self ) ->List[str]: '''simple docstring''' __lowerCAmelCase : Any = self.get_image_processor() __lowerCAmelCase : Optional[Any] = self.get_tokenizer() __lowerCAmelCase : int = MgpstrProcessor(tokenizer=A_ , image_processor=A_ ) __lowerCAmelCase : Optional[int] = self.prepare_image_inputs() __lowerCAmelCase : Optional[Any] = image_processor(A_ , return_tensors='''np''' ) __lowerCAmelCase : Tuple = processor(images=A_ , return_tensors='''np''' ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1e-2 ) def UpperCamelCase__ ( self ) ->str: '''simple docstring''' __lowerCAmelCase : str = self.get_image_processor() __lowerCAmelCase : Union[str, Any] = self.get_tokenizer() __lowerCAmelCase : Optional[Any] = MgpstrProcessor(tokenizer=A_ , image_processor=A_ ) __lowerCAmelCase : Any = '''test''' __lowerCAmelCase : Dict = processor(text=A_ ) __lowerCAmelCase : str = tokenizer(A_ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def UpperCamelCase__ ( self ) ->Optional[int]: '''simple docstring''' __lowerCAmelCase : Dict = self.get_image_processor() __lowerCAmelCase : Any = self.get_tokenizer() __lowerCAmelCase : str = MgpstrProcessor(tokenizer=A_ , image_processor=A_ ) __lowerCAmelCase : List[Any] = '''test''' __lowerCAmelCase : int = self.prepare_image_inputs() __lowerCAmelCase : int = processor(text=A_ , images=A_ ) self.assertListEqual(list(inputs.keys() ) , ['''pixel_values''', '''labels'''] ) # test if it raises when no input is passed with pytest.raises(A_ ): processor() def UpperCamelCase__ ( self ) ->Union[str, Any]: '''simple docstring''' __lowerCAmelCase : List[Any] = self.get_image_processor() __lowerCAmelCase : int = self.get_tokenizer() __lowerCAmelCase : Any = MgpstrProcessor(tokenizer=A_ , image_processor=A_ ) __lowerCAmelCase : List[str] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9], [3, 4, 3, 1, 1, 8, 9]] __lowerCAmelCase : Optional[int] = processor.char_decode(A_ ) __lowerCAmelCase : Tuple = tokenizer.batch_decode(A_ ) __lowerCAmelCase : Any = [seq.replace(''' ''' , '''''' ) for seq in decoded_tok] self.assertListEqual(A_ , A_ ) def UpperCamelCase__ ( self ) ->Any: '''simple docstring''' __lowerCAmelCase : str = self.get_image_processor() __lowerCAmelCase : Any = self.get_tokenizer() __lowerCAmelCase : int = MgpstrProcessor(tokenizer=A_ , image_processor=A_ ) __lowerCAmelCase : Union[str, Any] = None __lowerCAmelCase : Optional[Any] = self.prepare_image_inputs() __lowerCAmelCase : List[Any] = processor(text=A_ , images=A_ ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names ) def UpperCamelCase__ ( self ) ->List[str]: '''simple docstring''' __lowerCAmelCase : List[str] = self.get_image_processor() __lowerCAmelCase : List[str] = self.get_tokenizer() __lowerCAmelCase : Any = MgpstrProcessor(tokenizer=A_ , image_processor=A_ ) __lowerCAmelCase : List[Any] = torch.randn(1 , 27 , 38 ) __lowerCAmelCase : Optional[int] = torch.randn(1 , 27 , 5_0257 ) __lowerCAmelCase : Optional[Any] = torch.randn(1 , 27 , 3_0522 ) __lowerCAmelCase : List[str] = processor.batch_decode([char_input, bpe_input, wp_input] ) self.assertListEqual(list(results.keys() ) , ['''generated_text''', '''scores''', '''char_preds''', '''bpe_preds''', '''wp_preds'''] )
275
0
'''simple docstring''' def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int = 1000 ) -> int: _a : int =-1 _a : Tuple =0 for a in range(1 ,n // 3 ): # Solving the two equations a**2+b**2=c**2 and a+b+c=N eliminating c _a : str =(n * n - 2 * a * n) // (2 * n - 2 * a) _a : Tuple =n - a - b if c * c == (a * a + b * b): _a : Tuple =a * b * c if candidate >= product: _a : Any =candidate return product if __name__ == "__main__": print(F"{solution() = }")
276
'''simple docstring''' import unittest from transformers import EsmConfig, is_torch_available from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import EsmForMaskedLM, EsmForSequenceClassification, EsmForTokenClassification, EsmModel from transformers.models.esm.modeling_esm import ( ESM_PRETRAINED_MODEL_ARCHIVE_LIST, EsmEmbeddings, create_position_ids_from_input_ids, ) class A__ : def __init__( self :Tuple , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :Optional[int]=1_3 , SCREAMING_SNAKE_CASE :Optional[int]=7 , SCREAMING_SNAKE_CASE :Tuple=False , SCREAMING_SNAKE_CASE :Dict=True , SCREAMING_SNAKE_CASE :Optional[int]=False , SCREAMING_SNAKE_CASE :Optional[Any]=True , SCREAMING_SNAKE_CASE :List[str]=3_3 , SCREAMING_SNAKE_CASE :Tuple=3_2 , SCREAMING_SNAKE_CASE :Tuple=5 , SCREAMING_SNAKE_CASE :int=4 , SCREAMING_SNAKE_CASE :Union[str, Any]=3_7 , SCREAMING_SNAKE_CASE :List[str]="gelu" , SCREAMING_SNAKE_CASE :Optional[Any]=0.1 , SCREAMING_SNAKE_CASE :Tuple=0.1 , SCREAMING_SNAKE_CASE :str=5_1_2 , SCREAMING_SNAKE_CASE :Dict=1_6 , SCREAMING_SNAKE_CASE :Dict=2 , SCREAMING_SNAKE_CASE :Union[str, Any]=0.02 , SCREAMING_SNAKE_CASE :str=3 , SCREAMING_SNAKE_CASE :List[str]=4 , SCREAMING_SNAKE_CASE :List[str]=None , ) -> Union[str, Any]: '''simple docstring''' _a : Union[str, Any] =parent _a : List[Any] =batch_size _a : Optional[int] =seq_length _a : Union[str, Any] =is_training _a : List[Any] =use_input_mask _a : Optional[int] =use_token_type_ids _a : int =use_labels _a : List[str] =vocab_size _a : List[Any] =hidden_size _a : int =num_hidden_layers _a : Tuple =num_attention_heads _a : Any =intermediate_size _a : str =hidden_act _a : Union[str, Any] =hidden_dropout_prob _a : Union[str, Any] =attention_probs_dropout_prob _a : str =max_position_embeddings _a : Dict =type_vocab_size _a : Tuple =type_sequence_label_size _a : Dict =initializer_range _a : List[str] =num_labels _a : Tuple =num_choices _a : int =scope def __UpperCAmelCase ( self :Union[str, Any] ) -> str: '''simple docstring''' _a : Optional[int] =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _a : List[Any] =None if self.use_input_mask: _a : Any =random_attention_mask([self.batch_size, self.seq_length] ) _a : Optional[int] =None _a : str =None _a : Dict =None if self.use_labels: _a : Dict =ids_tensor([self.batch_size] , self.type_sequence_label_size ) _a : str =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _a : List[str] =ids_tensor([self.batch_size] , self.num_choices ) _a : List[Any] =self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCAmelCase ( self :str ) -> Optional[int]: '''simple docstring''' return EsmConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , pad_token_id=1 , 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 __UpperCAmelCase ( self :List[str] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :Optional[Any] , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :int ) -> Tuple: '''simple docstring''' _a : Any =EsmModel(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() _a : Optional[Any] =model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =model(SCREAMING_SNAKE_CASE ) _a : str =model(SCREAMING_SNAKE_CASE ) 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 __UpperCAmelCase ( self :str , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :Optional[Any] ) -> Dict: '''simple docstring''' _a : str =EsmForMaskedLM(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() _a : Union[str, Any] =model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :Optional[Any] , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :List[Any] , SCREAMING_SNAKE_CASE :Union[str, Any] ) -> Optional[Any]: '''simple docstring''' _a : int =self.num_labels _a : Tuple =EsmForTokenClassification(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() _a : Tuple =model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCAmelCase ( self :Dict ) -> List[str]: '''simple docstring''' _a : Optional[Any] =self.prepare_config_and_inputs() ( ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ) : Any =config_and_inputs _a : List[Any] ={"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class A__ ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): __UpperCamelCase : Any = False __UpperCamelCase : Any = ( ( EsmForMaskedLM, EsmModel, EsmForSequenceClassification, EsmForTokenClassification, ) if is_torch_available() else () ) __UpperCamelCase : str = () __UpperCamelCase : List[str] = ( { "feature-extraction": EsmModel, "fill-mask": EsmForMaskedLM, "text-classification": EsmForSequenceClassification, "token-classification": EsmForTokenClassification, "zero-shot": EsmForSequenceClassification, } if is_torch_available() else {} ) __UpperCamelCase : Union[str, Any] = True def __UpperCAmelCase ( self :Optional[int] ) -> int: '''simple docstring''' _a : Dict =EsmModelTester(self ) _a : Optional[Any] =ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , hidden_size=3_7 ) def __UpperCAmelCase ( self :Tuple ) -> List[Any]: '''simple docstring''' self.config_tester.run_common_tests() def __UpperCAmelCase ( self :Optional[int] ) -> str: '''simple docstring''' _a : List[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :List[Any] ) -> Dict: '''simple docstring''' _a : List[str] =self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: _a : Dict =type self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Dict ) -> List[str]: '''simple docstring''' _a : Tuple =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :List[Any] ) -> List[str]: '''simple docstring''' _a : str =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*SCREAMING_SNAKE_CASE ) @slow def __UpperCAmelCase ( self :str ) -> Dict: '''simple docstring''' for model_name in ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _a : Union[str, Any] =EsmModel.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Tuple ) -> int: '''simple docstring''' _a : Optional[Any] =self.model_tester.prepare_config_and_inputs()[0] _a : Dict =EsmEmbeddings(config=SCREAMING_SNAKE_CASE ) _a : Tuple =torch.as_tensor([[1_2, 3_1, 1_3, model.padding_idx]] ) _a : Optional[Any] =torch.as_tensor( [ [ 0 + model.padding_idx + 1, 1 + model.padding_idx + 1, 2 + model.padding_idx + 1, model.padding_idx, ] ] ) _a : Any =create_position_ids_from_input_ids(SCREAMING_SNAKE_CASE , model.padding_idx ) self.assertEqual(position_ids.shape , expected_positions.shape ) self.assertTrue(torch.all(torch.eq(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) ) def __UpperCAmelCase ( self :Optional[Any] ) -> Tuple: '''simple docstring''' _a : List[Any] =self.model_tester.prepare_config_and_inputs()[0] _a : Optional[int] =EsmEmbeddings(config=SCREAMING_SNAKE_CASE ) _a : Tuple =torch.empty(2 , 4 , 3_0 ) _a : str =[ 0 + embeddings.padding_idx + 1, 1 + embeddings.padding_idx + 1, 2 + embeddings.padding_idx + 1, 3 + embeddings.padding_idx + 1, ] _a : int =torch.as_tensor([expected_single_positions, expected_single_positions] ) _a : Any =embeddings.create_position_ids_from_inputs_embeds(SCREAMING_SNAKE_CASE ) self.assertEqual(position_ids.shape , expected_positions.shape ) self.assertTrue(torch.all(torch.eq(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) ) @unittest.skip("""Esm does not support embedding resizing""" ) def __UpperCAmelCase ( self :Tuple ) -> List[str]: '''simple docstring''' pass @unittest.skip("""Esm does not support embedding resizing""" ) def __UpperCAmelCase ( self :str ) -> Any: '''simple docstring''' pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def __UpperCAmelCase ( self :Dict ) -> Any: '''simple docstring''' pass @require_torch class A__ ( UpperCAmelCase__ ): @slow def __UpperCAmelCase ( self :List[Any] ) -> str: '''simple docstring''' with torch.no_grad(): _a : Optional[int] =EsmForMaskedLM.from_pretrained("""facebook/esm2_t6_8M_UR50D""" ) model.eval() _a : Any =torch.tensor([[0, 1, 2, 3, 4, 5]] ) _a : Tuple =model(SCREAMING_SNAKE_CASE )[0] _a : int =3_3 _a : Tuple =torch.Size((1, 6, vocab_size) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =torch.tensor( [[[8.9_215, -10.5_898, -6.4_671], [-6.3_967, -13.9_114, -1.1_212], [-7.7_812, -13.9_516, -3.7_406]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) ) @slow def __UpperCAmelCase ( self :Union[str, Any] ) -> Tuple: '''simple docstring''' with torch.no_grad(): _a : Any =EsmModel.from_pretrained("""facebook/esm2_t6_8M_UR50D""" ) model.eval() _a : Any =torch.tensor([[0, 6, 4, 1_3, 5, 4, 1_6, 1_2, 1_1, 7, 2]] ) _a : int =model(SCREAMING_SNAKE_CASE )[0] # compare the actual values for a slice. _a : str =torch.tensor( [[[0.1_444, 0.5_413, 0.3_248], [0.3_034, 0.0_053, 0.3_108], [0.3_228, -0.2_499, 0.3_415]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) )
276
1
'''simple docstring''' import inspect import unittest from transformers import ConvNextVaConfig from transformers.models.auto import get_values from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class A__ : def __init__( self :Tuple , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Union[str, Any]=1_3 , SCREAMING_SNAKE_CASE :List[Any]=3_2 , SCREAMING_SNAKE_CASE :List[Any]=3 , SCREAMING_SNAKE_CASE :Optional[int]=4 , SCREAMING_SNAKE_CASE :Any=[1_0, 2_0, 3_0, 4_0] , SCREAMING_SNAKE_CASE :str=[2, 2, 3, 2] , SCREAMING_SNAKE_CASE :List[str]=True , SCREAMING_SNAKE_CASE :Optional[Any]=True , SCREAMING_SNAKE_CASE :str=3_7 , SCREAMING_SNAKE_CASE :List[Any]="gelu" , SCREAMING_SNAKE_CASE :List[Any]=1_0 , SCREAMING_SNAKE_CASE :List[str]=0.02 , SCREAMING_SNAKE_CASE :List[str]=["stage2", "stage3", "stage4"] , SCREAMING_SNAKE_CASE :Optional[Any]=[2, 3, 4] , SCREAMING_SNAKE_CASE :Tuple=None , ) -> str: '''simple docstring''' _a : Any =parent _a : Union[str, Any] =batch_size _a : int =image_size _a : Optional[Any] =num_channels _a : Tuple =num_stages _a : List[Any] =hidden_sizes _a : Union[str, Any] =depths _a : List[str] =is_training _a : str =use_labels _a : Optional[Any] =intermediate_size _a : Optional[Any] =hidden_act _a : Any =num_labels _a : str =initializer_range _a : Optional[Any] =out_features _a : Any =out_indices _a : List[Any] =scope def __UpperCAmelCase ( self :Any ) -> List[str]: '''simple docstring''' _a : List[str] =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _a : Any =None if self.use_labels: _a : Optional[Any] =ids_tensor([self.batch_size] , self.num_labels ) _a : Optional[int] =self.get_config() return config, pixel_values, labels def __UpperCAmelCase ( self :Optional[int] ) -> Optional[Any]: '''simple docstring''' return ConvNextVaConfig( num_channels=self.num_channels , hidden_sizes=self.hidden_sizes , depths=self.depths , num_stages=self.num_stages , hidden_act=self.hidden_act , is_decoder=SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , out_features=self.out_features , out_indices=self.out_indices , num_labels=self.num_labels , ) def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :Optional[Any] , SCREAMING_SNAKE_CASE :str ) -> List[Any]: '''simple docstring''' _a : Tuple =ConvNextVaModel(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() _a : List[str] =model(SCREAMING_SNAKE_CASE ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 3_2, self.image_size // 3_2) , ) def __UpperCAmelCase ( self :str , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :int ) -> List[str]: '''simple docstring''' _a : int =ConvNextVaForImageClassification(SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() _a : Optional[Any] =model(SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :Optional[Any] , SCREAMING_SNAKE_CASE :str ) -> Any: '''simple docstring''' _a : Union[str, Any] =ConvNextVaBackbone(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() _a : Tuple =model(SCREAMING_SNAKE_CASE ) # verify hidden states 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 _a : Union[str, Any] =None _a : Optional[Any] =ConvNextVaBackbone(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() _a : Optional[int] =model(SCREAMING_SNAKE_CASE ) # 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 __UpperCAmelCase ( self :Tuple ) -> Dict: '''simple docstring''' _a : Dict =self.prepare_config_and_inputs() _a , _a , _a : Any =config_and_inputs _a : Union[str, Any] ={"""pixel_values""": pixel_values} return config, inputs_dict def __UpperCAmelCase ( self :Optional[int] ) -> int: '''simple docstring''' _a : Tuple =self.prepare_config_and_inputs() _a , _a , _a : List[Any] =config_and_inputs _a : Tuple ={"""pixel_values""": pixel_values, """labels""": labels} return config, inputs_dict @require_torch class A__ ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): __UpperCamelCase : Optional[int] = ( ( ConvNextVaModel, ConvNextVaForImageClassification, ConvNextVaBackbone, ) if is_torch_available() else () ) __UpperCamelCase : Tuple = ( {"feature-extraction": ConvNextVaModel, "image-classification": ConvNextVaForImageClassification} if is_torch_available() else {} ) __UpperCamelCase : Any = False __UpperCamelCase : Any = False __UpperCamelCase : Optional[int] = False __UpperCamelCase : Any = False __UpperCamelCase : List[Any] = False def __UpperCAmelCase ( self :Optional[Any] ) -> str: '''simple docstring''' _a : Optional[int] =ConvNextVaModelTester(self ) _a : List[str] =ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , has_text_modality=SCREAMING_SNAKE_CASE , hidden_size=3_7 ) def __UpperCAmelCase ( self :List[str] ) -> Tuple: '''simple docstring''' self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def __UpperCAmelCase ( self :List[str] ) -> Any: '''simple docstring''' return @unittest.skip(reason="""ConvNextV2 does not use inputs_embeds""" ) def __UpperCAmelCase ( self :str ) -> Optional[int]: '''simple docstring''' pass @unittest.skip(reason="""ConvNextV2 does not support input and output embeddings""" ) def __UpperCAmelCase ( self :Union[str, Any] ) -> int: '''simple docstring''' pass @unittest.skip(reason="""ConvNextV2 does not use feedforward chunking""" ) def __UpperCAmelCase ( self :Any ) -> List[Any]: '''simple docstring''' pass def __UpperCAmelCase ( self :List[Any] ) -> List[str]: '''simple docstring''' if not self.model_tester.is_training: return for model_class in self.all_model_classes: _a , _a : Any =self.model_tester.prepare_config_and_inputs_with_labels() _a : Dict =True if model_class.__name__ in [ *get_values(SCREAMING_SNAKE_CASE ), *get_values(SCREAMING_SNAKE_CASE ), ]: continue _a : Union[str, Any] =model_class(SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.train() _a : Optional[Any] =self._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , return_labels=SCREAMING_SNAKE_CASE ) _a : List[Any] =model(**SCREAMING_SNAKE_CASE ).loss loss.backward() def __UpperCAmelCase ( self :List[Any] ) -> Optional[int]: '''simple docstring''' if not self.model_tester.is_training: return for model_class in self.all_model_classes: _a , _a : Any =self.model_tester.prepare_config_and_inputs_with_labels() _a : List[str] =False _a : Any =True if ( model_class.__name__ in [*get_values(SCREAMING_SNAKE_CASE ), *get_values(SCREAMING_SNAKE_CASE )] or not model_class.supports_gradient_checkpointing ): continue _a : List[str] =model_class(SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.gradient_checkpointing_enable() model.train() _a : Union[str, Any] =self._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , return_labels=SCREAMING_SNAKE_CASE ) _a : Any =model(**SCREAMING_SNAKE_CASE ).loss loss.backward() def __UpperCAmelCase ( self :List[str] ) -> Optional[int]: '''simple docstring''' _a , _a : Union[str, Any] =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _a : Any =model_class(SCREAMING_SNAKE_CASE ) _a : Optional[Any] =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _a : Union[str, Any] =[*signature.parameters.keys()] _a : List[str] =["""pixel_values"""] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Union[str, Any] ) -> Any: '''simple docstring''' _a : List[str] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Dict ) -> Union[str, Any]: '''simple docstring''' def check_hidden_states_output(SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :List[Any] , SCREAMING_SNAKE_CASE :Tuple ): _a : str =model_class(SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): _a : Tuple =model(**self._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) _a : Optional[Any] =outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states _a : str =self.model_tester.num_stages self.assertEqual(len(SCREAMING_SNAKE_CASE ) , expected_num_stages + 1 ) # ConvNextV2'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] , ) _a , _a : Tuple =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _a : List[Any] =True check_hidden_states_output(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _a : List[Any] =True check_hidden_states_output(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Any ) -> List[str]: '''simple docstring''' _a : str =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE ) @slow def __UpperCAmelCase ( self :Optional[Any] ) -> Any: '''simple docstring''' for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _a : Dict =ConvNextVaModel.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) def SCREAMING_SNAKE_CASE_ ( ) -> List[str]: _a : Any =Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class A__ ( unittest.TestCase ): @cached_property def __UpperCAmelCase ( self :List[Any] ) -> Dict: '''simple docstring''' return AutoImageProcessor.from_pretrained("""facebook/convnextv2-tiny-1k-224""" ) if is_vision_available() else None @slow def __UpperCAmelCase ( self :int ) -> Union[str, Any]: '''simple docstring''' _a : Any =ConvNextVaForImageClassification.from_pretrained("""facebook/convnextv2-tiny-1k-224""" ).to(SCREAMING_SNAKE_CASE ) _a : Tuple =self.default_image_processor _a : Optional[int] =prepare_img() _a : List[Any] =preprocessor(images=SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).to(SCREAMING_SNAKE_CASE ) # forward pass with torch.no_grad(): _a : List[Any] =model(**SCREAMING_SNAKE_CASE ) # verify the logits _a : Any =torch.Size((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE ) _a : Optional[Any] =torch.tensor([0.9_996, 0.1_966, -0.4_386] ).to(SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) )
276
'''simple docstring''' from math import isqrt def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ) -> bool: return all(number % divisor != 0 for divisor in range(2 ,isqrt(_UpperCAmelCase ) + 1 ) ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int = 10**6 ) -> int: _a : List[Any] =0 _a : str =1 _a : Optional[Any] =7 while prime_candidate < max_prime: primes_count += is_prime(_UpperCAmelCase ) cube_index += 1 prime_candidate += 6 * cube_index return primes_count if __name__ == "__main__": print(F"{solution() = }")
276
1
'''simple docstring''' from typing import List, Optional, Tuple, Union import torch from torch import nn from torch.nn import CrossEntropyLoss from ... import AutoBackbone from ...modeling_outputs import SemanticSegmenterOutput from ...modeling_utils import PreTrainedModel from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings from ...utils.backbone_utils import BackboneMixin from .configuration_upernet import UperNetConfig A__: int = [ '''openmmlab/upernet-convnext-tiny''', # See all UperNet models at https://huggingface.co/models?filter=upernet ] # General docstring A__: Tuple = '''UperNetConfig''' class A__ ( nn.Module ): def __init__( self :str , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :Union[int, Tuple[int, int]] , SCREAMING_SNAKE_CASE :Union[int, Tuple[int, int], str] = 0 , SCREAMING_SNAKE_CASE :bool = False , SCREAMING_SNAKE_CASE :Union[int, Tuple[int, int]] = 1 , ) -> None: '''simple docstring''' super().__init__() _a : Tuple =nn.Convad( in_channels=SCREAMING_SNAKE_CASE , out_channels=SCREAMING_SNAKE_CASE , kernel_size=SCREAMING_SNAKE_CASE , padding=SCREAMING_SNAKE_CASE , bias=SCREAMING_SNAKE_CASE , dilation=SCREAMING_SNAKE_CASE , ) _a : Optional[Any] =nn.BatchNormad(SCREAMING_SNAKE_CASE ) _a : Tuple =nn.ReLU() def __UpperCAmelCase ( self :int , SCREAMING_SNAKE_CASE :torch.Tensor ) -> torch.Tensor: '''simple docstring''' _a : List[str] =self.conv(SCREAMING_SNAKE_CASE ) _a : Tuple =self.batch_norm(SCREAMING_SNAKE_CASE ) _a : List[Any] =self.activation(SCREAMING_SNAKE_CASE ) return output class A__ ( nn.Module ): def __init__( self :Any , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :int ) -> None: '''simple docstring''' super().__init__() _a : List[Any] =[ nn.AdaptiveAvgPoolad(SCREAMING_SNAKE_CASE ), UperNetConvModule(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , kernel_size=1 ), ] for i, layer in enumerate(self.layers ): self.add_module(str(SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :List[Any] , SCREAMING_SNAKE_CASE :torch.Tensor ) -> torch.Tensor: '''simple docstring''' _a : List[Any] =input for layer in self.layers: _a : Tuple =layer(SCREAMING_SNAKE_CASE ) return hidden_state class A__ ( nn.Module ): def __init__( self :List[str] , SCREAMING_SNAKE_CASE :Tuple[int, ...] , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :bool ) -> None: '''simple docstring''' super().__init__() _a : Union[str, Any] =pool_scales _a : Union[str, Any] =align_corners _a : int =in_channels _a : List[str] =channels _a : str =[] for i, pool_scale in enumerate(SCREAMING_SNAKE_CASE ): _a : Optional[int] =UperNetPyramidPoolingBlock(pool_scale=SCREAMING_SNAKE_CASE , in_channels=SCREAMING_SNAKE_CASE , channels=SCREAMING_SNAKE_CASE ) self.blocks.append(SCREAMING_SNAKE_CASE ) self.add_module(str(SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :torch.Tensor ) -> List[torch.Tensor]: '''simple docstring''' _a : List[str] =[] for ppm in self.blocks: _a : Any =ppm(SCREAMING_SNAKE_CASE ) _a : Dict =nn.functional.interpolate( SCREAMING_SNAKE_CASE , size=x.size()[2:] , mode="""bilinear""" , align_corners=self.align_corners ) ppm_outs.append(SCREAMING_SNAKE_CASE ) return ppm_outs class A__ ( nn.Module ): def __init__( self :Optional[int] , SCREAMING_SNAKE_CASE :Optional[Any] , SCREAMING_SNAKE_CASE :Optional[Any] ) -> List[str]: '''simple docstring''' super().__init__() _a : List[Any] =config _a : Optional[int] =config.pool_scales # e.g. (1, 2, 3, 6) _a : Any =in_channels _a : Optional[Any] =config.hidden_size _a : Any =False _a : int =nn.Convad(self.channels , config.num_labels , kernel_size=1 ) # PSP Module _a : Any =UperNetPyramidPoolingModule( self.pool_scales , self.in_channels[-1] , self.channels , align_corners=self.align_corners , ) _a : Tuple =UperNetConvModule( self.in_channels[-1] + len(self.pool_scales ) * self.channels , self.channels , kernel_size=3 , padding=1 , ) # FPN Module _a : Tuple =nn.ModuleList() _a : Dict =nn.ModuleList() for in_channels in self.in_channels[:-1]: # skip the top layer _a : str =UperNetConvModule(SCREAMING_SNAKE_CASE , self.channels , kernel_size=1 ) _a : Union[str, Any] =UperNetConvModule(self.channels , self.channels , kernel_size=3 , padding=1 ) self.lateral_convs.append(SCREAMING_SNAKE_CASE ) self.fpn_convs.append(SCREAMING_SNAKE_CASE ) _a : Any =UperNetConvModule( len(self.in_channels ) * self.channels , self.channels , kernel_size=3 , padding=1 , ) def __UpperCAmelCase ( self :List[str] ) -> Any: '''simple docstring''' self.apply(self._init_weights ) def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :List[Any] ) -> Union[str, Any]: '''simple docstring''' if isinstance(SCREAMING_SNAKE_CASE , nn.Convad ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() def __UpperCAmelCase ( self :int , SCREAMING_SNAKE_CASE :List[Any] ) -> List[str]: '''simple docstring''' _a : Dict =inputs[-1] _a : str =[x] psp_outs.extend(self.psp_modules(SCREAMING_SNAKE_CASE ) ) _a : str =torch.cat(SCREAMING_SNAKE_CASE , dim=1 ) _a : str =self.bottleneck(SCREAMING_SNAKE_CASE ) return output def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :torch.Tensor ) -> torch.Tensor: '''simple docstring''' # build laterals _a : Optional[Any] =[lateral_conv(encoder_hidden_states[i] ) for i, lateral_conv in enumerate(self.lateral_convs )] laterals.append(self.psp_forward(SCREAMING_SNAKE_CASE ) ) # build top-down path _a : List[str] =len(SCREAMING_SNAKE_CASE ) for i in range(used_backbone_levels - 1 , 0 , -1 ): _a : Tuple =laterals[i - 1].shape[2:] _a : List[str] =laterals[i - 1] + nn.functional.interpolate( laterals[i] , size=SCREAMING_SNAKE_CASE , mode="""bilinear""" , align_corners=self.align_corners ) # build outputs _a : int =[self.fpn_convs[i](laterals[i] ) for i in range(used_backbone_levels - 1 )] # append psp feature fpn_outs.append(laterals[-1] ) for i in range(used_backbone_levels - 1 , 0 , -1 ): _a : Dict =nn.functional.interpolate( fpn_outs[i] , size=fpn_outs[0].shape[2:] , mode="""bilinear""" , align_corners=self.align_corners ) _a : int =torch.cat(SCREAMING_SNAKE_CASE , dim=1 ) _a : List[Any] =self.fpn_bottleneck(SCREAMING_SNAKE_CASE ) _a : Any =self.classifier(SCREAMING_SNAKE_CASE ) return output class A__ ( nn.Module ): def __init__( self :Tuple , SCREAMING_SNAKE_CASE :List[Any] , SCREAMING_SNAKE_CASE :int = 2 , SCREAMING_SNAKE_CASE :int = 3 , SCREAMING_SNAKE_CASE :Union[int, Tuple[int, int]] = 1 ) -> None: '''simple docstring''' super().__init__() _a : Optional[int] =config _a : Any =config.auxiliary_in_channels _a : Tuple =config.auxiliary_channels _a : List[str] =config.auxiliary_num_convs _a : Dict =config.auxiliary_concat_input _a : int =in_index _a : Tuple =(kernel_size // 2) * dilation _a : Dict =[] convs.append( UperNetConvModule( self.in_channels , self.channels , kernel_size=SCREAMING_SNAKE_CASE , padding=SCREAMING_SNAKE_CASE , dilation=SCREAMING_SNAKE_CASE ) ) for i in range(self.num_convs - 1 ): convs.append( UperNetConvModule( self.channels , self.channels , kernel_size=SCREAMING_SNAKE_CASE , padding=SCREAMING_SNAKE_CASE , dilation=SCREAMING_SNAKE_CASE ) ) if self.num_convs == 0: _a : str =nn.Identity() else: _a : Tuple =nn.Sequential(*SCREAMING_SNAKE_CASE ) if self.concat_input: _a : Optional[int] =UperNetConvModule( self.in_channels + self.channels , self.channels , kernel_size=SCREAMING_SNAKE_CASE , padding=kernel_size // 2 ) _a : List[Any] =nn.Convad(self.channels , config.num_labels , kernel_size=1 ) def __UpperCAmelCase ( self :int ) -> List[str]: '''simple docstring''' self.apply(self._init_weights ) def __UpperCAmelCase ( self :str , SCREAMING_SNAKE_CASE :Union[str, Any] ) -> Tuple: '''simple docstring''' if isinstance(SCREAMING_SNAKE_CASE , nn.Convad ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() def __UpperCAmelCase ( self :Tuple , SCREAMING_SNAKE_CASE :torch.Tensor ) -> torch.Tensor: '''simple docstring''' # just take the relevant feature maps _a : Optional[int] =encoder_hidden_states[self.in_index] _a : Optional[Any] =self.convs(SCREAMING_SNAKE_CASE ) if self.concat_input: _a : Tuple =self.conv_cat(torch.cat([hidden_states, output] , dim=1 ) ) _a : Tuple =self.classifier(SCREAMING_SNAKE_CASE ) return output class A__ ( UpperCAmelCase__ ): __UpperCamelCase : Optional[int] = UperNetConfig __UpperCamelCase : Any = "pixel_values" __UpperCamelCase : List[Any] = True def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :Union[str, Any] ) -> Union[str, Any]: '''simple docstring''' if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): module.backbone.init_weights() module.decode_head.init_weights() module.auxiliary_head.init_weights() def __UpperCAmelCase ( self :List[Any] ) -> Dict: '''simple docstring''' self.backbone.init_weights() self.decode_head.init_weights() self.auxiliary_head.init_weights() def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :Optional[int] , SCREAMING_SNAKE_CASE :List[Any]=False ) -> Optional[Any]: '''simple docstring''' if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): _a : List[Any] =value A__: List[Any] = R''' Parameters: This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. config ([`UperNetConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. ''' A__: Dict = R''' Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using [`AutoImageProcessor`]. See [`SegformerImageProcessor.__call__`] for details. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers in case the backbone has them. See `attentions` under returned tensors for more detail. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers of the backbone. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. ''' @add_start_docstrings( "UperNet framework leveraging any vision backbone e.g. for ADE20k, CityScapes." , UpperCAmelCase__ , ) class A__ ( UpperCAmelCase__ ): def __init__( self :Dict , SCREAMING_SNAKE_CASE :str ) -> List[str]: '''simple docstring''' super().__init__(SCREAMING_SNAKE_CASE ) _a : Optional[int] =AutoBackbone.from_config(config.backbone_config ) # Semantic segmentation head(s) _a : Dict =UperNetHead(SCREAMING_SNAKE_CASE , in_channels=self.backbone.channels ) _a : Dict =UperNetFCNHead(SCREAMING_SNAKE_CASE ) if config.use_auxiliary_head else None # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(UPERNET_INPUTS_DOCSTRING.format("""batch_size, sequence_length""" ) ) @replace_return_docstrings(output_type=SCREAMING_SNAKE_CASE , config_class=_CONFIG_FOR_DOC ) def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :Optional[torch.Tensor] = None , SCREAMING_SNAKE_CASE :Optional[bool] = None , SCREAMING_SNAKE_CASE :Optional[bool] = None , SCREAMING_SNAKE_CASE :Optional[torch.Tensor] = None , SCREAMING_SNAKE_CASE :Optional[bool] = None , ) -> Union[tuple, SemanticSegmenterOutput]: '''simple docstring''' _a : Union[str, Any] =return_dict if return_dict is not None else self.config.use_return_dict _a : Tuple =( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) _a : Dict =output_attentions if output_attentions is not None else self.config.output_attentions _a : Any =self.backbone.forward_with_filtered_kwargs( SCREAMING_SNAKE_CASE , output_hidden_states=SCREAMING_SNAKE_CASE , output_attentions=SCREAMING_SNAKE_CASE ) _a : List[Any] =outputs.feature_maps _a : int =self.decode_head(SCREAMING_SNAKE_CASE ) _a : List[str] =nn.functional.interpolate(SCREAMING_SNAKE_CASE , size=pixel_values.shape[2:] , mode="""bilinear""" , align_corners=SCREAMING_SNAKE_CASE ) _a : str =None if self.auxiliary_head is not None: _a : str =self.auxiliary_head(SCREAMING_SNAKE_CASE ) _a : Dict =nn.functional.interpolate( SCREAMING_SNAKE_CASE , size=pixel_values.shape[2:] , mode="""bilinear""" , align_corners=SCREAMING_SNAKE_CASE ) _a : str =None if labels is not None: if self.config.num_labels == 1: raise ValueError("""The number of labels should be greater than one""" ) else: # compute weighted loss _a : Dict =CrossEntropyLoss(ignore_index=self.config.loss_ignore_index ) _a : Union[str, Any] =loss_fct(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) _a : Tuple =loss_fct(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) _a : Any =main_loss + self.config.auxiliary_loss_weight * auxiliary_loss if not return_dict: if output_hidden_states: _a : Dict =(logits,) + outputs[1:] else: _a : Tuple =(logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return SemanticSegmenterOutput( loss=SCREAMING_SNAKE_CASE , logits=SCREAMING_SNAKE_CASE , hidden_states=outputs.hidden_states , attentions=outputs.attentions , )
276
'''simple docstring''' # 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 ...utils import deprecate from ..controlnet.multicontrolnet import MultiControlNetModel # noqa: F401 from ..controlnet.pipeline_controlnet import StableDiffusionControlNetPipeline # noqa: F401 deprecate( '''stable diffusion controlnet''', '''0.22.0''', '''Importing `StableDiffusionControlNetPipeline` or `MultiControlNetModel` from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import StableDiffusionControlNetPipeline` instead.''', standard_warn=False, stacklevel=3, )
276
1
'''simple docstring''' import random def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ,_UpperCAmelCase : float ,_UpperCAmelCase : bool = False ) -> dict: _a : dict ={i: [] for i in range(_UpperCAmelCase )} # if probability is greater or equal than 1, then generate a complete graph if probability >= 1: return complete_graph(_UpperCAmelCase ) # if probability is lower or equal than 0, then return a graph without edges if probability <= 0: return graph # for each couple of nodes, add an edge from u to v # if the number randomly generated is greater than probability probability for i in range(_UpperCAmelCase ): for j in range(i + 1 ,_UpperCAmelCase ): if random.random() < probability: graph[i].append(_UpperCAmelCase ) if not directed: # if the graph is undirected, add an edge in from j to i, either graph[j].append(_UpperCAmelCase ) return graph def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ) -> dict: return { i: [j for j in range(_UpperCAmelCase ) if i != j] for i in range(_UpperCAmelCase ) } if __name__ == "__main__": import doctest doctest.testmod()
276
'''simple docstring''' import pytest from datasets.utils.sharding import _distribute_shards, _number_of_shards_in_gen_kwargs, _split_gen_kwargs @pytest.mark.parametrize( """kwargs, expected""" ,[ ({"""num_shards""": 0, """max_num_jobs""": 1}, []), ({"""num_shards""": 10, """max_num_jobs""": 1}, [range(10 )]), ({"""num_shards""": 10, """max_num_jobs""": 10}, [range(_UpperCAmelCase ,i + 1 ) for i in range(10 )]), ({"""num_shards""": 1, """max_num_jobs""": 10}, [range(1 )]), ({"""num_shards""": 10, """max_num_jobs""": 3}, [range(0 ,4 ), range(4 ,7 ), range(7 ,10 )]), ({"""num_shards""": 3, """max_num_jobs""": 10}, [range(0 ,1 ), range(1 ,2 ), range(2 ,3 )]), ] ,) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : Dict ) -> Optional[Any]: _a : Tuple =_distribute_shards(**_UpperCAmelCase ) assert out == expected @pytest.mark.parametrize( """gen_kwargs, max_num_jobs, expected""" ,[ ({"""foo""": 0}, 10, [{"""foo""": 0}]), ({"""shards""": [0, 1, 2, 3]}, 1, [{"""shards""": [0, 1, 2, 3]}]), ({"""shards""": [0, 1, 2, 3]}, 4, [{"""shards""": [0]}, {"""shards""": [1]}, {"""shards""": [2]}, {"""shards""": [3]}]), ({"""shards""": [0, 1]}, 4, [{"""shards""": [0]}, {"""shards""": [1]}]), ({"""shards""": [0, 1, 2, 3]}, 2, [{"""shards""": [0, 1]}, {"""shards""": [2, 3]}]), ] ,) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : List[Any] ,_UpperCAmelCase : Union[str, Any] ) -> List[str]: _a : List[str] =_split_gen_kwargs(_UpperCAmelCase ,_UpperCAmelCase ) assert out == expected @pytest.mark.parametrize( """gen_kwargs, expected""" ,[ ({"""foo""": 0}, 1), ({"""shards""": [0]}, 1), ({"""shards""": [0, 1, 2, 3]}, 4), ({"""shards""": [0, 1, 2, 3], """foo""": 0}, 4), ({"""shards""": [0, 1, 2, 3], """other""": (0, 1)}, 4), ({"""shards""": [0, 1, 2, 3], """shards2""": [0, 1]}, RuntimeError), ] ,) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : List[Any] ) -> Union[str, Any]: if expected is RuntimeError: with pytest.raises(_UpperCAmelCase ): _number_of_shards_in_gen_kwargs(_UpperCAmelCase ) else: _a : Dict =_number_of_shards_in_gen_kwargs(_UpperCAmelCase ) assert out == expected
276
1
'''simple docstring''' import unittest from knapsack import greedy_knapsack as kp class A__ ( unittest.TestCase ): def __UpperCAmelCase ( self :Optional[int] ) -> Dict: '''simple docstring''' _a : int =[1_0, 2_0, 3_0, 4_0, 5_0, 6_0] _a : Tuple =[2, 4, 6, 8, 1_0, 1_2] _a : List[str] =1_0_0 self.assertEqual(kp.calc_profit(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) , 2_1_0 ) def __UpperCAmelCase ( self :int ) -> Optional[Any]: '''simple docstring''' self.assertRaisesRegex(SCREAMING_SNAKE_CASE , """max_weight must greater than zero.""" ) def __UpperCAmelCase ( self :Any ) -> str: '''simple docstring''' self.assertRaisesRegex(SCREAMING_SNAKE_CASE , """Weight can not be negative.""" ) def __UpperCAmelCase ( self :List[str] ) -> int: '''simple docstring''' self.assertRaisesRegex(SCREAMING_SNAKE_CASE , """Profit can not be negative.""" ) def __UpperCAmelCase ( self :List[Any] ) -> Dict: '''simple docstring''' self.assertRaisesRegex(SCREAMING_SNAKE_CASE , """max_weight must greater than zero.""" ) def __UpperCAmelCase ( self :List[str] ) -> int: '''simple docstring''' self.assertRaisesRegex( SCREAMING_SNAKE_CASE , """The length of profit and weight must be same.""" ) if __name__ == "__main__": unittest.main()
276
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A__: Dict = logging.get_logger(__name__) A__: Tuple = { '''weiweishi/roc-bert-base-zh''': '''https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json''', } class A__ ( UpperCAmelCase__ ): __UpperCamelCase : Tuple = "roc_bert" def __init__( self :Optional[int] , SCREAMING_SNAKE_CASE :Tuple=3_0_5_2_2 , SCREAMING_SNAKE_CASE :List[str]=7_6_8 , SCREAMING_SNAKE_CASE :Dict=1_2 , SCREAMING_SNAKE_CASE :List[str]=1_2 , SCREAMING_SNAKE_CASE :Tuple=3_0_7_2 , SCREAMING_SNAKE_CASE :List[Any]="gelu" , SCREAMING_SNAKE_CASE :Union[str, Any]=0.1 , SCREAMING_SNAKE_CASE :List[Any]=0.1 , SCREAMING_SNAKE_CASE :int=5_1_2 , SCREAMING_SNAKE_CASE :Optional[Any]=2 , SCREAMING_SNAKE_CASE :Union[str, Any]=0.02 , SCREAMING_SNAKE_CASE :Optional[Any]=1e-12 , SCREAMING_SNAKE_CASE :Any=True , SCREAMING_SNAKE_CASE :List[Any]=0 , SCREAMING_SNAKE_CASE :Optional[int]="absolute" , SCREAMING_SNAKE_CASE :Union[str, Any]=None , SCREAMING_SNAKE_CASE :List[Any]=True , SCREAMING_SNAKE_CASE :int=True , SCREAMING_SNAKE_CASE :Optional[int]=7_6_8 , SCREAMING_SNAKE_CASE :Optional[Any]=9_1_0 , SCREAMING_SNAKE_CASE :Union[str, Any]=5_1_2 , SCREAMING_SNAKE_CASE :str=2_4_8_5_8 , SCREAMING_SNAKE_CASE :List[Any]=True , **SCREAMING_SNAKE_CASE :Tuple , ) -> Optional[int]: '''simple docstring''' _a : List[str] =vocab_size _a : List[str] =max_position_embeddings _a : Optional[Any] =hidden_size _a : List[Any] =num_hidden_layers _a : List[str] =num_attention_heads _a : int =intermediate_size _a : Any =hidden_act _a : Dict =hidden_dropout_prob _a : int =attention_probs_dropout_prob _a : str =initializer_range _a : Optional[int] =type_vocab_size _a : Any =layer_norm_eps _a : Any =use_cache _a : Optional[int] =enable_pronunciation _a : Optional[Any] =enable_shape _a : Optional[Any] =pronunciation_embed_dim _a : Tuple =pronunciation_vocab_size _a : Union[str, Any] =shape_embed_dim _a : Any =shape_vocab_size _a : Tuple =concat_input _a : List[str] =position_embedding_type _a : List[str] =classifier_dropout super().__init__(pad_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE )
276
1
'''simple docstring''' from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A__: int = {'''configuration_focalnet''': ['''FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''FocalNetConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Optional[Any] = [ '''FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST''', '''FocalNetForImageClassification''', '''FocalNetForMaskedImageModeling''', '''FocalNetBackbone''', '''FocalNetModel''', '''FocalNetPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_focalnet import FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FocalNetConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_focalnet import ( FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST, FocalNetBackbone, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetModel, FocalNetPreTrainedModel, ) else: import sys A__: Optional[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
276
'''simple docstring''' class A__ : def __init__( self :List[str] ) -> List[Any]: '''simple docstring''' _a : Tuple =0 _a : Any =0 _a : int ={} def __UpperCAmelCase ( self :Any , SCREAMING_SNAKE_CASE :List[str] ) -> Optional[int]: '''simple docstring''' if vertex not in self.adjacency: _a : Dict ={} self.num_vertices += 1 def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Any ) -> List[str]: '''simple docstring''' self.add_vertex(SCREAMING_SNAKE_CASE ) self.add_vertex(SCREAMING_SNAKE_CASE ) if head == tail: return _a : Any =weight _a : Tuple =weight def __UpperCAmelCase ( self :Dict ) -> Optional[int]: '''simple docstring''' _a : Union[str, Any] =self.get_edges() for edge in edges: _a , _a , _a : List[str] =edge edges.remove((tail, head, weight) ) for i in range(len(SCREAMING_SNAKE_CASE ) ): _a : str =list(edges[i] ) edges.sort(key=lambda SCREAMING_SNAKE_CASE : e[2] ) for i in range(len(SCREAMING_SNAKE_CASE ) - 1 ): if edges[i][2] >= edges[i + 1][2]: _a : Union[str, Any] =edges[i][2] + 1 for edge in edges: _a , _a , _a : Tuple =edge _a : Tuple =weight _a : List[Any] =weight def __str__( self :int ) -> str: '''simple docstring''' _a : int ="""""" for tail in self.adjacency: for head in self.adjacency[tail]: _a : str =self.adjacency[head][tail] string += f"{head} -> {tail} == {weight}\n" return string.rstrip("""\n""" ) def __UpperCAmelCase ( self :Optional[int] ) -> Optional[Any]: '''simple docstring''' _a : Union[str, Any] =[] for tail in self.adjacency: for head in self.adjacency[tail]: output.append((tail, head, self.adjacency[head][tail]) ) return output def __UpperCAmelCase ( self :List[Any] ) -> List[Any]: '''simple docstring''' return self.adjacency.keys() @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :Dict=None , SCREAMING_SNAKE_CASE :List[Any]=None ) -> Optional[int]: '''simple docstring''' _a : str =Graph() if vertices is None: _a : Union[str, Any] =[] if edges is None: _a : List[Any] =[] for vertex in vertices: g.add_vertex(SCREAMING_SNAKE_CASE ) for edge in edges: g.add_edge(*SCREAMING_SNAKE_CASE ) return g class A__ : def __init__( self :Optional[int] ) -> Union[str, Any]: '''simple docstring''' _a : Optional[int] ={} _a : List[str] ={} def __len__( self :List[Any] ) -> List[Any]: '''simple docstring''' return len(self.parent ) def __UpperCAmelCase ( self :Tuple , SCREAMING_SNAKE_CASE :Tuple ) -> Dict: '''simple docstring''' if item in self.parent: return self.find(SCREAMING_SNAKE_CASE ) _a : Optional[Any] =item _a : List[str] =0 return item def __UpperCAmelCase ( self :int , SCREAMING_SNAKE_CASE :Dict ) -> List[str]: '''simple docstring''' if item not in self.parent: return self.make_set(SCREAMING_SNAKE_CASE ) if item != self.parent[item]: _a : str =self.find(self.parent[item] ) return self.parent[item] def __UpperCAmelCase ( self :Optional[int] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :List[Any] ) -> Optional[Any]: '''simple docstring''' _a : Optional[int] =self.find(SCREAMING_SNAKE_CASE ) _a : Dict =self.find(SCREAMING_SNAKE_CASE ) if roota == roota: return roota if self.rank[roota] > self.rank[roota]: _a : Any =roota return roota if self.rank[roota] < self.rank[roota]: _a : List[str] =roota return roota if self.rank[roota] == self.rank[roota]: self.rank[roota] += 1 _a : List[Any] =roota return roota return None @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :Dict ) -> Union[str, Any]: '''simple docstring''' _a : Any =graph.num_vertices _a : Union[str, Any] =Graph.UnionFind() _a : Optional[int] =[] while num_components > 1: _a : str ={} for vertex in graph.get_vertices(): _a : List[str] =-1 _a : Any =graph.get_edges() for edge in edges: _a , _a , _a : Tuple =edge edges.remove((tail, head, weight) ) for edge in edges: _a , _a , _a : Any =edge _a : Any =union_find.find(SCREAMING_SNAKE_CASE ) _a : List[Any] =union_find.find(SCREAMING_SNAKE_CASE ) if seta != seta: if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight: _a : Optional[int] =[head, tail, weight] if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight: _a : List[Any] =[head, tail, weight] for vertex in cheap_edge: if cheap_edge[vertex] != -1: _a , _a , _a : Optional[Any] =cheap_edge[vertex] if union_find.find(SCREAMING_SNAKE_CASE ) != union_find.find(SCREAMING_SNAKE_CASE ): union_find.union(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) mst_edges.append(cheap_edge[vertex] ) _a : str =num_components - 1 _a : str =Graph.build(edges=SCREAMING_SNAKE_CASE ) return mst
276
1
'''simple docstring''' import math def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : list ,_UpperCAmelCase : int ) -> int: _a : Any =len(_UpperCAmelCase ) _a : Tuple =int(math.floor(math.sqrt(_UpperCAmelCase ) ) ) _a : List[str] =0 while arr[min(_UpperCAmelCase ,_UpperCAmelCase ) - 1] < x: _a : Dict =step step += int(math.floor(math.sqrt(_UpperCAmelCase ) ) ) if prev >= n: return -1 while arr[prev] < x: _a : str =prev + 1 if prev == min(_UpperCAmelCase ,_UpperCAmelCase ): return -1 if arr[prev] == x: return prev return -1 if __name__ == "__main__": A__: Any = input('''Enter numbers separated by a comma:\n''').strip() A__: Dict = [int(item) for item in user_input.split(''',''')] A__: Dict = int(input('''Enter the number to be searched:\n''')) A__: Any = jump_search(arr, x) if res == -1: print('''Number not found!''') else: print(F"Number {x} is at index {res}")
276
'''simple docstring''' from datetime import datetime import requests from bsa import BeautifulSoup if __name__ == "__main__": A__: Union[str, Any] = input('''Enter image url: ''').strip() print(F"Downloading image from {url} ...") A__: Tuple = BeautifulSoup(requests.get(url).content, '''html.parser''') # The image URL is in the content field of the first meta tag with property og:image A__: Union[str, Any] = soup.find('''meta''', {'''property''': '''og:image'''})['''content'''] A__: List[Any] = requests.get(image_url).content A__: List[str] = F"{datetime.now():%Y-%m-%d_%H:%M:%S}.jpg" with open(file_name, '''wb''') as fp: fp.write(image_data) print(F"Done. Image saved to disk as {file_name}.")
276
1
'''simple docstring''' import json import os import shutil import tempfile from unittest import TestCase from transformers import BartTokenizer, BartTokenizerFast, DPRQuestionEncoderTokenizer, DPRQuestionEncoderTokenizerFast from transformers.models.bart.configuration_bart import BartConfig from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES from transformers.models.dpr.configuration_dpr import DPRConfig from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES from transformers.testing_utils import require_faiss, require_tokenizers, require_torch, slow from transformers.utils import is_datasets_available, is_faiss_available, is_torch_available if is_torch_available() and is_datasets_available() and is_faiss_available(): from transformers.models.rag.configuration_rag import RagConfig from transformers.models.rag.tokenization_rag import RagTokenizer @require_faiss @require_torch class A__ ( UpperCAmelCase__ ): def __UpperCAmelCase ( self :Dict ) -> List[str]: '''simple docstring''' _a : Optional[Any] =tempfile.mkdtemp() _a : Any =8 # DPR tok _a : Tuple =[ """[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] _a : Optional[int] =os.path.join(self.tmpdirname , """dpr_tokenizer""" ) os.makedirs(SCREAMING_SNAKE_CASE , exist_ok=SCREAMING_SNAKE_CASE ) _a : Dict =os.path.join(SCREAMING_SNAKE_CASE , DPR_VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) # BART tok _a : List[str] =[ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """\u0120""", """\u0120l""", """\u0120n""", """\u0120lo""", """\u0120low""", """er""", """\u0120lowest""", """\u0120newer""", """\u0120wider""", """<unk>""", ] _a : List[Any] =dict(zip(SCREAMING_SNAKE_CASE , range(len(SCREAMING_SNAKE_CASE ) ) ) ) _a : Union[str, Any] =["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""] _a : Any ={"""unk_token""": """<unk>"""} _a : str =os.path.join(self.tmpdirname , """bart_tokenizer""" ) os.makedirs(SCREAMING_SNAKE_CASE , exist_ok=SCREAMING_SNAKE_CASE ) _a : int =os.path.join(SCREAMING_SNAKE_CASE , BART_VOCAB_FILES_NAMES["""vocab_file"""] ) _a : List[str] =os.path.join(SCREAMING_SNAKE_CASE , BART_VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(SCREAMING_SNAKE_CASE ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(SCREAMING_SNAKE_CASE ) ) def __UpperCAmelCase ( self :List[Any] ) -> DPRQuestionEncoderTokenizer: '''simple docstring''' return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname , """dpr_tokenizer""" ) ) def __UpperCAmelCase ( self :Optional[Any] ) -> BartTokenizer: '''simple docstring''' return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname , """bart_tokenizer""" ) ) def __UpperCAmelCase ( self :Optional[int] ) -> str: '''simple docstring''' shutil.rmtree(self.tmpdirname ) @require_tokenizers def __UpperCAmelCase ( self :List[str] ) -> str: '''simple docstring''' _a : Optional[Any] =os.path.join(self.tmpdirname , """rag_tokenizer""" ) _a : Optional[int] =RagConfig(question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() ) _a : Any =RagTokenizer(question_encoder=self.get_dpr_tokenizer() , generator=self.get_bart_tokenizer() ) rag_config.save_pretrained(SCREAMING_SNAKE_CASE ) rag_tokenizer.save_pretrained(SCREAMING_SNAKE_CASE ) _a : Any =RagTokenizer.from_pretrained(SCREAMING_SNAKE_CASE , config=SCREAMING_SNAKE_CASE ) self.assertIsInstance(new_rag_tokenizer.question_encoder , SCREAMING_SNAKE_CASE ) self.assertEqual(new_rag_tokenizer.question_encoder.get_vocab() , rag_tokenizer.question_encoder.get_vocab() ) self.assertIsInstance(new_rag_tokenizer.generator , SCREAMING_SNAKE_CASE ) self.assertEqual(new_rag_tokenizer.generator.get_vocab() , rag_tokenizer.generator.get_vocab() ) @slow def __UpperCAmelCase ( self :str ) -> Any: '''simple docstring''' _a : Union[str, Any] =RagTokenizer.from_pretrained("""facebook/rag-token-nq""" ) _a : Union[str, Any] =[ """who got the first nobel prize in physics""", """when is the next deadpool movie being released""", """which mode is used for short wave broadcast service""", """who is the owner of reading football club""", """when is the next scandal episode coming out""", """when is the last time the philadelphia won the superbowl""", """what is the most current adobe flash player version""", """how many episodes are there in dragon ball z""", """what is the first step in the evolution of the eye""", """where is gall bladder situated in human body""", """what is the main mineral in lithium batteries""", """who is the president of usa right now""", """where do the greasers live in the outsiders""", """panda is a national animal of which country""", """what is the name of manchester united stadium""", ] _a : Any =tokenizer(SCREAMING_SNAKE_CASE ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) @slow def __UpperCAmelCase ( self :Tuple ) -> List[Any]: '''simple docstring''' _a : Union[str, Any] =RagTokenizer.from_pretrained("""facebook/rag-sequence-nq""" ) _a : int =[ """who got the first nobel prize in physics""", """when is the next deadpool movie being released""", """which mode is used for short wave broadcast service""", """who is the owner of reading football club""", """when is the next scandal episode coming out""", """when is the last time the philadelphia won the superbowl""", """what is the most current adobe flash player version""", """how many episodes are there in dragon ball z""", """what is the first step in the evolution of the eye""", """where is gall bladder situated in human body""", """what is the main mineral in lithium batteries""", """who is the president of usa right now""", """where do the greasers live in the outsiders""", """panda is a national animal of which country""", """what is the name of manchester united stadium""", ] _a : Optional[int] =tokenizer(SCREAMING_SNAKE_CASE ) self.assertIsNotNone(SCREAMING_SNAKE_CASE )
276
'''simple docstring''' A__: Tuple = ''' # Installazione di Transformers ! pip install transformers datasets # Per installare dalla fonte invece dell\'ultima versione rilasciata, commenta il comando sopra e # rimuovi la modalità commento al comando seguente. # ! pip install git+https://github.com/huggingface/transformers.git ''' A__: Tuple = [{'''type''': '''code''', '''content''': INSTALL_CONTENT}] A__: Any = { '''{processor_class}''': '''FakeProcessorClass''', '''{model_class}''': '''FakeModelClass''', '''{object_class}''': '''FakeObjectClass''', }
276
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available A__: Optional[Any] = { '''configuration_transfo_xl''': ['''TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''TransfoXLConfig'''], '''tokenization_transfo_xl''': ['''TransfoXLCorpus''', '''TransfoXLTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: str = [ '''TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST''', '''AdaptiveEmbedding''', '''TransfoXLForSequenceClassification''', '''TransfoXLLMHeadModel''', '''TransfoXLModel''', '''TransfoXLPreTrainedModel''', '''load_tf_weights_in_transfo_xl''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: List[Any] = [ '''TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFAdaptiveEmbedding''', '''TFTransfoXLForSequenceClassification''', '''TFTransfoXLLMHeadModel''', '''TFTransfoXLMainLayer''', '''TFTransfoXLModel''', '''TFTransfoXLPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_transfo_xl import TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, TransfoXLConfig from .tokenization_transfo_xl import TransfoXLCorpus, TransfoXLTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_transfo_xl import ( TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST, AdaptiveEmbedding, TransfoXLForSequenceClassification, TransfoXLLMHeadModel, TransfoXLModel, TransfoXLPreTrainedModel, load_tf_weights_in_transfo_xl, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_transfo_xl import ( TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST, TFAdaptiveEmbedding, TFTransfoXLForSequenceClassification, TFTransfoXLLMHeadModel, TFTransfoXLMainLayer, TFTransfoXLModel, TFTransfoXLPreTrainedModel, ) else: import sys A__: Optional[int] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
276
'''simple docstring''' A__: Optional[int] = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] A__: Any = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] A__: int = { 0: '''Sunday''', 1: '''Monday''', 2: '''Tuesday''', 3: '''Wednesday''', 4: '''Thursday''', 5: '''Friday''', 6: '''Saturday''', } def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ,_UpperCAmelCase : int ,_UpperCAmelCase : int ) -> str: assert len(str(_UpperCAmelCase ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 12, "month should be between 1 to 12" assert 1 <= day <= 31, "day should be between 1 to 31" # Doomsday algorithm: _a : List[str] =year // 100 _a : List[str] =(5 * (century % 4) + 2) % 7 _a : Optional[int] =year % 100 _a : Any =centurian % 12 _a : int =( (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 _a : Optional[Any] =( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 400) == 0) else DOOMSDAY_LEAP[month - 1] ) _a : str =(dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
276
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available A__: Union[str, Any] = { '''configuration_pix2struct''': [ '''PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Pix2StructConfig''', '''Pix2StructTextConfig''', '''Pix2StructVisionConfig''', ], '''processing_pix2struct''': ['''Pix2StructProcessor'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Tuple = ['''Pix2StructImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Union[str, Any] = [ '''PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Pix2StructPreTrainedModel''', '''Pix2StructForConditionalGeneration''', '''Pix2StructVisionModel''', '''Pix2StructTextModel''', ] if TYPE_CHECKING: from .configuration_pixastruct import ( PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP, PixaStructConfig, PixaStructTextConfig, PixaStructVisionConfig, ) from .processing_pixastruct import PixaStructProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_pixastruct import PixaStructImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pixastruct import ( PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST, PixaStructForConditionalGeneration, PixaStructPreTrainedModel, PixaStructTextModel, PixaStructVisionModel, ) else: import sys A__: int = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
276
'''simple docstring''' from __future__ import annotations from typing import TypedDict class A__ ( UpperCAmelCase__ ): __UpperCamelCase : str __UpperCamelCase : int def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ) -> list[str]: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError("""The parameter s type must be str.""" ) return [s[i:] + s[:i] for i in range(len(_UpperCAmelCase ) )] def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ) -> BWTTransformDict: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError("""The parameter s type must be str.""" ) if not s: raise ValueError("""The parameter s must not be empty.""" ) _a : List[Any] =all_rotations(_UpperCAmelCase ) rotations.sort() # sort the list of rotations in alphabetically order # make a string composed of the last char of each rotation _a : BWTTransformDict ={ "bwt_string": "".join([word[-1] for word in rotations] ), "idx_original_string": rotations.index(_UpperCAmelCase ), } return response def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : int ) -> str: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError("""The parameter bwt_string type must be str.""" ) if not bwt_string: raise ValueError("""The parameter bwt_string must not be empty.""" ) try: _a : List[str] =int(_UpperCAmelCase ) except ValueError: raise TypeError( """The parameter idx_original_string type must be int or passive""" """ of cast to int.""" ) if idx_original_string < 0: raise ValueError("""The parameter idx_original_string must not be lower than 0.""" ) if idx_original_string >= len(_UpperCAmelCase ): raise ValueError( """The parameter idx_original_string must be lower than""" """ len(bwt_string).""" ) _a : Optional[int] =[""""""] * len(_UpperCAmelCase ) for _ in range(len(_UpperCAmelCase ) ): for i in range(len(_UpperCAmelCase ) ): _a : int =bwt_string[i] + ordered_rotations[i] ordered_rotations.sort() return ordered_rotations[idx_original_string] if __name__ == "__main__": A__: Any = '''Provide a string that I will generate its BWT transform: ''' A__: Union[str, Any] = input(entry_msg).strip() A__: Optional[int] = bwt_transform(s) print( F"Burrows Wheeler transform for string '{s}' results " F"in '{result['bwt_string']}'" ) A__: Union[str, Any] = reverse_bwt(result['''bwt_string'''], result['''idx_original_string''']) print( F"Reversing Burrows Wheeler transform for entry '{result['bwt_string']}' " F"we get original string '{original_string}'" )
276
1
'''simple docstring''' import itertools import os from collections import Counter, defaultdict from concurrent.futures import ThreadPoolExecutor, as_completed import numpy as np import datasets from .execute import check_correctness A__: Optional[int] = '''\ @misc{chen2021evaluating, title={Evaluating Large Language Models Trained on Code}, author={Mark Chen and Jerry Tworek and Heewoo Jun and Qiming Yuan \ and Henrique Ponde de Oliveira Pinto and Jared Kaplan and Harri Edwards \ and Yuri Burda and Nicholas Joseph and Greg Brockman and Alex Ray \ and Raul Puri and Gretchen Krueger and Michael Petrov and Heidy Khlaaf \ and Girish Sastry and Pamela Mishkin and Brooke Chan and Scott Gray \ and Nick Ryder and Mikhail Pavlov and Alethea Power and Lukasz Kaiser \ and Mohammad Bavarian and Clemens Winter and Philippe Tillet \ and Felipe Petroski Such and Dave Cummings and Matthias Plappert \ and Fotios Chantzis and Elizabeth Barnes and Ariel Herbert-Voss \ and William Hebgen Guss and Alex Nichol and Alex Paino and Nikolas Tezak \ and Jie Tang and Igor Babuschkin and Suchir Balaji and Shantanu Jain \ and William Saunders and Christopher Hesse and Andrew N. Carr \ and Jan Leike and Josh Achiam and Vedant Misra and Evan Morikawa \ and Alec Radford and Matthew Knight and Miles Brundage and Mira Murati \ and Katie Mayer and Peter Welinder and Bob McGrew and Dario Amodei \ and Sam McCandlish and Ilya Sutskever and Wojciech Zaremba}, year={2021}, eprint={2107.03374}, archivePrefix={arXiv}, primaryClass={cs.LG} } ''' A__: Tuple = '''\ This metric implements the evaluation harness for the HumanEval problem solving dataset described in the paper "Evaluating Large Language Models Trained on Code" (https://arxiv.org/abs/2107.03374). ''' A__: Dict = ''' Calculates how good are predictions given some references, using certain scores Args: predictions: list of candidates to evaluate. Each candidates should be a list of strings with several code candidates to solve the problem. references: a list with a test for each prediction. Each test should evaluate the correctness of a code candidate. k: number of code candidates to consider in the evaluation (Default: [1, 10, 100]) num_workers: number of workers used to evaluate the canidate programs (Default: 4). timeout: Returns: pass_at_k: dict with pass rates for each k results: dict with granular results of each unittest Examples: >>> code_eval = datasets.load_metric("code_eval") >>> test_cases = ["assert add(2,3)==5"] >>> candidates = [["def add(a,b): return a*b", "def add(a, b): return a+b"]] >>> pass_at_k, results = code_eval.compute(references=test_cases, predictions=candidates, k=[1, 2]) >>> print(pass_at_k) {\'pass@1\': 0.5, \'pass@2\': 1.0} ''' A__: int = ''' ################################################################################ !!!WARNING!!! ################################################################################ The "code_eval" metric executes untrusted model-generated code in Python. Although it is highly unlikely that model-generated code will do something overtly malicious in response to this test suite, model-generated code may act destructively due to a lack of model capability or alignment. Users are strongly encouraged to sandbox this evaluation suite so that it does not perform destructive actions on their host or network. For more information on how OpenAI sandboxes its code, see the paper "Evaluating Large Language Models Trained on Code" (https://arxiv.org/abs/2107.03374). Once you have read this disclaimer and taken appropriate precautions, set the environment variable HF_ALLOW_CODE_EVAL="1". Within Python you can to this with: >>> import os >>> os.environ["HF_ALLOW_CODE_EVAL"] = "1" ################################################################################\ ''' A__: List[Any] = '''The MIT License Copyright (c) OpenAI (https://openai.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A__ ( datasets.Metric ): def __UpperCAmelCase ( self :str ) -> Optional[int]: '''simple docstring''' return datasets.MetricInfo( # This is the description that will appear on the metrics page. description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Sequence(datasets.Value("""string""" ) ), """references""": datasets.Value("""string""" ), } ) , homepage="""https://github.com/openai/human-eval""" , codebase_urls=["""https://github.com/openai/human-eval"""] , reference_urls=["""https://github.com/openai/human-eval"""] , license=_LICENSE , ) def __UpperCAmelCase ( self :List[str] , SCREAMING_SNAKE_CASE :List[Any] , SCREAMING_SNAKE_CASE :List[Any] , SCREAMING_SNAKE_CASE :int=[1, 1_0, 1_0_0] , SCREAMING_SNAKE_CASE :List[Any]=4 , SCREAMING_SNAKE_CASE :Any=3.0 ) -> Optional[Any]: '''simple docstring''' if os.getenv("""HF_ALLOW_CODE_EVAL""" , 0 ) != "1": raise ValueError(_WARNING ) if os.name == "nt": raise NotImplementedError("""This metric is currently not supported on Windows.""" ) with ThreadPoolExecutor(max_workers=SCREAMING_SNAKE_CASE ) as executor: _a : Any =[] _a : Optional[int] =Counter() _a : Dict =0 _a : Dict =defaultdict(SCREAMING_SNAKE_CASE ) for task_id, (candidates, test_case) in enumerate(zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ): for candidate in candidates: _a : int =candidate + """\n""" + test_case _a : Any =(test_program, timeout, task_id, completion_id[task_id]) _a : List[Any] =executor.submit(SCREAMING_SNAKE_CASE , *SCREAMING_SNAKE_CASE ) futures.append(SCREAMING_SNAKE_CASE ) completion_id[task_id] += 1 n_samples += 1 for future in as_completed(SCREAMING_SNAKE_CASE ): _a : Tuple =future.result() results[result["task_id"]].append((result["""completion_id"""], result) ) _a , _a : Optional[Any] =[], [] for result in results.values(): result.sort() _a : Any =[r[1]["""passed"""] for r in result] total.append(len(SCREAMING_SNAKE_CASE ) ) correct.append(sum(SCREAMING_SNAKE_CASE ) ) _a : Optional[Any] =np.array(SCREAMING_SNAKE_CASE ) _a : List[str] =np.array(SCREAMING_SNAKE_CASE ) _a : Any =k _a : Tuple ={f"pass@{k}": estimate_pass_at_k(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ).mean() for k in ks if (total >= k).all()} return pass_at_k, results def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Any ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : int ) -> Optional[int]: def estimator(_UpperCAmelCase : int ,_UpperCAmelCase : int ,_UpperCAmelCase : int ) -> float: if n - c < k: return 1.0 return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1 ,n + 1 ) ) if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): _a : Tuple =itertools.repeat(_UpperCAmelCase ,len(_UpperCAmelCase ) ) else: assert len(_UpperCAmelCase ) == len(_UpperCAmelCase ) _a : List[Any] =iter(_UpperCAmelCase ) return np.array([estimator(int(_UpperCAmelCase ) ,int(_UpperCAmelCase ) ,_UpperCAmelCase ) for n, c in zip(_UpperCAmelCase ,_UpperCAmelCase )] )
276
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available A__: List[str] = { '''configuration_chinese_clip''': [ '''CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ChineseCLIPConfig''', '''ChineseCLIPOnnxConfig''', '''ChineseCLIPTextConfig''', '''ChineseCLIPVisionConfig''', ], '''processing_chinese_clip''': ['''ChineseCLIPProcessor'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Optional[int] = ['''ChineseCLIPFeatureExtractor'''] A__: Any = ['''ChineseCLIPImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Dict = [ '''CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ChineseCLIPModel''', '''ChineseCLIPPreTrainedModel''', '''ChineseCLIPTextModel''', '''ChineseCLIPVisionModel''', ] if TYPE_CHECKING: from .configuration_chinese_clip import ( CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, ChineseCLIPConfig, ChineseCLIPOnnxConfig, ChineseCLIPTextConfig, ChineseCLIPVisionConfig, ) from .processing_chinese_clip import ChineseCLIPProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_chinese_clip import ChineseCLIPFeatureExtractor, ChineseCLIPImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_chinese_clip import ( CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, ChineseCLIPModel, ChineseCLIPPreTrainedModel, ChineseCLIPTextModel, ChineseCLIPVisionModel, ) else: import sys A__: str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
276
1
'''simple docstring''' import math def SCREAMING_SNAKE_CASE_ ( ) -> None: _a : List[str] =input("""Enter message: """ ) _a : Optional[Any] =int(input(F"Enter key [2-{len(_UpperCAmelCase ) - 1}]: " ) ) _a : List[Any] =input("""Encryption/Decryption [e/d]: """ ) if mode.lower().startswith("""e""" ): _a : Optional[Any] =encrypt_message(_UpperCAmelCase ,_UpperCAmelCase ) elif mode.lower().startswith("""d""" ): _a : Tuple =decrypt_message(_UpperCAmelCase ,_UpperCAmelCase ) # Append pipe symbol (vertical bar) to identify spaces at the end. print(F"Output:\n{text + '|'}" ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ,_UpperCAmelCase : str ) -> str: _a : int =[""""""] * key for col in range(_UpperCAmelCase ): _a : List[Any] =col while pointer < len(_UpperCAmelCase ): cipher_text[col] += message[pointer] pointer += key return "".join(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ,_UpperCAmelCase : str ) -> str: _a : Union[str, Any] =math.ceil(len(_UpperCAmelCase ) / key ) _a : List[Any] =key _a : List[Any] =(num_cols * num_rows) - len(_UpperCAmelCase ) _a : Union[str, Any] =[""""""] * num_cols _a : List[str] =0 _a : str =0 for symbol in message: plain_text[col] += symbol col += 1 if ( (col == num_cols) or (col == num_cols - 1) and (row >= num_rows - num_shaded_boxes) ): _a : List[Any] =0 row += 1 return "".join(_UpperCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod() main()
276
'''simple docstring''' class A__ : def __init__( self :List[Any] ) -> None: '''simple docstring''' _a : dict[str, TrieNode] ={} # Mapping from char to TrieNode _a : List[str] =False def __UpperCAmelCase ( self :Tuple , SCREAMING_SNAKE_CASE :list[str] ) -> None: '''simple docstring''' for word in words: self.insert(SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :str ) -> None: '''simple docstring''' _a : str =self for char in word: if char not in curr.nodes: _a : Dict =TrieNode() _a : List[Any] =curr.nodes[char] _a : int =True def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :str ) -> bool: '''simple docstring''' _a : int =self for char in word: if char not in curr.nodes: return False _a : List[Any] =curr.nodes[char] return curr.is_leaf def __UpperCAmelCase ( self :Dict , SCREAMING_SNAKE_CASE :str ) -> None: '''simple docstring''' def _delete(SCREAMING_SNAKE_CASE :TrieNode , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :int ) -> bool: if index == len(SCREAMING_SNAKE_CASE ): # If word does not exist if not curr.is_leaf: return False _a : Any =False return len(curr.nodes ) == 0 _a : int =word[index] _a : int =curr.nodes.get(SCREAMING_SNAKE_CASE ) # If char not in current trie node if not char_node: return False # Flag to check if node can be deleted _a : List[Any] =_delete(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , index + 1 ) if delete_curr: del curr.nodes[char] return len(curr.nodes ) == 0 return delete_curr _delete(self , SCREAMING_SNAKE_CASE , 0 ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : TrieNode ,_UpperCAmelCase : str ) -> None: if node.is_leaf: print(_UpperCAmelCase ,end=""" """ ) for key, value in node.nodes.items(): print_words(_UpperCAmelCase ,word + key ) def SCREAMING_SNAKE_CASE_ ( ) -> bool: _a : List[str] ="""banana bananas bandana band apple all beast""".split() _a : List[Any] =TrieNode() root.insert_many(_UpperCAmelCase ) # print_words(root, "") assert all(root.find(_UpperCAmelCase ) for word in words ) assert root.find("""banana""" ) assert not root.find("""bandanas""" ) assert not root.find("""apps""" ) assert root.find("""apple""" ) assert root.find("""all""" ) root.delete("""all""" ) assert not root.find("""all""" ) root.delete("""banana""" ) assert not root.find("""banana""" ) assert root.find("""bananas""" ) return True def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : bool ) -> None: print(str(_UpperCAmelCase ) ,"""works!""" if passes else """doesn't work :(""" ) def SCREAMING_SNAKE_CASE_ ( ) -> None: assert test_trie() def SCREAMING_SNAKE_CASE_ ( ) -> None: print_results("""Testing trie functionality""" ,test_trie() ) if __name__ == "__main__": main()
276
1
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING A__: List[str] = logging.get_logger(__name__) A__: List[str] = { '''salesforce/blip2-opt-2.7b''': '''https://huggingface.co/salesforce/blip2-opt-2.7b/resolve/main/config.json''', } class A__ ( UpperCAmelCase__ ): __UpperCamelCase : Tuple = "blip_2_vision_model" def __init__( self :Any , SCREAMING_SNAKE_CASE :Optional[int]=1_4_0_8 , SCREAMING_SNAKE_CASE :Optional[Any]=6_1_4_4 , SCREAMING_SNAKE_CASE :List[Any]=3_9 , SCREAMING_SNAKE_CASE :Tuple=1_6 , SCREAMING_SNAKE_CASE :str=2_2_4 , SCREAMING_SNAKE_CASE :Optional[int]=1_4 , SCREAMING_SNAKE_CASE :List[str]="gelu" , SCREAMING_SNAKE_CASE :List[Any]=0.00_001 , SCREAMING_SNAKE_CASE :Union[str, Any]=0.0 , SCREAMING_SNAKE_CASE :Optional[int]=1e-10 , SCREAMING_SNAKE_CASE :Dict=True , **SCREAMING_SNAKE_CASE :Optional[Any] , ) -> Optional[Any]: '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE ) _a : Any =hidden_size _a : List[Any] =intermediate_size _a : List[Any] =num_hidden_layers _a : Any =num_attention_heads _a : Any =patch_size _a : Optional[int] =image_size _a : Optional[Any] =initializer_range _a : List[str] =attention_dropout _a : Tuple =layer_norm_eps _a : int =hidden_act _a : Tuple =qkv_bias @classmethod def __UpperCAmelCase ( cls :List[str] , SCREAMING_SNAKE_CASE :Union[str, os.PathLike] , **SCREAMING_SNAKE_CASE :Dict ) -> "PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE ) _a , _a : Tuple =cls.get_config_dict(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) # get the vision config dict if we are loading from Blip2Config if config_dict.get("""model_type""" ) == "blip-2": _a : List[Any] =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(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) class A__ ( UpperCAmelCase__ ): __UpperCamelCase : str = "blip_2_qformer" def __init__( self :List[Any] , SCREAMING_SNAKE_CASE :Any=3_0_5_2_2 , SCREAMING_SNAKE_CASE :Optional[int]=7_6_8 , SCREAMING_SNAKE_CASE :Any=1_2 , SCREAMING_SNAKE_CASE :str=1_2 , SCREAMING_SNAKE_CASE :int=3_0_7_2 , SCREAMING_SNAKE_CASE :Dict="gelu" , SCREAMING_SNAKE_CASE :List[Any]=0.1 , SCREAMING_SNAKE_CASE :Optional[int]=0.1 , SCREAMING_SNAKE_CASE :List[Any]=5_1_2 , SCREAMING_SNAKE_CASE :int=0.02 , SCREAMING_SNAKE_CASE :Tuple=1e-12 , SCREAMING_SNAKE_CASE :Optional[Any]=0 , SCREAMING_SNAKE_CASE :Optional[int]="absolute" , SCREAMING_SNAKE_CASE :List[Any]=2 , SCREAMING_SNAKE_CASE :Dict=1_4_0_8 , **SCREAMING_SNAKE_CASE :int , ) -> Optional[int]: '''simple docstring''' super().__init__(pad_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) _a : int =vocab_size _a : Tuple =hidden_size _a : List[str] =num_hidden_layers _a : Optional[Any] =num_attention_heads _a : Optional[Any] =hidden_act _a : Tuple =intermediate_size _a : List[str] =hidden_dropout_prob _a : List[str] =attention_probs_dropout_prob _a : int =max_position_embeddings _a : Optional[Any] =initializer_range _a : Tuple =layer_norm_eps _a : Dict =position_embedding_type _a : List[Any] =cross_attention_frequency _a : int =encoder_hidden_size @classmethod def __UpperCAmelCase ( cls :int , SCREAMING_SNAKE_CASE :Union[str, os.PathLike] , **SCREAMING_SNAKE_CASE :Any ) -> "PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE ) _a , _a : Any =cls.get_config_dict(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) # get the qformer config dict if we are loading from Blip2Config if config_dict.get("""model_type""" ) == "blip-2": _a : List[str] =config_dict["""qformer_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(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) class A__ ( UpperCAmelCase__ ): __UpperCamelCase : Optional[int] = "blip-2" __UpperCamelCase : Tuple = True def __init__( self :List[str] , SCREAMING_SNAKE_CASE :List[str]=None , SCREAMING_SNAKE_CASE :Optional[int]=None , SCREAMING_SNAKE_CASE :Optional[Any]=None , SCREAMING_SNAKE_CASE :int=3_2 , **SCREAMING_SNAKE_CASE :Optional[Any] ) -> List[str]: '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE ) if vision_config is None: _a : str ={} logger.info("""vision_config is None. initializing the Blip2VisionConfig with default values.""" ) if qformer_config is None: _a : Any ={} logger.info("""qformer_config is None. Initializing the Blip2QFormerConfig with default values.""" ) if text_config is None: _a : Any ={} logger.info("""text_config is None. Initializing the text config with default values (`OPTConfig`).""" ) _a : List[str] =BlipaVisionConfig(**SCREAMING_SNAKE_CASE ) _a : List[Any] =BlipaQFormerConfig(**SCREAMING_SNAKE_CASE ) _a : Tuple =text_config["""model_type"""] if """model_type""" in text_config else """opt""" _a : str =CONFIG_MAPPING[text_model_type](**SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =self.text_config.tie_word_embeddings _a : Union[str, Any] =self.text_config.is_encoder_decoder _a : str =num_query_tokens _a : Dict =self.vision_config.hidden_size _a : str =self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES _a : Dict =1.0 _a : Tuple =0.02 @classmethod def __UpperCAmelCase ( cls :List[Any] , SCREAMING_SNAKE_CASE :BlipaVisionConfig , SCREAMING_SNAKE_CASE :BlipaQFormerConfig , SCREAMING_SNAKE_CASE :PretrainedConfig , **SCREAMING_SNAKE_CASE :Any , ) -> Any: '''simple docstring''' return cls( vision_config=vision_config.to_dict() , qformer_config=qformer_config.to_dict() , text_config=text_config.to_dict() , **SCREAMING_SNAKE_CASE , ) def __UpperCAmelCase ( self :Optional[int] ) -> Dict: '''simple docstring''' _a : List[Any] =copy.deepcopy(self.__dict__ ) _a : Any =self.vision_config.to_dict() _a : Optional[int] =self.qformer_config.to_dict() _a : Any =self.text_config.to_dict() _a : str =self.__class__.model_type return output
276
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available A__: str = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Tuple = ['''GPTSw3Tokenizer'''] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_swa import GPTSwaTokenizer else: import sys A__: str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
276
1
'''simple docstring''' import argparse import math import traceback import dateutil.parser as date_parser import requests def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ) -> Union[str, Any]: _a : Union[str, Any] ={} _a : str =job["""started_at"""] _a : str =job["""completed_at"""] _a : List[Any] =date_parser.parse(_UpperCAmelCase ) _a : Dict =date_parser.parse(_UpperCAmelCase ) _a : Tuple =round((end_datetime - start_datetime).total_seconds() / 6_0.0 ) _a : Union[str, Any] =start _a : Optional[int] =end _a : Union[str, Any] =duration_in_min return job_info def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[Any] ,_UpperCAmelCase : Tuple=None ) -> List[Any]: _a : Tuple =None if token is not None: _a : Any ={"""Accept""": """application/vnd.github+json""", """Authorization""": F"Bearer {token}"} _a : Optional[Any] =F"https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100" _a : List[str] =requests.get(_UpperCAmelCase ,headers=_UpperCAmelCase ).json() _a : Optional[int] ={} try: job_time.update({job["""name"""]: extract_time_from_single_job(_UpperCAmelCase ) for job in result["""jobs"""]} ) _a : Tuple =math.ceil((result["""total_count"""] - 100) / 100 ) for i in range(_UpperCAmelCase ): _a : Tuple =requests.get(url + F"&page={i + 2}" ,headers=_UpperCAmelCase ).json() job_time.update({job["""name"""]: extract_time_from_single_job(_UpperCAmelCase ) for job in result["""jobs"""]} ) return job_time except Exception: print(F"Unknown error, could not fetch links:\n{traceback.format_exc()}" ) return {} if __name__ == "__main__": A__: List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument('''--workflow_run_id''', type=str, required=True, help='''A GitHub Actions workflow run id.''') A__: str = parser.parse_args() A__: Any = get_job_time(args.workflow_run_id) A__: Tuple = dict(sorted(job_time.items(), key=lambda item: item[1]["duration"], reverse=True)) for k, v in job_time.items(): print(F"{k}: {v['duration']}")
276
'''simple docstring''' import importlib.metadata import warnings from copy import deepcopy from packaging import version from ..utils import logging from .import_utils import is_accelerate_available, is_bitsandbytes_available if is_bitsandbytes_available(): import bitsandbytes as bnb import torch import torch.nn as nn from ..pytorch_utils import ConvaD if is_accelerate_available(): from accelerate import init_empty_weights from accelerate.utils import find_tied_parameters A__: str = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[Any] ,_UpperCAmelCase : List[str] ,_UpperCAmelCase : int ,_UpperCAmelCase : int=None ,_UpperCAmelCase : Optional[Any]=None ) -> Optional[Any]: # Recurse if needed if "." in tensor_name: _a : Union[str, Any] =tensor_name.split(""".""" ) for split in splits[:-1]: _a : Optional[Any] =getattr(_UpperCAmelCase ,_UpperCAmelCase ) if new_module is None: raise ValueError(F"{module} has no attribute {split}." ) _a : Optional[int] =new_module _a : Optional[int] =splits[-1] if tensor_name not in module._parameters and tensor_name not in module._buffers: raise ValueError(F"{module} does not have a parameter or a buffer named {tensor_name}." ) _a : Optional[Any] =tensor_name in module._buffers _a : str =getattr(_UpperCAmelCase ,_UpperCAmelCase ) if old_value.device == torch.device("""meta""" ) and device not in ["meta", torch.device("""meta""" )] and value is None: raise ValueError(F"{tensor_name} is on the meta device, we need a `value` to put in on {device}." ) _a : int =False _a : Tuple =False if is_buffer or not is_bitsandbytes_available(): _a : str =False _a : Optional[Any] =False else: _a : int =hasattr(bnb.nn ,"""Params4bit""" ) and isinstance(module._parameters[tensor_name] ,bnb.nn.Paramsabit ) _a : int =isinstance(module._parameters[tensor_name] ,bnb.nn.IntaParams ) if is_abit or is_abit: _a : Any =module._parameters[tensor_name] if param.device.type != "cuda": if value is None: _a : int =old_value.to(_UpperCAmelCase ) elif isinstance(_UpperCAmelCase ,torch.Tensor ): _a : str =value.to("""cpu""" ) if value.dtype == torch.inta: _a : int =version.parse(importlib.metadata.version("""bitsandbytes""" ) ) > version.parse( """0.37.2""" ) if not is_abit_serializable: raise ValueError( """Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. """ """Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`.""" ) else: _a : Dict =torch.tensor(_UpperCAmelCase ,device="""cpu""" ) # Support models using `Conv1D` in place of `nn.Linear` (e.g. gpt2) by transposing the weight matrix prior to quantization. # Since weights are saved in the correct "orientation", we skip transposing when loading. if issubclass(module.source_cls ,_UpperCAmelCase ) and fpaa_statistics is None: _a : int =new_value.T _a : Any =old_value.__dict__ if is_abit: _a : Any =bnb.nn.IntaParams(_UpperCAmelCase ,requires_grad=_UpperCAmelCase ,**_UpperCAmelCase ).to(_UpperCAmelCase ) elif is_abit: _a : Union[str, Any] =bnb.nn.Paramsabit(_UpperCAmelCase ,requires_grad=_UpperCAmelCase ,**_UpperCAmelCase ).to(_UpperCAmelCase ) _a : List[Any] =new_value if fpaa_statistics is not None: setattr(module.weight ,"""SCB""" ,fpaa_statistics.to(_UpperCAmelCase ) ) else: if value is None: _a : str =old_value.to(_UpperCAmelCase ) elif isinstance(_UpperCAmelCase ,torch.Tensor ): _a : Any =value.to(_UpperCAmelCase ) else: _a : str =torch.tensor(_UpperCAmelCase ,device=_UpperCAmelCase ) if is_buffer: _a : Optional[int] =new_value else: _a : Optional[Any] =nn.Parameter(_UpperCAmelCase ,requires_grad=old_value.requires_grad ) _a : Tuple =new_value def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : Union[str, Any]=None ,_UpperCAmelCase : List[Any]=None ,_UpperCAmelCase : str=None ,_UpperCAmelCase : Union[str, Any]=False ) -> Dict: for name, module in model.named_children(): if current_key_name is None: _a : Optional[int] =[] current_key_name.append(_UpperCAmelCase ) if (isinstance(_UpperCAmelCase ,nn.Linear ) or isinstance(_UpperCAmelCase ,_UpperCAmelCase )) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` if not any(key in """.""".join(_UpperCAmelCase ) for key in modules_to_not_convert ): with init_empty_weights(): if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): _a , _a : int =module.weight.shape else: _a : List[str] =module.in_features _a : Tuple =module.out_features if quantization_config.quantization_method() == "llm_int8": _a : Optional[Any] =bnb.nn.LinearabitLt( _UpperCAmelCase ,_UpperCAmelCase ,module.bias is not None ,has_fpaa_weights=quantization_config.llm_inta_has_fpaa_weight ,threshold=quantization_config.llm_inta_threshold ,) _a : Optional[Any] =True else: if ( quantization_config.llm_inta_skip_modules is not None and name in quantization_config.llm_inta_skip_modules ): pass else: _a : Dict =bnb.nn.Linearabit( _UpperCAmelCase ,_UpperCAmelCase ,module.bias is not None ,quantization_config.bnb_abit_compute_dtype ,compress_statistics=quantization_config.bnb_abit_use_double_quant ,quant_type=quantization_config.bnb_abit_quant_type ,) _a : List[Any] =True # Store the module class in case we need to transpose the weight later _a : int =type(_UpperCAmelCase ) # Force requires grad to False to avoid unexpected errors model._modules[name].requires_grad_(_UpperCAmelCase ) if len(list(module.children() ) ) > 0: _a , _a : List[Any] =_replace_with_bnb_linear( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,has_been_replaced=_UpperCAmelCase ,) # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : int=None ,_UpperCAmelCase : Union[str, Any]=None ,_UpperCAmelCase : Any=None ) -> Tuple: _a : Dict =["""lm_head"""] if modules_to_not_convert is None else modules_to_not_convert _a , _a : List[Any] =_replace_with_bnb_linear( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) 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.""" """ Please double check your model architecture, or submit an issue on github if you think this is""" """ a bug.""" ) return model def SCREAMING_SNAKE_CASE_ ( *_UpperCAmelCase : Any ,**_UpperCAmelCase : Any ) -> str: warnings.warn( """`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead""" ,_UpperCAmelCase ,) return replace_with_bnb_linear(*_UpperCAmelCase ,**_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( *_UpperCAmelCase : str ,**_UpperCAmelCase : Optional[int] ) -> Optional[int]: warnings.warn( """`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead""" ,_UpperCAmelCase ,) return set_module_quantized_tensor_to_device(*_UpperCAmelCase ,**_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ) -> Union[str, Any]: _a : Any =deepcopy(_UpperCAmelCase ) # this has 0 cost since it is done inside `init_empty_weights` context manager` tied_model.tie_weights() _a : List[Any] =find_tied_parameters(_UpperCAmelCase ) # For compatibility with Accelerate < 0.18 if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): _a : str =sum(list(tied_params.values() ) ,[] ) + list(tied_params.keys() ) else: _a : Optional[int] =sum(_UpperCAmelCase ,[] ) _a : List[Any] =len(_UpperCAmelCase ) > 0 # Check if it is a base model _a : Tuple =not hasattr(_UpperCAmelCase ,model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head _a : List[Any] =list(model.named_children() ) _a : Dict =[list_modules[-1][0]] # add last module together with tied weights _a : List[str] =set(_UpperCAmelCase ) - set(_UpperCAmelCase ) _a : str =list(set(_UpperCAmelCase ) ) + list(_UpperCAmelCase ) # remove ".weight" from the keys _a : List[Any] =[""".weight""", """.bias"""] _a : Any =[] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: _a : Any =name.replace(_UpperCAmelCase ,"""""" ) filtered_module_names.append(_UpperCAmelCase ) return filtered_module_names
276
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A__: Any = {'''configuration_ibert''': ['''IBERT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''IBertConfig''', '''IBertOnnxConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: str = [ '''IBERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''IBertForMaskedLM''', '''IBertForMultipleChoice''', '''IBertForQuestionAnswering''', '''IBertForSequenceClassification''', '''IBertForTokenClassification''', '''IBertModel''', '''IBertPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_ibert import IBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, IBertConfig, IBertOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ibert import ( IBERT_PRETRAINED_MODEL_ARCHIVE_LIST, IBertForMaskedLM, IBertForMultipleChoice, IBertForQuestionAnswering, IBertForSequenceClassification, IBertForTokenClassification, IBertModel, IBertPreTrainedModel, ) else: import sys A__: Optional[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
276
'''simple docstring''' import logging import os from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union from filelock import FileLock from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available A__: int = logging.getLogger(__name__) @dataclass class A__ : __UpperCamelCase : str __UpperCamelCase : List[str] __UpperCamelCase : Optional[List[str]] @dataclass class A__ : __UpperCamelCase : List[int] __UpperCamelCase : List[int] __UpperCamelCase : Optional[List[int]] = None __UpperCamelCase : Optional[List[int]] = None class A__ ( UpperCAmelCase__ ): __UpperCamelCase : str = "train" __UpperCamelCase : Tuple = "dev" __UpperCamelCase : str = "test" class A__ : @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :Union[Split, str] ) -> List[InputExample]: '''simple docstring''' raise NotImplementedError @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :str ) -> List[str]: '''simple docstring''' raise NotImplementedError @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :List[InputExample] , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :PreTrainedTokenizer , SCREAMING_SNAKE_CASE :str=False , SCREAMING_SNAKE_CASE :Optional[Any]="[CLS]" , SCREAMING_SNAKE_CASE :Optional[int]=1 , SCREAMING_SNAKE_CASE :Any="[SEP]" , SCREAMING_SNAKE_CASE :List[Any]=False , SCREAMING_SNAKE_CASE :Union[str, Any]=False , SCREAMING_SNAKE_CASE :List[str]=0 , SCREAMING_SNAKE_CASE :str=0 , SCREAMING_SNAKE_CASE :Dict=-1_0_0 , SCREAMING_SNAKE_CASE :Optional[int]=0 , SCREAMING_SNAKE_CASE :Tuple=True , ) -> List[InputFeatures]: '''simple docstring''' _a : str ={label: i for i, label in enumerate(SCREAMING_SNAKE_CASE )} _a : Tuple =[] for ex_index, example in enumerate(SCREAMING_SNAKE_CASE ): if ex_index % 1_0_0_0_0 == 0: logger.info("""Writing example %d of %d""" , SCREAMING_SNAKE_CASE , len(SCREAMING_SNAKE_CASE ) ) _a : Optional[Any] =[] _a : List[Any] =[] for word, label in zip(example.words , example.labels ): _a : Optional[int] =tokenizer.tokenize(SCREAMING_SNAKE_CASE ) # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space. if len(SCREAMING_SNAKE_CASE ) > 0: tokens.extend(SCREAMING_SNAKE_CASE ) # Use the real label id for the first token of the word, and padding ids for the remaining tokens label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(SCREAMING_SNAKE_CASE ) - 1) ) # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa. _a : Optional[int] =tokenizer.num_special_tokens_to_add() if len(SCREAMING_SNAKE_CASE ) > max_seq_length - special_tokens_count: _a : List[Any] =tokens[: (max_seq_length - special_tokens_count)] _a : Tuple =label_ids[: (max_seq_length - special_tokens_count)] # The convention in BERT is: # (a) For sequence pairs: # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP] # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1 # (b) For single sequences: # tokens: [CLS] the dog is hairy . [SEP] # type_ids: 0 0 0 0 0 0 0 # # Where "type_ids" are used to indicate whether this is the first # sequence or the second sequence. The embedding vectors for `type=0` and # `type=1` were learned during pre-training and are added to the wordpiece # embedding vector (and position vector). This is not *strictly* necessary # since the [SEP] token unambiguously separates the sequences, but it makes # it easier for the model to learn the concept of sequences. # # For classification tasks, the first vector (corresponding to [CLS]) is # used as the "sentence vector". Note that this only makes sense because # the entire model is fine-tuned. tokens += [sep_token] label_ids += [pad_token_label_id] if sep_token_extra: # roberta uses an extra separator b/w pairs of sentences tokens += [sep_token] label_ids += [pad_token_label_id] _a : Dict =[sequence_a_segment_id] * len(SCREAMING_SNAKE_CASE ) if cls_token_at_end: tokens += [cls_token] label_ids += [pad_token_label_id] segment_ids += [cls_token_segment_id] else: _a : Any =[cls_token] + tokens _a : Dict =[pad_token_label_id] + label_ids _a : Union[str, Any] =[cls_token_segment_id] + segment_ids _a : List[str] =tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE ) # The mask has 1 for real tokens and 0 for padding tokens. Only real # tokens are attended to. _a : Optional[int] =[1 if mask_padding_with_zero else 0] * len(SCREAMING_SNAKE_CASE ) # Zero-pad up to the sequence length. _a : Union[str, Any] =max_seq_length - len(SCREAMING_SNAKE_CASE ) if pad_on_left: _a : Optional[Any] =([pad_token] * padding_length) + input_ids _a : Optional[int] =([0 if mask_padding_with_zero else 1] * padding_length) + input_mask _a : Union[str, Any] =([pad_token_segment_id] * padding_length) + segment_ids _a : Dict =([pad_token_label_id] * padding_length) + label_ids else: input_ids += [pad_token] * padding_length input_mask += [0 if mask_padding_with_zero else 1] * padding_length segment_ids += [pad_token_segment_id] * padding_length label_ids += [pad_token_label_id] * padding_length assert len(SCREAMING_SNAKE_CASE ) == max_seq_length assert len(SCREAMING_SNAKE_CASE ) == max_seq_length assert len(SCREAMING_SNAKE_CASE ) == max_seq_length assert len(SCREAMING_SNAKE_CASE ) == max_seq_length if ex_index < 5: logger.info("""*** Example ***""" ) logger.info("""guid: %s""" , example.guid ) logger.info("""tokens: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in tokens] ) ) logger.info("""input_ids: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in input_ids] ) ) logger.info("""input_mask: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in input_mask] ) ) logger.info("""segment_ids: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in segment_ids] ) ) logger.info("""label_ids: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in label_ids] ) ) if "token_type_ids" not in tokenizer.model_input_names: _a : Tuple =None features.append( InputFeatures( input_ids=SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , token_type_ids=SCREAMING_SNAKE_CASE , label_ids=SCREAMING_SNAKE_CASE ) ) return features if is_torch_available(): import torch from torch import nn from torch.utils.data import Dataset class A__ ( UpperCAmelCase__ ): __UpperCamelCase : List[InputFeatures] __UpperCamelCase : int = nn.CrossEntropyLoss().ignore_index def __init__( self :Dict , SCREAMING_SNAKE_CASE :TokenClassificationTask , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :PreTrainedTokenizer , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Optional[int] = None , SCREAMING_SNAKE_CASE :int=False , SCREAMING_SNAKE_CASE :Split = Split.train , ) -> List[str]: '''simple docstring''' # Load data features from cache or dataset file _a : Optional[Any] =os.path.join( SCREAMING_SNAKE_CASE , """cached_{}_{}_{}""".format(mode.value , tokenizer.__class__.__name__ , str(SCREAMING_SNAKE_CASE ) ) , ) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. _a : List[str] =cached_features_file + """.lock""" with FileLock(SCREAMING_SNAKE_CASE ): if os.path.exists(SCREAMING_SNAKE_CASE ) and not overwrite_cache: logger.info(f"Loading features from cached file {cached_features_file}" ) _a : Any =torch.load(SCREAMING_SNAKE_CASE ) else: logger.info(f"Creating features from dataset file at {data_dir}" ) _a : Any =token_classification_task.read_examples_from_file(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # TODO clean up all this to leverage built-in features of tokenizers _a : List[str] =token_classification_task.convert_examples_to_features( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , cls_token_at_end=bool(model_type in ["""xlnet"""] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ["""xlnet"""] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=SCREAMING_SNAKE_CASE , pad_on_left=bool(tokenizer.padding_side == """left""" ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info(f"Saving features into cached file {cached_features_file}" ) torch.save(self.features , SCREAMING_SNAKE_CASE ) def __len__( self :Optional[int] ) -> Union[str, Any]: '''simple docstring''' return len(self.features ) def __getitem__( self :Dict , SCREAMING_SNAKE_CASE :int ) -> InputFeatures: '''simple docstring''' return self.features[i] if is_tf_available(): import tensorflow as tf class A__ : __UpperCamelCase : List[InputFeatures] __UpperCamelCase : int = -100 def __init__( self :str , SCREAMING_SNAKE_CASE :TokenClassificationTask , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :PreTrainedTokenizer , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Optional[int] = None , SCREAMING_SNAKE_CASE :str=False , SCREAMING_SNAKE_CASE :Split = Split.train , ) -> Any: '''simple docstring''' _a : Tuple =token_classification_task.read_examples_from_file(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # TODO clean up all this to leverage built-in features of tokenizers _a : List[Any] =token_classification_task.convert_examples_to_features( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , cls_token_at_end=bool(model_type in ["""xlnet"""] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ["""xlnet"""] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=SCREAMING_SNAKE_CASE , pad_on_left=bool(tokenizer.padding_side == """left""" ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) def gen(): for ex in self.features: if ex.token_type_ids is None: yield ( {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask}, ex.label_ids, ) else: yield ( { "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label_ids, ) if "token_type_ids" not in tokenizer.model_input_names: _a : Union[str, Any] =tf.data.Dataset.from_generator( SCREAMING_SNAKE_CASE , ({"""input_ids""": tf.intaa, """attention_mask""": tf.intaa}, tf.intaa) , ( {"""input_ids""": tf.TensorShape([None] ), """attention_mask""": tf.TensorShape([None] )}, tf.TensorShape([None] ), ) , ) else: _a : Union[str, Any] =tf.data.Dataset.from_generator( SCREAMING_SNAKE_CASE , ({"""input_ids""": tf.intaa, """attention_mask""": tf.intaa, """token_type_ids""": tf.intaa}, tf.intaa) , ( { """input_ids""": tf.TensorShape([None] ), """attention_mask""": tf.TensorShape([None] ), """token_type_ids""": tf.TensorShape([None] ), }, tf.TensorShape([None] ), ) , ) def __UpperCAmelCase ( self :Tuple ) -> Any: '''simple docstring''' _a : List[Any] =self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features ) ) ) return self.dataset def __len__( self :str ) -> Optional[int]: '''simple docstring''' return len(self.features ) def __getitem__( self :int , SCREAMING_SNAKE_CASE :str ) -> InputFeatures: '''simple docstring''' return self.features[i]
276
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available A__: Dict = { '''configuration_xlm''': ['''XLM_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XLMConfig''', '''XLMOnnxConfig'''], '''tokenization_xlm''': ['''XLMTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Union[str, Any] = [ '''XLM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XLMForMultipleChoice''', '''XLMForQuestionAnswering''', '''XLMForQuestionAnsweringSimple''', '''XLMForSequenceClassification''', '''XLMForTokenClassification''', '''XLMModel''', '''XLMPreTrainedModel''', '''XLMWithLMHeadModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Any = [ '''TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFXLMForMultipleChoice''', '''TFXLMForQuestionAnsweringSimple''', '''TFXLMForSequenceClassification''', '''TFXLMForTokenClassification''', '''TFXLMMainLayer''', '''TFXLMModel''', '''TFXLMPreTrainedModel''', '''TFXLMWithLMHeadModel''', ] if TYPE_CHECKING: from .configuration_xlm import XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMConfig, XLMOnnxConfig from .tokenization_xlm import XLMTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm import ( XLM_PRETRAINED_MODEL_ARCHIVE_LIST, XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMPreTrainedModel, XLMWithLMHeadModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlm import ( TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLMForMultipleChoice, TFXLMForQuestionAnsweringSimple, TFXLMForSequenceClassification, TFXLMForTokenClassification, TFXLMMainLayer, TFXLMModel, TFXLMPreTrainedModel, TFXLMWithLMHeadModel, ) else: import sys A__: List[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
276
'''simple docstring''' from __future__ import annotations class A__ : def __init__( self :Union[str, Any] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :str ) -> Optional[int]: '''simple docstring''' _a , _a : List[str] =text, pattern _a , _a : Union[str, Any] =len(SCREAMING_SNAKE_CASE ), len(SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Optional[int] , SCREAMING_SNAKE_CASE :str ) -> int: '''simple docstring''' for i in range(self.patLen - 1 , -1 , -1 ): if char == self.pattern[i]: return i return -1 def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :int ) -> int: '''simple docstring''' for i in range(self.patLen - 1 , -1 , -1 ): if self.pattern[i] != self.text[current_pos + i]: return current_pos + i return -1 def __UpperCAmelCase ( self :Union[str, Any] ) -> list[int]: '''simple docstring''' # searches pattern in text and returns index positions _a : Union[str, Any] =[] for i in range(self.textLen - self.patLen + 1 ): _a : Any =self.mismatch_in_text(SCREAMING_SNAKE_CASE ) if mismatch_index == -1: positions.append(SCREAMING_SNAKE_CASE ) else: _a : int =self.match_in_pattern(self.text[mismatch_index] ) _a : List[str] =( mismatch_index - match_index ) # shifting index lgtm [py/multiple-definition] return positions A__: Any = '''ABAABA''' A__: int = '''AB''' A__: Optional[int] = BoyerMooreSearch(text, pattern) A__: Optional[Any] = bms.bad_character_heuristic() if len(positions) == 0: print('''No match found''') else: print('''Pattern found in following positions: ''') print(positions)
276
1
'''simple docstring''' def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : list ) -> list: if len(_UpperCAmelCase ) < 2: return collection def circle_sort_util(_UpperCAmelCase : list ,_UpperCAmelCase : int ,_UpperCAmelCase : int ) -> bool: _a : List[Any] =False if low == high: return swapped _a : Tuple =low _a : Dict =high while left < right: if collection[left] > collection[right]: _a , _a : Optional[int] =( collection[right], collection[left], ) _a : Tuple =True left += 1 right -= 1 if left == right and collection[left] > collection[right + 1]: _a , _a : Union[str, Any] =( collection[right + 1], collection[left], ) _a : Optional[int] =True _a : int =low + int((high - low) / 2 ) _a : str =circle_sort_util(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) _a : Optional[int] =circle_sort_util(_UpperCAmelCase ,mid + 1 ,_UpperCAmelCase ) return swapped or left_swap or right_swap _a : int =True while is_not_sorted is True: _a : Tuple =circle_sort_util(_UpperCAmelCase ,0 ,len(_UpperCAmelCase ) - 1 ) return collection if __name__ == "__main__": A__: Optional[Any] = input('''Enter numbers separated by a comma:\n''').strip() A__: Tuple = [int(item) for item in user_input.split(''',''')] print(circle_sort(unsorted))
276
'''simple docstring''' import argparse import gc import json import os import shutil import warnings import torch from transformers import LlamaConfig, LlamaForCausalLM, LlamaTokenizer try: from transformers import LlamaTokenizerFast except ImportError as e: warnings.warn(e) warnings.warn( '''The converted tokenizer will be the `slow` tokenizer. To use the fast, update your `tokenizers` library and re-run the tokenizer conversion''' ) A__: Dict = None A__: Tuple = { '''7B''': 1_1008, '''13B''': 1_3824, '''30B''': 1_7920, '''65B''': 2_2016, '''70B''': 2_8672, } A__: Any = { '''7B''': 1, '''7Bf''': 1, '''13B''': 2, '''13Bf''': 2, '''30B''': 4, '''65B''': 8, '''70B''': 8, '''70Bf''': 8, } def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Optional[int]=1 ,_UpperCAmelCase : List[str]=256 ) -> Dict: return multiple_of * ((int(ffn_dim_multiplier * int(8 * n / 3 ) ) + multiple_of - 1) // multiple_of) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[Any] ) -> List[str]: with open(_UpperCAmelCase ,"""r""" ) as f: return json.load(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : Optional[Any] ) -> Tuple: with open(_UpperCAmelCase ,"""w""" ) as f: json.dump(_UpperCAmelCase ,_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : int ,_UpperCAmelCase : List[Any]=True ) -> Union[str, Any]: os.makedirs(_UpperCAmelCase ,exist_ok=_UpperCAmelCase ) _a : Union[str, Any] =os.path.join(_UpperCAmelCase ,"""tmp""" ) os.makedirs(_UpperCAmelCase ,exist_ok=_UpperCAmelCase ) _a : int =read_json(os.path.join(_UpperCAmelCase ,"""params.json""" ) ) _a : int =NUM_SHARDS[model_size] _a : Dict =params["""n_layers"""] _a : Union[str, Any] =params["""n_heads"""] _a : List[str] =n_heads // num_shards _a : int =params["""dim"""] _a : Union[str, Any] =dim // n_heads _a : int =1_0_0_0_0.0 _a : str =1.0 / (base ** (torch.arange(0 ,_UpperCAmelCase ,2 ).float() / dims_per_head)) if "n_kv_heads" in params: _a : str =params["""n_kv_heads"""] # for GQA / MQA _a : Optional[Any] =n_heads_per_shard // num_key_value_heads _a : Optional[int] =dim // num_key_value_heads else: # compatibility with other checkpoints _a : str =n_heads _a : Any =n_heads_per_shard _a : str =dim # permute for sliced rotary def permute(_UpperCAmelCase : Tuple ,_UpperCAmelCase : Optional[int]=n_heads ,_UpperCAmelCase : Optional[int]=dim ,_UpperCAmelCase : List[str]=dim ): return w.view(_UpperCAmelCase ,dima // n_heads // 2 ,2 ,_UpperCAmelCase ).transpose(1 ,2 ).reshape(_UpperCAmelCase ,_UpperCAmelCase ) print(F"Fetching all parameters from the checkpoint at {input_base_path}." ) # Load weights if model_size == "7B": # Not sharded # (The sharded implementation would also work, but this is simpler.) _a : Any =torch.load(os.path.join(_UpperCAmelCase ,"""consolidated.00.pth""" ) ,map_location="""cpu""" ) else: # Sharded _a : List[Any] =[ torch.load(os.path.join(_UpperCAmelCase ,F"consolidated.{i:02d}.pth" ) ,map_location="""cpu""" ) for i in range(_UpperCAmelCase ) ] _a : Any =0 _a : Optional[int] ={"""weight_map""": {}} for layer_i in range(_UpperCAmelCase ): _a : List[str] =F"pytorch_model-{layer_i + 1}-of-{n_layers + 1}.bin" if model_size == "7B": # Unsharded _a : List[str] ={ F"model.layers.{layer_i}.self_attn.q_proj.weight": permute( loaded[F"layers.{layer_i}.attention.wq.weight"] ), F"model.layers.{layer_i}.self_attn.k_proj.weight": permute( loaded[F"layers.{layer_i}.attention.wk.weight"] ), F"model.layers.{layer_i}.self_attn.v_proj.weight": loaded[F"layers.{layer_i}.attention.wv.weight"], F"model.layers.{layer_i}.self_attn.o_proj.weight": loaded[F"layers.{layer_i}.attention.wo.weight"], F"model.layers.{layer_i}.mlp.gate_proj.weight": loaded[F"layers.{layer_i}.feed_forward.w1.weight"], F"model.layers.{layer_i}.mlp.down_proj.weight": loaded[F"layers.{layer_i}.feed_forward.w2.weight"], F"model.layers.{layer_i}.mlp.up_proj.weight": loaded[F"layers.{layer_i}.feed_forward.w3.weight"], F"model.layers.{layer_i}.input_layernorm.weight": loaded[F"layers.{layer_i}.attention_norm.weight"], F"model.layers.{layer_i}.post_attention_layernorm.weight": loaded[F"layers.{layer_i}.ffn_norm.weight"], } else: # Sharded # Note that attention.w{q,k,v,o}, feed_fordward.w[1,2,3], attention_norm.weight and ffn_norm.weight share # the same storage object, saving attention_norm and ffn_norm will save other weights too, which is # redundant as other weights will be stitched from multiple shards. To avoid that, they are cloned. _a : Tuple ={ F"model.layers.{layer_i}.input_layernorm.weight": loaded[0][ F"layers.{layer_i}.attention_norm.weight" ].clone(), F"model.layers.{layer_i}.post_attention_layernorm.weight": loaded[0][ F"layers.{layer_i}.ffn_norm.weight" ].clone(), } _a : str =permute( torch.cat( [ loaded[i][F"layers.{layer_i}.attention.wq.weight"].view(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) for i in range(_UpperCAmelCase ) ] ,dim=0 ,).reshape(_UpperCAmelCase ,_UpperCAmelCase ) ) _a : Tuple =permute( torch.cat( [ loaded[i][F"layers.{layer_i}.attention.wk.weight"].view( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) for i in range(_UpperCAmelCase ) ] ,dim=0 ,).reshape(_UpperCAmelCase ,_UpperCAmelCase ) ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,) _a : Any =torch.cat( [ loaded[i][F"layers.{layer_i}.attention.wv.weight"].view( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) for i in range(_UpperCAmelCase ) ] ,dim=0 ,).reshape(_UpperCAmelCase ,_UpperCAmelCase ) _a : List[str] =torch.cat( [loaded[i][F"layers.{layer_i}.attention.wo.weight"] for i in range(_UpperCAmelCase )] ,dim=1 ) _a : Union[str, Any] =torch.cat( [loaded[i][F"layers.{layer_i}.feed_forward.w1.weight"] for i in range(_UpperCAmelCase )] ,dim=0 ) _a : Tuple =torch.cat( [loaded[i][F"layers.{layer_i}.feed_forward.w2.weight"] for i in range(_UpperCAmelCase )] ,dim=1 ) _a : Union[str, Any] =torch.cat( [loaded[i][F"layers.{layer_i}.feed_forward.w3.weight"] for i in range(_UpperCAmelCase )] ,dim=0 ) _a : str =inv_freq for k, v in state_dict.items(): _a : Any =filename param_count += v.numel() torch.save(_UpperCAmelCase ,os.path.join(_UpperCAmelCase ,_UpperCAmelCase ) ) _a : Union[str, Any] =F"pytorch_model-{n_layers + 1}-of-{n_layers + 1}.bin" if model_size == "7B": # Unsharded _a : List[str] ={ """model.embed_tokens.weight""": loaded["""tok_embeddings.weight"""], """model.norm.weight""": loaded["""norm.weight"""], """lm_head.weight""": loaded["""output.weight"""], } else: _a : int ={ """model.norm.weight""": loaded[0]["""norm.weight"""], """model.embed_tokens.weight""": torch.cat( [loaded[i]["""tok_embeddings.weight"""] for i in range(_UpperCAmelCase )] ,dim=1 ), """lm_head.weight""": torch.cat([loaded[i]["""output.weight"""] for i in range(_UpperCAmelCase )] ,dim=0 ), } for k, v in state_dict.items(): _a : Dict =filename param_count += v.numel() torch.save(_UpperCAmelCase ,os.path.join(_UpperCAmelCase ,_UpperCAmelCase ) ) # Write configs _a : Tuple ={"""total_size""": param_count * 2} write_json(_UpperCAmelCase ,os.path.join(_UpperCAmelCase ,"""pytorch_model.bin.index.json""" ) ) _a : Optional[Any] =params["""ffn_dim_multiplier"""] if """ffn_dim_multiplier""" in params else 1 _a : int =params["""multiple_of"""] if """multiple_of""" in params else 256 _a : List[Any] =LlamaConfig( hidden_size=_UpperCAmelCase ,intermediate_size=compute_intermediate_size(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) ,num_attention_heads=params["""n_heads"""] ,num_hidden_layers=params["""n_layers"""] ,rms_norm_eps=params["""norm_eps"""] ,num_key_value_heads=_UpperCAmelCase ,) config.save_pretrained(_UpperCAmelCase ) # Make space so we can load the model properly now. del state_dict del loaded gc.collect() print("""Loading the checkpoint in a Llama model.""" ) _a : Any =LlamaForCausalLM.from_pretrained(_UpperCAmelCase ,torch_dtype=torch.floataa ,low_cpu_mem_usage=_UpperCAmelCase ) # Avoid saving this as part of the config. del model.config._name_or_path print("""Saving in the Transformers format.""" ) model.save_pretrained(_UpperCAmelCase ,safe_serialization=_UpperCAmelCase ) shutil.rmtree(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ,_UpperCAmelCase : int ) -> Optional[Any]: # Initialize the tokenizer based on the `spm` model _a : List[str] =LlamaTokenizer if LlamaTokenizerFast is None else LlamaTokenizerFast print(F"Saving a {tokenizer_class.__name__} to {tokenizer_path}." ) _a : List[Any] =tokenizer_class(_UpperCAmelCase ) tokenizer.save_pretrained(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( ) -> Union[str, Any]: _a : List[str] =argparse.ArgumentParser() parser.add_argument( """--input_dir""" ,help="""Location of LLaMA weights, which contains tokenizer.model and model folders""" ,) parser.add_argument( """--model_size""" ,choices=["""7B""", """7Bf""", """13B""", """13Bf""", """30B""", """65B""", """70B""", """70Bf""", """tokenizer_only"""] ,) parser.add_argument( """--output_dir""" ,help="""Location to write HF model and tokenizer""" ,) parser.add_argument("""--safe_serialization""" ,type=_UpperCAmelCase ,help="""Whether or not to save using `safetensors`.""" ) _a : Optional[Any] =parser.parse_args() if args.model_size != "tokenizer_only": write_model( model_path=args.output_dir ,input_base_path=os.path.join(args.input_dir ,args.model_size ) ,model_size=args.model_size ,safe_serialization=args.safe_serialization ,) _a : List[Any] =os.path.join(args.input_dir ,"""tokenizer.model""" ) write_tokenizer(args.output_dir ,_UpperCAmelCase ) if __name__ == "__main__": main()
276
1
'''simple docstring''' import inspect import os import torch from transformers import AutoModel from transformers.testing_utils import mockenv_context from transformers.trainer_utils import set_seed import accelerate from accelerate.accelerator import Accelerator from accelerate.state import AcceleratorState from accelerate.test_utils.testing import ( AccelerateTestCase, TempDirTestCase, execute_subprocess_async, require_cuda, require_fsdp, require_multi_gpu, slow, ) from accelerate.utils.constants import ( FSDP_AUTO_WRAP_POLICY, FSDP_BACKWARD_PREFETCH, FSDP_SHARDING_STRATEGY, FSDP_STATE_DICT_TYPE, ) from accelerate.utils.dataclasses import FullyShardedDataParallelPlugin from accelerate.utils.other import patch_environment set_seed(42) A__: Optional[Any] = '''bert-base-cased''' A__: Union[str, Any] = '''fp16''' A__: Tuple = '''bf16''' A__: Optional[Any] = [FPaa, BFaa] @require_fsdp @require_cuda class A__ ( UpperCAmelCase__ ): def __UpperCAmelCase ( self :Union[str, Any] ) -> Dict: '''simple docstring''' super().setUp() _a : int =dict( ACCELERATE_USE_FSDP="""true""" , MASTER_ADDR="""localhost""" , MASTER_PORT="""10999""" , RANK="""0""" , LOCAL_RANK="""0""" , WORLD_SIZE="""1""" , ) def __UpperCAmelCase ( self :Dict ) -> List[str]: '''simple docstring''' from torch.distributed.fsdp.fully_sharded_data_parallel import ShardingStrategy for i, strategy in enumerate(SCREAMING_SNAKE_CASE ): _a : Dict =self.dist_env.copy() _a : int =f"{i + 1}" _a : List[str] =strategy with mockenv_context(**SCREAMING_SNAKE_CASE ): _a : Dict =FullyShardedDataParallelPlugin() self.assertEqual(fsdp_plugin.sharding_strategy , ShardingStrategy(i + 1 ) ) def __UpperCAmelCase ( self :Dict ) -> int: '''simple docstring''' from torch.distributed.fsdp.fully_sharded_data_parallel import BackwardPrefetch for i, prefetch_policy in enumerate(SCREAMING_SNAKE_CASE ): _a : int =self.dist_env.copy() _a : Union[str, Any] =prefetch_policy with mockenv_context(**SCREAMING_SNAKE_CASE ): _a : Tuple =FullyShardedDataParallelPlugin() if prefetch_policy == "NO_PREFETCH": self.assertIsNone(fsdp_plugin.backward_prefetch ) else: self.assertEqual(fsdp_plugin.backward_prefetch , BackwardPrefetch(i + 1 ) ) def __UpperCAmelCase ( self :Union[str, Any] ) -> Tuple: '''simple docstring''' from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType for i, state_dict_type in enumerate(SCREAMING_SNAKE_CASE ): _a : Optional[int] =self.dist_env.copy() _a : Optional[int] =state_dict_type with mockenv_context(**SCREAMING_SNAKE_CASE ): _a : Dict =FullyShardedDataParallelPlugin() self.assertEqual(fsdp_plugin.state_dict_type , StateDictType(i + 1 ) ) if state_dict_type == "FULL_STATE_DICT": self.assertTrue(fsdp_plugin.state_dict_config.offload_to_cpu ) self.assertTrue(fsdp_plugin.state_dict_config.ranka_only ) def __UpperCAmelCase ( self :Optional[int] ) -> Optional[int]: '''simple docstring''' _a : List[Any] =AutoModel.from_pretrained(SCREAMING_SNAKE_CASE ) for policy in FSDP_AUTO_WRAP_POLICY: _a : int =self.dist_env.copy() _a : Optional[Any] =policy if policy == "TRANSFORMER_BASED_WRAP": _a : int ="""BertLayer""" elif policy == "SIZE_BASED_WRAP": _a : Any ="""2000""" with mockenv_context(**SCREAMING_SNAKE_CASE ): _a : Dict =FullyShardedDataParallelPlugin() fsdp_plugin.set_auto_wrap_policy(SCREAMING_SNAKE_CASE ) if policy == "NO_WRAP": self.assertIsNone(fsdp_plugin.auto_wrap_policy ) else: self.assertIsNotNone(fsdp_plugin.auto_wrap_policy ) _a : Union[str, Any] =self.dist_env.copy() _a : Tuple ="""TRANSFORMER_BASED_WRAP""" _a : List[str] ="""T5Layer""" with mockenv_context(**SCREAMING_SNAKE_CASE ): _a : Optional[int] =FullyShardedDataParallelPlugin() with self.assertRaises(SCREAMING_SNAKE_CASE ) as cm: fsdp_plugin.set_auto_wrap_policy(SCREAMING_SNAKE_CASE ) self.assertTrue("""Could not find the transformer layer class to wrap in the model.""" in str(cm.exception ) ) _a : Optional[Any] =self.dist_env.copy() _a : Union[str, Any] ="""SIZE_BASED_WRAP""" _a : int ="""0""" with mockenv_context(**SCREAMING_SNAKE_CASE ): _a : str =FullyShardedDataParallelPlugin() fsdp_plugin.set_auto_wrap_policy(SCREAMING_SNAKE_CASE ) self.assertIsNone(fsdp_plugin.auto_wrap_policy ) def __UpperCAmelCase ( self :Union[str, Any] ) -> List[str]: '''simple docstring''' from torch.distributed.fsdp.fully_sharded_data_parallel import MixedPrecision from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler for mp_dtype in dtypes: _a : Dict =self.dist_env.copy() _a : List[str] =mp_dtype with mockenv_context(**SCREAMING_SNAKE_CASE ): _a : Dict =Accelerator() if mp_dtype == "fp16": _a : int =torch.floataa elif mp_dtype == "bf16": _a : int =torch.bfloataa _a : str =MixedPrecision(param_dtype=SCREAMING_SNAKE_CASE , reduce_dtype=SCREAMING_SNAKE_CASE , buffer_dtype=SCREAMING_SNAKE_CASE ) self.assertEqual(accelerator.state.fsdp_plugin.mixed_precision_policy , SCREAMING_SNAKE_CASE ) if mp_dtype == FPaa: self.assertTrue(isinstance(accelerator.scaler , SCREAMING_SNAKE_CASE ) ) elif mp_dtype == BFaa: self.assertIsNone(accelerator.scaler ) AcceleratorState._reset_state(SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Any ) -> Any: '''simple docstring''' from torch.distributed.fsdp.fully_sharded_data_parallel import CPUOffload for flag in [True, False]: _a : Union[str, Any] =self.dist_env.copy() _a : Optional[int] =str(SCREAMING_SNAKE_CASE ).lower() with mockenv_context(**SCREAMING_SNAKE_CASE ): _a : Optional[Any] =FullyShardedDataParallelPlugin() self.assertEqual(fsdp_plugin.cpu_offload , CPUOffload(offload_params=SCREAMING_SNAKE_CASE ) ) @require_fsdp @require_multi_gpu @slow class A__ ( UpperCAmelCase__ ): def __UpperCAmelCase ( self :Optional[int] ) -> List[str]: '''simple docstring''' super().setUp() _a : str =0.82 _a : Optional[int] =[ """fsdp_shard_grad_op_transformer_based_wrap""", """fsdp_full_shard_transformer_based_wrap""", ] _a : Union[str, Any] ={ """multi_gpu_fp16""": 3_2_0_0, """fsdp_shard_grad_op_transformer_based_wrap_fp16""": 2_0_0_0, """fsdp_full_shard_transformer_based_wrap_fp16""": 1_9_0_0, # Disabling below test as it overwhelms the RAM memory usage # on CI self-hosted runner leading to tests getting killed. # "fsdp_full_shard_cpu_offload_transformer_based_wrap_fp32": 1500, # fp16 was leading to indefinite hang } _a : Dict =1_6_0 _a : Optional[int] =1_6_0 _a : str =inspect.getfile(accelerate.test_utils ) _a : str =os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ["""scripts""", """external_deps"""] ) def __UpperCAmelCase ( self :Union[str, Any] ) -> str: '''simple docstring''' _a : Union[str, Any] =os.path.join(self.test_scripts_folder , """test_performance.py""" ) _a : List[str] =["""accelerate""", """launch""", """--num_processes=2""", """--num_machines=1""", """--machine_rank=0""", """--use_fsdp"""] for config in self.performance_configs: _a : Dict =cmd.copy() for i, strategy in enumerate(SCREAMING_SNAKE_CASE ): if strategy.lower() in config: cmd_config.append(f"--fsdp_sharding_strategy={i+1}" ) break if "fp32" in config: cmd_config.append("""--mixed_precision=no""" ) else: cmd_config.append("""--mixed_precision=fp16""" ) if "cpu_offload" in config: cmd_config.append("""--fsdp_offload_params=True""" ) for policy in FSDP_AUTO_WRAP_POLICY: if policy.lower() in config: cmd_config.append(f"--fsdp_auto_wrap_policy={policy}" ) break if policy == "TRANSFORMER_BASED_WRAP": cmd_config.append("""--fsdp_transformer_layer_cls_to_wrap=BertLayer""" ) elif policy == "SIZE_BASED_WRAP": cmd_config.append("""--fsdp_min_num_params=2000""" ) cmd_config.extend( [ self.test_file_path, f"--output_dir={self.tmpdir}", f"--performance_lower_bound={self.performance_lower_bound}", ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(SCREAMING_SNAKE_CASE , env=os.environ.copy() ) def __UpperCAmelCase ( self :Union[str, Any] ) -> int: '''simple docstring''' _a : Tuple =os.path.join(self.test_scripts_folder , """test_checkpointing.py""" ) _a : Any =[ """accelerate""", """launch""", """--num_processes=2""", """--num_machines=1""", """--machine_rank=0""", """--use_fsdp""", """--mixed_precision=fp16""", """--fsdp_transformer_layer_cls_to_wrap=BertLayer""", ] for i, strategy in enumerate(SCREAMING_SNAKE_CASE ): _a : Tuple =cmd.copy() cmd_config.append(f"--fsdp_sharding_strategy={i+1}" ) if strategy != "FULL_SHARD": continue _a : Optional[Any] =len(SCREAMING_SNAKE_CASE ) for state_dict_type in FSDP_STATE_DICT_TYPE: _a : Dict =cmd_config[:state_dict_config_index] cmd_config.append(f"--fsdp_state_dict_type={state_dict_type}" ) cmd_config.extend( [ self.test_file_path, f"--output_dir={self.tmpdir}", """--partial_train_epoch=1""", ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(SCREAMING_SNAKE_CASE , env=os.environ.copy() ) _a : str =cmd_config[:-1] _a : List[Any] =os.path.join(self.tmpdir , """epoch_0""" ) cmd_config.extend( [ f"--resume_from_checkpoint={resume_from_checkpoint}", ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(SCREAMING_SNAKE_CASE , env=os.environ.copy() ) def __UpperCAmelCase ( self :Optional[int] ) -> List[Any]: '''simple docstring''' _a : str =os.path.join(self.test_scripts_folder , """test_peak_memory_usage.py""" ) _a : Optional[int] =[ """accelerate""", """launch""", """--num_processes=2""", """--num_machines=1""", """--machine_rank=0""", ] for spec, peak_mem_upper_bound in self.peak_memory_usage_upper_bound.items(): _a : List[str] =cmd.copy() if "fp16" in spec: cmd_config.extend(["""--mixed_precision=fp16"""] ) else: cmd_config.extend(["""--mixed_precision=no"""] ) if "multi_gpu" in spec: continue else: cmd_config.extend(["""--use_fsdp"""] ) for i, strategy in enumerate(SCREAMING_SNAKE_CASE ): if strategy.lower() in spec: cmd_config.append(f"--fsdp_sharding_strategy={i+1}" ) break if "cpu_offload" in spec: cmd_config.append("""--fsdp_offload_params=True""" ) for policy in FSDP_AUTO_WRAP_POLICY: if policy.lower() in spec: cmd_config.append(f"--fsdp_auto_wrap_policy={policy}" ) break if policy == "TRANSFORMER_BASED_WRAP": cmd_config.append("""--fsdp_transformer_layer_cls_to_wrap=BertLayer""" ) elif policy == "SIZE_BASED_WRAP": cmd_config.append("""--fsdp_min_num_params=2000""" ) cmd_config.extend( [ self.test_file_path, f"--output_dir={self.tmpdir}", f"--peak_memory_upper_bound={peak_mem_upper_bound}", f"--n_train={self.n_train}", f"--n_val={self.n_val}", ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(SCREAMING_SNAKE_CASE , env=os.environ.copy() )
276
'''simple docstring''' import contextlib import os import sqlitea import pytest from datasets import Dataset, Features, Value from datasets.io.sql import SqlDatasetReader, SqlDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases, require_sqlalchemy def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Any ,_UpperCAmelCase : str ) -> Dict: assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ) 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 @require_sqlalchemy @pytest.mark.parametrize("""keep_in_memory""" ,[False, True] ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Optional[int] ,_UpperCAmelCase : str ) -> Optional[Any]: _a : Any =tmp_path / """cache""" _a : int ={"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): _a : Tuple =SqlDatasetReader( """dataset""" ,"""sqlite:///""" + sqlite_path ,cache_dir=_UpperCAmelCase ,keep_in_memory=_UpperCAmelCase ).read() _check_sql_dataset(_UpperCAmelCase ,_UpperCAmelCase ) @require_sqlalchemy @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 SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[Any] ,_UpperCAmelCase : Dict ,_UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : int ) -> List[Any]: _a : Union[str, Any] =tmp_path / """cache""" _a : str ={"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} _a : Optional[int] =features.copy() if features else default_expected_features _a : Union[str, Any] =( Features({feature: Value(_UpperCAmelCase ) for feature, dtype in features.items()} ) if features is not None else None ) _a : Optional[Any] =SqlDatasetReader("""dataset""" ,"""sqlite:///""" + sqlite_path ,features=_UpperCAmelCase ,cache_dir=_UpperCAmelCase ).read() _check_sql_dataset(_UpperCAmelCase ,_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[Any] ) -> List[str]: with contextlib.closing(sqlitea.connect(_UpperCAmelCase ) ) as con: _a : Any =con.cursor() cur.execute("""SELECT * FROM dataset""" ) for row in cur: yield row @require_sqlalchemy def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Dict ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : List[str] ) -> Union[str, Any]: _a : Union[str, Any] =tmp_path / """cache""" _a : Union[str, Any] =os.path.join(_UpperCAmelCase ,"""tmp.sql""" ) _a : Tuple =SqlDatasetReader("""dataset""" ,"""sqlite:///""" + sqlite_path ,cache_dir=_UpperCAmelCase ).read() SqlDatasetWriter(_UpperCAmelCase ,"""dataset""" ,"""sqlite:///""" + output_sqlite_path ,num_proc=1 ).write() _a : Tuple =iter_sql_file(_UpperCAmelCase ) _a : List[Any] =iter_sql_file(_UpperCAmelCase ) for rowa, rowa in zip(_UpperCAmelCase ,_UpperCAmelCase ): assert rowa == rowa @require_sqlalchemy def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Any ,_UpperCAmelCase : List[Any] ) -> Optional[int]: _a : int =tmp_path / """cache""" _a : Any =os.path.join(_UpperCAmelCase ,"""tmp.sql""" ) _a : Union[str, Any] =SqlDatasetReader("""dataset""" ,"""sqlite:///""" + sqlite_path ,cache_dir=_UpperCAmelCase ).read() SqlDatasetWriter(_UpperCAmelCase ,"""dataset""" ,"""sqlite:///""" + output_sqlite_path ,num_proc=2 ).write() _a : List[Any] =iter_sql_file(_UpperCAmelCase ) _a : str =iter_sql_file(_UpperCAmelCase ) for rowa, rowa in zip(_UpperCAmelCase ,_UpperCAmelCase ): assert rowa == rowa @require_sqlalchemy def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : str ,_UpperCAmelCase : List[Any] ) -> List[str]: _a : List[str] =tmp_path / """cache""" _a : Dict =os.path.join(_UpperCAmelCase ,"""tmp.sql""" ) _a : Optional[Any] =SqlDatasetReader("""dataset""" ,"""sqlite:///""" + sqlite_path ,cache_dir=_UpperCAmelCase ).read() with pytest.raises(_UpperCAmelCase ): SqlDatasetWriter(_UpperCAmelCase ,"""dataset""" ,"""sqlite:///""" + output_sqlite_path ,num_proc=0 ).write()
276
1
'''simple docstring''' from __future__ import annotations import time A__: List[Any] = list[tuple[int, int]] A__: Optional[Any] = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] A__: Union[str, Any] = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right class A__ : def __init__( self :Union[str, Any] , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :Node | None ) -> Tuple: '''simple docstring''' _a : Optional[Any] =pos_x _a : Dict =pos_y _a : List[str] =(pos_y, pos_x) _a : Optional[Any] =goal_x _a : Any =goal_y _a : List[Any] =parent class A__ : def __init__( self :Optional[Any] , SCREAMING_SNAKE_CASE :tuple[int, int] , SCREAMING_SNAKE_CASE :tuple[int, int] ) -> Optional[int]: '''simple docstring''' _a : Union[str, Any] =Node(start[1] , start[0] , goal[1] , goal[0] , SCREAMING_SNAKE_CASE ) _a : Dict =Node(goal[1] , goal[0] , goal[1] , goal[0] , SCREAMING_SNAKE_CASE ) _a : Any =[self.start] _a : Union[str, Any] =False def __UpperCAmelCase ( self :Dict ) -> Path | None: '''simple docstring''' while self.node_queue: _a : List[Any] =self.node_queue.pop(0 ) if current_node.pos == self.target.pos: _a : Optional[int] =True return self.retrace_path(SCREAMING_SNAKE_CASE ) _a : str =self.get_successors(SCREAMING_SNAKE_CASE ) for node in successors: self.node_queue.append(SCREAMING_SNAKE_CASE ) if not self.reached: return [self.start.pos] return None def __UpperCAmelCase ( self :str , SCREAMING_SNAKE_CASE :Node ) -> list[Node]: '''simple docstring''' _a : Optional[Any] =[] for action in delta: _a : int =parent.pos_x + action[1] _a : Optional[int] =parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(SCREAMING_SNAKE_CASE ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , self.target.pos_y , self.target.pos_x , SCREAMING_SNAKE_CASE ) ) return successors def __UpperCAmelCase ( self :Dict , SCREAMING_SNAKE_CASE :Node | None ) -> Path: '''simple docstring''' _a : List[Any] =node _a : List[str] =[] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) _a : List[Any] =current_node.parent path.reverse() return path class A__ : def __init__( self :List[str] , SCREAMING_SNAKE_CASE :Optional[int] , SCREAMING_SNAKE_CASE :List[str] ) -> Optional[int]: '''simple docstring''' _a : Union[str, Any] =BreadthFirstSearch(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) _a : List[str] =BreadthFirstSearch(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) _a : str =False def __UpperCAmelCase ( self :Any ) -> Path | None: '''simple docstring''' while self.fwd_bfs.node_queue or self.bwd_bfs.node_queue: _a : List[Any] =self.fwd_bfs.node_queue.pop(0 ) _a : Optional[int] =self.bwd_bfs.node_queue.pop(0 ) if current_bwd_node.pos == current_fwd_node.pos: _a : Dict =True return self.retrace_bidirectional_path( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) _a : List[str] =current_bwd_node _a : List[Any] =current_fwd_node _a : Optional[int] ={ self.fwd_bfs: self.fwd_bfs.get_successors(SCREAMING_SNAKE_CASE ), self.bwd_bfs: self.bwd_bfs.get_successors(SCREAMING_SNAKE_CASE ), } for bfs in [self.fwd_bfs, self.bwd_bfs]: for node in successors[bfs]: bfs.node_queue.append(SCREAMING_SNAKE_CASE ) if not self.reached: return [self.fwd_bfs.start.pos] return None def __UpperCAmelCase ( self :List[Any] , SCREAMING_SNAKE_CASE :Node , SCREAMING_SNAKE_CASE :Node ) -> Path: '''simple docstring''' _a : Tuple =self.fwd_bfs.retrace_path(SCREAMING_SNAKE_CASE ) _a : int =self.bwd_bfs.retrace_path(SCREAMING_SNAKE_CASE ) bwd_path.pop() bwd_path.reverse() _a : Union[str, Any] =fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] import doctest doctest.testmod() A__: List[str] = (0, 0) A__: List[str] = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) A__: Optional[Any] = time.time() A__: List[str] = BreadthFirstSearch(init, goal) A__: Optional[Any] = bfs.search() A__: Tuple = time.time() - start_bfs_time print('''Unidirectional BFS computation time : ''', bfs_time) A__: int = time.time() A__: List[str] = BidirectionalBreadthFirstSearch(init, goal) A__: Dict = bd_bfs.search() A__: Optional[Any] = time.time() - start_bd_bfs_time print('''Bidirectional BFS computation time : ''', bd_bfs_time)
276
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A__: List[str] = logging.get_logger(__name__) A__: Union[str, Any] = { '''facebook/data2vec-text-base''': '''https://huggingface.co/data2vec/resolve/main/config.json''', } class A__ ( UpperCAmelCase__ ): __UpperCamelCase : int = "data2vec-text" def __init__( self :str , SCREAMING_SNAKE_CASE :Optional[Any]=3_0_5_2_2 , SCREAMING_SNAKE_CASE :Any=7_6_8 , SCREAMING_SNAKE_CASE :List[Any]=1_2 , SCREAMING_SNAKE_CASE :List[str]=1_2 , SCREAMING_SNAKE_CASE :Dict=3_0_7_2 , SCREAMING_SNAKE_CASE :List[str]="gelu" , SCREAMING_SNAKE_CASE :Any=0.1 , SCREAMING_SNAKE_CASE :List[str]=0.1 , SCREAMING_SNAKE_CASE :int=5_1_2 , SCREAMING_SNAKE_CASE :int=2 , SCREAMING_SNAKE_CASE :Union[str, Any]=0.02 , SCREAMING_SNAKE_CASE :Dict=1e-12 , SCREAMING_SNAKE_CASE :int=1 , SCREAMING_SNAKE_CASE :Dict=0 , SCREAMING_SNAKE_CASE :List[Any]=2 , SCREAMING_SNAKE_CASE :str="absolute" , SCREAMING_SNAKE_CASE :Tuple=True , SCREAMING_SNAKE_CASE :Union[str, Any]=None , **SCREAMING_SNAKE_CASE :Union[str, Any] , ) -> List[str]: '''simple docstring''' super().__init__(pad_token_id=SCREAMING_SNAKE_CASE , bos_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) _a : Optional[Any] =vocab_size _a : Optional[Any] =hidden_size _a : Any =num_hidden_layers _a : List[str] =num_attention_heads _a : Union[str, Any] =hidden_act _a : Any =intermediate_size _a : str =hidden_dropout_prob _a : Optional[Any] =attention_probs_dropout_prob _a : Optional[Any] =max_position_embeddings _a : Union[str, Any] =type_vocab_size _a : Tuple =initializer_range _a : Optional[int] =layer_norm_eps _a : Tuple =position_embedding_type _a : int =use_cache _a : List[str] =classifier_dropout class A__ ( UpperCAmelCase__ ): @property def __UpperCAmelCase ( self :int ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task == "multiple-choice": _a : Tuple ={0: """batch""", 1: """choice""", 2: """sequence"""} else: _a : List[Any] ={0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ] )
276
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) A__: List[str] = { '''configuration_swiftformer''': [ '''SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''SwiftFormerConfig''', '''SwiftFormerOnnxConfig''', ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: List[Any] = [ '''SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''SwiftFormerForImageClassification''', '''SwiftFormerModel''', '''SwiftFormerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_swiftformer import ( SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, SwiftFormerConfig, SwiftFormerOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_swiftformer import ( SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, SwiftFormerForImageClassification, SwiftFormerModel, SwiftFormerPreTrainedModel, ) else: import sys A__: int = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
276
'''simple docstring''' from typing import Dict, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import flip_channel_order, resize, to_channel_dimension_format, to_pil_image from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_pytesseract_available, is_vision_available, logging, requires_backends if is_vision_available(): import PIL # soft dependency if is_pytesseract_available(): import pytesseract A__: Union[str, Any] = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : List[str] ) -> int: return [ int(1000 * (box[0] / width) ), int(1000 * (box[1] / height) ), int(1000 * (box[2] / width) ), int(1000 * (box[3] / height) ), ] def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : np.ndarray ,_UpperCAmelCase : Optional[str] ,_UpperCAmelCase : Optional[str] = None ) -> Optional[int]: _a : Any =tesseract_config if tesseract_config is not None else """""" # apply OCR _a : Optional[Any] =to_pil_image(_UpperCAmelCase ) _a , _a : List[Any] =pil_image.size _a : List[str] =pytesseract.image_to_data(_UpperCAmelCase ,lang=_UpperCAmelCase ,output_type="""dict""" ,config=_UpperCAmelCase ) _a , _a , _a , _a , _a : str =data["""text"""], data["""left"""], data["""top"""], data["""width"""], data["""height"""] # filter empty words and corresponding coordinates _a : Tuple =[idx for idx, word in enumerate(_UpperCAmelCase ) if not word.strip()] _a : List[Any] =[word for idx, word in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] _a : Dict =[coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] _a : List[str] =[coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] _a : Union[str, Any] =[coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] _a : Union[str, Any] =[coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] # turn coordinates into (left, top, left+width, top+height) format _a : List[str] =[] for x, y, w, h in zip(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ): _a : int =[x, y, x + w, y + h] actual_boxes.append(_UpperCAmelCase ) # finally, normalize the bounding boxes _a : str =[] for box in actual_boxes: normalized_boxes.append(normalize_box(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) ) assert len(_UpperCAmelCase ) == len(_UpperCAmelCase ), "Not as many words as there are bounding boxes" return words, normalized_boxes class A__ ( UpperCAmelCase__ ): __UpperCamelCase : List[Any] = ["pixel_values"] def __init__( self :Tuple , SCREAMING_SNAKE_CASE :bool = True , SCREAMING_SNAKE_CASE :Dict[str, int] = None , SCREAMING_SNAKE_CASE :PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE :bool = True , SCREAMING_SNAKE_CASE :Optional[str] = None , SCREAMING_SNAKE_CASE :Optional[str] = "" , **SCREAMING_SNAKE_CASE :Tuple , ) -> None: '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE ) _a : List[Any] =size if size is not None else {"""height""": 2_2_4, """width""": 2_2_4} _a : Tuple =get_size_dict(SCREAMING_SNAKE_CASE ) _a : Dict =do_resize _a : Tuple =size _a : str =resample _a : Dict =apply_ocr _a : Union[str, Any] =ocr_lang _a : Dict =tesseract_config def __UpperCAmelCase ( self :List[str] , SCREAMING_SNAKE_CASE :np.ndarray , SCREAMING_SNAKE_CASE :Dict[str, int] , SCREAMING_SNAKE_CASE :PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE :Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE :Dict , ) -> np.ndarray: '''simple docstring''' _a : int =get_size_dict(SCREAMING_SNAKE_CASE ) if "height" not in size or "width" not in size: raise ValueError(f"The size dictionary must contain the keys 'height' and 'width'. Got {size.keys()}" ) _a : Any =(size["""height"""], size["""width"""]) return resize(SCREAMING_SNAKE_CASE , size=SCREAMING_SNAKE_CASE , resample=SCREAMING_SNAKE_CASE , data_format=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Dict , SCREAMING_SNAKE_CASE :ImageInput , SCREAMING_SNAKE_CASE :bool = None , SCREAMING_SNAKE_CASE :Dict[str, int] = None , SCREAMING_SNAKE_CASE :PILImageResampling = None , SCREAMING_SNAKE_CASE :bool = None , SCREAMING_SNAKE_CASE :Optional[str] = None , SCREAMING_SNAKE_CASE :Optional[str] = None , SCREAMING_SNAKE_CASE :Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE :ChannelDimension = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE :Optional[Any] , ) -> PIL.Image.Image: '''simple docstring''' _a : Optional[int] =do_resize if do_resize is not None else self.do_resize _a : Optional[int] =size if size is not None else self.size _a : str =get_size_dict(SCREAMING_SNAKE_CASE ) _a : List[str] =resample if resample is not None else self.resample _a : int =apply_ocr if apply_ocr is not None else self.apply_ocr _a : str =ocr_lang if ocr_lang is not None else self.ocr_lang _a : Union[str, Any] =tesseract_config if tesseract_config is not None else self.tesseract_config _a : List[str] =make_list_of_images(SCREAMING_SNAKE_CASE ) if not valid_images(SCREAMING_SNAKE_CASE ): 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.""" ) # All transformations expect numpy arrays. _a : List[Any] =[to_numpy_array(SCREAMING_SNAKE_CASE ) for image in images] if apply_ocr: requires_backends(self , """pytesseract""" ) _a : Any =[] _a : Any =[] for image in images: _a , _a : int =apply_tesseract(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) words_batch.append(SCREAMING_SNAKE_CASE ) boxes_batch.append(SCREAMING_SNAKE_CASE ) if do_resize: _a : Union[str, Any] =[self.resize(image=SCREAMING_SNAKE_CASE , size=SCREAMING_SNAKE_CASE , resample=SCREAMING_SNAKE_CASE ) for image in images] # flip color channels from RGB to BGR (as Detectron2 requires this) _a : Dict =[flip_channel_order(SCREAMING_SNAKE_CASE ) for image in images] _a : str =[to_channel_dimension_format(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for image in images] _a : str =BatchFeature(data={"""pixel_values""": images} , tensor_type=SCREAMING_SNAKE_CASE ) if apply_ocr: _a : List[Any] =words_batch _a : Dict =boxes_batch return data
276
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A__: Dict = logging.get_logger(__name__) A__: Dict = { '''microsoft/markuplm-base''': '''https://huggingface.co/microsoft/markuplm-base/resolve/main/config.json''', '''microsoft/markuplm-large''': '''https://huggingface.co/microsoft/markuplm-large/resolve/main/config.json''', } class A__ ( UpperCAmelCase__ ): __UpperCamelCase : Union[str, Any] = "markuplm" def __init__( self :Dict , SCREAMING_SNAKE_CASE :str=3_0_5_2_2 , SCREAMING_SNAKE_CASE :Dict=7_6_8 , SCREAMING_SNAKE_CASE :int=1_2 , SCREAMING_SNAKE_CASE :Any=1_2 , SCREAMING_SNAKE_CASE :List[Any]=3_0_7_2 , SCREAMING_SNAKE_CASE :Optional[int]="gelu" , SCREAMING_SNAKE_CASE :List[str]=0.1 , SCREAMING_SNAKE_CASE :List[Any]=0.1 , SCREAMING_SNAKE_CASE :int=5_1_2 , SCREAMING_SNAKE_CASE :Optional[int]=2 , SCREAMING_SNAKE_CASE :Any=0.02 , SCREAMING_SNAKE_CASE :str=1e-12 , SCREAMING_SNAKE_CASE :List[str]=0 , SCREAMING_SNAKE_CASE :Tuple=0 , SCREAMING_SNAKE_CASE :str=2 , SCREAMING_SNAKE_CASE :Union[str, Any]=2_5_6 , SCREAMING_SNAKE_CASE :Optional[Any]=1_0_2_4 , SCREAMING_SNAKE_CASE :Dict=2_1_6 , SCREAMING_SNAKE_CASE :Union[str, Any]=1_0_0_1 , SCREAMING_SNAKE_CASE :List[Any]=3_2 , SCREAMING_SNAKE_CASE :Optional[Any]=5_0 , SCREAMING_SNAKE_CASE :Union[str, Any]="absolute" , SCREAMING_SNAKE_CASE :int=True , SCREAMING_SNAKE_CASE :Any=None , **SCREAMING_SNAKE_CASE :Tuple , ) -> Tuple: '''simple docstring''' super().__init__( pad_token_id=SCREAMING_SNAKE_CASE , bos_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) _a : str =vocab_size _a : List[Any] =hidden_size _a : Tuple =num_hidden_layers _a : Dict =num_attention_heads _a : int =hidden_act _a : Union[str, Any] =intermediate_size _a : str =hidden_dropout_prob _a : List[Any] =attention_probs_dropout_prob _a : Union[str, Any] =max_position_embeddings _a : Any =type_vocab_size _a : Any =initializer_range _a : int =layer_norm_eps _a : Any =position_embedding_type _a : List[str] =use_cache _a : Union[str, Any] =classifier_dropout # additional properties _a : Optional[int] =max_depth _a : Optional[Any] =max_xpath_tag_unit_embeddings _a : Optional[Any] =max_xpath_subs_unit_embeddings _a : Dict =tag_pad_id _a : str =subs_pad_id _a : List[str] =xpath_unit_hidden_size
276
'''simple docstring''' from __future__ import annotations import requests def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ) -> dict: _a : Any =F"https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty" return requests.get(_UpperCAmelCase ).json() def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int = 10 ) -> list[dict]: _a : Union[str, Any] ="""https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty""" _a : int =requests.get(_UpperCAmelCase ).json()[:max_stories] return [get_hackernews_story(_UpperCAmelCase ) for story_id in story_ids] def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int = 10 ) -> str: _a : Union[str, Any] =hackernews_top_stories(_UpperCAmelCase ) return "\n".join("""* [{title}]({url})""".format(**_UpperCAmelCase ) for story in stories ) if __name__ == "__main__": print(hackernews_top_stories_as_markdown())
276
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available A__: List[str] = {'''configuration_speech_encoder_decoder''': ['''SpeechEncoderDecoderConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: List[Any] = ['''SpeechEncoderDecoderModel'''] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Optional[int] = ['''FlaxSpeechEncoderDecoderModel'''] if TYPE_CHECKING: from .configuration_speech_encoder_decoder import SpeechEncoderDecoderConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_encoder_decoder import SpeechEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_speech_encoder_decoder import FlaxSpeechEncoderDecoderModel else: import sys A__: Tuple = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
276
'''simple docstring''' from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, apply_forward_hook from .modeling_utils import ModelMixin from .vae import Decoder, DecoderOutput, Encoder, VectorQuantizer @dataclass class A__ ( UpperCAmelCase__ ): __UpperCamelCase : torch.FloatTensor class A__ ( UpperCAmelCase__ , UpperCAmelCase__ ): @register_to_config def __init__( self :Optional[Any] , SCREAMING_SNAKE_CASE :int = 3 , SCREAMING_SNAKE_CASE :int = 3 , SCREAMING_SNAKE_CASE :Tuple[str] = ("DownEncoderBlock2D",) , SCREAMING_SNAKE_CASE :Tuple[str] = ("UpDecoderBlock2D",) , SCREAMING_SNAKE_CASE :Tuple[int] = (6_4,) , SCREAMING_SNAKE_CASE :int = 1 , SCREAMING_SNAKE_CASE :str = "silu" , SCREAMING_SNAKE_CASE :int = 3 , SCREAMING_SNAKE_CASE :int = 3_2 , SCREAMING_SNAKE_CASE :int = 2_5_6 , SCREAMING_SNAKE_CASE :int = 3_2 , SCREAMING_SNAKE_CASE :Optional[int] = None , SCREAMING_SNAKE_CASE :float = 0.18_215 , SCREAMING_SNAKE_CASE :str = "group" , ) -> Optional[int]: '''simple docstring''' super().__init__() # pass init params to Encoder _a : Union[str, Any] =Encoder( in_channels=SCREAMING_SNAKE_CASE , out_channels=SCREAMING_SNAKE_CASE , down_block_types=SCREAMING_SNAKE_CASE , block_out_channels=SCREAMING_SNAKE_CASE , layers_per_block=SCREAMING_SNAKE_CASE , act_fn=SCREAMING_SNAKE_CASE , norm_num_groups=SCREAMING_SNAKE_CASE , double_z=SCREAMING_SNAKE_CASE , ) _a : Optional[int] =vq_embed_dim if vq_embed_dim is not None else latent_channels _a : Optional[int] =nn.Convad(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , 1 ) _a : str =VectorQuantizer(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , beta=0.25 , remap=SCREAMING_SNAKE_CASE , sane_index_shape=SCREAMING_SNAKE_CASE ) _a : List[str] =nn.Convad(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , 1 ) # pass init params to Decoder _a : List[str] =Decoder( in_channels=SCREAMING_SNAKE_CASE , out_channels=SCREAMING_SNAKE_CASE , up_block_types=SCREAMING_SNAKE_CASE , block_out_channels=SCREAMING_SNAKE_CASE , layers_per_block=SCREAMING_SNAKE_CASE , act_fn=SCREAMING_SNAKE_CASE , norm_num_groups=SCREAMING_SNAKE_CASE , norm_type=SCREAMING_SNAKE_CASE , ) @apply_forward_hook def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :torch.FloatTensor , SCREAMING_SNAKE_CASE :bool = True ) -> VQEncoderOutput: '''simple docstring''' _a : Optional[int] =self.encoder(SCREAMING_SNAKE_CASE ) _a : int =self.quant_conv(SCREAMING_SNAKE_CASE ) if not return_dict: return (h,) return VQEncoderOutput(latents=SCREAMING_SNAKE_CASE ) @apply_forward_hook def __UpperCAmelCase ( self :List[Any] , SCREAMING_SNAKE_CASE :torch.FloatTensor , SCREAMING_SNAKE_CASE :bool = False , SCREAMING_SNAKE_CASE :bool = True ) -> Union[DecoderOutput, torch.FloatTensor]: '''simple docstring''' # also go through quantization layer if not force_not_quantize: _a , _a , _a : Tuple =self.quantize(SCREAMING_SNAKE_CASE ) else: _a : str =h _a : Dict =self.post_quant_conv(SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =self.decoder(SCREAMING_SNAKE_CASE , quant if self.config.norm_type == """spatial""" else None ) if not return_dict: return (dec,) return DecoderOutput(sample=SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :torch.FloatTensor , SCREAMING_SNAKE_CASE :bool = True ) -> Union[DecoderOutput, torch.FloatTensor]: '''simple docstring''' _a : Tuple =sample _a : int =self.encode(SCREAMING_SNAKE_CASE ).latents _a : List[Any] =self.decode(SCREAMING_SNAKE_CASE ).sample if not return_dict: return (dec,) return DecoderOutput(sample=SCREAMING_SNAKE_CASE )
276
1
'''simple docstring''' import os from pathlib import Path import numpy as np import pytest from pack_dataset import pack_data_dir from parameterized import parameterized from save_len_file import save_len_file from torch.utils.data import DataLoader from transformers import AutoTokenizer from transformers.models.mbart.modeling_mbart import shift_tokens_right from transformers.testing_utils import TestCasePlus, slow from utils import FAIRSEQ_AVAILABLE, DistributedSortishSampler, LegacySeqaSeqDataset, SeqaSeqDataset A__: Dict = '''bert-base-cased''' A__: Union[str, Any] = '''google/pegasus-xsum''' A__: Tuple = [''' Sam ate lunch today.''', '''Sams lunch ingredients.'''] A__: Optional[int] = ['''A very interesting story about what I ate for lunch.''', '''Avocado, celery, turkey, coffee'''] A__: Tuple = '''patrickvonplaten/t5-tiny-random''' A__: List[str] = '''sshleifer/bart-tiny-random''' A__: List[str] = '''sshleifer/tiny-mbart''' A__: List[str] = '''sshleifer/tiny-marian-en-de''' def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Path ,_UpperCAmelCase : list ) -> Tuple: _a : str ="""\n""".join(_UpperCAmelCase ) Path(_UpperCAmelCase ).open("""w""" ).writelines(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Any ) -> Dict: for split in ["train", "val", "test"]: _dump_articles(os.path.join(_UpperCAmelCase ,F"{split}.source" ) ,_UpperCAmelCase ) _dump_articles(os.path.join(_UpperCAmelCase ,F"{split}.target" ) ,_UpperCAmelCase ) return tmp_dir class A__ ( UpperCAmelCase__ ): @parameterized.expand( [ MBART_TINY, MARIAN_TINY, T5_TINY, BART_TINY, PEGASUS_XSUM, ] , ) @slow def __UpperCAmelCase ( self :Any , SCREAMING_SNAKE_CASE :Optional[Any] ) -> Optional[int]: '''simple docstring''' _a : List[Any] =AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE ) _a : Any =make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) _a : str =max(len(tokenizer.encode(SCREAMING_SNAKE_CASE ) ) for a in ARTICLES ) _a : List[str] =max(len(tokenizer.encode(SCREAMING_SNAKE_CASE ) ) for a in SUMMARIES ) _a : str =4 _a : int =8 assert max_len_target > max_src_len # Will be truncated assert max_len_source > max_src_len # Will be truncated _a , _a : str ="""ro_RO""", """de_DE""" # ignored for all but mbart, but never causes error. _a : Tuple =SeqaSeqDataset( SCREAMING_SNAKE_CASE , data_dir=SCREAMING_SNAKE_CASE , type_path="""train""" , max_source_length=SCREAMING_SNAKE_CASE , max_target_length=SCREAMING_SNAKE_CASE , src_lang=SCREAMING_SNAKE_CASE , tgt_lang=SCREAMING_SNAKE_CASE , ) _a : Optional[Any] =DataLoader(SCREAMING_SNAKE_CASE , batch_size=2 , collate_fn=train_dataset.collate_fn ) for batch in dataloader: assert isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) assert batch["attention_mask"].shape == batch["input_ids"].shape # show that articles were trimmed. assert batch["input_ids"].shape[1] == max_src_len # show that targets are the same len assert batch["labels"].shape[1] == max_tgt_len if tok_name != MBART_TINY: continue # check language codes in correct place _a : List[str] =shift_tokens_right(batch["""labels"""] , tokenizer.pad_token_id ) assert batch["decoder_input_ids"][0, 0].item() == tokenizer.lang_code_to_id[tgt_lang] assert batch["decoder_input_ids"][0, -1].item() == tokenizer.eos_token_id assert batch["input_ids"][0, -2].item() == tokenizer.eos_token_id assert batch["input_ids"][0, -1].item() == tokenizer.lang_code_to_id[src_lang] break # No need to test every batch @parameterized.expand([BART_TINY, BERT_BASE_CASED] ) def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :Optional[Any] ) -> List[str]: '''simple docstring''' _a : Optional[Any] =AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE ) _a : Optional[Any] =make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) _a : str =max(len(tokenizer.encode(SCREAMING_SNAKE_CASE ) ) for a in ARTICLES ) _a : List[str] =max(len(tokenizer.encode(SCREAMING_SNAKE_CASE ) ) for a in SUMMARIES ) _a : List[Any] =4 _a : Any =LegacySeqaSeqDataset( SCREAMING_SNAKE_CASE , data_dir=SCREAMING_SNAKE_CASE , type_path="""train""" , max_source_length=2_0 , max_target_length=SCREAMING_SNAKE_CASE , ) _a : List[str] =DataLoader(SCREAMING_SNAKE_CASE , batch_size=2 , collate_fn=train_dataset.collate_fn ) for batch in dataloader: assert batch["attention_mask"].shape == batch["input_ids"].shape # show that articles were trimmed. assert batch["input_ids"].shape[1] == max_len_source assert 2_0 >= batch["input_ids"].shape[1] # trimmed significantly # show that targets were truncated assert batch["labels"].shape[1] == trunc_target # Truncated assert max_len_target > trunc_target # Truncated break # No need to test every batch def __UpperCAmelCase ( self :Union[str, Any] ) -> Dict: '''simple docstring''' _a : List[str] =AutoTokenizer.from_pretrained("""facebook/mbart-large-cc25""" ) _a : Any =Path(make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) ) _a : str =tmp_dir.joinpath("""train.source""" ).open().readlines() _a : Optional[Any] =Path(make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) ) pack_data_dir(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , 1_2_8 , SCREAMING_SNAKE_CASE ) _a : int ={x.name for x in tmp_dir.iterdir()} _a : List[str] ={x.name for x in save_dir.iterdir()} _a : Any =save_dir.joinpath("""train.source""" ).open().readlines() # orig: [' Sam ate lunch today.\n', 'Sams lunch ingredients.'] # desired_packed: [' Sam ate lunch today.\n Sams lunch ingredients.'] assert len(SCREAMING_SNAKE_CASE ) < len(SCREAMING_SNAKE_CASE ) assert len(SCREAMING_SNAKE_CASE ) == 1 assert len(packed_examples[0] ) == sum(len(SCREAMING_SNAKE_CASE ) for x in orig_examples ) assert orig_paths == new_paths @pytest.mark.skipif(not FAIRSEQ_AVAILABLE , reason="""This test requires fairseq""" ) def __UpperCAmelCase ( self :str ) -> Optional[int]: '''simple docstring''' if not FAIRSEQ_AVAILABLE: return _a , _a , _a : str =self._get_dataset(max_len=6_4 ) _a : List[Any] =6_4 _a : List[str] =ds.make_dynamic_sampler(SCREAMING_SNAKE_CASE , required_batch_size_multiple=SCREAMING_SNAKE_CASE ) _a : Optional[Any] =[len(SCREAMING_SNAKE_CASE ) for x in batch_sampler] assert len(set(SCREAMING_SNAKE_CASE ) ) > 1 # it's not dynamic batch size if every batch is the same length assert sum(SCREAMING_SNAKE_CASE ) == len(SCREAMING_SNAKE_CASE ) # no dropped or added examples _a : Tuple =DataLoader(SCREAMING_SNAKE_CASE , batch_sampler=SCREAMING_SNAKE_CASE , collate_fn=ds.collate_fn , num_workers=2 ) _a : Union[str, Any] =[] _a : str =[] for batch in data_loader: _a : int =batch["""input_ids"""].shape _a : Optional[int] =src_shape[0] assert bs % required_batch_size_multiple == 0 or bs < required_batch_size_multiple _a : Optional[int] =np.product(batch["""input_ids"""].shape ) num_src_per_batch.append(SCREAMING_SNAKE_CASE ) if num_src_tokens > (max_tokens * 1.1): failures.append(SCREAMING_SNAKE_CASE ) assert num_src_per_batch[0] == max(SCREAMING_SNAKE_CASE ) if failures: raise AssertionError(f"too many tokens in {len(SCREAMING_SNAKE_CASE )} batches" ) def __UpperCAmelCase ( self :Dict ) -> List[Any]: '''simple docstring''' _a , _a , _a : Optional[int] =self._get_dataset(max_len=5_1_2 ) _a : List[str] =2 _a : Dict =ds.make_sortish_sampler(SCREAMING_SNAKE_CASE , shuffle=SCREAMING_SNAKE_CASE ) _a : List[Any] =DataLoader(SCREAMING_SNAKE_CASE , batch_size=SCREAMING_SNAKE_CASE , collate_fn=ds.collate_fn , num_workers=2 ) _a : Any =DataLoader(SCREAMING_SNAKE_CASE , batch_size=SCREAMING_SNAKE_CASE , collate_fn=ds.collate_fn , num_workers=2 , sampler=SCREAMING_SNAKE_CASE ) _a : List[Any] =tokenizer.pad_token_id def count_pad_tokens(SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :Any="input_ids" ): return [batch[k].eq(SCREAMING_SNAKE_CASE ).sum().item() for batch in data_loader] assert sum(count_pad_tokens(SCREAMING_SNAKE_CASE , k="""labels""" ) ) < sum(count_pad_tokens(SCREAMING_SNAKE_CASE , k="""labels""" ) ) assert sum(count_pad_tokens(SCREAMING_SNAKE_CASE ) ) < sum(count_pad_tokens(SCREAMING_SNAKE_CASE ) ) assert len(SCREAMING_SNAKE_CASE ) == len(SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :str , SCREAMING_SNAKE_CASE :Tuple=1_0_0_0 , SCREAMING_SNAKE_CASE :Tuple=1_2_8 ) -> List[Any]: '''simple docstring''' if os.getenv("""USE_REAL_DATA""" , SCREAMING_SNAKE_CASE ): _a : Optional[Any] ="""examples/seq2seq/wmt_en_ro""" _a : Optional[Any] =max_len * 2 * 6_4 if not Path(SCREAMING_SNAKE_CASE ).joinpath("""train.len""" ).exists(): save_len_file(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) else: _a : Union[str, Any] ="""examples/seq2seq/test_data/wmt_en_ro""" _a : List[Any] =max_len * 4 save_len_file(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) _a : Optional[Any] =AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE ) _a : str =SeqaSeqDataset( SCREAMING_SNAKE_CASE , data_dir=SCREAMING_SNAKE_CASE , type_path="""train""" , max_source_length=SCREAMING_SNAKE_CASE , max_target_length=SCREAMING_SNAKE_CASE , n_obs=SCREAMING_SNAKE_CASE , ) return ds, max_tokens, tokenizer def __UpperCAmelCase ( self :int ) -> Any: '''simple docstring''' _a , _a , _a : Optional[Any] =self._get_dataset() _a : int =set(DistributedSortishSampler(SCREAMING_SNAKE_CASE , 2_5_6 , num_replicas=2 , rank=0 , add_extra_examples=SCREAMING_SNAKE_CASE ) ) _a : List[str] =set(DistributedSortishSampler(SCREAMING_SNAKE_CASE , 2_5_6 , num_replicas=2 , rank=1 , add_extra_examples=SCREAMING_SNAKE_CASE ) ) assert idsa.intersection(SCREAMING_SNAKE_CASE ) == set() @parameterized.expand( [ MBART_TINY, MARIAN_TINY, T5_TINY, BART_TINY, PEGASUS_XSUM, ] , ) def __UpperCAmelCase ( self :Optional[int] , SCREAMING_SNAKE_CASE :List[Any] ) -> Tuple: '''simple docstring''' _a : str =AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE , use_fast=SCREAMING_SNAKE_CASE ) if tok_name == MBART_TINY: _a : Tuple =SeqaSeqDataset( SCREAMING_SNAKE_CASE , data_dir=make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) , type_path="""train""" , max_source_length=4 , max_target_length=8 , src_lang="""EN""" , tgt_lang="""FR""" , ) _a : int =train_dataset.dataset_kwargs assert "src_lang" in kwargs and "tgt_lang" in kwargs else: _a : str =SeqaSeqDataset( SCREAMING_SNAKE_CASE , data_dir=make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) , type_path="""train""" , max_source_length=4 , max_target_length=8 , ) _a : Union[str, Any] =train_dataset.dataset_kwargs assert "add_prefix_space" not in kwargs if tok_name != BART_TINY else "add_prefix_space" in kwargs assert len(SCREAMING_SNAKE_CASE ) == 1 if tok_name == BART_TINY else len(SCREAMING_SNAKE_CASE ) == 0
276
'''simple docstring''' import unittest from transformers import EsmConfig, is_torch_available from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import EsmForMaskedLM, EsmForSequenceClassification, EsmForTokenClassification, EsmModel from transformers.models.esm.modeling_esm import ( ESM_PRETRAINED_MODEL_ARCHIVE_LIST, EsmEmbeddings, create_position_ids_from_input_ids, ) class A__ : def __init__( self :Tuple , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :Optional[int]=1_3 , SCREAMING_SNAKE_CASE :Optional[int]=7 , SCREAMING_SNAKE_CASE :Tuple=False , SCREAMING_SNAKE_CASE :Dict=True , SCREAMING_SNAKE_CASE :Optional[int]=False , SCREAMING_SNAKE_CASE :Optional[Any]=True , SCREAMING_SNAKE_CASE :List[str]=3_3 , SCREAMING_SNAKE_CASE :Tuple=3_2 , SCREAMING_SNAKE_CASE :Tuple=5 , SCREAMING_SNAKE_CASE :int=4 , SCREAMING_SNAKE_CASE :Union[str, Any]=3_7 , SCREAMING_SNAKE_CASE :List[str]="gelu" , SCREAMING_SNAKE_CASE :Optional[Any]=0.1 , SCREAMING_SNAKE_CASE :Tuple=0.1 , SCREAMING_SNAKE_CASE :str=5_1_2 , SCREAMING_SNAKE_CASE :Dict=1_6 , SCREAMING_SNAKE_CASE :Dict=2 , SCREAMING_SNAKE_CASE :Union[str, Any]=0.02 , SCREAMING_SNAKE_CASE :str=3 , SCREAMING_SNAKE_CASE :List[str]=4 , SCREAMING_SNAKE_CASE :List[str]=None , ) -> Union[str, Any]: '''simple docstring''' _a : Union[str, Any] =parent _a : List[Any] =batch_size _a : Optional[int] =seq_length _a : Union[str, Any] =is_training _a : List[Any] =use_input_mask _a : Optional[int] =use_token_type_ids _a : int =use_labels _a : List[str] =vocab_size _a : List[Any] =hidden_size _a : int =num_hidden_layers _a : Tuple =num_attention_heads _a : Any =intermediate_size _a : str =hidden_act _a : Union[str, Any] =hidden_dropout_prob _a : Union[str, Any] =attention_probs_dropout_prob _a : str =max_position_embeddings _a : Dict =type_vocab_size _a : Tuple =type_sequence_label_size _a : Dict =initializer_range _a : List[str] =num_labels _a : Tuple =num_choices _a : int =scope def __UpperCAmelCase ( self :Union[str, Any] ) -> str: '''simple docstring''' _a : Optional[int] =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _a : List[Any] =None if self.use_input_mask: _a : Any =random_attention_mask([self.batch_size, self.seq_length] ) _a : Optional[int] =None _a : str =None _a : Dict =None if self.use_labels: _a : Dict =ids_tensor([self.batch_size] , self.type_sequence_label_size ) _a : str =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _a : List[str] =ids_tensor([self.batch_size] , self.num_choices ) _a : List[Any] =self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCAmelCase ( self :str ) -> Optional[int]: '''simple docstring''' return EsmConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , pad_token_id=1 , 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 __UpperCAmelCase ( self :List[str] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :Optional[Any] , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :int ) -> Tuple: '''simple docstring''' _a : Any =EsmModel(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() _a : Optional[Any] =model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =model(SCREAMING_SNAKE_CASE ) _a : str =model(SCREAMING_SNAKE_CASE ) 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 __UpperCAmelCase ( self :str , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :Optional[Any] ) -> Dict: '''simple docstring''' _a : str =EsmForMaskedLM(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() _a : Union[str, Any] =model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :Optional[Any] , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :List[Any] , SCREAMING_SNAKE_CASE :Union[str, Any] ) -> Optional[Any]: '''simple docstring''' _a : int =self.num_labels _a : Tuple =EsmForTokenClassification(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() _a : Tuple =model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCAmelCase ( self :Dict ) -> List[str]: '''simple docstring''' _a : Optional[Any] =self.prepare_config_and_inputs() ( ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ) : Any =config_and_inputs _a : List[Any] ={"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class A__ ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): __UpperCamelCase : Any = False __UpperCamelCase : Any = ( ( EsmForMaskedLM, EsmModel, EsmForSequenceClassification, EsmForTokenClassification, ) if is_torch_available() else () ) __UpperCamelCase : str = () __UpperCamelCase : List[str] = ( { "feature-extraction": EsmModel, "fill-mask": EsmForMaskedLM, "text-classification": EsmForSequenceClassification, "token-classification": EsmForTokenClassification, "zero-shot": EsmForSequenceClassification, } if is_torch_available() else {} ) __UpperCamelCase : Union[str, Any] = True def __UpperCAmelCase ( self :Optional[int] ) -> int: '''simple docstring''' _a : Dict =EsmModelTester(self ) _a : Optional[Any] =ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , hidden_size=3_7 ) def __UpperCAmelCase ( self :Tuple ) -> List[Any]: '''simple docstring''' self.config_tester.run_common_tests() def __UpperCAmelCase ( self :Optional[int] ) -> str: '''simple docstring''' _a : List[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :List[Any] ) -> Dict: '''simple docstring''' _a : List[str] =self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: _a : Dict =type self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Dict ) -> List[str]: '''simple docstring''' _a : Tuple =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :List[Any] ) -> List[str]: '''simple docstring''' _a : str =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*SCREAMING_SNAKE_CASE ) @slow def __UpperCAmelCase ( self :str ) -> Dict: '''simple docstring''' for model_name in ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _a : Union[str, Any] =EsmModel.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Tuple ) -> int: '''simple docstring''' _a : Optional[Any] =self.model_tester.prepare_config_and_inputs()[0] _a : Dict =EsmEmbeddings(config=SCREAMING_SNAKE_CASE ) _a : Tuple =torch.as_tensor([[1_2, 3_1, 1_3, model.padding_idx]] ) _a : Optional[Any] =torch.as_tensor( [ [ 0 + model.padding_idx + 1, 1 + model.padding_idx + 1, 2 + model.padding_idx + 1, model.padding_idx, ] ] ) _a : Any =create_position_ids_from_input_ids(SCREAMING_SNAKE_CASE , model.padding_idx ) self.assertEqual(position_ids.shape , expected_positions.shape ) self.assertTrue(torch.all(torch.eq(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) ) def __UpperCAmelCase ( self :Optional[Any] ) -> Tuple: '''simple docstring''' _a : List[Any] =self.model_tester.prepare_config_and_inputs()[0] _a : Optional[int] =EsmEmbeddings(config=SCREAMING_SNAKE_CASE ) _a : Tuple =torch.empty(2 , 4 , 3_0 ) _a : str =[ 0 + embeddings.padding_idx + 1, 1 + embeddings.padding_idx + 1, 2 + embeddings.padding_idx + 1, 3 + embeddings.padding_idx + 1, ] _a : int =torch.as_tensor([expected_single_positions, expected_single_positions] ) _a : Any =embeddings.create_position_ids_from_inputs_embeds(SCREAMING_SNAKE_CASE ) self.assertEqual(position_ids.shape , expected_positions.shape ) self.assertTrue(torch.all(torch.eq(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) ) @unittest.skip("""Esm does not support embedding resizing""" ) def __UpperCAmelCase ( self :Tuple ) -> List[str]: '''simple docstring''' pass @unittest.skip("""Esm does not support embedding resizing""" ) def __UpperCAmelCase ( self :str ) -> Any: '''simple docstring''' pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def __UpperCAmelCase ( self :Dict ) -> Any: '''simple docstring''' pass @require_torch class A__ ( UpperCAmelCase__ ): @slow def __UpperCAmelCase ( self :List[Any] ) -> str: '''simple docstring''' with torch.no_grad(): _a : Optional[int] =EsmForMaskedLM.from_pretrained("""facebook/esm2_t6_8M_UR50D""" ) model.eval() _a : Any =torch.tensor([[0, 1, 2, 3, 4, 5]] ) _a : Tuple =model(SCREAMING_SNAKE_CASE )[0] _a : int =3_3 _a : Tuple =torch.Size((1, 6, vocab_size) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =torch.tensor( [[[8.9_215, -10.5_898, -6.4_671], [-6.3_967, -13.9_114, -1.1_212], [-7.7_812, -13.9_516, -3.7_406]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) ) @slow def __UpperCAmelCase ( self :Union[str, Any] ) -> Tuple: '''simple docstring''' with torch.no_grad(): _a : Any =EsmModel.from_pretrained("""facebook/esm2_t6_8M_UR50D""" ) model.eval() _a : Any =torch.tensor([[0, 6, 4, 1_3, 5, 4, 1_6, 1_2, 1_1, 7, 2]] ) _a : int =model(SCREAMING_SNAKE_CASE )[0] # compare the actual values for a slice. _a : str =torch.tensor( [[[0.1_444, 0.5_413, 0.3_248], [0.3_034, 0.0_053, 0.3_108], [0.3_228, -0.2_499, 0.3_415]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) )
276
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 # and perform gradient accumulation # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## A__: List[Any] = 16 A__: Tuple = 32 def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Accelerator ,_UpperCAmelCase : int = 16 ) -> Any: _a : Union[str, Any] =AutoTokenizer.from_pretrained("""bert-base-cased""" ) _a : Tuple =load_dataset("""glue""" ,"""mrpc""" ) def tokenize_function(_UpperCAmelCase : List[str] ): # max_length=None => use the model max length (it's actually the default) _a : str =tokenizer(examples["""sentence1"""] ,examples["""sentence2"""] ,truncation=_UpperCAmelCase ,max_length=_UpperCAmelCase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): _a : str =datasets.map( _UpperCAmelCase ,batched=_UpperCAmelCase ,remove_columns=["""idx""", """sentence1""", """sentence2"""] ,) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library _a : Any =tokenized_datasets.rename_column("""label""" ,"""labels""" ) def collate_fn(_UpperCAmelCase : List[Any] ): # On TPU it's best to pad everything to the same length or training will be very slow. _a : Optional[Any] =128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": _a : Union[str, Any] =16 elif accelerator.mixed_precision != "no": _a : Optional[Any] =8 else: _a : Union[str, Any] =None return tokenizer.pad( _UpperCAmelCase ,padding="""longest""" ,max_length=_UpperCAmelCase ,pad_to_multiple_of=_UpperCAmelCase ,return_tensors="""pt""" ,) # Instantiate dataloaders. _a : str =DataLoader( tokenized_datasets["""train"""] ,shuffle=_UpperCAmelCase ,collate_fn=_UpperCAmelCase ,batch_size=_UpperCAmelCase ) _a : List[Any] =DataLoader( tokenized_datasets["""validation"""] ,shuffle=_UpperCAmelCase ,collate_fn=_UpperCAmelCase ,batch_size=_UpperCAmelCase ) 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 A__: List[str] = mocked_dataloaders # noqa: F811 def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Any ) -> int: # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""" ,_UpperCAmelCase ) == "1": _a : int =2 # New Code # _a : int =int(args.gradient_accumulation_steps ) # Initialize accelerator _a : Optional[Any] =Accelerator( cpu=args.cpu ,mixed_precision=args.mixed_precision ,gradient_accumulation_steps=_UpperCAmelCase ) if accelerator.distributed_type == DistributedType.TPU and gradient_accumulation_steps > 1: raise NotImplementedError( """Gradient accumulation on TPUs is currently not supported. Pass `gradient_accumulation_steps=1`""" ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs _a : List[Any] =config["""lr"""] _a : List[str] =int(config["""num_epochs"""] ) _a : Any =int(config["""seed"""] ) _a : Tuple =int(config["""batch_size"""] ) _a : Any =evaluate.load("""glue""" ,"""mrpc""" ) set_seed(_UpperCAmelCase ) _a , _a : Tuple =get_dataloaders(_UpperCAmelCase ,_UpperCAmelCase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) _a : List[str] =AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" ,return_dict=_UpperCAmelCase ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). _a : Tuple =model.to(accelerator.device ) # Instantiate optimizer _a : Dict =AdamW(params=model.parameters() ,lr=_UpperCAmelCase ) # Instantiate scheduler _a : Any =get_linear_schedule_with_warmup( optimizer=_UpperCAmelCase ,num_warmup_steps=100 ,num_training_steps=(len(_UpperCAmelCase ) * num_epochs) ,) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. _a , _a , _a , _a , _a : Optional[Any] =accelerator.prepare( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) # Now we train the model for epoch in range(_UpperCAmelCase ): model.train() for step, batch in enumerate(_UpperCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) # New code # # We use the new `accumulate` context manager to perform gradient accumulation # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. with accelerator.accumulate(_UpperCAmelCase ): _a : int =model(**_UpperCAmelCase ) _a : Union[str, Any] =output.loss accelerator.backward(_UpperCAmelCase ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(_UpperCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): _a : Optional[Any] =model(**_UpperCAmelCase ) _a : Any =outputs.logits.argmax(dim=-1 ) _a , _a : Dict =accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=_UpperCAmelCase ,references=_UpperCAmelCase ,) _a : List[str] =metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F"epoch {epoch}:" ,_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( ) -> Optional[int]: _a : List[Any] =argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" ,type=_UpperCAmelCase ,default=_UpperCAmelCase ,choices=["""no""", """fp16""", """bf16""", """fp8"""] ,help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" ,) # New Code # parser.add_argument( """--gradient_accumulation_steps""" ,type=_UpperCAmelCase ,default=1 ,help="""The number of minibatches to be ran before gradients are accumulated.""" ,) parser.add_argument("""--cpu""" ,action="""store_true""" ,help="""If passed, will train on the CPU.""" ) _a : int =parser.parse_args() _a : int ={"""lr""": 2e-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16} training_function(_UpperCAmelCase ,_UpperCAmelCase ) if __name__ == "__main__": main()
276
'''simple docstring''' from math import isqrt def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ) -> bool: return all(number % divisor != 0 for divisor in range(2 ,isqrt(_UpperCAmelCase ) + 1 ) ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int = 10**6 ) -> int: _a : List[Any] =0 _a : str =1 _a : Optional[Any] =7 while prime_candidate < max_prime: primes_count += is_prime(_UpperCAmelCase ) cube_index += 1 prime_candidate += 6 * cube_index return primes_count if __name__ == "__main__": print(F"{solution() = }")
276
1
'''simple docstring''' from abc import ABC, abstractmethod from argparse import ArgumentParser class A__ ( UpperCAmelCase__ ): @staticmethod @abstractmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :ArgumentParser ) -> Dict: '''simple docstring''' raise NotImplementedError() @abstractmethod def __UpperCAmelCase ( self :Union[str, Any] ) -> List[str]: '''simple docstring''' raise NotImplementedError()
276
'''simple docstring''' # 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 ...utils import deprecate from ..controlnet.multicontrolnet import MultiControlNetModel # noqa: F401 from ..controlnet.pipeline_controlnet import StableDiffusionControlNetPipeline # noqa: F401 deprecate( '''stable diffusion controlnet''', '''0.22.0''', '''Importing `StableDiffusionControlNetPipeline` or `MultiControlNetModel` from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import StableDiffusionControlNetPipeline` instead.''', standard_warn=False, stacklevel=3, )
276
1
'''simple docstring''' import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import datasets import datasets.config from .utils import require_beam class A__ ( datasets.BeamBasedBuilder ): def __UpperCAmelCase ( self :Optional[int] ) -> Dict: '''simple docstring''' return datasets.DatasetInfo( features=datasets.Features({"""content""": datasets.Value("""string""" )} ) , supervised_keys=SCREAMING_SNAKE_CASE , ) def __UpperCAmelCase ( self :List[Any] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :Optional[Any] ) -> str: '''simple docstring''' return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"""examples""": get_test_dummy_examples()} )] def __UpperCAmelCase ( self :List[str] , SCREAMING_SNAKE_CASE :Optional[Any] , SCREAMING_SNAKE_CASE :str ) -> List[Any]: '''simple docstring''' import apache_beam as beam return pipeline | "Load Examples" >> beam.Create(SCREAMING_SNAKE_CASE ) class A__ ( datasets.BeamBasedBuilder ): def __UpperCAmelCase ( self :List[str] ) -> Optional[int]: '''simple docstring''' return datasets.DatasetInfo( features=datasets.Features({"""a""": datasets.Sequence({"""b""": datasets.Value("""string""" )} )} ) , supervised_keys=SCREAMING_SNAKE_CASE , ) def __UpperCAmelCase ( self :Any , SCREAMING_SNAKE_CASE :Optional[int] , SCREAMING_SNAKE_CASE :int ) -> Optional[int]: '''simple docstring''' return [ datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"""examples""": get_test_nested_examples()} ) ] def __UpperCAmelCase ( self :int , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :Any ) -> Dict: '''simple docstring''' import apache_beam as beam return pipeline | "Load Examples" >> beam.Create(SCREAMING_SNAKE_CASE ) def SCREAMING_SNAKE_CASE_ ( ) -> int: return [(i, {"content": content}) for i, content in enumerate(["""foo""", """bar""", """foobar"""] )] def SCREAMING_SNAKE_CASE_ ( ) -> List[Any]: return [(i, {"a": {"b": [content]}}) for i, content in enumerate(["""foo""", """bar""", """foobar"""] )] class A__ ( UpperCAmelCase__ ): @require_beam def __UpperCAmelCase ( self :List[Any] ) -> Optional[Any]: '''simple docstring''' _a : int =len(get_test_dummy_examples() ) with tempfile.TemporaryDirectory() as tmp_cache_dir: _a : Optional[int] =DummyBeamDataset(cache_dir=SCREAMING_SNAKE_CASE , beam_runner="""DirectRunner""" ) builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join(SCREAMING_SNAKE_CASE , builder.name , """default""" , """0.0.0""" , f"{builder.name}-train.arrow" ) ) ) self.assertDictEqual(builder.info.features , datasets.Features({"""content""": datasets.Value("""string""" )} ) ) _a : int =builder.as_dataset() self.assertEqual(dset["""train"""].num_rows , SCREAMING_SNAKE_CASE ) self.assertEqual(dset["""train"""].info.splits["""train"""].num_examples , SCREAMING_SNAKE_CASE ) self.assertDictEqual(dset["""train"""][0] , get_test_dummy_examples()[0][1] ) self.assertDictEqual( dset["""train"""][expected_num_examples - 1] , get_test_dummy_examples()[expected_num_examples - 1][1] ) self.assertTrue( os.path.exists(os.path.join(SCREAMING_SNAKE_CASE , builder.name , """default""" , """0.0.0""" , """dataset_info.json""" ) ) ) del dset @require_beam def __UpperCAmelCase ( self :Optional[int] ) -> int: '''simple docstring''' import apache_beam as beam _a : int =beam.io.parquetio.WriteToParquet _a : Union[str, Any] =len(get_test_dummy_examples() ) with tempfile.TemporaryDirectory() as tmp_cache_dir: _a : Optional[int] =DummyBeamDataset(cache_dir=SCREAMING_SNAKE_CASE , beam_runner="""DirectRunner""" ) with patch("""apache_beam.io.parquetio.WriteToParquet""" ) as write_parquet_mock: _a : Union[str, Any] =partial(SCREAMING_SNAKE_CASE , num_shards=2 ) builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join( SCREAMING_SNAKE_CASE , builder.name , """default""" , """0.0.0""" , f"{builder.name}-train-00000-of-00002.arrow" ) ) ) self.assertTrue( os.path.exists( os.path.join( SCREAMING_SNAKE_CASE , builder.name , """default""" , """0.0.0""" , f"{builder.name}-train-00000-of-00002.arrow" ) ) ) self.assertDictEqual(builder.info.features , datasets.Features({"""content""": datasets.Value("""string""" )} ) ) _a : Tuple =builder.as_dataset() self.assertEqual(dset["""train"""].num_rows , SCREAMING_SNAKE_CASE ) self.assertEqual(dset["""train"""].info.splits["""train"""].num_examples , SCREAMING_SNAKE_CASE ) # Order is not preserved when sharding, so we just check that all the elements are there self.assertListEqual(sorted(dset["""train"""]["""content"""] ) , sorted(["""foo""", """bar""", """foobar"""] ) ) self.assertTrue( os.path.exists(os.path.join(SCREAMING_SNAKE_CASE , builder.name , """default""" , """0.0.0""" , """dataset_info.json""" ) ) ) del dset @require_beam def __UpperCAmelCase ( self :List[Any] ) -> Optional[Any]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_cache_dir: _a : List[Any] =DummyBeamDataset(cache_dir=SCREAMING_SNAKE_CASE ) self.assertRaises(datasets.builder.MissingBeamOptions , builder.download_and_prepare ) @require_beam def __UpperCAmelCase ( self :Optional[int] ) -> List[str]: '''simple docstring''' _a : List[Any] =len(get_test_nested_examples() ) with tempfile.TemporaryDirectory() as tmp_cache_dir: _a : str =NestedBeamDataset(cache_dir=SCREAMING_SNAKE_CASE , beam_runner="""DirectRunner""" ) builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join(SCREAMING_SNAKE_CASE , builder.name , """default""" , """0.0.0""" , f"{builder.name}-train.arrow" ) ) ) self.assertDictEqual( builder.info.features , datasets.Features({"""a""": datasets.Sequence({"""b""": datasets.Value("""string""" )} )} ) ) _a : str =builder.as_dataset() self.assertEqual(dset["""train"""].num_rows , SCREAMING_SNAKE_CASE ) self.assertEqual(dset["""train"""].info.splits["""train"""].num_examples , SCREAMING_SNAKE_CASE ) self.assertDictEqual(dset["""train"""][0] , get_test_nested_examples()[0][1] ) self.assertDictEqual( dset["""train"""][expected_num_examples - 1] , get_test_nested_examples()[expected_num_examples - 1][1] ) self.assertTrue( os.path.exists(os.path.join(SCREAMING_SNAKE_CASE , builder.name , """default""" , """0.0.0""" , """dataset_info.json""" ) ) ) del dset
276
'''simple docstring''' import pytest from datasets.utils.sharding import _distribute_shards, _number_of_shards_in_gen_kwargs, _split_gen_kwargs @pytest.mark.parametrize( """kwargs, expected""" ,[ ({"""num_shards""": 0, """max_num_jobs""": 1}, []), ({"""num_shards""": 10, """max_num_jobs""": 1}, [range(10 )]), ({"""num_shards""": 10, """max_num_jobs""": 10}, [range(_UpperCAmelCase ,i + 1 ) for i in range(10 )]), ({"""num_shards""": 1, """max_num_jobs""": 10}, [range(1 )]), ({"""num_shards""": 10, """max_num_jobs""": 3}, [range(0 ,4 ), range(4 ,7 ), range(7 ,10 )]), ({"""num_shards""": 3, """max_num_jobs""": 10}, [range(0 ,1 ), range(1 ,2 ), range(2 ,3 )]), ] ,) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : Dict ) -> Optional[Any]: _a : Tuple =_distribute_shards(**_UpperCAmelCase ) assert out == expected @pytest.mark.parametrize( """gen_kwargs, max_num_jobs, expected""" ,[ ({"""foo""": 0}, 10, [{"""foo""": 0}]), ({"""shards""": [0, 1, 2, 3]}, 1, [{"""shards""": [0, 1, 2, 3]}]), ({"""shards""": [0, 1, 2, 3]}, 4, [{"""shards""": [0]}, {"""shards""": [1]}, {"""shards""": [2]}, {"""shards""": [3]}]), ({"""shards""": [0, 1]}, 4, [{"""shards""": [0]}, {"""shards""": [1]}]), ({"""shards""": [0, 1, 2, 3]}, 2, [{"""shards""": [0, 1]}, {"""shards""": [2, 3]}]), ] ,) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : List[Any] ,_UpperCAmelCase : Union[str, Any] ) -> List[str]: _a : List[str] =_split_gen_kwargs(_UpperCAmelCase ,_UpperCAmelCase ) assert out == expected @pytest.mark.parametrize( """gen_kwargs, expected""" ,[ ({"""foo""": 0}, 1), ({"""shards""": [0]}, 1), ({"""shards""": [0, 1, 2, 3]}, 4), ({"""shards""": [0, 1, 2, 3], """foo""": 0}, 4), ({"""shards""": [0, 1, 2, 3], """other""": (0, 1)}, 4), ({"""shards""": [0, 1, 2, 3], """shards2""": [0, 1]}, RuntimeError), ] ,) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : List[Any] ) -> Union[str, Any]: if expected is RuntimeError: with pytest.raises(_UpperCAmelCase ): _number_of_shards_in_gen_kwargs(_UpperCAmelCase ) else: _a : Dict =_number_of_shards_in_gen_kwargs(_UpperCAmelCase ) assert out == expected
276
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 from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import numpy as np import tensorflow as tf from transformers import ( TF_FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST, FlaubertConfig, TFFlaubertForMultipleChoice, TFFlaubertForQuestionAnsweringSimple, TFFlaubertForSequenceClassification, TFFlaubertForTokenClassification, TFFlaubertModel, TFFlaubertWithLMHeadModel, ) class A__ : def __init__( self :int , SCREAMING_SNAKE_CASE :Union[str, Any] , ) -> List[str]: '''simple docstring''' _a : Any =parent _a : Optional[int] =1_3 _a : Any =7 _a : List[str] =True _a : Union[str, Any] =True _a : Any =True _a : Any =True _a : int =True _a : Tuple =False _a : List[str] =False _a : List[str] =False _a : Tuple =2 _a : List[str] =9_9 _a : Dict =0 _a : Dict =3_2 _a : Optional[int] =2 _a : Optional[Any] =4 _a : Any =0.1 _a : str =0.1 _a : Union[str, Any] =5_1_2 _a : List[str] =1_6 _a : str =2 _a : Dict =0.02 _a : Dict =3 _a : str =4 _a : int ="""last""" _a : List[Any] =True _a : Optional[int] =None _a : Union[str, Any] =0 def __UpperCAmelCase ( self :List[str] ) -> Any: '''simple docstring''' _a : List[Any] =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _a : Tuple =random_attention_mask([self.batch_size, self.seq_length] , dtype=tf.floataa ) _a : Union[str, Any] =None if self.use_input_lengths: _a : List[str] =( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length _a : str =None if self.use_token_type_ids: _a : List[str] =ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) _a : int =None _a : Optional[Any] =None _a : Tuple =None if self.use_labels: _a : Optional[int] =ids_tensor([self.batch_size] , self.type_sequence_label_size ) _a : Dict =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _a : Tuple =ids_tensor([self.batch_size] , 2 , dtype=tf.floataa ) _a : List[Any] =ids_tensor([self.batch_size] , self.num_choices ) _a : List[str] =FlaubertConfig( vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , bos_token_id=self.bos_token_id , ) return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def __UpperCAmelCase ( self :Any , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :Optional[int] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :Optional[Any] , SCREAMING_SNAKE_CASE :List[Any] , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :Optional[Any] , SCREAMING_SNAKE_CASE :Any , ) -> Union[str, Any]: '''simple docstring''' _a : Optional[Any] =TFFlaubertModel(config=SCREAMING_SNAKE_CASE ) _a : List[str] ={"""input_ids""": input_ids, """lengths""": input_lengths, """langs""": token_type_ids} _a : List[str] =model(SCREAMING_SNAKE_CASE ) _a : List[str] =[input_ids, input_mask] _a : int =model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self :Any , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :Optional[Any] , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :Union[str, Any] , ) -> List[Any]: '''simple docstring''' _a : int =TFFlaubertWithLMHeadModel(SCREAMING_SNAKE_CASE ) _a : Optional[int] ={"""input_ids""": input_ids, """lengths""": input_lengths, """langs""": token_type_ids} _a : Dict =model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self :List[Any] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :List[Any] , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :List[Any] , ) -> Any: '''simple docstring''' _a : Union[str, Any] =TFFlaubertForQuestionAnsweringSimple(SCREAMING_SNAKE_CASE ) _a : Union[str, Any] ={"""input_ids""": input_ids, """lengths""": input_lengths} _a : Optional[int] =model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __UpperCAmelCase ( self :List[Any] , SCREAMING_SNAKE_CASE :List[Any] , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :List[Any] , ) -> str: '''simple docstring''' _a : int =TFFlaubertForSequenceClassification(SCREAMING_SNAKE_CASE ) _a : List[str] ={"""input_ids""": input_ids, """lengths""": input_lengths} _a : Any =model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __UpperCAmelCase ( self :str , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :Optional[int] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :List[Any] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :List[Any] , SCREAMING_SNAKE_CASE :str , ) -> Any: '''simple docstring''' _a : Any =self.num_labels _a : List[Any] =TFFlaubertForTokenClassification(config=SCREAMING_SNAKE_CASE ) _a : List[str] ={"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids} _a : Optional[int] =model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :List[Any] , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :Optional[Any] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Optional[Any] , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :Dict , ) -> Dict: '''simple docstring''' _a : int =self.num_choices _a : Optional[Any] =TFFlaubertForMultipleChoice(config=SCREAMING_SNAKE_CASE ) _a : Tuple =tf.tile(tf.expand_dims(SCREAMING_SNAKE_CASE , 1 ) , (1, self.num_choices, 1) ) _a : List[str] =tf.tile(tf.expand_dims(SCREAMING_SNAKE_CASE , 1 ) , (1, self.num_choices, 1) ) _a : Optional[Any] =tf.tile(tf.expand_dims(SCREAMING_SNAKE_CASE , 1 ) , (1, self.num_choices, 1) ) _a : Tuple ={ """input_ids""": multiple_choice_inputs_ids, """attention_mask""": multiple_choice_input_mask, """token_type_ids""": multiple_choice_token_type_ids, } _a : Optional[Any] =model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __UpperCAmelCase ( self :Optional[int] ) -> Dict: '''simple docstring''' _a : List[Any] =self.prepare_config_and_inputs() ( ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ) : Tuple =config_and_inputs _a : Dict ={ """input_ids""": input_ids, """token_type_ids""": token_type_ids, """langs""": token_type_ids, """lengths""": input_lengths, } return config, inputs_dict @require_tf class A__ ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): __UpperCamelCase : Union[str, Any] = ( ( TFFlaubertModel, TFFlaubertWithLMHeadModel, TFFlaubertForSequenceClassification, TFFlaubertForQuestionAnsweringSimple, TFFlaubertForTokenClassification, TFFlaubertForMultipleChoice, ) if is_tf_available() else () ) __UpperCamelCase : str = ( (TFFlaubertWithLMHeadModel,) if is_tf_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable __UpperCamelCase : Optional[int] = ( { "feature-extraction": TFFlaubertModel, "fill-mask": TFFlaubertWithLMHeadModel, "question-answering": TFFlaubertForQuestionAnsweringSimple, "text-classification": TFFlaubertForSequenceClassification, "token-classification": TFFlaubertForTokenClassification, "zero-shot": TFFlaubertForSequenceClassification, } if is_tf_available() else {} ) __UpperCamelCase : Tuple = False __UpperCamelCase : List[Any] = False def __UpperCAmelCase ( self :Tuple , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :Optional[Any] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :Any ) -> Union[str, Any]: '''simple docstring''' if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith("""Fast""" ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def __UpperCAmelCase ( self :int ) -> Any: '''simple docstring''' _a : Optional[int] =TFFlaubertModelTester(self ) _a : List[str] =ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , emb_dim=3_7 ) def __UpperCAmelCase ( self :Any ) -> Union[str, Any]: '''simple docstring''' self.config_tester.run_common_tests() def __UpperCAmelCase ( self :str ) -> Optional[Any]: '''simple docstring''' _a : str =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_model(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :List[str] ) -> List[str]: '''simple docstring''' _a : Tuple =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_lm_head(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Union[str, Any] ) -> Dict: '''simple docstring''' _a : Dict =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_qa(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Optional[Any] ) -> Any: '''simple docstring''' _a : int =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_sequence_classif(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :str ) -> Dict: '''simple docstring''' _a : Tuple =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_for_token_classification(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :str ) -> Optional[int]: '''simple docstring''' _a : str =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_for_multiple_choice(*SCREAMING_SNAKE_CASE ) @slow def __UpperCAmelCase ( self :Tuple ) -> str: '''simple docstring''' for model_name in TF_FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _a : Any =TFFlaubertModel.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) @require_tf @require_sentencepiece @require_tokenizers class A__ ( unittest.TestCase ): @slow def __UpperCAmelCase ( self :int ) -> List[Any]: '''simple docstring''' _a : List[str] =TFFlaubertModel.from_pretrained("""jplu/tf-flaubert-small-cased""" ) _a : List[Any] =tf.convert_to_tensor( [[0, 1_5_8, 7_3_5, 2_5_9_2, 1_4_2_4, 6_7_2_7, 8_2, 1]] , dtype=tf.intaa , ) # "J'aime flaubert !" _a : Optional[Any] =model(SCREAMING_SNAKE_CASE )[0] _a : List[str] =tf.TensorShape((1, 8, 5_1_2) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE ) # compare the actual values for a slice. _a : List[str] =tf.convert_to_tensor( [ [ [-1.8_768_773, -1.566_555, 0.27_072_418], [-1.6_920_038, -0.5_873_505, 1.9_329_599], [-2.9_563_985, -1.6_993_835, 1.7_972_052], ] ] , dtype=tf.floataa , ) self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1e-4 ) )
276
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A__: Dict = logging.get_logger(__name__) A__: Tuple = { '''weiweishi/roc-bert-base-zh''': '''https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json''', } class A__ ( UpperCAmelCase__ ): __UpperCamelCase : Tuple = "roc_bert" def __init__( self :Optional[int] , SCREAMING_SNAKE_CASE :Tuple=3_0_5_2_2 , SCREAMING_SNAKE_CASE :List[str]=7_6_8 , SCREAMING_SNAKE_CASE :Dict=1_2 , SCREAMING_SNAKE_CASE :List[str]=1_2 , SCREAMING_SNAKE_CASE :Tuple=3_0_7_2 , SCREAMING_SNAKE_CASE :List[Any]="gelu" , SCREAMING_SNAKE_CASE :Union[str, Any]=0.1 , SCREAMING_SNAKE_CASE :List[Any]=0.1 , SCREAMING_SNAKE_CASE :int=5_1_2 , SCREAMING_SNAKE_CASE :Optional[Any]=2 , SCREAMING_SNAKE_CASE :Union[str, Any]=0.02 , SCREAMING_SNAKE_CASE :Optional[Any]=1e-12 , SCREAMING_SNAKE_CASE :Any=True , SCREAMING_SNAKE_CASE :List[Any]=0 , SCREAMING_SNAKE_CASE :Optional[int]="absolute" , SCREAMING_SNAKE_CASE :Union[str, Any]=None , SCREAMING_SNAKE_CASE :List[Any]=True , SCREAMING_SNAKE_CASE :int=True , SCREAMING_SNAKE_CASE :Optional[int]=7_6_8 , SCREAMING_SNAKE_CASE :Optional[Any]=9_1_0 , SCREAMING_SNAKE_CASE :Union[str, Any]=5_1_2 , SCREAMING_SNAKE_CASE :str=2_4_8_5_8 , SCREAMING_SNAKE_CASE :List[Any]=True , **SCREAMING_SNAKE_CASE :Tuple , ) -> Optional[int]: '''simple docstring''' _a : List[str] =vocab_size _a : List[str] =max_position_embeddings _a : Optional[Any] =hidden_size _a : List[Any] =num_hidden_layers _a : List[str] =num_attention_heads _a : int =intermediate_size _a : Any =hidden_act _a : Dict =hidden_dropout_prob _a : int =attention_probs_dropout_prob _a : str =initializer_range _a : Optional[int] =type_vocab_size _a : Any =layer_norm_eps _a : Any =use_cache _a : Optional[int] =enable_pronunciation _a : Optional[Any] =enable_shape _a : Optional[Any] =pronunciation_embed_dim _a : Tuple =pronunciation_vocab_size _a : Union[str, Any] =shape_embed_dim _a : Any =shape_vocab_size _a : Tuple =concat_input _a : List[str] =position_embedding_type _a : List[str] =classifier_dropout super().__init__(pad_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE )
276
1
'''simple docstring''' # 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 ...utils import deprecate from ..controlnet.multicontrolnet import MultiControlNetModel # noqa: F401 from ..controlnet.pipeline_controlnet import StableDiffusionControlNetPipeline # noqa: F401 deprecate( '''stable diffusion controlnet''', '''0.22.0''', '''Importing `StableDiffusionControlNetPipeline` or `MultiControlNetModel` from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import StableDiffusionControlNetPipeline` instead.''', standard_warn=False, stacklevel=3, )
276
'''simple docstring''' class A__ : def __init__( self :List[str] ) -> List[Any]: '''simple docstring''' _a : Tuple =0 _a : Any =0 _a : int ={} def __UpperCAmelCase ( self :Any , SCREAMING_SNAKE_CASE :List[str] ) -> Optional[int]: '''simple docstring''' if vertex not in self.adjacency: _a : Dict ={} self.num_vertices += 1 def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Any ) -> List[str]: '''simple docstring''' self.add_vertex(SCREAMING_SNAKE_CASE ) self.add_vertex(SCREAMING_SNAKE_CASE ) if head == tail: return _a : Any =weight _a : Tuple =weight def __UpperCAmelCase ( self :Dict ) -> Optional[int]: '''simple docstring''' _a : Union[str, Any] =self.get_edges() for edge in edges: _a , _a , _a : List[str] =edge edges.remove((tail, head, weight) ) for i in range(len(SCREAMING_SNAKE_CASE ) ): _a : str =list(edges[i] ) edges.sort(key=lambda SCREAMING_SNAKE_CASE : e[2] ) for i in range(len(SCREAMING_SNAKE_CASE ) - 1 ): if edges[i][2] >= edges[i + 1][2]: _a : Union[str, Any] =edges[i][2] + 1 for edge in edges: _a , _a , _a : Tuple =edge _a : Tuple =weight _a : List[Any] =weight def __str__( self :int ) -> str: '''simple docstring''' _a : int ="""""" for tail in self.adjacency: for head in self.adjacency[tail]: _a : str =self.adjacency[head][tail] string += f"{head} -> {tail} == {weight}\n" return string.rstrip("""\n""" ) def __UpperCAmelCase ( self :Optional[int] ) -> Optional[Any]: '''simple docstring''' _a : Union[str, Any] =[] for tail in self.adjacency: for head in self.adjacency[tail]: output.append((tail, head, self.adjacency[head][tail]) ) return output def __UpperCAmelCase ( self :List[Any] ) -> List[Any]: '''simple docstring''' return self.adjacency.keys() @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :Dict=None , SCREAMING_SNAKE_CASE :List[Any]=None ) -> Optional[int]: '''simple docstring''' _a : str =Graph() if vertices is None: _a : Union[str, Any] =[] if edges is None: _a : List[Any] =[] for vertex in vertices: g.add_vertex(SCREAMING_SNAKE_CASE ) for edge in edges: g.add_edge(*SCREAMING_SNAKE_CASE ) return g class A__ : def __init__( self :Optional[int] ) -> Union[str, Any]: '''simple docstring''' _a : Optional[int] ={} _a : List[str] ={} def __len__( self :List[Any] ) -> List[Any]: '''simple docstring''' return len(self.parent ) def __UpperCAmelCase ( self :Tuple , SCREAMING_SNAKE_CASE :Tuple ) -> Dict: '''simple docstring''' if item in self.parent: return self.find(SCREAMING_SNAKE_CASE ) _a : Optional[Any] =item _a : List[str] =0 return item def __UpperCAmelCase ( self :int , SCREAMING_SNAKE_CASE :Dict ) -> List[str]: '''simple docstring''' if item not in self.parent: return self.make_set(SCREAMING_SNAKE_CASE ) if item != self.parent[item]: _a : str =self.find(self.parent[item] ) return self.parent[item] def __UpperCAmelCase ( self :Optional[int] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :List[Any] ) -> Optional[Any]: '''simple docstring''' _a : Optional[int] =self.find(SCREAMING_SNAKE_CASE ) _a : Dict =self.find(SCREAMING_SNAKE_CASE ) if roota == roota: return roota if self.rank[roota] > self.rank[roota]: _a : Any =roota return roota if self.rank[roota] < self.rank[roota]: _a : List[str] =roota return roota if self.rank[roota] == self.rank[roota]: self.rank[roota] += 1 _a : List[Any] =roota return roota return None @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :Dict ) -> Union[str, Any]: '''simple docstring''' _a : Any =graph.num_vertices _a : Union[str, Any] =Graph.UnionFind() _a : Optional[int] =[] while num_components > 1: _a : str ={} for vertex in graph.get_vertices(): _a : List[str] =-1 _a : Any =graph.get_edges() for edge in edges: _a , _a , _a : Tuple =edge edges.remove((tail, head, weight) ) for edge in edges: _a , _a , _a : Any =edge _a : Any =union_find.find(SCREAMING_SNAKE_CASE ) _a : List[Any] =union_find.find(SCREAMING_SNAKE_CASE ) if seta != seta: if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight: _a : Optional[int] =[head, tail, weight] if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight: _a : List[Any] =[head, tail, weight] for vertex in cheap_edge: if cheap_edge[vertex] != -1: _a , _a , _a : Optional[Any] =cheap_edge[vertex] if union_find.find(SCREAMING_SNAKE_CASE ) != union_find.find(SCREAMING_SNAKE_CASE ): union_find.union(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) mst_edges.append(cheap_edge[vertex] ) _a : str =num_components - 1 _a : str =Graph.build(edges=SCREAMING_SNAKE_CASE ) return mst
276
1
'''simple docstring''' def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : float ,_UpperCAmelCase : float ) -> float: return price * (1 + tax_rate) if __name__ == "__main__": print(F"{price_plus_tax(100, 0.25) = }") print(F"{price_plus_tax(125.50, 0.05) = }")
276
'''simple docstring''' from datetime import datetime import requests from bsa import BeautifulSoup if __name__ == "__main__": A__: Union[str, Any] = input('''Enter image url: ''').strip() print(F"Downloading image from {url} ...") A__: Tuple = BeautifulSoup(requests.get(url).content, '''html.parser''') # The image URL is in the content field of the first meta tag with property og:image A__: Union[str, Any] = soup.find('''meta''', {'''property''': '''og:image'''})['''content'''] A__: List[Any] = requests.get(image_url).content A__: List[str] = F"{datetime.now():%Y-%m-%d_%H:%M:%S}.jpg" with open(file_name, '''wb''') as fp: fp.write(image_data) print(F"Done. Image saved to disk as {file_name}.")
276
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) A__: str = { '''configuration_lxmert''': ['''LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''LxmertConfig'''], '''tokenization_lxmert''': ['''LxmertTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Optional[int] = ['''LxmertTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Dict = [ '''LxmertEncoder''', '''LxmertForPreTraining''', '''LxmertForQuestionAnswering''', '''LxmertModel''', '''LxmertPreTrainedModel''', '''LxmertVisualFeatureEncoder''', '''LxmertXLayer''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Optional[Any] = [ '''TF_LXMERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFLxmertForPreTraining''', '''TFLxmertMainLayer''', '''TFLxmertModel''', '''TFLxmertPreTrainedModel''', '''TFLxmertVisualFeatureEncoder''', ] if TYPE_CHECKING: from .configuration_lxmert import LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, LxmertConfig from .tokenization_lxmert import LxmertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_lxmert_fast import LxmertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_lxmert import ( LxmertEncoder, LxmertForPreTraining, LxmertForQuestionAnswering, LxmertModel, LxmertPreTrainedModel, LxmertVisualFeatureEncoder, LxmertXLayer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_lxmert import ( TF_LXMERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFLxmertForPreTraining, TFLxmertMainLayer, TFLxmertModel, TFLxmertPreTrainedModel, TFLxmertVisualFeatureEncoder, ) else: import sys A__: Optional[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
276
'''simple docstring''' A__: Tuple = ''' # Installazione di Transformers ! pip install transformers datasets # Per installare dalla fonte invece dell\'ultima versione rilasciata, commenta il comando sopra e # rimuovi la modalità commento al comando seguente. # ! pip install git+https://github.com/huggingface/transformers.git ''' A__: Tuple = [{'''type''': '''code''', '''content''': INSTALL_CONTENT}] A__: Any = { '''{processor_class}''': '''FakeProcessorClass''', '''{model_class}''': '''FakeModelClass''', '''{object_class}''': '''FakeObjectClass''', }
276
1
'''simple docstring''' from sklearn.metrics import matthews_corrcoef import datasets A__: Union[str, Any] = ''' Compute the Matthews correlation coefficient (MCC) The Matthews correlation coefficient is used in machine learning as a measure of the quality of binary and multiclass classifications. It takes into account true and false positives and negatives and is generally regarded as a balanced measure which can be used even if the classes are of very different sizes. The MCC is in essence a correlation coefficient value between -1 and +1. A coefficient of +1 represents a perfect prediction, 0 an average random prediction and -1 an inverse prediction. The statistic is also known as the phi coefficient. [source: Wikipedia] ''' A__: Optional[Any] = ''' Args: predictions (list of int): Predicted labels, as returned by a model. references (list of int): Ground truth labels. sample_weight (list of int, float, or bool): Sample weights. Defaults to `None`. Returns: matthews_correlation (dict containing float): Matthews correlation. Examples: Example 1, a basic example with only predictions and references as inputs: >>> matthews_metric = datasets.load_metric("matthews_correlation") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3]) >>> print(round(results[\'matthews_correlation\'], 2)) 0.54 Example 2, the same example as above, but also including sample weights: >>> matthews_metric = datasets.load_metric("matthews_correlation") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3], ... sample_weight=[0.5, 3, 1, 1, 1, 2]) >>> print(round(results[\'matthews_correlation\'], 2)) 0.1 Example 3, the same example as above, but with sample weights that cause a negative correlation: >>> matthews_metric = datasets.load_metric("matthews_correlation") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3], ... sample_weight=[0.5, 1, 0, 0, 0, 1]) >>> print(round(results[\'matthews_correlation\'], 2)) -0.25 ''' A__: Optional[Any] = '''\ @article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011} } ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A__ ( datasets.Metric ): def __UpperCAmelCase ( self :int ) -> List[Any]: '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""int32""" ), """references""": datasets.Value("""int32""" ), } ) , reference_urls=[ """https://scikit-learn.org/stable/modules/generated/sklearn.metrics.matthews_corrcoef.html""" ] , ) def __UpperCAmelCase ( self :Tuple , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :Union[str, Any]=None ) -> Tuple: '''simple docstring''' return { "matthews_correlation": float(matthews_corrcoef(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , sample_weight=SCREAMING_SNAKE_CASE ) ), }
276
'''simple docstring''' A__: Optional[int] = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] A__: Any = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] A__: int = { 0: '''Sunday''', 1: '''Monday''', 2: '''Tuesday''', 3: '''Wednesday''', 4: '''Thursday''', 5: '''Friday''', 6: '''Saturday''', } def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ,_UpperCAmelCase : int ,_UpperCAmelCase : int ) -> str: assert len(str(_UpperCAmelCase ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 12, "month should be between 1 to 12" assert 1 <= day <= 31, "day should be between 1 to 31" # Doomsday algorithm: _a : List[str] =year // 100 _a : List[str] =(5 * (century % 4) + 2) % 7 _a : Optional[int] =year % 100 _a : Any =centurian % 12 _a : int =( (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 _a : Optional[Any] =( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 400) == 0) else DOOMSDAY_LEAP[month - 1] ) _a : str =(dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
276
1
'''simple docstring''' A__: Union[str, Any] = '''Alexander Joslin''' import operator as op from .stack import Stack def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ) -> int: _a : Optional[int] ={"""*""": op.mul, """/""": op.truediv, """+""": op.add, """-""": op.sub} _a : Stack[int] =Stack() _a : Stack[str] =Stack() for i in equation: if i.isdigit(): # RULE 1 operand_stack.push(int(_UpperCAmelCase ) ) elif i in operators: # RULE 2 operator_stack.push(_UpperCAmelCase ) elif i == ")": # RULE 4 _a : Union[str, Any] =operator_stack.peek() operator_stack.pop() _a : int =operand_stack.peek() operand_stack.pop() _a : Union[str, Any] =operand_stack.peek() operand_stack.pop() _a : Any =operators[opr](_UpperCAmelCase ,_UpperCAmelCase ) operand_stack.push(_UpperCAmelCase ) # RULE 5 return operand_stack.peek() if __name__ == "__main__": A__: Dict = '''(5 + ((4 * 2) * (2 + 3)))''' # answer = 45 print(F"{equation} = {dijkstras_two_stack_algorithm(equation)}")
276
'''simple docstring''' from __future__ import annotations from typing import TypedDict class A__ ( UpperCAmelCase__ ): __UpperCamelCase : str __UpperCamelCase : int def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ) -> list[str]: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError("""The parameter s type must be str.""" ) return [s[i:] + s[:i] for i in range(len(_UpperCAmelCase ) )] def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ) -> BWTTransformDict: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError("""The parameter s type must be str.""" ) if not s: raise ValueError("""The parameter s must not be empty.""" ) _a : List[Any] =all_rotations(_UpperCAmelCase ) rotations.sort() # sort the list of rotations in alphabetically order # make a string composed of the last char of each rotation _a : BWTTransformDict ={ "bwt_string": "".join([word[-1] for word in rotations] ), "idx_original_string": rotations.index(_UpperCAmelCase ), } return response def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : int ) -> str: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError("""The parameter bwt_string type must be str.""" ) if not bwt_string: raise ValueError("""The parameter bwt_string must not be empty.""" ) try: _a : List[str] =int(_UpperCAmelCase ) except ValueError: raise TypeError( """The parameter idx_original_string type must be int or passive""" """ of cast to int.""" ) if idx_original_string < 0: raise ValueError("""The parameter idx_original_string must not be lower than 0.""" ) if idx_original_string >= len(_UpperCAmelCase ): raise ValueError( """The parameter idx_original_string must be lower than""" """ len(bwt_string).""" ) _a : Optional[int] =[""""""] * len(_UpperCAmelCase ) for _ in range(len(_UpperCAmelCase ) ): for i in range(len(_UpperCAmelCase ) ): _a : int =bwt_string[i] + ordered_rotations[i] ordered_rotations.sort() return ordered_rotations[idx_original_string] if __name__ == "__main__": A__: Any = '''Provide a string that I will generate its BWT transform: ''' A__: Union[str, Any] = input(entry_msg).strip() A__: Optional[int] = bwt_transform(s) print( F"Burrows Wheeler transform for string '{s}' results " F"in '{result['bwt_string']}'" ) A__: Union[str, Any] = reverse_bwt(result['''bwt_string'''], result['''idx_original_string''']) print( F"Reversing Burrows Wheeler transform for entry '{result['bwt_string']}' " F"we get original string '{original_string}'" )
276
1
'''simple docstring''' from __future__ import annotations import math import numpy as np from numpy.linalg import norm def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : np.ndarray ,_UpperCAmelCase : np.ndarray ) -> float: return math.sqrt(sum(pow(a - b ,2 ) for a, b in zip(_UpperCAmelCase ,_UpperCAmelCase ) ) ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : np.ndarray ,_UpperCAmelCase : np.ndarray ) -> list[list[list[float] | float]]: if dataset.ndim != value_array.ndim: _a : int =( """Wrong input data's dimensions... """ F"dataset : {dataset.ndim}, value_array : {value_array.ndim}" ) raise ValueError(_UpperCAmelCase ) try: if dataset.shape[1] != value_array.shape[1]: _a : Optional[Any] =( """Wrong input data's shape... """ F"dataset : {dataset.shape[1]}, value_array : {value_array.shape[1]}" ) raise ValueError(_UpperCAmelCase ) except IndexError: if dataset.ndim != value_array.ndim: raise TypeError("""Wrong shape""" ) if dataset.dtype != value_array.dtype: _a : Tuple =( """Input data have different datatype... """ F"dataset : {dataset.dtype}, value_array : {value_array.dtype}" ) raise TypeError(_UpperCAmelCase ) _a : Dict =[] for value in value_array: _a : Optional[int] =euclidean(_UpperCAmelCase ,dataset[0] ) _a : List[Any] =dataset[0].tolist() for dataset_value in dataset[1:]: _a : Any =euclidean(_UpperCAmelCase ,_UpperCAmelCase ) if dist > temp_dist: _a : Any =temp_dist _a : int =dataset_value.tolist() answer.append([vector, dist] ) return answer def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : np.ndarray ,_UpperCAmelCase : np.ndarray ) -> float: return np.dot(_UpperCAmelCase ,_UpperCAmelCase ) / (norm(_UpperCAmelCase ) * norm(_UpperCAmelCase )) if __name__ == "__main__": import doctest doctest.testmod()
276
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available A__: List[str] = { '''configuration_chinese_clip''': [ '''CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ChineseCLIPConfig''', '''ChineseCLIPOnnxConfig''', '''ChineseCLIPTextConfig''', '''ChineseCLIPVisionConfig''', ], '''processing_chinese_clip''': ['''ChineseCLIPProcessor'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Optional[int] = ['''ChineseCLIPFeatureExtractor'''] A__: Any = ['''ChineseCLIPImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Dict = [ '''CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ChineseCLIPModel''', '''ChineseCLIPPreTrainedModel''', '''ChineseCLIPTextModel''', '''ChineseCLIPVisionModel''', ] if TYPE_CHECKING: from .configuration_chinese_clip import ( CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, ChineseCLIPConfig, ChineseCLIPOnnxConfig, ChineseCLIPTextConfig, ChineseCLIPVisionConfig, ) from .processing_chinese_clip import ChineseCLIPProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_chinese_clip import ChineseCLIPFeatureExtractor, ChineseCLIPImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_chinese_clip import ( CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, ChineseCLIPModel, ChineseCLIPPreTrainedModel, ChineseCLIPTextModel, ChineseCLIPVisionModel, ) else: import sys A__: str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
276
1
'''simple docstring''' import json import os import unittest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class A__ ( UpperCAmelCase__ , unittest.TestCase ): __UpperCamelCase : int = CLIPTokenizer __UpperCamelCase : Dict = CLIPTokenizerFast __UpperCamelCase : List[str] = True __UpperCamelCase : Optional[Any] = {} __UpperCamelCase : str = False def __UpperCAmelCase ( self :Union[str, Any] ) -> str: '''simple docstring''' super().setUp() # fmt: off _a : Optional[Any] =["""l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """lo""", """l</w>""", """w</w>""", """r</w>""", """t</w>""", """low</w>""", """er</w>""", """lowest</w>""", """newer</w>""", """wider""", """<unk>""", """<|startoftext|>""", """<|endoftext|>"""] # fmt: on _a : List[Any] =dict(zip(SCREAMING_SNAKE_CASE , range(len(SCREAMING_SNAKE_CASE ) ) ) ) _a : List[Any] =["""#version: 0.2""", """l o""", """lo w</w>""", """e r</w>"""] _a : Dict ={"""unk_token""": """<unk>"""} _a : List[str] =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) _a : Optional[int] =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(SCREAMING_SNAKE_CASE ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(SCREAMING_SNAKE_CASE ) ) def __UpperCAmelCase ( self :List[Any] , **SCREAMING_SNAKE_CASE :Optional[int] ) -> Dict: '''simple docstring''' kwargs.update(self.special_tokens_map ) return CLIPTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Any , **SCREAMING_SNAKE_CASE :Optional[Any] ) -> Optional[int]: '''simple docstring''' kwargs.update(self.special_tokens_map ) return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :str ) -> int: '''simple docstring''' _a : int ="""lower newer""" _a : List[str] ="""lower newer""" return input_text, output_text def __UpperCAmelCase ( self :str ) -> List[str]: '''simple docstring''' _a : Any =CLIPTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) _a : Dict ="""lower newer""" _a : str =["""lo""", """w""", """er</w>""", """n""", """e""", """w""", """er</w>"""] _a : int =tokenizer.tokenize(SCREAMING_SNAKE_CASE ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) _a : List[str] =tokens + [tokenizer.unk_token] _a : Optional[Any] =[1_0, 2, 1_6, 9, 3, 2, 1_6, 2_0] self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE ) @require_ftfy def __UpperCAmelCase ( self :Optional[int] ) -> Optional[Any]: '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})" ): _a : List[str] =self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) _a : Tuple =self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) _a : Union[str, Any] ="""A\n'll 11p223RF☆ho!!to?'d'd''d of a cat to-$''d.""" _a : List[str] =tokenizer_s.tokenize(SCREAMING_SNAKE_CASE ) _a : List[Any] =tokenizer_r.tokenize(SCREAMING_SNAKE_CASE ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # Test that the tokenization is identical on an example containing a character (Latin Small Letter A # with Tilde) encoded in 2 different ways _a : int ="""xa\u0303y""" + """ """ + """x\xe3y""" _a : Tuple =tokenizer_s.tokenize(SCREAMING_SNAKE_CASE ) _a : str =tokenizer_r.tokenize(SCREAMING_SNAKE_CASE ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # Test that the tokenization is identical on unicode of space type _a : Tuple =[ """\u0009""", # (horizontal tab, '\t') """\u000B""", # (vertical tab) """\u000C""", # (form feed) """\u0020""", # (space, ' ') """\u200E""", # (left-to-right mark):w """\u200F""", # (right-to-left mark) ] for unicode_seq in spaces_unicodes: _a : List[Any] =tokenizer_s.tokenize(SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =tokenizer_r.tokenize(SCREAMING_SNAKE_CASE ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # Test that the tokenization is identical on unicode of line break type _a : int =[ """\u000A""", # (line feed, '\n') """\r\n""", # (carriage return and line feed, '\r\n') """\u000D""", # (carriage return, '\r') """\r""", # (carriage return, '\r') """\u000D""", # (carriage return, '\r') """\u2028""", # (line separator) """\u2029""", # (paragraph separator) # "\u0085", # (next line) ] # The tokenization is not identical for the character "\u0085" (next line). The slow version using ftfy transforms # it into the Horizontal Ellipsis character "…" ("\u2026") while the fast version transforms it into a # space (and thus into an empty list). for unicode_seq in line_break_unicodes: _a : int =tokenizer_s.tokenize(SCREAMING_SNAKE_CASE ) _a : List[str] =tokenizer_r.tokenize(SCREAMING_SNAKE_CASE ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :List[str] ) -> Any: '''simple docstring''' # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})" ): _a : int ="""hello""" # `hello` is a token in the vocabulary of `pretrained_name` _a : Any =f"{text_of_1_token} {text_of_1_token}" _a : str =self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE , use_fast=SCREAMING_SNAKE_CASE , ) _a : Union[str, Any] =tokenizer_r(SCREAMING_SNAKE_CASE , return_offsets_mapping=SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE ) self.assertEqual(encoding.offset_mapping[0] , (0, len(SCREAMING_SNAKE_CASE )) ) self.assertEqual( encoding.offset_mapping[1] , (len(SCREAMING_SNAKE_CASE ) + 1, len(SCREAMING_SNAKE_CASE ) + 1 + len(SCREAMING_SNAKE_CASE )) , ) _a : Union[str, Any] =f" {text}" _a : int =self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE , use_fast=SCREAMING_SNAKE_CASE , ) _a : int =tokenizer_r(SCREAMING_SNAKE_CASE , return_offsets_mapping=SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(SCREAMING_SNAKE_CASE )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(SCREAMING_SNAKE_CASE ) + 1, 1 + len(SCREAMING_SNAKE_CASE ) + 1 + len(SCREAMING_SNAKE_CASE )) , ) def __UpperCAmelCase ( self :List[str] ) -> str: '''simple docstring''' # Test related to the breaking change introduced in transformers v4.17.0 # We need to check that an error in raised when the user try to load a previous version of the tokenizer. with self.assertRaises(SCREAMING_SNAKE_CASE ) as context: self.rust_tokenizer_class.from_pretrained("""robot-test/old-clip-tokenizer""" ) self.assertTrue( context.exception.args[0].startswith( """The `backend_tokenizer` provided does not match the expected format.""" ) ) @require_ftfy def __UpperCAmelCase ( self :int ) -> Dict: '''simple docstring''' super().test_tokenization_python_rust_equals() def __UpperCAmelCase ( self :Optional[int] ) -> Optional[int]: '''simple docstring''' # CLIP always lower cases letters pass
276
'''simple docstring''' class A__ : def __init__( self :List[Any] ) -> None: '''simple docstring''' _a : dict[str, TrieNode] ={} # Mapping from char to TrieNode _a : List[str] =False def __UpperCAmelCase ( self :Tuple , SCREAMING_SNAKE_CASE :list[str] ) -> None: '''simple docstring''' for word in words: self.insert(SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :str ) -> None: '''simple docstring''' _a : str =self for char in word: if char not in curr.nodes: _a : Dict =TrieNode() _a : List[Any] =curr.nodes[char] _a : int =True def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :str ) -> bool: '''simple docstring''' _a : int =self for char in word: if char not in curr.nodes: return False _a : List[Any] =curr.nodes[char] return curr.is_leaf def __UpperCAmelCase ( self :Dict , SCREAMING_SNAKE_CASE :str ) -> None: '''simple docstring''' def _delete(SCREAMING_SNAKE_CASE :TrieNode , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :int ) -> bool: if index == len(SCREAMING_SNAKE_CASE ): # If word does not exist if not curr.is_leaf: return False _a : Any =False return len(curr.nodes ) == 0 _a : int =word[index] _a : int =curr.nodes.get(SCREAMING_SNAKE_CASE ) # If char not in current trie node if not char_node: return False # Flag to check if node can be deleted _a : List[Any] =_delete(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , index + 1 ) if delete_curr: del curr.nodes[char] return len(curr.nodes ) == 0 return delete_curr _delete(self , SCREAMING_SNAKE_CASE , 0 ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : TrieNode ,_UpperCAmelCase : str ) -> None: if node.is_leaf: print(_UpperCAmelCase ,end=""" """ ) for key, value in node.nodes.items(): print_words(_UpperCAmelCase ,word + key ) def SCREAMING_SNAKE_CASE_ ( ) -> bool: _a : List[str] ="""banana bananas bandana band apple all beast""".split() _a : List[Any] =TrieNode() root.insert_many(_UpperCAmelCase ) # print_words(root, "") assert all(root.find(_UpperCAmelCase ) for word in words ) assert root.find("""banana""" ) assert not root.find("""bandanas""" ) assert not root.find("""apps""" ) assert root.find("""apple""" ) assert root.find("""all""" ) root.delete("""all""" ) assert not root.find("""all""" ) root.delete("""banana""" ) assert not root.find("""banana""" ) assert root.find("""bananas""" ) return True def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : bool ) -> None: print(str(_UpperCAmelCase ) ,"""works!""" if passes else """doesn't work :(""" ) def SCREAMING_SNAKE_CASE_ ( ) -> None: assert test_trie() def SCREAMING_SNAKE_CASE_ ( ) -> None: print_results("""Testing trie functionality""" ,test_trie() ) if __name__ == "__main__": main()
276
1
'''simple docstring''' import argparse import os import re import packaging.version A__: Optional[Any] = '''examples/''' A__: Optional[Any] = { '''examples''': (re.compile(R'''^check_min_version\("[^"]+"\)\s*$''', re.MULTILINE), '''check_min_version("VERSION")\n'''), '''init''': (re.compile(R'''^__version__\s+=\s+"([^"]+)"\s*$''', re.MULTILINE), '''__version__ = "VERSION"\n'''), '''setup''': (re.compile(R'''^(\s*)version\s*=\s*"[^"]+",''', re.MULTILINE), R'''\1version="VERSION",'''), '''doc''': (re.compile(R'''^(\s*)release\s*=\s*"[^"]+"$''', re.MULTILINE), '''release = "VERSION"\n'''), } A__: Optional[int] = { '''init''': '''src/diffusers/__init__.py''', '''setup''': '''setup.py''', } A__: int = '''README.md''' def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[Any] ,_UpperCAmelCase : Dict ,_UpperCAmelCase : Any ) -> Tuple: with open(_UpperCAmelCase ,"""r""" ,encoding="""utf-8""" ,newline="""\n""" ) as f: _a : Any =f.read() _a , _a : Any =REPLACE_PATTERNS[pattern] _a : List[Any] =replace.replace("""VERSION""" ,_UpperCAmelCase ) _a : str =re_pattern.sub(_UpperCAmelCase ,_UpperCAmelCase ) with open(_UpperCAmelCase ,"""w""" ,encoding="""utf-8""" ,newline="""\n""" ) as f: f.write(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ) -> Tuple: for folder, directories, fnames in os.walk(_UpperCAmelCase ): # Removing some of the folders with non-actively maintained examples from the walk if "research_projects" in directories: directories.remove("""research_projects""" ) if "legacy" in directories: directories.remove("""legacy""" ) for fname in fnames: if fname.endswith(""".py""" ): update_version_in_file(os.path.join(_UpperCAmelCase ,_UpperCAmelCase ) ,_UpperCAmelCase ,pattern="""examples""" ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ,_UpperCAmelCase : Optional[int]=False ) -> List[Any]: for pattern, fname in REPLACE_FILES.items(): update_version_in_file(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) if not patch: update_version_in_examples(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( ) -> Any: _a : List[Any] ="""🤗 Transformers currently provides the following architectures""" _a : str ="""1. Want to contribute a new model?""" with open(_UpperCAmelCase ,"""r""" ,encoding="""utf-8""" ,newline="""\n""" ) as f: _a : str =f.readlines() # Find the start of the list. _a : Union[str, Any] =0 while not lines[start_index].startswith(_start_prompt ): start_index += 1 start_index += 1 _a : Dict =start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt ): if lines[index].startswith("""1.""" ): _a : Optional[int] =lines[index].replace( """https://huggingface.co/docs/diffusers/main/model_doc""" ,"""https://huggingface.co/docs/diffusers/model_doc""" ,) index += 1 with open(_UpperCAmelCase ,"""w""" ,encoding="""utf-8""" ,newline="""\n""" ) as f: f.writelines(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( ) -> List[Any]: with open(REPLACE_FILES["""init"""] ,"""r""" ) as f: _a : List[str] =f.read() _a : Dict =REPLACE_PATTERNS["""init"""][0].search(_UpperCAmelCase ).groups()[0] return packaging.version.parse(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Tuple=False ) -> str: _a : Optional[int] =get_version() if patch and default_version.is_devrelease: raise ValueError("""Can't create a patch version from the dev branch, checkout a released version!""" ) if default_version.is_devrelease: _a : Union[str, Any] =default_version.base_version elif patch: _a : str =F"{default_version.major}.{default_version.minor}.{default_version.micro + 1}" else: _a : Optional[int] =F"{default_version.major}.{default_version.minor + 1}.0" # Now let's ask nicely if that's the right one. _a : Dict =input(F"Which version are you releasing? [{default_version}]" ) if len(_UpperCAmelCase ) == 0: _a : Optional[int] =default_version print(F"Updating version to {version}." ) global_version_update(_UpperCAmelCase ,patch=_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( ) -> Optional[int]: _a : Dict =get_version() _a : Any =F"{current_version.major}.{current_version.minor + 1}.0.dev0" _a : int =current_version.base_version # Check with the user we got that right. _a : List[Any] =input(F"Which version are we developing now? [{dev_version}]" ) if len(_UpperCAmelCase ) == 0: _a : Tuple =dev_version print(F"Updating version to {version}." ) global_version_update(_UpperCAmelCase ) # print("Cleaning main README, don't forget to run `make fix-copies`.") # clean_main_ref_in_model_list() if __name__ == "__main__": A__: int = argparse.ArgumentParser() parser.add_argument('''--post_release''', action='''store_true''', help='''Whether this is pre or post release.''') parser.add_argument('''--patch''', action='''store_true''', help='''Whether or not this is a patch release.''') A__: Tuple = parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print('''Nothing to do after a patch :-)''') else: post_release_work()
276
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available A__: str = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Tuple = ['''GPTSw3Tokenizer'''] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_swa import GPTSwaTokenizer else: import sys A__: str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
276
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A__: List[Any] = {'''configuration_sew''': ['''SEW_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''SEWConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: str = [ '''SEW_PRETRAINED_MODEL_ARCHIVE_LIST''', '''SEWForCTC''', '''SEWForSequenceClassification''', '''SEWModel''', '''SEWPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_sew import SEW_PRETRAINED_CONFIG_ARCHIVE_MAP, SEWConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_sew import ( SEW_PRETRAINED_MODEL_ARCHIVE_LIST, SEWForCTC, SEWForSequenceClassification, SEWModel, SEWPreTrainedModel, ) else: import sys A__: Optional[int] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
276
'''simple docstring''' import importlib.metadata import warnings from copy import deepcopy from packaging import version from ..utils import logging from .import_utils import is_accelerate_available, is_bitsandbytes_available if is_bitsandbytes_available(): import bitsandbytes as bnb import torch import torch.nn as nn from ..pytorch_utils import ConvaD if is_accelerate_available(): from accelerate import init_empty_weights from accelerate.utils import find_tied_parameters A__: str = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[Any] ,_UpperCAmelCase : List[str] ,_UpperCAmelCase : int ,_UpperCAmelCase : int=None ,_UpperCAmelCase : Optional[Any]=None ) -> Optional[Any]: # Recurse if needed if "." in tensor_name: _a : Union[str, Any] =tensor_name.split(""".""" ) for split in splits[:-1]: _a : Optional[Any] =getattr(_UpperCAmelCase ,_UpperCAmelCase ) if new_module is None: raise ValueError(F"{module} has no attribute {split}." ) _a : Optional[int] =new_module _a : Optional[int] =splits[-1] if tensor_name not in module._parameters and tensor_name not in module._buffers: raise ValueError(F"{module} does not have a parameter or a buffer named {tensor_name}." ) _a : Optional[Any] =tensor_name in module._buffers _a : str =getattr(_UpperCAmelCase ,_UpperCAmelCase ) if old_value.device == torch.device("""meta""" ) and device not in ["meta", torch.device("""meta""" )] and value is None: raise ValueError(F"{tensor_name} is on the meta device, we need a `value` to put in on {device}." ) _a : int =False _a : Tuple =False if is_buffer or not is_bitsandbytes_available(): _a : str =False _a : Optional[Any] =False else: _a : int =hasattr(bnb.nn ,"""Params4bit""" ) and isinstance(module._parameters[tensor_name] ,bnb.nn.Paramsabit ) _a : int =isinstance(module._parameters[tensor_name] ,bnb.nn.IntaParams ) if is_abit or is_abit: _a : Any =module._parameters[tensor_name] if param.device.type != "cuda": if value is None: _a : int =old_value.to(_UpperCAmelCase ) elif isinstance(_UpperCAmelCase ,torch.Tensor ): _a : str =value.to("""cpu""" ) if value.dtype == torch.inta: _a : int =version.parse(importlib.metadata.version("""bitsandbytes""" ) ) > version.parse( """0.37.2""" ) if not is_abit_serializable: raise ValueError( """Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. """ """Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`.""" ) else: _a : Dict =torch.tensor(_UpperCAmelCase ,device="""cpu""" ) # Support models using `Conv1D` in place of `nn.Linear` (e.g. gpt2) by transposing the weight matrix prior to quantization. # Since weights are saved in the correct "orientation", we skip transposing when loading. if issubclass(module.source_cls ,_UpperCAmelCase ) and fpaa_statistics is None: _a : int =new_value.T _a : Any =old_value.__dict__ if is_abit: _a : Any =bnb.nn.IntaParams(_UpperCAmelCase ,requires_grad=_UpperCAmelCase ,**_UpperCAmelCase ).to(_UpperCAmelCase ) elif is_abit: _a : Union[str, Any] =bnb.nn.Paramsabit(_UpperCAmelCase ,requires_grad=_UpperCAmelCase ,**_UpperCAmelCase ).to(_UpperCAmelCase ) _a : List[Any] =new_value if fpaa_statistics is not None: setattr(module.weight ,"""SCB""" ,fpaa_statistics.to(_UpperCAmelCase ) ) else: if value is None: _a : str =old_value.to(_UpperCAmelCase ) elif isinstance(_UpperCAmelCase ,torch.Tensor ): _a : Any =value.to(_UpperCAmelCase ) else: _a : str =torch.tensor(_UpperCAmelCase ,device=_UpperCAmelCase ) if is_buffer: _a : Optional[int] =new_value else: _a : Optional[Any] =nn.Parameter(_UpperCAmelCase ,requires_grad=old_value.requires_grad ) _a : Tuple =new_value def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : Union[str, Any]=None ,_UpperCAmelCase : List[Any]=None ,_UpperCAmelCase : str=None ,_UpperCAmelCase : Union[str, Any]=False ) -> Dict: for name, module in model.named_children(): if current_key_name is None: _a : Optional[int] =[] current_key_name.append(_UpperCAmelCase ) if (isinstance(_UpperCAmelCase ,nn.Linear ) or isinstance(_UpperCAmelCase ,_UpperCAmelCase )) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` if not any(key in """.""".join(_UpperCAmelCase ) for key in modules_to_not_convert ): with init_empty_weights(): if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): _a , _a : int =module.weight.shape else: _a : List[str] =module.in_features _a : Tuple =module.out_features if quantization_config.quantization_method() == "llm_int8": _a : Optional[Any] =bnb.nn.LinearabitLt( _UpperCAmelCase ,_UpperCAmelCase ,module.bias is not None ,has_fpaa_weights=quantization_config.llm_inta_has_fpaa_weight ,threshold=quantization_config.llm_inta_threshold ,) _a : Optional[Any] =True else: if ( quantization_config.llm_inta_skip_modules is not None and name in quantization_config.llm_inta_skip_modules ): pass else: _a : Dict =bnb.nn.Linearabit( _UpperCAmelCase ,_UpperCAmelCase ,module.bias is not None ,quantization_config.bnb_abit_compute_dtype ,compress_statistics=quantization_config.bnb_abit_use_double_quant ,quant_type=quantization_config.bnb_abit_quant_type ,) _a : List[Any] =True # Store the module class in case we need to transpose the weight later _a : int =type(_UpperCAmelCase ) # Force requires grad to False to avoid unexpected errors model._modules[name].requires_grad_(_UpperCAmelCase ) if len(list(module.children() ) ) > 0: _a , _a : List[Any] =_replace_with_bnb_linear( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,has_been_replaced=_UpperCAmelCase ,) # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : int=None ,_UpperCAmelCase : Union[str, Any]=None ,_UpperCAmelCase : Any=None ) -> Tuple: _a : Dict =["""lm_head"""] if modules_to_not_convert is None else modules_to_not_convert _a , _a : List[Any] =_replace_with_bnb_linear( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) 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.""" """ Please double check your model architecture, or submit an issue on github if you think this is""" """ a bug.""" ) return model def SCREAMING_SNAKE_CASE_ ( *_UpperCAmelCase : Any ,**_UpperCAmelCase : Any ) -> str: warnings.warn( """`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead""" ,_UpperCAmelCase ,) return replace_with_bnb_linear(*_UpperCAmelCase ,**_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( *_UpperCAmelCase : str ,**_UpperCAmelCase : Optional[int] ) -> Optional[int]: warnings.warn( """`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead""" ,_UpperCAmelCase ,) return set_module_quantized_tensor_to_device(*_UpperCAmelCase ,**_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ) -> Union[str, Any]: _a : Any =deepcopy(_UpperCAmelCase ) # this has 0 cost since it is done inside `init_empty_weights` context manager` tied_model.tie_weights() _a : List[Any] =find_tied_parameters(_UpperCAmelCase ) # For compatibility with Accelerate < 0.18 if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): _a : str =sum(list(tied_params.values() ) ,[] ) + list(tied_params.keys() ) else: _a : Optional[int] =sum(_UpperCAmelCase ,[] ) _a : List[Any] =len(_UpperCAmelCase ) > 0 # Check if it is a base model _a : Tuple =not hasattr(_UpperCAmelCase ,model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head _a : List[Any] =list(model.named_children() ) _a : Dict =[list_modules[-1][0]] # add last module together with tied weights _a : List[str] =set(_UpperCAmelCase ) - set(_UpperCAmelCase ) _a : str =list(set(_UpperCAmelCase ) ) + list(_UpperCAmelCase ) # remove ".weight" from the keys _a : List[Any] =[""".weight""", """.bias"""] _a : Any =[] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: _a : Any =name.replace(_UpperCAmelCase ,"""""" ) filtered_module_names.append(_UpperCAmelCase ) return filtered_module_names
276
1
'''simple docstring''' # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.test_utils import execute_subprocess_async def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Union[str, Any]=None ) -> List[str]: if subparsers is not None: _a : Optional[int] =subparsers.add_parser("""test""" ) else: _a : Union[str, Any] =argparse.ArgumentParser("""Accelerate test command""" ) parser.add_argument( """--config_file""" ,default=_UpperCAmelCase ,help=( """The path to use to store the config file. Will default to a file named default_config.yaml in the cache """ """location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have """ """such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed """ """with 'huggingface'.""" ) ,) if subparsers is not None: parser.set_defaults(func=_UpperCAmelCase ) return parser def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Any ) -> Dict: _a : Any =os.path.sep.join(__file__.split(os.path.sep )[:-2] + ["""test_utils""", """scripts""", """test_script.py"""] ) if args.config_file is None: _a : List[str] =script_name else: _a : Dict =F"--config_file={args.config_file} {script_name}" _a : int =["""accelerate-launch"""] + test_args.split() _a : int =execute_subprocess_async(_UpperCAmelCase ,env=os.environ.copy() ) if result.returncode == 0: print("""Test is a success! You are ready for your distributed training!""" ) def SCREAMING_SNAKE_CASE_ ( ) -> Any: _a : Optional[int] =test_command_parser() _a : Tuple =parser.parse_args() test_command(_UpperCAmelCase ) if __name__ == "__main__": main()
276
'''simple docstring''' import logging import os from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union from filelock import FileLock from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available A__: int = logging.getLogger(__name__) @dataclass class A__ : __UpperCamelCase : str __UpperCamelCase : List[str] __UpperCamelCase : Optional[List[str]] @dataclass class A__ : __UpperCamelCase : List[int] __UpperCamelCase : List[int] __UpperCamelCase : Optional[List[int]] = None __UpperCamelCase : Optional[List[int]] = None class A__ ( UpperCAmelCase__ ): __UpperCamelCase : str = "train" __UpperCamelCase : Tuple = "dev" __UpperCamelCase : str = "test" class A__ : @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :Union[Split, str] ) -> List[InputExample]: '''simple docstring''' raise NotImplementedError @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :str ) -> List[str]: '''simple docstring''' raise NotImplementedError @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :List[InputExample] , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :PreTrainedTokenizer , SCREAMING_SNAKE_CASE :str=False , SCREAMING_SNAKE_CASE :Optional[Any]="[CLS]" , SCREAMING_SNAKE_CASE :Optional[int]=1 , SCREAMING_SNAKE_CASE :Any="[SEP]" , SCREAMING_SNAKE_CASE :List[Any]=False , SCREAMING_SNAKE_CASE :Union[str, Any]=False , SCREAMING_SNAKE_CASE :List[str]=0 , SCREAMING_SNAKE_CASE :str=0 , SCREAMING_SNAKE_CASE :Dict=-1_0_0 , SCREAMING_SNAKE_CASE :Optional[int]=0 , SCREAMING_SNAKE_CASE :Tuple=True , ) -> List[InputFeatures]: '''simple docstring''' _a : str ={label: i for i, label in enumerate(SCREAMING_SNAKE_CASE )} _a : Tuple =[] for ex_index, example in enumerate(SCREAMING_SNAKE_CASE ): if ex_index % 1_0_0_0_0 == 0: logger.info("""Writing example %d of %d""" , SCREAMING_SNAKE_CASE , len(SCREAMING_SNAKE_CASE ) ) _a : Optional[Any] =[] _a : List[Any] =[] for word, label in zip(example.words , example.labels ): _a : Optional[int] =tokenizer.tokenize(SCREAMING_SNAKE_CASE ) # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space. if len(SCREAMING_SNAKE_CASE ) > 0: tokens.extend(SCREAMING_SNAKE_CASE ) # Use the real label id for the first token of the word, and padding ids for the remaining tokens label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(SCREAMING_SNAKE_CASE ) - 1) ) # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa. _a : Optional[int] =tokenizer.num_special_tokens_to_add() if len(SCREAMING_SNAKE_CASE ) > max_seq_length - special_tokens_count: _a : List[Any] =tokens[: (max_seq_length - special_tokens_count)] _a : Tuple =label_ids[: (max_seq_length - special_tokens_count)] # The convention in BERT is: # (a) For sequence pairs: # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP] # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1 # (b) For single sequences: # tokens: [CLS] the dog is hairy . [SEP] # type_ids: 0 0 0 0 0 0 0 # # Where "type_ids" are used to indicate whether this is the first # sequence or the second sequence. The embedding vectors for `type=0` and # `type=1` were learned during pre-training and are added to the wordpiece # embedding vector (and position vector). This is not *strictly* necessary # since the [SEP] token unambiguously separates the sequences, but it makes # it easier for the model to learn the concept of sequences. # # For classification tasks, the first vector (corresponding to [CLS]) is # used as the "sentence vector". Note that this only makes sense because # the entire model is fine-tuned. tokens += [sep_token] label_ids += [pad_token_label_id] if sep_token_extra: # roberta uses an extra separator b/w pairs of sentences tokens += [sep_token] label_ids += [pad_token_label_id] _a : Dict =[sequence_a_segment_id] * len(SCREAMING_SNAKE_CASE ) if cls_token_at_end: tokens += [cls_token] label_ids += [pad_token_label_id] segment_ids += [cls_token_segment_id] else: _a : Any =[cls_token] + tokens _a : Dict =[pad_token_label_id] + label_ids _a : Union[str, Any] =[cls_token_segment_id] + segment_ids _a : List[str] =tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE ) # The mask has 1 for real tokens and 0 for padding tokens. Only real # tokens are attended to. _a : Optional[int] =[1 if mask_padding_with_zero else 0] * len(SCREAMING_SNAKE_CASE ) # Zero-pad up to the sequence length. _a : Union[str, Any] =max_seq_length - len(SCREAMING_SNAKE_CASE ) if pad_on_left: _a : Optional[Any] =([pad_token] * padding_length) + input_ids _a : Optional[int] =([0 if mask_padding_with_zero else 1] * padding_length) + input_mask _a : Union[str, Any] =([pad_token_segment_id] * padding_length) + segment_ids _a : Dict =([pad_token_label_id] * padding_length) + label_ids else: input_ids += [pad_token] * padding_length input_mask += [0 if mask_padding_with_zero else 1] * padding_length segment_ids += [pad_token_segment_id] * padding_length label_ids += [pad_token_label_id] * padding_length assert len(SCREAMING_SNAKE_CASE ) == max_seq_length assert len(SCREAMING_SNAKE_CASE ) == max_seq_length assert len(SCREAMING_SNAKE_CASE ) == max_seq_length assert len(SCREAMING_SNAKE_CASE ) == max_seq_length if ex_index < 5: logger.info("""*** Example ***""" ) logger.info("""guid: %s""" , example.guid ) logger.info("""tokens: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in tokens] ) ) logger.info("""input_ids: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in input_ids] ) ) logger.info("""input_mask: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in input_mask] ) ) logger.info("""segment_ids: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in segment_ids] ) ) logger.info("""label_ids: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in label_ids] ) ) if "token_type_ids" not in tokenizer.model_input_names: _a : Tuple =None features.append( InputFeatures( input_ids=SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , token_type_ids=SCREAMING_SNAKE_CASE , label_ids=SCREAMING_SNAKE_CASE ) ) return features if is_torch_available(): import torch from torch import nn from torch.utils.data import Dataset class A__ ( UpperCAmelCase__ ): __UpperCamelCase : List[InputFeatures] __UpperCamelCase : int = nn.CrossEntropyLoss().ignore_index def __init__( self :Dict , SCREAMING_SNAKE_CASE :TokenClassificationTask , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :PreTrainedTokenizer , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Optional[int] = None , SCREAMING_SNAKE_CASE :int=False , SCREAMING_SNAKE_CASE :Split = Split.train , ) -> List[str]: '''simple docstring''' # Load data features from cache or dataset file _a : Optional[Any] =os.path.join( SCREAMING_SNAKE_CASE , """cached_{}_{}_{}""".format(mode.value , tokenizer.__class__.__name__ , str(SCREAMING_SNAKE_CASE ) ) , ) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. _a : List[str] =cached_features_file + """.lock""" with FileLock(SCREAMING_SNAKE_CASE ): if os.path.exists(SCREAMING_SNAKE_CASE ) and not overwrite_cache: logger.info(f"Loading features from cached file {cached_features_file}" ) _a : Any =torch.load(SCREAMING_SNAKE_CASE ) else: logger.info(f"Creating features from dataset file at {data_dir}" ) _a : Any =token_classification_task.read_examples_from_file(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # TODO clean up all this to leverage built-in features of tokenizers _a : List[str] =token_classification_task.convert_examples_to_features( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , cls_token_at_end=bool(model_type in ["""xlnet"""] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ["""xlnet"""] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=SCREAMING_SNAKE_CASE , pad_on_left=bool(tokenizer.padding_side == """left""" ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info(f"Saving features into cached file {cached_features_file}" ) torch.save(self.features , SCREAMING_SNAKE_CASE ) def __len__( self :Optional[int] ) -> Union[str, Any]: '''simple docstring''' return len(self.features ) def __getitem__( self :Dict , SCREAMING_SNAKE_CASE :int ) -> InputFeatures: '''simple docstring''' return self.features[i] if is_tf_available(): import tensorflow as tf class A__ : __UpperCamelCase : List[InputFeatures] __UpperCamelCase : int = -100 def __init__( self :str , SCREAMING_SNAKE_CASE :TokenClassificationTask , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :PreTrainedTokenizer , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Optional[int] = None , SCREAMING_SNAKE_CASE :str=False , SCREAMING_SNAKE_CASE :Split = Split.train , ) -> Any: '''simple docstring''' _a : Tuple =token_classification_task.read_examples_from_file(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # TODO clean up all this to leverage built-in features of tokenizers _a : List[Any] =token_classification_task.convert_examples_to_features( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , cls_token_at_end=bool(model_type in ["""xlnet"""] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ["""xlnet"""] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=SCREAMING_SNAKE_CASE , pad_on_left=bool(tokenizer.padding_side == """left""" ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) def gen(): for ex in self.features: if ex.token_type_ids is None: yield ( {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask}, ex.label_ids, ) else: yield ( { "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label_ids, ) if "token_type_ids" not in tokenizer.model_input_names: _a : Union[str, Any] =tf.data.Dataset.from_generator( SCREAMING_SNAKE_CASE , ({"""input_ids""": tf.intaa, """attention_mask""": tf.intaa}, tf.intaa) , ( {"""input_ids""": tf.TensorShape([None] ), """attention_mask""": tf.TensorShape([None] )}, tf.TensorShape([None] ), ) , ) else: _a : Union[str, Any] =tf.data.Dataset.from_generator( SCREAMING_SNAKE_CASE , ({"""input_ids""": tf.intaa, """attention_mask""": tf.intaa, """token_type_ids""": tf.intaa}, tf.intaa) , ( { """input_ids""": tf.TensorShape([None] ), """attention_mask""": tf.TensorShape([None] ), """token_type_ids""": tf.TensorShape([None] ), }, tf.TensorShape([None] ), ) , ) def __UpperCAmelCase ( self :Tuple ) -> Any: '''simple docstring''' _a : List[Any] =self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features ) ) ) return self.dataset def __len__( self :str ) -> Optional[int]: '''simple docstring''' return len(self.features ) def __getitem__( self :int , SCREAMING_SNAKE_CASE :str ) -> InputFeatures: '''simple docstring''' return self.features[i]
276
1
'''simple docstring''' from random import shuffle import tensorflow as tf from numpy import array def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : Optional[Any] ) -> Optional[int]: _a : Tuple =int(_UpperCAmelCase ) assert noofclusters < len(_UpperCAmelCase ) # Find out the dimensionality _a : List[Any] =len(vectors[0] ) # Will help select random centroids from among the available vectors _a : List[Any] =list(range(len(_UpperCAmelCase ) ) ) shuffle(_UpperCAmelCase ) # GRAPH OF COMPUTATION # We initialize a new graph and set it as the default during each run # of this algorithm. This ensures that as this function is called # multiple times, the default graph doesn't keep getting crowded with # unused ops and Variables from previous function calls. _a : Optional[int] =tf.Graph() with graph.as_default(): # SESSION OF COMPUTATION _a : List[Any] =tf.Session() ##CONSTRUCTING THE ELEMENTS OF COMPUTATION ##First lets ensure we have a Variable vector for each centroid, ##initialized to one of the vectors from the available data points _a : Tuple =[ tf.Variable(vectors[vector_indices[i]] ) for i in range(_UpperCAmelCase ) ] ##These nodes will assign the centroid Variables the appropriate ##values _a : Dict =tf.placeholder("""float64""" ,[dim] ) _a : List[str] =[] for centroid in centroids: cent_assigns.append(tf.assign(_UpperCAmelCase ,_UpperCAmelCase ) ) ##Variables for cluster assignments of individual vectors(initialized ##to 0 at first) _a : List[Any] =[tf.Variable(0 ) for i in range(len(_UpperCAmelCase ) )] ##These nodes will assign an assignment Variable the appropriate ##value _a : Optional[int] =tf.placeholder("""int32""" ) _a : Any =[] for assignment in assignments: cluster_assigns.append(tf.assign(_UpperCAmelCase ,_UpperCAmelCase ) ) ##Now lets construct the node that will compute the mean # The placeholder for the input _a : Optional[int] =tf.placeholder("""float""" ,[None, dim] ) # The Node/op takes the input and computes a mean along the 0th # dimension, i.e. the list of input vectors _a : str =tf.reduce_mean(_UpperCAmelCase ,0 ) ##Node for computing Euclidean distances # Placeholders for input _a : Union[str, Any] =tf.placeholder("""float""" ,[dim] ) _a : Any =tf.placeholder("""float""" ,[dim] ) _a : Any =tf.sqrt(tf.reduce_sum(tf.pow(tf.sub(_UpperCAmelCase ,_UpperCAmelCase ) ,2 ) ) ) ##This node will figure out which cluster to assign a vector to, ##based on Euclidean distances of the vector from the centroids. # Placeholder for input _a : Dict =tf.placeholder("""float""" ,[noofclusters] ) _a : Optional[Any] =tf.argmin(_UpperCAmelCase ,0 ) ##INITIALIZING STATE VARIABLES ##This will help initialization of all Variables defined with respect ##to the graph. The Variable-initializer should be defined after ##all the Variables have been constructed, so that each of them ##will be included in the initialization. _a : Dict =tf.initialize_all_variables() # Initialize all variables sess.run(_UpperCAmelCase ) ##CLUSTERING ITERATIONS # Now perform the Expectation-Maximization steps of K-Means clustering # iterations. To keep things simple, we will only do a set number of # iterations, instead of using a Stopping Criterion. _a : Union[str, Any] =100 for _ in range(_UpperCAmelCase ): ##EXPECTATION STEP ##Based on the centroid locations till last iteration, compute ##the _expected_ centroid assignments. # Iterate over each vector for vector_n in range(len(_UpperCAmelCase ) ): _a : str =vectors[vector_n] # Compute Euclidean distance between this vector and each # centroid. Remember that this list cannot be named #'centroid_distances', since that is the input to the # cluster assignment node. _a : int =[ sess.run(_UpperCAmelCase ,feed_dict={va: vect, va: sess.run(_UpperCAmelCase )} ) for centroid in centroids ] # Now use the cluster assignment node, with the distances # as the input _a : int =sess.run( _UpperCAmelCase ,feed_dict={centroid_distances: distances} ) # Now assign the value to the appropriate state variable sess.run( cluster_assigns[vector_n] ,feed_dict={assignment_value: assignment} ) ##MAXIMIZATION STEP # Based on the expected state computed from the Expectation Step, # compute the locations of the centroids so as to maximize the # overall objective of minimizing within-cluster Sum-of-Squares for cluster_n in range(_UpperCAmelCase ): # Collect all the vectors assigned to this cluster _a : str =[ vectors[i] for i in range(len(_UpperCAmelCase ) ) if sess.run(assignments[i] ) == cluster_n ] # Compute new centroid location _a : Union[str, Any] =sess.run( _UpperCAmelCase ,feed_dict={mean_input: array(_UpperCAmelCase )} ) # Assign value to appropriate variable sess.run( cent_assigns[cluster_n] ,feed_dict={centroid_value: new_location} ) # Return centroids and assignments _a : str =sess.run(_UpperCAmelCase ) _a : Optional[int] =sess.run(_UpperCAmelCase ) return centroids, assignments
276
'''simple docstring''' from __future__ import annotations class A__ : def __init__( self :Union[str, Any] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :str ) -> Optional[int]: '''simple docstring''' _a , _a : List[str] =text, pattern _a , _a : Union[str, Any] =len(SCREAMING_SNAKE_CASE ), len(SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Optional[int] , SCREAMING_SNAKE_CASE :str ) -> int: '''simple docstring''' for i in range(self.patLen - 1 , -1 , -1 ): if char == self.pattern[i]: return i return -1 def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :int ) -> int: '''simple docstring''' for i in range(self.patLen - 1 , -1 , -1 ): if self.pattern[i] != self.text[current_pos + i]: return current_pos + i return -1 def __UpperCAmelCase ( self :Union[str, Any] ) -> list[int]: '''simple docstring''' # searches pattern in text and returns index positions _a : Union[str, Any] =[] for i in range(self.textLen - self.patLen + 1 ): _a : Any =self.mismatch_in_text(SCREAMING_SNAKE_CASE ) if mismatch_index == -1: positions.append(SCREAMING_SNAKE_CASE ) else: _a : int =self.match_in_pattern(self.text[mismatch_index] ) _a : List[str] =( mismatch_index - match_index ) # shifting index lgtm [py/multiple-definition] return positions A__: Any = '''ABAABA''' A__: int = '''AB''' A__: Optional[int] = BoyerMooreSearch(text, pattern) A__: Optional[Any] = bms.bad_character_heuristic() if len(positions) == 0: print('''No match found''') else: print('''Pattern found in following positions: ''') print(positions)
276
1
'''simple docstring''' import tempfile import unittest from transformers import TaConfig, is_torch_available from transformers.testing_utils import ( require_sentencepiece, require_tokenizers, require_torch, slow, torch_device, ) from ...generation.test_utils import GenerationTesterMixin from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import AutoTokenizer, UMTaForConditionalGeneration, UMTaForQuestionAnswering, UMTaModel class A__ : def __init__( self :Tuple , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :List[str]=9_9 , SCREAMING_SNAKE_CASE :List[str]=1_3 , SCREAMING_SNAKE_CASE :Optional[int]=7 , SCREAMING_SNAKE_CASE :Tuple=9 , SCREAMING_SNAKE_CASE :Any=True , SCREAMING_SNAKE_CASE :str=True , SCREAMING_SNAKE_CASE :Optional[Any]=False , SCREAMING_SNAKE_CASE :str=3_2 , SCREAMING_SNAKE_CASE :List[str]=5 , SCREAMING_SNAKE_CASE :Union[str, Any]=4 , SCREAMING_SNAKE_CASE :Tuple=3_7 , SCREAMING_SNAKE_CASE :Optional[int]=8 , SCREAMING_SNAKE_CASE :str=0.1 , SCREAMING_SNAKE_CASE :Tuple=0.002 , SCREAMING_SNAKE_CASE :Optional[Any]=1 , SCREAMING_SNAKE_CASE :Optional[int]=0 , SCREAMING_SNAKE_CASE :Tuple=0 , SCREAMING_SNAKE_CASE :str=None , SCREAMING_SNAKE_CASE :Optional[Any]=None , ) -> int: '''simple docstring''' _a : int =parent _a : Tuple =batch_size _a : List[Any] =encoder_seq_length _a : List[str] =decoder_seq_length # For common tests _a : str =self.decoder_seq_length _a : Optional[int] =is_training _a : List[str] =use_attention_mask _a : Union[str, Any] =use_labels _a : List[str] =vocab_size _a : Union[str, Any] =hidden_size _a : int =num_hidden_layers _a : Dict =num_attention_heads _a : List[str] =d_ff _a : Tuple =relative_attention_num_buckets _a : List[Any] =dropout_rate _a : List[str] =initializer_factor _a : str =eos_token_id _a : Union[str, Any] =pad_token_id _a : Any =decoder_start_token_id _a : Union[str, Any] =None _a : int =decoder_layers def __UpperCAmelCase ( self :int ) -> Union[str, Any]: '''simple docstring''' return TaConfig.from_pretrained("""google/umt5-base""" ) def __UpperCAmelCase ( self :List[Any] , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :Optional[int]=None , SCREAMING_SNAKE_CASE :Optional[Any]=None , SCREAMING_SNAKE_CASE :Any=None , SCREAMING_SNAKE_CASE :int=None , SCREAMING_SNAKE_CASE :List[str]=None , ) -> List[Any]: '''simple docstring''' if attention_mask is None: _a : str =input_ids.ne(config.pad_token_id ) if decoder_attention_mask is None: _a : str =decoder_input_ids.ne(config.pad_token_id ) if head_mask is None: _a : Optional[int] =torch.ones(config.num_hidden_layers , config.num_attention_heads , device=SCREAMING_SNAKE_CASE ) if decoder_head_mask is None: _a : int =torch.ones(config.num_decoder_layers , config.num_attention_heads , device=SCREAMING_SNAKE_CASE ) if cross_attn_head_mask is None: _a : Tuple =torch.ones( config.num_decoder_layers , config.num_attention_heads , device=SCREAMING_SNAKE_CASE ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } def __UpperCAmelCase ( self :Union[str, Any] ) -> str: '''simple docstring''' _a : List[str] =ids_tensor([self.batch_size, self.encoder_seq_length] , self.vocab_size ) _a : Optional[int] =ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) # we need to clamp the input ids here to avoid having pad token in between # this is because for NllbMoe the position_ids are prepared such that # all pad tokens have pos id = 2 and rest are between 2..seq_length # and the seq_length here is seq_length - num_pad_tokens # but when using past, there is no way of knowing if the past input ids had # pad tokens in them, which results in incorrect seq_lenth and which in turn results in # position_ids being off by num_pad_tokens in past input _a : Optional[int] =input_ids.clamp(self.pad_token_id + 1 ) _a : List[str] =decoder_input_ids.clamp(self.pad_token_id + 1 ) _a : List[Any] =self.get_config() _a : int =config.num_attention_heads _a : Union[str, Any] =self.prepare_inputs_dict(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) return config, input_dict def __UpperCAmelCase ( self :int ) -> int: '''simple docstring''' _a , _a : Dict =self.prepare_config_and_inputs() return config, inputs_dict def __UpperCAmelCase ( self :List[Any] ) -> str: '''simple docstring''' return TaConfig( vocab_size=1_6_6 , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def __UpperCAmelCase ( self :Dict ) -> Dict: '''simple docstring''' return TaConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def __UpperCAmelCase ( self :Optional[int] , SCREAMING_SNAKE_CASE :Optional[int] , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :Tuple , ) -> Union[str, Any]: '''simple docstring''' _a : Optional[Any] =UMTaModel(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() _a : Optional[int] =model( input_ids=SCREAMING_SNAKE_CASE , decoder_input_ids=SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , decoder_attention_mask=SCREAMING_SNAKE_CASE , ) _a : Optional[int] =model(input_ids=SCREAMING_SNAKE_CASE , decoder_input_ids=SCREAMING_SNAKE_CASE ) _a : Any =result.last_hidden_state _a : List[Any] =result.past_key_values _a : List[str] =result.encoder_last_hidden_state self.parent.assertEqual(encoder_output.size() , (self.batch_size, self.encoder_seq_length, self.hidden_size) ) self.parent.assertEqual(decoder_output.size() , (self.batch_size, self.decoder_seq_length, self.hidden_size) ) # There should be `num_layers` key value embeddings stored in decoder_past self.parent.assertEqual(len(SCREAMING_SNAKE_CASE ) , config.num_layers ) # There should be a self attn key, a self attn value, a cross attn key and a cross attn value stored in each decoder_past tuple self.parent.assertEqual(len(decoder_past[0] ) , 4 ) def __UpperCAmelCase ( self :Dict , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :List[Any] , SCREAMING_SNAKE_CASE :List[str] , ) -> List[str]: '''simple docstring''' _a : Any =UMTaModel(config=SCREAMING_SNAKE_CASE ).get_decoder().to(SCREAMING_SNAKE_CASE ).eval() # first forward pass _a : Tuple =model(SCREAMING_SNAKE_CASE , use_cache=SCREAMING_SNAKE_CASE ) _a : List[Any] =model(SCREAMING_SNAKE_CASE ) _a : str =model(SCREAMING_SNAKE_CASE , use_cache=SCREAMING_SNAKE_CASE ) self.parent.assertTrue(len(SCREAMING_SNAKE_CASE ) == len(SCREAMING_SNAKE_CASE ) ) self.parent.assertTrue(len(SCREAMING_SNAKE_CASE ) == len(SCREAMING_SNAKE_CASE ) + 1 ) _a , _a : List[Any] =outputs.to_tuple() # create hypothetical next token and extent to next_input_ids _a : str =ids_tensor((self.batch_size, 1) , config.vocab_size ) # append to next input_ids and _a : Tuple =torch.cat([input_ids, next_tokens] , dim=-1 ) _a : Optional[Any] =model(SCREAMING_SNAKE_CASE )["""last_hidden_state"""] _a : Optional[int] =model(SCREAMING_SNAKE_CASE , past_key_values=SCREAMING_SNAKE_CASE )["""last_hidden_state"""] # select random slice _a : Union[str, Any] =ids_tensor((1,) , output_from_past.shape[-1] ).item() _a : Optional[int] =output_from_no_past[:, -1, random_slice_idx].detach() _a : str =output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=1e-3 ) ) def __UpperCAmelCase ( self :Dict , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :str , ) -> List[str]: '''simple docstring''' _a : Dict =UMTaModel(config=SCREAMING_SNAKE_CASE ).to(SCREAMING_SNAKE_CASE ).half().eval() _a : int =model(**SCREAMING_SNAKE_CASE )["""last_hidden_state"""] self.parent.assertFalse(torch.isnan(SCREAMING_SNAKE_CASE ).any().item() ) @require_torch class A__ ( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): __UpperCamelCase : Any = ( (UMTaModel, UMTaForConditionalGeneration, UMTaForQuestionAnswering) if is_torch_available() else () ) __UpperCamelCase : Optional[int] = (UMTaForConditionalGeneration,) if is_torch_available() else () __UpperCamelCase : Union[str, Any] = ( { "conversational": UMTaForConditionalGeneration, "feature-extraction": UMTaModel, "summarization": UMTaForConditionalGeneration, "text2text-generation": UMTaForConditionalGeneration, "translation": UMTaForConditionalGeneration, "question-answering": UMTaForQuestionAnswering, } if is_torch_available() else {} ) __UpperCamelCase : Any = True __UpperCamelCase : Union[str, Any] = False __UpperCamelCase : int = False __UpperCamelCase : int = True __UpperCamelCase : str = True # The small UMT5 model needs higher percentages for CPU/MP tests __UpperCamelCase : Optional[Any] = [0.8, 0.9] def __UpperCAmelCase ( self :Optional[Any] ) -> List[Any]: '''simple docstring''' _a : Tuple =UMTaModelTester(self ) @unittest.skip("""Test has a segmentation fault on torch 1.8.0""" ) def __UpperCAmelCase ( self :Dict ) -> Tuple: '''simple docstring''' _a : List[str] =self.model_tester.prepare_config_and_inputs() _a : Union[str, Any] =UMTaModel(config_and_inputs[0] ).to(SCREAMING_SNAKE_CASE ) with tempfile.TemporaryDirectory() as tmpdirname: torch.onnx.export( SCREAMING_SNAKE_CASE , (config_and_inputs[1], config_and_inputs[3], config_and_inputs[2]) , f"{tmpdirname}/t5_test.onnx" , export_params=SCREAMING_SNAKE_CASE , opset_version=9 , input_names=["""input_ids""", """decoder_input_ids"""] , ) @unittest.skipIf(torch_device == """cpu""" , """Cant do half precision""" ) def __UpperCAmelCase ( self :Optional[int] ) -> Optional[int]: '''simple docstring''' _a : Optional[int] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model_fpaa_forward(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :List[Any] ) -> List[str]: '''simple docstring''' _a : Any =["""encoder_attentions""", """decoder_attentions""", """cross_attentions"""] _a : Any =self.model_tester.prepare_config_and_inputs() _a : int =config_and_inputs[0] _a : Tuple =UMTaForConditionalGeneration(SCREAMING_SNAKE_CASE ).eval() model.to(SCREAMING_SNAKE_CASE ) _a : List[Any] ={ """head_mask""": torch.zeros(config.num_layers , config.num_heads , device=SCREAMING_SNAKE_CASE ), """decoder_head_mask""": torch.zeros(config.num_decoder_layers , config.num_heads , device=SCREAMING_SNAKE_CASE ), """cross_attn_head_mask""": torch.zeros(config.num_decoder_layers , config.num_heads , device=SCREAMING_SNAKE_CASE ), } for attn_name, (name, mask) in zip(SCREAMING_SNAKE_CASE , head_masking.items() ): _a : str ={name: mask} # Explicitly pass decoder_head_mask as it is required from T5 model when head_mask specified if name == "head_mask": _a : Optional[Any] =torch.ones( config.num_decoder_layers , config.num_heads , device=SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =model.generate( config_and_inputs[1]["""input_ids"""] , num_beams=1 , max_length=3 , output_attentions=SCREAMING_SNAKE_CASE , return_dict_in_generate=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) # We check the state of decoder_attentions and cross_attentions just from the last step _a : int =out[attn_name] if attn_name == attention_names[0] else out[attn_name][-1] self.assertEqual(sum([w.sum().item() for w in attn_weights] ) , 0.0 ) @unittest.skip("""Does not work on the tiny model as we keep hitting edge cases.""" ) def __UpperCAmelCase ( self :List[Any] ) -> Optional[int]: '''simple docstring''' pass @require_torch @require_sentencepiece @require_tokenizers class A__ ( unittest.TestCase ): @slow @unittest.skip( """Unless we stop stripping left and right by default for all special tokens, the expected ids obtained here will not match the original ones. Wait for https://github.com/huggingface/transformers/pull/23909 to be merged""" ) def __UpperCAmelCase ( self :Tuple ) -> Dict: '''simple docstring''' _a : Tuple =UMTaForConditionalGeneration.from_pretrained("""google/umt5-small""" , return_dict=SCREAMING_SNAKE_CASE ).to(SCREAMING_SNAKE_CASE ) _a : Dict =AutoTokenizer.from_pretrained("""google/umt5-small""" , use_fast=SCREAMING_SNAKE_CASE , legacy=SCREAMING_SNAKE_CASE ) _a : Tuple =[ """Bonjour monsieur <extra_id_0> bien <extra_id_1>.""", """No se como puedo <extra_id_0>.""", """This is the reason why we <extra_id_0> them.""", """The <extra_id_0> walks in <extra_id_1>, seats""", """A <extra_id_0> walks into a bar and orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.""", ] _a : int =tokenizer(SCREAMING_SNAKE_CASE , return_tensors="""pt""" , padding=SCREAMING_SNAKE_CASE ).input_ids # fmt: off _a : Optional[int] =torch.tensor( [ [ 3_8_5_3_0, 2_1_0_7_0_3, 2_5_6_2_9_9, 1_4_1_0, 2_5_6_2_9_8, 2_7_4, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 8_2_6, 3_2_1, 6_7_1, 2_5_9_2_2, 2_5_6_2_9_9, 2_7_4, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 1_4_6_0, 3_3_9, 3_1_2, 1_9_0_1_4, 1_0_6_2_0, 7_5_8, 2_5_6_2_9_9, 2_3_5_5,2_7_4, 1, 0, 0, 0, 0, 0, 0,0, 0], [ 5_1_7, 2_5_6_2_9_9, 1_4_8_6_9, 2_8_1, 3_0_1, 2_5_6_2_9_8, 2_7_5, 1_1_9_9_8_3,1, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 3_2_0, 2_5_6_2_9_9, 1_4_8_6_9, 2_8_1, 2_2_3_4, 2_8_9, 2_2_7_5, 3_3_3,6_1_3_9_1, 2_8_9, 2_5_6_2_9_8, 5_4_3, 2_5_6_2_9_7, 1_6_8_7_1_4, 3_2_9, 2_5_6_2_9_6,2_7_4, 1], ] ) # fmt: on torch.testing.assert_allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) _a : Tuple =model.generate(input_ids.to(SCREAMING_SNAKE_CASE ) ) _a : Union[str, Any] =[ """<pad><extra_id_0> et<extra_id_1> [eod] <extra_id_2><extra_id_55>.. [eod] 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 <extra_id_56>ajšietosto<extra_id_56>lleux<extra_id_19><extra_id_6>ajšie</s>""", """<pad><extra_id_0>.<extra_id_1>.,<0x0A>...spech <0x0A><extra_id_20> <extra_id_21></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>""", """<pad><extra_id_0> are not going to be a part of the world. We are not going to be a part of<extra_id_1> and<extra_id_2><0x0A><extra_id_48>.<extra_id_48></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>""", """<pad><extra_id_0> door<extra_id_1>, the door<extra_id_2> 피해[/</s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>""", """<pad><extra_id_0>nyone who<extra_id_1> drink<extra_id_2> a<extra_id_3> alcohol<extra_id_4> A<extra_id_5> A. This<extra_id_6> I<extra_id_7><extra_id_52><extra_id_53></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>""", ] _a : Tuple =tokenizer.batch_decode(SCREAMING_SNAKE_CASE ) self.assertEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
276
'''simple docstring''' import argparse import gc import json import os import shutil import warnings import torch from transformers import LlamaConfig, LlamaForCausalLM, LlamaTokenizer try: from transformers import LlamaTokenizerFast except ImportError as e: warnings.warn(e) warnings.warn( '''The converted tokenizer will be the `slow` tokenizer. To use the fast, update your `tokenizers` library and re-run the tokenizer conversion''' ) A__: Dict = None A__: Tuple = { '''7B''': 1_1008, '''13B''': 1_3824, '''30B''': 1_7920, '''65B''': 2_2016, '''70B''': 2_8672, } A__: Any = { '''7B''': 1, '''7Bf''': 1, '''13B''': 2, '''13Bf''': 2, '''30B''': 4, '''65B''': 8, '''70B''': 8, '''70Bf''': 8, } def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Optional[int]=1 ,_UpperCAmelCase : List[str]=256 ) -> Dict: return multiple_of * ((int(ffn_dim_multiplier * int(8 * n / 3 ) ) + multiple_of - 1) // multiple_of) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[Any] ) -> List[str]: with open(_UpperCAmelCase ,"""r""" ) as f: return json.load(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : Optional[Any] ) -> Tuple: with open(_UpperCAmelCase ,"""w""" ) as f: json.dump(_UpperCAmelCase ,_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : int ,_UpperCAmelCase : List[Any]=True ) -> Union[str, Any]: os.makedirs(_UpperCAmelCase ,exist_ok=_UpperCAmelCase ) _a : Union[str, Any] =os.path.join(_UpperCAmelCase ,"""tmp""" ) os.makedirs(_UpperCAmelCase ,exist_ok=_UpperCAmelCase ) _a : int =read_json(os.path.join(_UpperCAmelCase ,"""params.json""" ) ) _a : int =NUM_SHARDS[model_size] _a : Dict =params["""n_layers"""] _a : Union[str, Any] =params["""n_heads"""] _a : List[str] =n_heads // num_shards _a : int =params["""dim"""] _a : Union[str, Any] =dim // n_heads _a : int =1_0_0_0_0.0 _a : str =1.0 / (base ** (torch.arange(0 ,_UpperCAmelCase ,2 ).float() / dims_per_head)) if "n_kv_heads" in params: _a : str =params["""n_kv_heads"""] # for GQA / MQA _a : Optional[Any] =n_heads_per_shard // num_key_value_heads _a : Optional[int] =dim // num_key_value_heads else: # compatibility with other checkpoints _a : str =n_heads _a : Any =n_heads_per_shard _a : str =dim # permute for sliced rotary def permute(_UpperCAmelCase : Tuple ,_UpperCAmelCase : Optional[int]=n_heads ,_UpperCAmelCase : Optional[int]=dim ,_UpperCAmelCase : List[str]=dim ): return w.view(_UpperCAmelCase ,dima // n_heads // 2 ,2 ,_UpperCAmelCase ).transpose(1 ,2 ).reshape(_UpperCAmelCase ,_UpperCAmelCase ) print(F"Fetching all parameters from the checkpoint at {input_base_path}." ) # Load weights if model_size == "7B": # Not sharded # (The sharded implementation would also work, but this is simpler.) _a : Any =torch.load(os.path.join(_UpperCAmelCase ,"""consolidated.00.pth""" ) ,map_location="""cpu""" ) else: # Sharded _a : List[Any] =[ torch.load(os.path.join(_UpperCAmelCase ,F"consolidated.{i:02d}.pth" ) ,map_location="""cpu""" ) for i in range(_UpperCAmelCase ) ] _a : Any =0 _a : Optional[int] ={"""weight_map""": {}} for layer_i in range(_UpperCAmelCase ): _a : List[str] =F"pytorch_model-{layer_i + 1}-of-{n_layers + 1}.bin" if model_size == "7B": # Unsharded _a : List[str] ={ F"model.layers.{layer_i}.self_attn.q_proj.weight": permute( loaded[F"layers.{layer_i}.attention.wq.weight"] ), F"model.layers.{layer_i}.self_attn.k_proj.weight": permute( loaded[F"layers.{layer_i}.attention.wk.weight"] ), F"model.layers.{layer_i}.self_attn.v_proj.weight": loaded[F"layers.{layer_i}.attention.wv.weight"], F"model.layers.{layer_i}.self_attn.o_proj.weight": loaded[F"layers.{layer_i}.attention.wo.weight"], F"model.layers.{layer_i}.mlp.gate_proj.weight": loaded[F"layers.{layer_i}.feed_forward.w1.weight"], F"model.layers.{layer_i}.mlp.down_proj.weight": loaded[F"layers.{layer_i}.feed_forward.w2.weight"], F"model.layers.{layer_i}.mlp.up_proj.weight": loaded[F"layers.{layer_i}.feed_forward.w3.weight"], F"model.layers.{layer_i}.input_layernorm.weight": loaded[F"layers.{layer_i}.attention_norm.weight"], F"model.layers.{layer_i}.post_attention_layernorm.weight": loaded[F"layers.{layer_i}.ffn_norm.weight"], } else: # Sharded # Note that attention.w{q,k,v,o}, feed_fordward.w[1,2,3], attention_norm.weight and ffn_norm.weight share # the same storage object, saving attention_norm and ffn_norm will save other weights too, which is # redundant as other weights will be stitched from multiple shards. To avoid that, they are cloned. _a : Tuple ={ F"model.layers.{layer_i}.input_layernorm.weight": loaded[0][ F"layers.{layer_i}.attention_norm.weight" ].clone(), F"model.layers.{layer_i}.post_attention_layernorm.weight": loaded[0][ F"layers.{layer_i}.ffn_norm.weight" ].clone(), } _a : str =permute( torch.cat( [ loaded[i][F"layers.{layer_i}.attention.wq.weight"].view(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) for i in range(_UpperCAmelCase ) ] ,dim=0 ,).reshape(_UpperCAmelCase ,_UpperCAmelCase ) ) _a : Tuple =permute( torch.cat( [ loaded[i][F"layers.{layer_i}.attention.wk.weight"].view( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) for i in range(_UpperCAmelCase ) ] ,dim=0 ,).reshape(_UpperCAmelCase ,_UpperCAmelCase ) ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,) _a : Any =torch.cat( [ loaded[i][F"layers.{layer_i}.attention.wv.weight"].view( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) for i in range(_UpperCAmelCase ) ] ,dim=0 ,).reshape(_UpperCAmelCase ,_UpperCAmelCase ) _a : List[str] =torch.cat( [loaded[i][F"layers.{layer_i}.attention.wo.weight"] for i in range(_UpperCAmelCase )] ,dim=1 ) _a : Union[str, Any] =torch.cat( [loaded[i][F"layers.{layer_i}.feed_forward.w1.weight"] for i in range(_UpperCAmelCase )] ,dim=0 ) _a : Tuple =torch.cat( [loaded[i][F"layers.{layer_i}.feed_forward.w2.weight"] for i in range(_UpperCAmelCase )] ,dim=1 ) _a : Union[str, Any] =torch.cat( [loaded[i][F"layers.{layer_i}.feed_forward.w3.weight"] for i in range(_UpperCAmelCase )] ,dim=0 ) _a : str =inv_freq for k, v in state_dict.items(): _a : Any =filename param_count += v.numel() torch.save(_UpperCAmelCase ,os.path.join(_UpperCAmelCase ,_UpperCAmelCase ) ) _a : Union[str, Any] =F"pytorch_model-{n_layers + 1}-of-{n_layers + 1}.bin" if model_size == "7B": # Unsharded _a : List[str] ={ """model.embed_tokens.weight""": loaded["""tok_embeddings.weight"""], """model.norm.weight""": loaded["""norm.weight"""], """lm_head.weight""": loaded["""output.weight"""], } else: _a : int ={ """model.norm.weight""": loaded[0]["""norm.weight"""], """model.embed_tokens.weight""": torch.cat( [loaded[i]["""tok_embeddings.weight"""] for i in range(_UpperCAmelCase )] ,dim=1 ), """lm_head.weight""": torch.cat([loaded[i]["""output.weight"""] for i in range(_UpperCAmelCase )] ,dim=0 ), } for k, v in state_dict.items(): _a : Dict =filename param_count += v.numel() torch.save(_UpperCAmelCase ,os.path.join(_UpperCAmelCase ,_UpperCAmelCase ) ) # Write configs _a : Tuple ={"""total_size""": param_count * 2} write_json(_UpperCAmelCase ,os.path.join(_UpperCAmelCase ,"""pytorch_model.bin.index.json""" ) ) _a : Optional[Any] =params["""ffn_dim_multiplier"""] if """ffn_dim_multiplier""" in params else 1 _a : int =params["""multiple_of"""] if """multiple_of""" in params else 256 _a : List[Any] =LlamaConfig( hidden_size=_UpperCAmelCase ,intermediate_size=compute_intermediate_size(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) ,num_attention_heads=params["""n_heads"""] ,num_hidden_layers=params["""n_layers"""] ,rms_norm_eps=params["""norm_eps"""] ,num_key_value_heads=_UpperCAmelCase ,) config.save_pretrained(_UpperCAmelCase ) # Make space so we can load the model properly now. del state_dict del loaded gc.collect() print("""Loading the checkpoint in a Llama model.""" ) _a : Any =LlamaForCausalLM.from_pretrained(_UpperCAmelCase ,torch_dtype=torch.floataa ,low_cpu_mem_usage=_UpperCAmelCase ) # Avoid saving this as part of the config. del model.config._name_or_path print("""Saving in the Transformers format.""" ) model.save_pretrained(_UpperCAmelCase ,safe_serialization=_UpperCAmelCase ) shutil.rmtree(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ,_UpperCAmelCase : int ) -> Optional[Any]: # Initialize the tokenizer based on the `spm` model _a : List[str] =LlamaTokenizer if LlamaTokenizerFast is None else LlamaTokenizerFast print(F"Saving a {tokenizer_class.__name__} to {tokenizer_path}." ) _a : List[Any] =tokenizer_class(_UpperCAmelCase ) tokenizer.save_pretrained(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( ) -> Union[str, Any]: _a : List[str] =argparse.ArgumentParser() parser.add_argument( """--input_dir""" ,help="""Location of LLaMA weights, which contains tokenizer.model and model folders""" ,) parser.add_argument( """--model_size""" ,choices=["""7B""", """7Bf""", """13B""", """13Bf""", """30B""", """65B""", """70B""", """70Bf""", """tokenizer_only"""] ,) parser.add_argument( """--output_dir""" ,help="""Location to write HF model and tokenizer""" ,) parser.add_argument("""--safe_serialization""" ,type=_UpperCAmelCase ,help="""Whether or not to save using `safetensors`.""" ) _a : Optional[Any] =parser.parse_args() if args.model_size != "tokenizer_only": write_model( model_path=args.output_dir ,input_base_path=os.path.join(args.input_dir ,args.model_size ) ,model_size=args.model_size ,safe_serialization=args.safe_serialization ,) _a : List[Any] =os.path.join(args.input_dir ,"""tokenizer.model""" ) write_tokenizer(args.output_dir ,_UpperCAmelCase ) if __name__ == "__main__": main()
276
1
'''simple docstring''' import warnings from ...utils import logging from .image_processing_layoutlmva import LayoutLMvaImageProcessor A__: List[Any] = logging.get_logger(__name__) class A__ ( UpperCAmelCase__ ): def __init__( self :int , *SCREAMING_SNAKE_CASE :Optional[int] , **SCREAMING_SNAKE_CASE :List[str] ) -> None: '''simple docstring''' warnings.warn( """The class LayoutLMv2FeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use LayoutLMv2ImageProcessor instead.""" , SCREAMING_SNAKE_CASE , ) super().__init__(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE )
276
'''simple docstring''' import contextlib import os import sqlitea import pytest from datasets import Dataset, Features, Value from datasets.io.sql import SqlDatasetReader, SqlDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases, require_sqlalchemy def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Any ,_UpperCAmelCase : str ) -> Dict: assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ) 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 @require_sqlalchemy @pytest.mark.parametrize("""keep_in_memory""" ,[False, True] ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Optional[int] ,_UpperCAmelCase : str ) -> Optional[Any]: _a : Any =tmp_path / """cache""" _a : int ={"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): _a : Tuple =SqlDatasetReader( """dataset""" ,"""sqlite:///""" + sqlite_path ,cache_dir=_UpperCAmelCase ,keep_in_memory=_UpperCAmelCase ).read() _check_sql_dataset(_UpperCAmelCase ,_UpperCAmelCase ) @require_sqlalchemy @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 SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[Any] ,_UpperCAmelCase : Dict ,_UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : int ) -> List[Any]: _a : Union[str, Any] =tmp_path / """cache""" _a : str ={"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} _a : Optional[int] =features.copy() if features else default_expected_features _a : Union[str, Any] =( Features({feature: Value(_UpperCAmelCase ) for feature, dtype in features.items()} ) if features is not None else None ) _a : Optional[Any] =SqlDatasetReader("""dataset""" ,"""sqlite:///""" + sqlite_path ,features=_UpperCAmelCase ,cache_dir=_UpperCAmelCase ).read() _check_sql_dataset(_UpperCAmelCase ,_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[Any] ) -> List[str]: with contextlib.closing(sqlitea.connect(_UpperCAmelCase ) ) as con: _a : Any =con.cursor() cur.execute("""SELECT * FROM dataset""" ) for row in cur: yield row @require_sqlalchemy def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Dict ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : List[str] ) -> Union[str, Any]: _a : Union[str, Any] =tmp_path / """cache""" _a : Union[str, Any] =os.path.join(_UpperCAmelCase ,"""tmp.sql""" ) _a : Tuple =SqlDatasetReader("""dataset""" ,"""sqlite:///""" + sqlite_path ,cache_dir=_UpperCAmelCase ).read() SqlDatasetWriter(_UpperCAmelCase ,"""dataset""" ,"""sqlite:///""" + output_sqlite_path ,num_proc=1 ).write() _a : Tuple =iter_sql_file(_UpperCAmelCase ) _a : List[Any] =iter_sql_file(_UpperCAmelCase ) for rowa, rowa in zip(_UpperCAmelCase ,_UpperCAmelCase ): assert rowa == rowa @require_sqlalchemy def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Any ,_UpperCAmelCase : List[Any] ) -> Optional[int]: _a : int =tmp_path / """cache""" _a : Any =os.path.join(_UpperCAmelCase ,"""tmp.sql""" ) _a : Union[str, Any] =SqlDatasetReader("""dataset""" ,"""sqlite:///""" + sqlite_path ,cache_dir=_UpperCAmelCase ).read() SqlDatasetWriter(_UpperCAmelCase ,"""dataset""" ,"""sqlite:///""" + output_sqlite_path ,num_proc=2 ).write() _a : List[Any] =iter_sql_file(_UpperCAmelCase ) _a : str =iter_sql_file(_UpperCAmelCase ) for rowa, rowa in zip(_UpperCAmelCase ,_UpperCAmelCase ): assert rowa == rowa @require_sqlalchemy def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : str ,_UpperCAmelCase : List[Any] ) -> List[str]: _a : List[str] =tmp_path / """cache""" _a : Dict =os.path.join(_UpperCAmelCase ,"""tmp.sql""" ) _a : Optional[Any] =SqlDatasetReader("""dataset""" ,"""sqlite:///""" + sqlite_path ,cache_dir=_UpperCAmelCase ).read() with pytest.raises(_UpperCAmelCase ): SqlDatasetWriter(_UpperCAmelCase ,"""dataset""" ,"""sqlite:///""" + output_sqlite_path ,num_proc=0 ).write()
276
1
'''simple docstring''' A__: str = ''' # Transformers 설치 방법 ! pip install transformers datasets # 마지막 릴리스 대신 소스에서 설치하려면, 위 명령을 주석으로 바꾸고 아래 명령을 해제하세요. # ! pip install git+https://github.com/huggingface/transformers.git ''' A__: Optional[Any] = [{'''type''': '''code''', '''content''': INSTALL_CONTENT}] A__: List[Any] = { '''{processor_class}''': '''FakeProcessorClass''', '''{model_class}''': '''FakeModelClass''', '''{object_class}''': '''FakeObjectClass''', }
276
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A__: List[str] = logging.get_logger(__name__) A__: Union[str, Any] = { '''facebook/data2vec-text-base''': '''https://huggingface.co/data2vec/resolve/main/config.json''', } class A__ ( UpperCAmelCase__ ): __UpperCamelCase : int = "data2vec-text" def __init__( self :str , SCREAMING_SNAKE_CASE :Optional[Any]=3_0_5_2_2 , SCREAMING_SNAKE_CASE :Any=7_6_8 , SCREAMING_SNAKE_CASE :List[Any]=1_2 , SCREAMING_SNAKE_CASE :List[str]=1_2 , SCREAMING_SNAKE_CASE :Dict=3_0_7_2 , SCREAMING_SNAKE_CASE :List[str]="gelu" , SCREAMING_SNAKE_CASE :Any=0.1 , SCREAMING_SNAKE_CASE :List[str]=0.1 , SCREAMING_SNAKE_CASE :int=5_1_2 , SCREAMING_SNAKE_CASE :int=2 , SCREAMING_SNAKE_CASE :Union[str, Any]=0.02 , SCREAMING_SNAKE_CASE :Dict=1e-12 , SCREAMING_SNAKE_CASE :int=1 , SCREAMING_SNAKE_CASE :Dict=0 , SCREAMING_SNAKE_CASE :List[Any]=2 , SCREAMING_SNAKE_CASE :str="absolute" , SCREAMING_SNAKE_CASE :Tuple=True , SCREAMING_SNAKE_CASE :Union[str, Any]=None , **SCREAMING_SNAKE_CASE :Union[str, Any] , ) -> List[str]: '''simple docstring''' super().__init__(pad_token_id=SCREAMING_SNAKE_CASE , bos_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) _a : Optional[Any] =vocab_size _a : Optional[Any] =hidden_size _a : Any =num_hidden_layers _a : List[str] =num_attention_heads _a : Union[str, Any] =hidden_act _a : Any =intermediate_size _a : str =hidden_dropout_prob _a : Optional[Any] =attention_probs_dropout_prob _a : Optional[Any] =max_position_embeddings _a : Union[str, Any] =type_vocab_size _a : Tuple =initializer_range _a : Optional[int] =layer_norm_eps _a : Tuple =position_embedding_type _a : int =use_cache _a : List[str] =classifier_dropout class A__ ( UpperCAmelCase__ ): @property def __UpperCAmelCase ( self :int ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task == "multiple-choice": _a : Tuple ={0: """batch""", 1: """choice""", 2: """sequence"""} else: _a : List[Any] ={0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ] )
276
1
'''simple docstring''' import unittest import numpy as np import torch from diffusers import ScoreSdeVePipeline, ScoreSdeVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class A__ ( unittest.TestCase ): @property def __UpperCAmelCase ( self :Dict ) -> Optional[Any]: '''simple docstring''' torch.manual_seed(0 ) _a : str =UNetaDModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=3 , out_channels=3 , down_block_types=("""DownBlock2D""", """AttnDownBlock2D""") , up_block_types=("""AttnUpBlock2D""", """UpBlock2D""") , ) return model def __UpperCAmelCase ( self :Tuple ) -> Union[str, Any]: '''simple docstring''' _a : Any =self.dummy_uncond_unet _a : Optional[Any] =ScoreSdeVeScheduler() _a : Tuple =ScoreSdeVePipeline(unet=SCREAMING_SNAKE_CASE , scheduler=SCREAMING_SNAKE_CASE ) sde_ve.to(SCREAMING_SNAKE_CASE ) sde_ve.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =torch.manual_seed(0 ) _a : Tuple =sde_ve(num_inference_steps=2 , output_type="""numpy""" , generator=SCREAMING_SNAKE_CASE ).images _a : Dict =torch.manual_seed(0 ) _a : Tuple =sde_ve(num_inference_steps=2 , output_type="""numpy""" , generator=SCREAMING_SNAKE_CASE , return_dict=SCREAMING_SNAKE_CASE )[ 0 ] _a : Any =image[0, -3:, -3:, -1] _a : Tuple =image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 3_2, 3_2, 3) _a : Any =np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch class A__ ( unittest.TestCase ): def __UpperCAmelCase ( self :List[str] ) -> Tuple: '''simple docstring''' _a : List[str] ="""google/ncsnpp-church-256""" _a : Optional[int] =UNetaDModel.from_pretrained(SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =ScoreSdeVeScheduler.from_pretrained(SCREAMING_SNAKE_CASE ) _a : Optional[Any] =ScoreSdeVePipeline(unet=SCREAMING_SNAKE_CASE , scheduler=SCREAMING_SNAKE_CASE ) sde_ve.to(SCREAMING_SNAKE_CASE ) sde_ve.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE ) _a : int =torch.manual_seed(0 ) _a : Optional[int] =sde_ve(num_inference_steps=1_0 , output_type="""numpy""" , generator=SCREAMING_SNAKE_CASE ).images _a : int =image[0, -3:, -3:, -1] assert image.shape == (1, 2_5_6, 2_5_6, 3) _a : str =np.array([0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
276
'''simple docstring''' from typing import Dict, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import flip_channel_order, resize, to_channel_dimension_format, to_pil_image from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_pytesseract_available, is_vision_available, logging, requires_backends if is_vision_available(): import PIL # soft dependency if is_pytesseract_available(): import pytesseract A__: Union[str, Any] = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : List[str] ) -> int: return [ int(1000 * (box[0] / width) ), int(1000 * (box[1] / height) ), int(1000 * (box[2] / width) ), int(1000 * (box[3] / height) ), ] def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : np.ndarray ,_UpperCAmelCase : Optional[str] ,_UpperCAmelCase : Optional[str] = None ) -> Optional[int]: _a : Any =tesseract_config if tesseract_config is not None else """""" # apply OCR _a : Optional[Any] =to_pil_image(_UpperCAmelCase ) _a , _a : List[Any] =pil_image.size _a : List[str] =pytesseract.image_to_data(_UpperCAmelCase ,lang=_UpperCAmelCase ,output_type="""dict""" ,config=_UpperCAmelCase ) _a , _a , _a , _a , _a : str =data["""text"""], data["""left"""], data["""top"""], data["""width"""], data["""height"""] # filter empty words and corresponding coordinates _a : Tuple =[idx for idx, word in enumerate(_UpperCAmelCase ) if not word.strip()] _a : List[Any] =[word for idx, word in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] _a : Dict =[coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] _a : List[str] =[coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] _a : Union[str, Any] =[coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] _a : Union[str, Any] =[coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] # turn coordinates into (left, top, left+width, top+height) format _a : List[str] =[] for x, y, w, h in zip(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ): _a : int =[x, y, x + w, y + h] actual_boxes.append(_UpperCAmelCase ) # finally, normalize the bounding boxes _a : str =[] for box in actual_boxes: normalized_boxes.append(normalize_box(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) ) assert len(_UpperCAmelCase ) == len(_UpperCAmelCase ), "Not as many words as there are bounding boxes" return words, normalized_boxes class A__ ( UpperCAmelCase__ ): __UpperCamelCase : List[Any] = ["pixel_values"] def __init__( self :Tuple , SCREAMING_SNAKE_CASE :bool = True , SCREAMING_SNAKE_CASE :Dict[str, int] = None , SCREAMING_SNAKE_CASE :PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE :bool = True , SCREAMING_SNAKE_CASE :Optional[str] = None , SCREAMING_SNAKE_CASE :Optional[str] = "" , **SCREAMING_SNAKE_CASE :Tuple , ) -> None: '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE ) _a : List[Any] =size if size is not None else {"""height""": 2_2_4, """width""": 2_2_4} _a : Tuple =get_size_dict(SCREAMING_SNAKE_CASE ) _a : Dict =do_resize _a : Tuple =size _a : str =resample _a : Dict =apply_ocr _a : Union[str, Any] =ocr_lang _a : Dict =tesseract_config def __UpperCAmelCase ( self :List[str] , SCREAMING_SNAKE_CASE :np.ndarray , SCREAMING_SNAKE_CASE :Dict[str, int] , SCREAMING_SNAKE_CASE :PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE :Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE :Dict , ) -> np.ndarray: '''simple docstring''' _a : int =get_size_dict(SCREAMING_SNAKE_CASE ) if "height" not in size or "width" not in size: raise ValueError(f"The size dictionary must contain the keys 'height' and 'width'. Got {size.keys()}" ) _a : Any =(size["""height"""], size["""width"""]) return resize(SCREAMING_SNAKE_CASE , size=SCREAMING_SNAKE_CASE , resample=SCREAMING_SNAKE_CASE , data_format=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Dict , SCREAMING_SNAKE_CASE :ImageInput , SCREAMING_SNAKE_CASE :bool = None , SCREAMING_SNAKE_CASE :Dict[str, int] = None , SCREAMING_SNAKE_CASE :PILImageResampling = None , SCREAMING_SNAKE_CASE :bool = None , SCREAMING_SNAKE_CASE :Optional[str] = None , SCREAMING_SNAKE_CASE :Optional[str] = None , SCREAMING_SNAKE_CASE :Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE :ChannelDimension = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE :Optional[Any] , ) -> PIL.Image.Image: '''simple docstring''' _a : Optional[int] =do_resize if do_resize is not None else self.do_resize _a : Optional[int] =size if size is not None else self.size _a : str =get_size_dict(SCREAMING_SNAKE_CASE ) _a : List[str] =resample if resample is not None else self.resample _a : int =apply_ocr if apply_ocr is not None else self.apply_ocr _a : str =ocr_lang if ocr_lang is not None else self.ocr_lang _a : Union[str, Any] =tesseract_config if tesseract_config is not None else self.tesseract_config _a : List[str] =make_list_of_images(SCREAMING_SNAKE_CASE ) if not valid_images(SCREAMING_SNAKE_CASE ): 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.""" ) # All transformations expect numpy arrays. _a : List[Any] =[to_numpy_array(SCREAMING_SNAKE_CASE ) for image in images] if apply_ocr: requires_backends(self , """pytesseract""" ) _a : Any =[] _a : Any =[] for image in images: _a , _a : int =apply_tesseract(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) words_batch.append(SCREAMING_SNAKE_CASE ) boxes_batch.append(SCREAMING_SNAKE_CASE ) if do_resize: _a : Union[str, Any] =[self.resize(image=SCREAMING_SNAKE_CASE , size=SCREAMING_SNAKE_CASE , resample=SCREAMING_SNAKE_CASE ) for image in images] # flip color channels from RGB to BGR (as Detectron2 requires this) _a : Dict =[flip_channel_order(SCREAMING_SNAKE_CASE ) for image in images] _a : str =[to_channel_dimension_format(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for image in images] _a : str =BatchFeature(data={"""pixel_values""": images} , tensor_type=SCREAMING_SNAKE_CASE ) if apply_ocr: _a : List[Any] =words_batch _a : Dict =boxes_batch return data
276
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) A__: List[str] = { '''configuration_blip''': [ '''BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BlipConfig''', '''BlipTextConfig''', '''BlipVisionConfig''', ], '''processing_blip''': ['''BlipProcessor'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: List[Any] = ['''BlipImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Optional[int] = [ '''BLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''BlipModel''', '''BlipPreTrainedModel''', '''BlipForConditionalGeneration''', '''BlipForQuestionAnswering''', '''BlipVisionModel''', '''BlipTextModel''', '''BlipForImageTextRetrieval''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Tuple = [ '''TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFBlipModel''', '''TFBlipPreTrainedModel''', '''TFBlipForConditionalGeneration''', '''TFBlipForQuestionAnswering''', '''TFBlipVisionModel''', '''TFBlipTextModel''', '''TFBlipForImageTextRetrieval''', ] if TYPE_CHECKING: from .configuration_blip import BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, BlipConfig, BlipTextConfig, BlipVisionConfig from .processing_blip import BlipProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_blip import BlipImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blip import ( BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, BlipModel, BlipPreTrainedModel, BlipTextModel, BlipVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blip import ( TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFBlipForConditionalGeneration, TFBlipForImageTextRetrieval, TFBlipForQuestionAnswering, TFBlipModel, TFBlipPreTrainedModel, TFBlipTextModel, TFBlipVisionModel, ) else: import sys A__: Union[str, Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
276
'''simple docstring''' from __future__ import annotations import requests def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ) -> dict: _a : Any =F"https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty" return requests.get(_UpperCAmelCase ).json() def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int = 10 ) -> list[dict]: _a : Union[str, Any] ="""https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty""" _a : int =requests.get(_UpperCAmelCase ).json()[:max_stories] return [get_hackernews_story(_UpperCAmelCase ) for story_id in story_ids] def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int = 10 ) -> str: _a : Union[str, Any] =hackernews_top_stories(_UpperCAmelCase ) return "\n".join("""* [{title}]({url})""".format(**_UpperCAmelCase ) for story in stories ) if __name__ == "__main__": print(hackernews_top_stories_as_markdown())
276
1
'''simple docstring''' from maths.prime_factors import prime_factors def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ) -> int: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): _a : str =F"Input value of [number={number}] must be an integer" raise TypeError(_UpperCAmelCase ) if number < 1: raise ValueError("""Input must be a positive integer""" ) return -1 if len(prime_factors(_UpperCAmelCase ) ) % 2 else 1 if __name__ == "__main__": import doctest doctest.testmod()
276
'''simple docstring''' from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, apply_forward_hook from .modeling_utils import ModelMixin from .vae import Decoder, DecoderOutput, Encoder, VectorQuantizer @dataclass class A__ ( UpperCAmelCase__ ): __UpperCamelCase : torch.FloatTensor class A__ ( UpperCAmelCase__ , UpperCAmelCase__ ): @register_to_config def __init__( self :Optional[Any] , SCREAMING_SNAKE_CASE :int = 3 , SCREAMING_SNAKE_CASE :int = 3 , SCREAMING_SNAKE_CASE :Tuple[str] = ("DownEncoderBlock2D",) , SCREAMING_SNAKE_CASE :Tuple[str] = ("UpDecoderBlock2D",) , SCREAMING_SNAKE_CASE :Tuple[int] = (6_4,) , SCREAMING_SNAKE_CASE :int = 1 , SCREAMING_SNAKE_CASE :str = "silu" , SCREAMING_SNAKE_CASE :int = 3 , SCREAMING_SNAKE_CASE :int = 3_2 , SCREAMING_SNAKE_CASE :int = 2_5_6 , SCREAMING_SNAKE_CASE :int = 3_2 , SCREAMING_SNAKE_CASE :Optional[int] = None , SCREAMING_SNAKE_CASE :float = 0.18_215 , SCREAMING_SNAKE_CASE :str = "group" , ) -> Optional[int]: '''simple docstring''' super().__init__() # pass init params to Encoder _a : Union[str, Any] =Encoder( in_channels=SCREAMING_SNAKE_CASE , out_channels=SCREAMING_SNAKE_CASE , down_block_types=SCREAMING_SNAKE_CASE , block_out_channels=SCREAMING_SNAKE_CASE , layers_per_block=SCREAMING_SNAKE_CASE , act_fn=SCREAMING_SNAKE_CASE , norm_num_groups=SCREAMING_SNAKE_CASE , double_z=SCREAMING_SNAKE_CASE , ) _a : Optional[int] =vq_embed_dim if vq_embed_dim is not None else latent_channels _a : Optional[int] =nn.Convad(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , 1 ) _a : str =VectorQuantizer(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , beta=0.25 , remap=SCREAMING_SNAKE_CASE , sane_index_shape=SCREAMING_SNAKE_CASE ) _a : List[str] =nn.Convad(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , 1 ) # pass init params to Decoder _a : List[str] =Decoder( in_channels=SCREAMING_SNAKE_CASE , out_channels=SCREAMING_SNAKE_CASE , up_block_types=SCREAMING_SNAKE_CASE , block_out_channels=SCREAMING_SNAKE_CASE , layers_per_block=SCREAMING_SNAKE_CASE , act_fn=SCREAMING_SNAKE_CASE , norm_num_groups=SCREAMING_SNAKE_CASE , norm_type=SCREAMING_SNAKE_CASE , ) @apply_forward_hook def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :torch.FloatTensor , SCREAMING_SNAKE_CASE :bool = True ) -> VQEncoderOutput: '''simple docstring''' _a : Optional[int] =self.encoder(SCREAMING_SNAKE_CASE ) _a : int =self.quant_conv(SCREAMING_SNAKE_CASE ) if not return_dict: return (h,) return VQEncoderOutput(latents=SCREAMING_SNAKE_CASE ) @apply_forward_hook def __UpperCAmelCase ( self :List[Any] , SCREAMING_SNAKE_CASE :torch.FloatTensor , SCREAMING_SNAKE_CASE :bool = False , SCREAMING_SNAKE_CASE :bool = True ) -> Union[DecoderOutput, torch.FloatTensor]: '''simple docstring''' # also go through quantization layer if not force_not_quantize: _a , _a , _a : Tuple =self.quantize(SCREAMING_SNAKE_CASE ) else: _a : str =h _a : Dict =self.post_quant_conv(SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =self.decoder(SCREAMING_SNAKE_CASE , quant if self.config.norm_type == """spatial""" else None ) if not return_dict: return (dec,) return DecoderOutput(sample=SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :torch.FloatTensor , SCREAMING_SNAKE_CASE :bool = True ) -> Union[DecoderOutput, torch.FloatTensor]: '''simple docstring''' _a : Tuple =sample _a : int =self.encode(SCREAMING_SNAKE_CASE ).latents _a : List[Any] =self.decode(SCREAMING_SNAKE_CASE ).sample if not return_dict: return (dec,) return DecoderOutput(sample=SCREAMING_SNAKE_CASE )
276
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_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL A__: Optional[int] = logging.get_logger(__name__) class A__ ( UpperCAmelCase__ ): __UpperCamelCase : Optional[Any] = ["pixel_values"] def __init__( self :Dict , SCREAMING_SNAKE_CASE :bool = True , SCREAMING_SNAKE_CASE :Dict[str, int] = None , SCREAMING_SNAKE_CASE :int = 0.9 , SCREAMING_SNAKE_CASE :PILImageResampling = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE :bool = True , SCREAMING_SNAKE_CASE :Dict[str, int] = None , SCREAMING_SNAKE_CASE :Union[int, float] = 1 / 2_5_5 , SCREAMING_SNAKE_CASE :bool = True , SCREAMING_SNAKE_CASE :bool = True , SCREAMING_SNAKE_CASE :Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE :Optional[Union[float, List[float]]] = None , **SCREAMING_SNAKE_CASE :Union[str, Any] , ) -> None: '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE ) _a : Optional[Any] =size if size is not None else {"""shortest_edge""": 2_2_4} _a : Union[str, Any] =get_size_dict(SCREAMING_SNAKE_CASE , default_to_square=SCREAMING_SNAKE_CASE ) _a : List[str] =crop_size if crop_size is not None else {"""height""": 2_2_4, """width""": 2_2_4} _a : Dict =get_size_dict(SCREAMING_SNAKE_CASE , param_name="""crop_size""" ) _a : Tuple =do_resize _a : List[Any] =size _a : List[Any] =crop_pct _a : str =resample _a : int =do_center_crop _a : Optional[int] =crop_size _a : Optional[Any] =do_rescale _a : str =rescale_factor _a : Any =do_normalize _a : Any =image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN _a : Tuple =image_std if image_std is not None else IMAGENET_DEFAULT_STD def __UpperCAmelCase ( self :Tuple , SCREAMING_SNAKE_CASE :np.ndarray , SCREAMING_SNAKE_CASE :Dict[str, int] , SCREAMING_SNAKE_CASE :Optional[float] = None , SCREAMING_SNAKE_CASE :PILImageResampling = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE :Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE :List[str] , ) -> np.ndarray: '''simple docstring''' _a : Union[str, Any] =get_size_dict(SCREAMING_SNAKE_CASE , default_to_square=SCREAMING_SNAKE_CASE ) if "shortest_edge" not in size and ("height" not in size or "width" not in size): raise ValueError(f"size must contain 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}" ) if crop_pct is not None: if "shortest_edge" in size: _a : List[str] =int(size["""shortest_edge"""] / crop_pct ) elif "height" in size and "width" in size: if size["height"] == size["width"]: _a : Union[str, Any] =int(size["""height"""] / crop_pct ) else: _a : Optional[int] =(int(size["""height"""] / crop_pct ), int(size["""width"""] / crop_pct )) else: raise ValueError("""Invalid size for resize: {}""".format(SCREAMING_SNAKE_CASE ) ) _a : int =get_resize_output_image_size(SCREAMING_SNAKE_CASE , size=SCREAMING_SNAKE_CASE , default_to_square=SCREAMING_SNAKE_CASE ) else: if "shortest_edge" in size: _a : Tuple =get_resize_output_image_size(SCREAMING_SNAKE_CASE , size=size["""shortest_edge"""] , default_to_square=SCREAMING_SNAKE_CASE ) elif "height" in size and "width" in size: _a : List[str] =(size["""height"""], size["""width"""]) else: raise ValueError("""Invalid size for resize: {}""".format(SCREAMING_SNAKE_CASE ) ) return resize(SCREAMING_SNAKE_CASE , size=SCREAMING_SNAKE_CASE , resample=SCREAMING_SNAKE_CASE , data_format=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :str , SCREAMING_SNAKE_CASE :np.ndarray , SCREAMING_SNAKE_CASE :Dict[str, int] , SCREAMING_SNAKE_CASE :Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE :str , ) -> np.ndarray: '''simple docstring''' _a : Optional[Any] =get_size_dict(SCREAMING_SNAKE_CASE ) if "height" not in size or "width" not in size: raise ValueError(f"size must contain 'height' and 'width' as keys. Got {size.keys()}" ) return center_crop(SCREAMING_SNAKE_CASE , size=(size["""height"""], size["""width"""]) , data_format=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :np.ndarray , SCREAMING_SNAKE_CASE :Union[int, float] , SCREAMING_SNAKE_CASE :Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE :str , ) -> Optional[int]: '''simple docstring''' return rescale(SCREAMING_SNAKE_CASE , scale=SCREAMING_SNAKE_CASE , data_format=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Any , SCREAMING_SNAKE_CASE :np.ndarray , SCREAMING_SNAKE_CASE :Union[float, List[float]] , SCREAMING_SNAKE_CASE :Union[float, List[float]] , SCREAMING_SNAKE_CASE :Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE :Optional[int] , ) -> np.ndarray: '''simple docstring''' return normalize(SCREAMING_SNAKE_CASE , mean=SCREAMING_SNAKE_CASE , std=SCREAMING_SNAKE_CASE , data_format=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Any , SCREAMING_SNAKE_CASE :ImageInput , SCREAMING_SNAKE_CASE :bool = None , SCREAMING_SNAKE_CASE :Dict[str, int] = None , SCREAMING_SNAKE_CASE :int = None , SCREAMING_SNAKE_CASE :PILImageResampling = None , SCREAMING_SNAKE_CASE :bool = None , SCREAMING_SNAKE_CASE :Dict[str, int] = None , SCREAMING_SNAKE_CASE :bool = None , SCREAMING_SNAKE_CASE :float = None , SCREAMING_SNAKE_CASE :bool = None , SCREAMING_SNAKE_CASE :Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE :Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE :Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE :ChannelDimension = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE :Union[str, Any] , ) -> PIL.Image.Image: '''simple docstring''' _a : int =do_resize if do_resize is not None else self.do_resize _a : int =crop_pct if crop_pct is not None else self.crop_pct _a : Optional[int] =resample if resample is not None else self.resample _a : List[Any] =do_center_crop if do_center_crop is not None else self.do_center_crop _a : Tuple =do_rescale if do_rescale is not None else self.do_rescale _a : Dict =rescale_factor if rescale_factor is not None else self.rescale_factor _a : Tuple =do_normalize if do_normalize is not None else self.do_normalize _a : Optional[Any] =image_mean if image_mean is not None else self.image_mean _a : Any =image_std if image_std is not None else self.image_std _a : Union[str, Any] =size if size is not None else self.size _a : Optional[Any] =get_size_dict(SCREAMING_SNAKE_CASE , default_to_square=SCREAMING_SNAKE_CASE ) _a : Optional[int] =crop_size if crop_size is not None else self.crop_size _a : int =get_size_dict(SCREAMING_SNAKE_CASE , param_name="""crop_size""" ) _a : int =make_list_of_images(SCREAMING_SNAKE_CASE ) if not valid_images(SCREAMING_SNAKE_CASE ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None or resample is None: raise ValueError("""Size and resample must be specified if do_resize is True.""" ) if do_center_crop and crop_pct is None: raise ValueError("""Crop_pct 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. _a : Optional[Any] =[to_numpy_array(SCREAMING_SNAKE_CASE ) for image in images] if do_resize: _a : List[str] =[self.resize(image=SCREAMING_SNAKE_CASE , size=SCREAMING_SNAKE_CASE , crop_pct=SCREAMING_SNAKE_CASE , resample=SCREAMING_SNAKE_CASE ) for image in images] if do_center_crop: _a : str =[self.center_crop(image=SCREAMING_SNAKE_CASE , size=SCREAMING_SNAKE_CASE ) for image in images] if do_rescale: _a : Optional[int] =[self.rescale(image=SCREAMING_SNAKE_CASE , scale=SCREAMING_SNAKE_CASE ) for image in images] if do_normalize: _a : Optional[int] =[self.normalize(image=SCREAMING_SNAKE_CASE , mean=SCREAMING_SNAKE_CASE , std=SCREAMING_SNAKE_CASE ) for image in images] _a : Union[str, Any] =[to_channel_dimension_format(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for image in images] _a : List[Any] ={"""pixel_values""": images} return BatchFeature(data=SCREAMING_SNAKE_CASE , tensor_type=SCREAMING_SNAKE_CASE )
276
'''simple docstring''' import unittest from transformers import EsmConfig, is_torch_available from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import EsmForMaskedLM, EsmForSequenceClassification, EsmForTokenClassification, EsmModel from transformers.models.esm.modeling_esm import ( ESM_PRETRAINED_MODEL_ARCHIVE_LIST, EsmEmbeddings, create_position_ids_from_input_ids, ) class A__ : def __init__( self :Tuple , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :Optional[int]=1_3 , SCREAMING_SNAKE_CASE :Optional[int]=7 , SCREAMING_SNAKE_CASE :Tuple=False , SCREAMING_SNAKE_CASE :Dict=True , SCREAMING_SNAKE_CASE :Optional[int]=False , SCREAMING_SNAKE_CASE :Optional[Any]=True , SCREAMING_SNAKE_CASE :List[str]=3_3 , SCREAMING_SNAKE_CASE :Tuple=3_2 , SCREAMING_SNAKE_CASE :Tuple=5 , SCREAMING_SNAKE_CASE :int=4 , SCREAMING_SNAKE_CASE :Union[str, Any]=3_7 , SCREAMING_SNAKE_CASE :List[str]="gelu" , SCREAMING_SNAKE_CASE :Optional[Any]=0.1 , SCREAMING_SNAKE_CASE :Tuple=0.1 , SCREAMING_SNAKE_CASE :str=5_1_2 , SCREAMING_SNAKE_CASE :Dict=1_6 , SCREAMING_SNAKE_CASE :Dict=2 , SCREAMING_SNAKE_CASE :Union[str, Any]=0.02 , SCREAMING_SNAKE_CASE :str=3 , SCREAMING_SNAKE_CASE :List[str]=4 , SCREAMING_SNAKE_CASE :List[str]=None , ) -> Union[str, Any]: '''simple docstring''' _a : Union[str, Any] =parent _a : List[Any] =batch_size _a : Optional[int] =seq_length _a : Union[str, Any] =is_training _a : List[Any] =use_input_mask _a : Optional[int] =use_token_type_ids _a : int =use_labels _a : List[str] =vocab_size _a : List[Any] =hidden_size _a : int =num_hidden_layers _a : Tuple =num_attention_heads _a : Any =intermediate_size _a : str =hidden_act _a : Union[str, Any] =hidden_dropout_prob _a : Union[str, Any] =attention_probs_dropout_prob _a : str =max_position_embeddings _a : Dict =type_vocab_size _a : Tuple =type_sequence_label_size _a : Dict =initializer_range _a : List[str] =num_labels _a : Tuple =num_choices _a : int =scope def __UpperCAmelCase ( self :Union[str, Any] ) -> str: '''simple docstring''' _a : Optional[int] =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _a : List[Any] =None if self.use_input_mask: _a : Any =random_attention_mask([self.batch_size, self.seq_length] ) _a : Optional[int] =None _a : str =None _a : Dict =None if self.use_labels: _a : Dict =ids_tensor([self.batch_size] , self.type_sequence_label_size ) _a : str =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _a : List[str] =ids_tensor([self.batch_size] , self.num_choices ) _a : List[Any] =self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCAmelCase ( self :str ) -> Optional[int]: '''simple docstring''' return EsmConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , pad_token_id=1 , 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 __UpperCAmelCase ( self :List[str] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :Optional[Any] , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :int ) -> Tuple: '''simple docstring''' _a : Any =EsmModel(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() _a : Optional[Any] =model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =model(SCREAMING_SNAKE_CASE ) _a : str =model(SCREAMING_SNAKE_CASE ) 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 __UpperCAmelCase ( self :str , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :Optional[Any] ) -> Dict: '''simple docstring''' _a : str =EsmForMaskedLM(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() _a : Union[str, Any] =model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :Optional[Any] , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :List[Any] , SCREAMING_SNAKE_CASE :Union[str, Any] ) -> Optional[Any]: '''simple docstring''' _a : int =self.num_labels _a : Tuple =EsmForTokenClassification(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() _a : Tuple =model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCAmelCase ( self :Dict ) -> List[str]: '''simple docstring''' _a : Optional[Any] =self.prepare_config_and_inputs() ( ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ) : Any =config_and_inputs _a : List[Any] ={"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class A__ ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): __UpperCamelCase : Any = False __UpperCamelCase : Any = ( ( EsmForMaskedLM, EsmModel, EsmForSequenceClassification, EsmForTokenClassification, ) if is_torch_available() else () ) __UpperCamelCase : str = () __UpperCamelCase : List[str] = ( { "feature-extraction": EsmModel, "fill-mask": EsmForMaskedLM, "text-classification": EsmForSequenceClassification, "token-classification": EsmForTokenClassification, "zero-shot": EsmForSequenceClassification, } if is_torch_available() else {} ) __UpperCamelCase : Union[str, Any] = True def __UpperCAmelCase ( self :Optional[int] ) -> int: '''simple docstring''' _a : Dict =EsmModelTester(self ) _a : Optional[Any] =ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , hidden_size=3_7 ) def __UpperCAmelCase ( self :Tuple ) -> List[Any]: '''simple docstring''' self.config_tester.run_common_tests() def __UpperCAmelCase ( self :Optional[int] ) -> str: '''simple docstring''' _a : List[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :List[Any] ) -> Dict: '''simple docstring''' _a : List[str] =self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: _a : Dict =type self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Dict ) -> List[str]: '''simple docstring''' _a : Tuple =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :List[Any] ) -> List[str]: '''simple docstring''' _a : str =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*SCREAMING_SNAKE_CASE ) @slow def __UpperCAmelCase ( self :str ) -> Dict: '''simple docstring''' for model_name in ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _a : Union[str, Any] =EsmModel.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Tuple ) -> int: '''simple docstring''' _a : Optional[Any] =self.model_tester.prepare_config_and_inputs()[0] _a : Dict =EsmEmbeddings(config=SCREAMING_SNAKE_CASE ) _a : Tuple =torch.as_tensor([[1_2, 3_1, 1_3, model.padding_idx]] ) _a : Optional[Any] =torch.as_tensor( [ [ 0 + model.padding_idx + 1, 1 + model.padding_idx + 1, 2 + model.padding_idx + 1, model.padding_idx, ] ] ) _a : Any =create_position_ids_from_input_ids(SCREAMING_SNAKE_CASE , model.padding_idx ) self.assertEqual(position_ids.shape , expected_positions.shape ) self.assertTrue(torch.all(torch.eq(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) ) def __UpperCAmelCase ( self :Optional[Any] ) -> Tuple: '''simple docstring''' _a : List[Any] =self.model_tester.prepare_config_and_inputs()[0] _a : Optional[int] =EsmEmbeddings(config=SCREAMING_SNAKE_CASE ) _a : Tuple =torch.empty(2 , 4 , 3_0 ) _a : str =[ 0 + embeddings.padding_idx + 1, 1 + embeddings.padding_idx + 1, 2 + embeddings.padding_idx + 1, 3 + embeddings.padding_idx + 1, ] _a : int =torch.as_tensor([expected_single_positions, expected_single_positions] ) _a : Any =embeddings.create_position_ids_from_inputs_embeds(SCREAMING_SNAKE_CASE ) self.assertEqual(position_ids.shape , expected_positions.shape ) self.assertTrue(torch.all(torch.eq(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) ) @unittest.skip("""Esm does not support embedding resizing""" ) def __UpperCAmelCase ( self :Tuple ) -> List[str]: '''simple docstring''' pass @unittest.skip("""Esm does not support embedding resizing""" ) def __UpperCAmelCase ( self :str ) -> Any: '''simple docstring''' pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def __UpperCAmelCase ( self :Dict ) -> Any: '''simple docstring''' pass @require_torch class A__ ( UpperCAmelCase__ ): @slow def __UpperCAmelCase ( self :List[Any] ) -> str: '''simple docstring''' with torch.no_grad(): _a : Optional[int] =EsmForMaskedLM.from_pretrained("""facebook/esm2_t6_8M_UR50D""" ) model.eval() _a : Any =torch.tensor([[0, 1, 2, 3, 4, 5]] ) _a : Tuple =model(SCREAMING_SNAKE_CASE )[0] _a : int =3_3 _a : Tuple =torch.Size((1, 6, vocab_size) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =torch.tensor( [[[8.9_215, -10.5_898, -6.4_671], [-6.3_967, -13.9_114, -1.1_212], [-7.7_812, -13.9_516, -3.7_406]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) ) @slow def __UpperCAmelCase ( self :Union[str, Any] ) -> Tuple: '''simple docstring''' with torch.no_grad(): _a : Any =EsmModel.from_pretrained("""facebook/esm2_t6_8M_UR50D""" ) model.eval() _a : Any =torch.tensor([[0, 6, 4, 1_3, 5, 4, 1_6, 1_2, 1_1, 7, 2]] ) _a : int =model(SCREAMING_SNAKE_CASE )[0] # compare the actual values for a slice. _a : str =torch.tensor( [[[0.1_444, 0.5_413, 0.3_248], [0.3_034, 0.0_053, 0.3_108], [0.3_228, -0.2_499, 0.3_415]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) )
276
1
'''simple docstring''' import warnings from ...utils import logging from .image_processing_mobilevit import MobileViTImageProcessor A__: Union[str, Any] = logging.get_logger(__name__) class A__ ( UpperCAmelCase__ ): def __init__( self :List[Any] , *SCREAMING_SNAKE_CASE :str , **SCREAMING_SNAKE_CASE :Tuple ) -> None: '''simple docstring''' warnings.warn( """The class MobileViTFeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use MobileViTImageProcessor instead.""" , SCREAMING_SNAKE_CASE , ) super().__init__(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE )
276
'''simple docstring''' from math import isqrt def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ) -> bool: return all(number % divisor != 0 for divisor in range(2 ,isqrt(_UpperCAmelCase ) + 1 ) ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int = 10**6 ) -> int: _a : List[Any] =0 _a : str =1 _a : Optional[Any] =7 while prime_candidate < max_prime: primes_count += is_prime(_UpperCAmelCase ) cube_index += 1 prime_candidate += 6 * cube_index return primes_count if __name__ == "__main__": print(F"{solution() = }")
276
1
'''simple docstring''' from maths.prime_check import is_prime def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ) -> int: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): _a : int =F"Input value of [number={number}] must be an integer" raise TypeError(_UpperCAmelCase ) if is_prime(_UpperCAmelCase ) and is_prime(number + 2 ): return number + 2 else: return -1 if __name__ == "__main__": import doctest doctest.testmod()
276
'''simple docstring''' # 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 ...utils import deprecate from ..controlnet.multicontrolnet import MultiControlNetModel # noqa: F401 from ..controlnet.pipeline_controlnet import StableDiffusionControlNetPipeline # noqa: F401 deprecate( '''stable diffusion controlnet''', '''0.22.0''', '''Importing `StableDiffusionControlNetPipeline` or `MultiControlNetModel` from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import StableDiffusionControlNetPipeline` instead.''', standard_warn=False, stacklevel=3, )
276
1
'''simple docstring''' import math def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ) -> bool: if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 ,int(math.sqrt(_UpperCAmelCase ) + 1 ) ,6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int = 10001 ) -> int: try: _a : List[str] =int(_UpperCAmelCase ) except (TypeError, ValueError): raise TypeError("""Parameter nth must be int or castable to int.""" ) from None if nth <= 0: raise ValueError("""Parameter nth must be greater than or equal to one.""" ) _a : list[int] =[] _a : Any =2 while len(_UpperCAmelCase ) < nth: if is_prime(_UpperCAmelCase ): primes.append(_UpperCAmelCase ) num += 1 else: num += 1 return primes[len(_UpperCAmelCase ) - 1] if __name__ == "__main__": print(F"{solution() = }")
276
'''simple docstring''' import pytest from datasets.utils.sharding import _distribute_shards, _number_of_shards_in_gen_kwargs, _split_gen_kwargs @pytest.mark.parametrize( """kwargs, expected""" ,[ ({"""num_shards""": 0, """max_num_jobs""": 1}, []), ({"""num_shards""": 10, """max_num_jobs""": 1}, [range(10 )]), ({"""num_shards""": 10, """max_num_jobs""": 10}, [range(_UpperCAmelCase ,i + 1 ) for i in range(10 )]), ({"""num_shards""": 1, """max_num_jobs""": 10}, [range(1 )]), ({"""num_shards""": 10, """max_num_jobs""": 3}, [range(0 ,4 ), range(4 ,7 ), range(7 ,10 )]), ({"""num_shards""": 3, """max_num_jobs""": 10}, [range(0 ,1 ), range(1 ,2 ), range(2 ,3 )]), ] ,) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : Dict ) -> Optional[Any]: _a : Tuple =_distribute_shards(**_UpperCAmelCase ) assert out == expected @pytest.mark.parametrize( """gen_kwargs, max_num_jobs, expected""" ,[ ({"""foo""": 0}, 10, [{"""foo""": 0}]), ({"""shards""": [0, 1, 2, 3]}, 1, [{"""shards""": [0, 1, 2, 3]}]), ({"""shards""": [0, 1, 2, 3]}, 4, [{"""shards""": [0]}, {"""shards""": [1]}, {"""shards""": [2]}, {"""shards""": [3]}]), ({"""shards""": [0, 1]}, 4, [{"""shards""": [0]}, {"""shards""": [1]}]), ({"""shards""": [0, 1, 2, 3]}, 2, [{"""shards""": [0, 1]}, {"""shards""": [2, 3]}]), ] ,) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : List[Any] ,_UpperCAmelCase : Union[str, Any] ) -> List[str]: _a : List[str] =_split_gen_kwargs(_UpperCAmelCase ,_UpperCAmelCase ) assert out == expected @pytest.mark.parametrize( """gen_kwargs, expected""" ,[ ({"""foo""": 0}, 1), ({"""shards""": [0]}, 1), ({"""shards""": [0, 1, 2, 3]}, 4), ({"""shards""": [0, 1, 2, 3], """foo""": 0}, 4), ({"""shards""": [0, 1, 2, 3], """other""": (0, 1)}, 4), ({"""shards""": [0, 1, 2, 3], """shards2""": [0, 1]}, RuntimeError), ] ,) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : List[Any] ) -> Union[str, Any]: if expected is RuntimeError: with pytest.raises(_UpperCAmelCase ): _number_of_shards_in_gen_kwargs(_UpperCAmelCase ) else: _a : Dict =_number_of_shards_in_gen_kwargs(_UpperCAmelCase ) assert out == expected
276
1
'''simple docstring''' def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ) -> list[int]: _a : Union[str, Any] =[0 for i in range(len(_UpperCAmelCase ) )] # initialize interval's left pointer and right pointer _a , _a : List[Any] =0, 0 for i in range(1 ,len(_UpperCAmelCase ) ): # case when current index is inside the interval if i <= right_pointer: _a : Any =min(right_pointer - i + 1 ,z_result[i - left_pointer] ) _a : Dict =min_edge while go_next(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ): z_result[i] += 1 # if new index's result gives us more right interval, # we've to update left_pointer and right_pointer if i + z_result[i] - 1 > right_pointer: _a , _a : Tuple =i, i + z_result[i] - 1 return z_result def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ,_UpperCAmelCase : list[int] ,_UpperCAmelCase : str ) -> bool: return i + z_result[i] < len(_UpperCAmelCase ) and s[z_result[i]] == s[i + z_result[i]] def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : str ) -> int: _a : int =0 # concatenate 'pattern' and 'input_str' and call z_function # with concatenated string _a : List[Any] =z_function(pattern + input_str ) for val in z_result: # if value is greater then length of the pattern string # that means this index is starting position of substring # which is equal to pattern string if val >= len(_UpperCAmelCase ): answer += 1 return answer if __name__ == "__main__": import doctest doctest.testmod()
276
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A__: Dict = logging.get_logger(__name__) A__: Tuple = { '''weiweishi/roc-bert-base-zh''': '''https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json''', } class A__ ( UpperCAmelCase__ ): __UpperCamelCase : Tuple = "roc_bert" def __init__( self :Optional[int] , SCREAMING_SNAKE_CASE :Tuple=3_0_5_2_2 , SCREAMING_SNAKE_CASE :List[str]=7_6_8 , SCREAMING_SNAKE_CASE :Dict=1_2 , SCREAMING_SNAKE_CASE :List[str]=1_2 , SCREAMING_SNAKE_CASE :Tuple=3_0_7_2 , SCREAMING_SNAKE_CASE :List[Any]="gelu" , SCREAMING_SNAKE_CASE :Union[str, Any]=0.1 , SCREAMING_SNAKE_CASE :List[Any]=0.1 , SCREAMING_SNAKE_CASE :int=5_1_2 , SCREAMING_SNAKE_CASE :Optional[Any]=2 , SCREAMING_SNAKE_CASE :Union[str, Any]=0.02 , SCREAMING_SNAKE_CASE :Optional[Any]=1e-12 , SCREAMING_SNAKE_CASE :Any=True , SCREAMING_SNAKE_CASE :List[Any]=0 , SCREAMING_SNAKE_CASE :Optional[int]="absolute" , SCREAMING_SNAKE_CASE :Union[str, Any]=None , SCREAMING_SNAKE_CASE :List[Any]=True , SCREAMING_SNAKE_CASE :int=True , SCREAMING_SNAKE_CASE :Optional[int]=7_6_8 , SCREAMING_SNAKE_CASE :Optional[Any]=9_1_0 , SCREAMING_SNAKE_CASE :Union[str, Any]=5_1_2 , SCREAMING_SNAKE_CASE :str=2_4_8_5_8 , SCREAMING_SNAKE_CASE :List[Any]=True , **SCREAMING_SNAKE_CASE :Tuple , ) -> Optional[int]: '''simple docstring''' _a : List[str] =vocab_size _a : List[str] =max_position_embeddings _a : Optional[Any] =hidden_size _a : List[Any] =num_hidden_layers _a : List[str] =num_attention_heads _a : int =intermediate_size _a : Any =hidden_act _a : Dict =hidden_dropout_prob _a : int =attention_probs_dropout_prob _a : str =initializer_range _a : Optional[int] =type_vocab_size _a : Any =layer_norm_eps _a : Any =use_cache _a : Optional[int] =enable_pronunciation _a : Optional[Any] =enable_shape _a : Optional[Any] =pronunciation_embed_dim _a : Tuple =pronunciation_vocab_size _a : Union[str, Any] =shape_embed_dim _a : Any =shape_vocab_size _a : Tuple =concat_input _a : List[str] =position_embedding_type _a : List[str] =classifier_dropout super().__init__(pad_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE )
276
1
'''simple docstring''' import argparse from pathlib import Path import torch from transformers import OPTConfig, OPTModel from transformers.utils import logging logging.set_verbosity_info() A__: int = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[Any] ) -> Dict: _a : Optional[int] =torch.load(_UpperCAmelCase ,map_location="""cpu""" ) if "model" in sd.keys(): _a : List[Any] =torch.load(_UpperCAmelCase ,map_location="""cpu""" )["""model"""] # pop unnecessary weights _a : List[Any] =[ """decoder.version""", """decoder.output_projection.weight""", ] for key in keys_to_delete: if key in sd: sd.pop(_UpperCAmelCase ) _a : List[str] ={ """decoder.project_in_dim.weight""": """decoder.project_in.weight""", """decoder.project_out_dim.weight""": """decoder.project_out.weight""", """decoder.layer_norm.weight""": """decoder.final_layer_norm.weight""", """decoder.layer_norm.bias""": """decoder.final_layer_norm.bias""", } for old_key, new_key in keys_to_rename.items(): if old_key in sd: _a : List[Any] =sd.pop(_UpperCAmelCase ) _a : Union[str, Any] =list(sd.keys() ) for key in keys: if ".qkv_proj." in key: _a : Union[str, Any] =sd[key] # We split QKV in separate Q,K,V _a : Tuple =key.replace(""".qkv_proj.""" ,""".q_proj.""" ) _a : Any =key.replace(""".qkv_proj.""" ,""".k_proj.""" ) _a : List[Any] =key.replace(""".qkv_proj.""" ,""".v_proj.""" ) _a : int =value.shape[0] assert depth % 3 == 0 # `SequeuceParallelTransformerBlock` has QKV weight is separated in K,V,Q despite the naming: # https://cs.github.com/facebookresearch/metaseq/blob/51871bd73cd04c038f239ea2a26db1d7f6b37927/metaseq/modules/sequence_parallel_transformer_layer.py#L97 _a , _a , _a : Optional[Any] =torch.split(_UpperCAmelCase ,depth // 3 ,dim=0 ) _a : str =q _a : Dict =k _a : Tuple =v del sd[key] return sd @torch.no_grad() def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : Optional[int] ,_UpperCAmelCase : int=None ) -> Dict: _a : Optional[Any] =load_checkpoint(_UpperCAmelCase ) if config is not None: _a : List[str] =OPTConfig.from_pretrained(_UpperCAmelCase ) else: _a : Dict =OPTConfig() _a : List[str] =OPTModel(_UpperCAmelCase ).half().eval() model.load_state_dict(_UpperCAmelCase ) # Check results Path(_UpperCAmelCase ).mkdir(exist_ok=_UpperCAmelCase ) model.save_pretrained(_UpperCAmelCase ) if __name__ == "__main__": A__: Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--fairseq_path''', type=str, help=( '''path to fairseq checkpoint in correct format. You can find all checkpoints in the correct format here:''' ''' https://huggingface.co/models?other=opt_metasq''' ), ) parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--hf_config''', default=None, type=str, help='''Define HF config.''') A__: Tuple = parser.parse_args() convert_opt_checkpoint(args.fairseq_path, args.pytorch_dump_folder_path, config=args.hf_config)
276
'''simple docstring''' class A__ : def __init__( self :List[str] ) -> List[Any]: '''simple docstring''' _a : Tuple =0 _a : Any =0 _a : int ={} def __UpperCAmelCase ( self :Any , SCREAMING_SNAKE_CASE :List[str] ) -> Optional[int]: '''simple docstring''' if vertex not in self.adjacency: _a : Dict ={} self.num_vertices += 1 def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Any ) -> List[str]: '''simple docstring''' self.add_vertex(SCREAMING_SNAKE_CASE ) self.add_vertex(SCREAMING_SNAKE_CASE ) if head == tail: return _a : Any =weight _a : Tuple =weight def __UpperCAmelCase ( self :Dict ) -> Optional[int]: '''simple docstring''' _a : Union[str, Any] =self.get_edges() for edge in edges: _a , _a , _a : List[str] =edge edges.remove((tail, head, weight) ) for i in range(len(SCREAMING_SNAKE_CASE ) ): _a : str =list(edges[i] ) edges.sort(key=lambda SCREAMING_SNAKE_CASE : e[2] ) for i in range(len(SCREAMING_SNAKE_CASE ) - 1 ): if edges[i][2] >= edges[i + 1][2]: _a : Union[str, Any] =edges[i][2] + 1 for edge in edges: _a , _a , _a : Tuple =edge _a : Tuple =weight _a : List[Any] =weight def __str__( self :int ) -> str: '''simple docstring''' _a : int ="""""" for tail in self.adjacency: for head in self.adjacency[tail]: _a : str =self.adjacency[head][tail] string += f"{head} -> {tail} == {weight}\n" return string.rstrip("""\n""" ) def __UpperCAmelCase ( self :Optional[int] ) -> Optional[Any]: '''simple docstring''' _a : Union[str, Any] =[] for tail in self.adjacency: for head in self.adjacency[tail]: output.append((tail, head, self.adjacency[head][tail]) ) return output def __UpperCAmelCase ( self :List[Any] ) -> List[Any]: '''simple docstring''' return self.adjacency.keys() @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :Dict=None , SCREAMING_SNAKE_CASE :List[Any]=None ) -> Optional[int]: '''simple docstring''' _a : str =Graph() if vertices is None: _a : Union[str, Any] =[] if edges is None: _a : List[Any] =[] for vertex in vertices: g.add_vertex(SCREAMING_SNAKE_CASE ) for edge in edges: g.add_edge(*SCREAMING_SNAKE_CASE ) return g class A__ : def __init__( self :Optional[int] ) -> Union[str, Any]: '''simple docstring''' _a : Optional[int] ={} _a : List[str] ={} def __len__( self :List[Any] ) -> List[Any]: '''simple docstring''' return len(self.parent ) def __UpperCAmelCase ( self :Tuple , SCREAMING_SNAKE_CASE :Tuple ) -> Dict: '''simple docstring''' if item in self.parent: return self.find(SCREAMING_SNAKE_CASE ) _a : Optional[Any] =item _a : List[str] =0 return item def __UpperCAmelCase ( self :int , SCREAMING_SNAKE_CASE :Dict ) -> List[str]: '''simple docstring''' if item not in self.parent: return self.make_set(SCREAMING_SNAKE_CASE ) if item != self.parent[item]: _a : str =self.find(self.parent[item] ) return self.parent[item] def __UpperCAmelCase ( self :Optional[int] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :List[Any] ) -> Optional[Any]: '''simple docstring''' _a : Optional[int] =self.find(SCREAMING_SNAKE_CASE ) _a : Dict =self.find(SCREAMING_SNAKE_CASE ) if roota == roota: return roota if self.rank[roota] > self.rank[roota]: _a : Any =roota return roota if self.rank[roota] < self.rank[roota]: _a : List[str] =roota return roota if self.rank[roota] == self.rank[roota]: self.rank[roota] += 1 _a : List[Any] =roota return roota return None @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :Dict ) -> Union[str, Any]: '''simple docstring''' _a : Any =graph.num_vertices _a : Union[str, Any] =Graph.UnionFind() _a : Optional[int] =[] while num_components > 1: _a : str ={} for vertex in graph.get_vertices(): _a : List[str] =-1 _a : Any =graph.get_edges() for edge in edges: _a , _a , _a : Tuple =edge edges.remove((tail, head, weight) ) for edge in edges: _a , _a , _a : Any =edge _a : Any =union_find.find(SCREAMING_SNAKE_CASE ) _a : List[Any] =union_find.find(SCREAMING_SNAKE_CASE ) if seta != seta: if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight: _a : Optional[int] =[head, tail, weight] if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight: _a : List[Any] =[head, tail, weight] for vertex in cheap_edge: if cheap_edge[vertex] != -1: _a , _a , _a : Optional[Any] =cheap_edge[vertex] if union_find.find(SCREAMING_SNAKE_CASE ) != union_find.find(SCREAMING_SNAKE_CASE ): union_find.union(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) mst_edges.append(cheap_edge[vertex] ) _a : str =num_components - 1 _a : str =Graph.build(edges=SCREAMING_SNAKE_CASE ) return mst
276
1
'''simple docstring''' from ..utils import DummyObject, requires_backends class A__ ( metaclass=UpperCAmelCase__ ): __UpperCamelCase : Optional[int] = ["torch", "torchsde"] def __init__( self :Optional[int] , *SCREAMING_SNAKE_CASE :Optional[int] , **SCREAMING_SNAKE_CASE :Optional[int] ) -> Union[str, Any]: '''simple docstring''' requires_backends(self , ["""torch""", """torchsde"""] ) @classmethod def __UpperCAmelCase ( cls :Dict , *SCREAMING_SNAKE_CASE :Optional[Any] , **SCREAMING_SNAKE_CASE :List[str] ) -> Optional[Any]: '''simple docstring''' requires_backends(cls , ["""torch""", """torchsde"""] ) @classmethod def __UpperCAmelCase ( cls :Optional[Any] , *SCREAMING_SNAKE_CASE :Union[str, Any] , **SCREAMING_SNAKE_CASE :int ) -> Union[str, Any]: '''simple docstring''' requires_backends(cls , ["""torch""", """torchsde"""] )
276
'''simple docstring''' from datetime import datetime import requests from bsa import BeautifulSoup if __name__ == "__main__": A__: Union[str, Any] = input('''Enter image url: ''').strip() print(F"Downloading image from {url} ...") A__: Tuple = BeautifulSoup(requests.get(url).content, '''html.parser''') # The image URL is in the content field of the first meta tag with property og:image A__: Union[str, Any] = soup.find('''meta''', {'''property''': '''og:image'''})['''content'''] A__: List[Any] = requests.get(image_url).content A__: List[str] = F"{datetime.now():%Y-%m-%d_%H:%M:%S}.jpg" with open(file_name, '''wb''') as fp: fp.write(image_data) print(F"Done. Image saved to disk as {file_name}.")
276
1
'''simple docstring''' from collections.abc import Generator from math import sin def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : bytes ) -> bytes: if len(_UpperCAmelCase ) != 32: raise ValueError("""Input must be of length 32""" ) _a : Union[str, Any] =B"""""" for i in [3, 2, 1, 0]: little_endian += string_aa[8 * i : 8 * i + 8] return little_endian def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ) -> bytes: if i < 0: raise ValueError("""Input must be non-negative""" ) _a : Dict =format(_UpperCAmelCase ,"""08x""" )[-8:] _a : Optional[Any] =B"""""" for i in [3, 2, 1, 0]: little_endian_hex += hex_rep[2 * i : 2 * i + 2].encode("""utf-8""" ) return little_endian_hex def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : bytes ) -> bytes: _a : Tuple =B"""""" for char in message: bit_string += format(_UpperCAmelCase ,"""08b""" ).encode("""utf-8""" ) _a : Optional[Any] =format(len(_UpperCAmelCase ) ,"""064b""" ).encode("""utf-8""" ) # Pad bit_string to a multiple of 512 chars bit_string += b"1" while len(_UpperCAmelCase ) % 512 != 448: bit_string += b"0" bit_string += to_little_endian(start_len[32:] ) + to_little_endian(start_len[:32] ) return bit_string def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : bytes ) -> Generator[list[int], None, None]: if len(_UpperCAmelCase ) % 512 != 0: raise ValueError("""Input must have length that's a multiple of 512""" ) for pos in range(0 ,len(_UpperCAmelCase ) ,512 ): _a : Optional[Any] =bit_string[pos : pos + 512] _a : Any =[] for i in range(0 ,512 ,32 ): block_words.append(int(to_little_endian(block[i : i + 32] ) ,2 ) ) yield block_words def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ) -> int: if i < 0: raise ValueError("""Input must be non-negative""" ) _a : Any =format(_UpperCAmelCase ,"""032b""" ) _a : str ="""""" for c in i_str: new_str += "1" if c == "0" else "0" return int(_UpperCAmelCase ,2 ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ,_UpperCAmelCase : int ) -> int: return (a + b) % 2**32 def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ,_UpperCAmelCase : int ) -> int: if i < 0: raise ValueError("""Input must be non-negative""" ) if shift < 0: raise ValueError("""Shift must be non-negative""" ) return ((i << shift) ^ (i >> (32 - shift))) % 2**32 def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : bytes ) -> bytes: _a : List[str] =preprocess(_UpperCAmelCase ) _a : Optional[int] =[int(2**32 * abs(sin(i + 1 ) ) ) for i in range(64 )] # Starting states _a : Union[str, Any] =0x67_452_301 _a : List[Any] =0xEF_CDA_B89 _a : int =0x98_BAD_CFE _a : List[str] =0x10_325_476 _a : List[Any] =[ 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, ] # Process bit string in chunks, each with 16 32-char words for block_words in get_block_words(_UpperCAmelCase ): _a : str =aa _a : str =ba _a : Optional[int] =ca _a : List[str] =da # Hash current chunk for i in range(64 ): if i <= 15: # f = (b & c) | (not_32(b) & d) # Alternate definition for f _a : Optional[int] =d ^ (b & (c ^ d)) _a : Dict =i elif i <= 31: # f = (d & b) | (not_32(d) & c) # Alternate definition for f _a : Optional[Any] =c ^ (d & (b ^ c)) _a : List[Any] =(5 * i + 1) % 16 elif i <= 47: _a : Union[str, Any] =b ^ c ^ d _a : Union[str, Any] =(3 * i + 5) % 16 else: _a : Any =c ^ (b | not_aa(_UpperCAmelCase )) _a : Optional[Any] =(7 * i) % 16 _a : Tuple =(f + a + added_consts[i] + block_words[g]) % 2**32 _a : List[Any] =d _a : List[str] =c _a : int =b _a : int =sum_aa(_UpperCAmelCase ,left_rotate_aa(_UpperCAmelCase ,shift_amounts[i] ) ) # Add hashed chunk to running total _a : int =sum_aa(_UpperCAmelCase ,_UpperCAmelCase ) _a : Dict =sum_aa(_UpperCAmelCase ,_UpperCAmelCase ) _a : Dict =sum_aa(_UpperCAmelCase ,_UpperCAmelCase ) _a : Any =sum_aa(_UpperCAmelCase ,_UpperCAmelCase ) _a : Any =reformat_hex(_UpperCAmelCase ) + reformat_hex(_UpperCAmelCase ) + reformat_hex(_UpperCAmelCase ) + reformat_hex(_UpperCAmelCase ) return digest if __name__ == "__main__": import doctest doctest.testmod()
276
'''simple docstring''' A__: Tuple = ''' # Installazione di Transformers ! pip install transformers datasets # Per installare dalla fonte invece dell\'ultima versione rilasciata, commenta il comando sopra e # rimuovi la modalità commento al comando seguente. # ! pip install git+https://github.com/huggingface/transformers.git ''' A__: Tuple = [{'''type''': '''code''', '''content''': INSTALL_CONTENT}] A__: Any = { '''{processor_class}''': '''FakeProcessorClass''', '''{model_class}''': '''FakeModelClass''', '''{object_class}''': '''FakeObjectClass''', }
276
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A__: int = logging.get_logger(__name__) A__: List[str] = { '''microsoft/trocr-base-handwritten''': ( '''https://huggingface.co/microsoft/trocr-base-handwritten/resolve/main/config.json''' ), # See all TrOCR models at https://huggingface.co/models?filter=trocr } class A__ ( UpperCAmelCase__ ): __UpperCamelCase : Optional[int] = "trocr" __UpperCamelCase : List[str] = ["past_key_values"] __UpperCamelCase : Optional[int] = { "num_attention_heads": "decoder_attention_heads", "hidden_size": "d_model", "num_hidden_layers": "decoder_layers", } def __init__( self :List[str] , SCREAMING_SNAKE_CASE :Tuple=5_0_2_6_5 , SCREAMING_SNAKE_CASE :List[str]=1_0_2_4 , SCREAMING_SNAKE_CASE :Optional[int]=1_2 , SCREAMING_SNAKE_CASE :Any=1_6 , SCREAMING_SNAKE_CASE :int=4_0_9_6 , SCREAMING_SNAKE_CASE :Optional[int]="gelu" , SCREAMING_SNAKE_CASE :Tuple=5_1_2 , SCREAMING_SNAKE_CASE :Tuple=0.1 , SCREAMING_SNAKE_CASE :Optional[Any]=0.0 , SCREAMING_SNAKE_CASE :Dict=0.0 , SCREAMING_SNAKE_CASE :str=2 , SCREAMING_SNAKE_CASE :Tuple=0.02 , SCREAMING_SNAKE_CASE :Tuple=0.0 , SCREAMING_SNAKE_CASE :List[str]=True , SCREAMING_SNAKE_CASE :Union[str, Any]=False , SCREAMING_SNAKE_CASE :Any=True , SCREAMING_SNAKE_CASE :List[Any]=True , SCREAMING_SNAKE_CASE :Dict=1 , SCREAMING_SNAKE_CASE :Any=0 , SCREAMING_SNAKE_CASE :Optional[Any]=2 , **SCREAMING_SNAKE_CASE :Any , ) -> Tuple: '''simple docstring''' _a : Optional[Any] =vocab_size _a : Tuple =d_model _a : int =decoder_layers _a : str =decoder_attention_heads _a : Union[str, Any] =decoder_ffn_dim _a : Union[str, Any] =activation_function _a : Any =max_position_embeddings _a : Any =dropout _a : Any =attention_dropout _a : List[Any] =activation_dropout _a : Union[str, Any] =init_std _a : Optional[int] =decoder_layerdrop _a : Optional[int] =use_cache _a : Optional[int] =scale_embedding _a : List[Any] =use_learned_position_embeddings _a : int =layernorm_embedding super().__init__( pad_token_id=SCREAMING_SNAKE_CASE , bos_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE , decoder_start_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , )
276
'''simple docstring''' A__: Optional[int] = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] A__: Any = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] A__: int = { 0: '''Sunday''', 1: '''Monday''', 2: '''Tuesday''', 3: '''Wednesday''', 4: '''Thursday''', 5: '''Friday''', 6: '''Saturday''', } def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ,_UpperCAmelCase : int ,_UpperCAmelCase : int ) -> str: assert len(str(_UpperCAmelCase ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 12, "month should be between 1 to 12" assert 1 <= day <= 31, "day should be between 1 to 31" # Doomsday algorithm: _a : List[str] =year // 100 _a : List[str] =(5 * (century % 4) + 2) % 7 _a : Optional[int] =year % 100 _a : Any =centurian % 12 _a : int =( (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 _a : Optional[Any] =( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 400) == 0) else DOOMSDAY_LEAP[month - 1] ) _a : str =(dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
276
1
'''simple docstring''' import unittest from transformers import SPIECE_UNDERLINE, ReformerTokenizer, ReformerTokenizerFast 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 A__: Any = get_tests_dir('''fixtures/test_sentencepiece.model''') @require_sentencepiece @require_tokenizers class A__ ( UpperCAmelCase__ , unittest.TestCase ): __UpperCamelCase : List[str] = ReformerTokenizer __UpperCamelCase : Any = ReformerTokenizerFast __UpperCamelCase : str = True __UpperCamelCase : Dict = False __UpperCamelCase : Any = True def __UpperCAmelCase ( self :Any ) -> Any: '''simple docstring''' super().setUp() _a : Union[str, Any] =ReformerTokenizer(SCREAMING_SNAKE_CASE , keep_accents=SCREAMING_SNAKE_CASE ) tokenizer.save_pretrained(self.tmpdirname ) def __UpperCAmelCase ( self :Optional[int] ) -> Dict: '''simple docstring''' _a : List[str] ="""<s>""" _a : List[str] =1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Dict ) -> Optional[Any]: '''simple docstring''' _a : Union[str, 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] , """j""" ) self.assertEqual(len(SCREAMING_SNAKE_CASE ) , 1_0_0_0 ) def __UpperCAmelCase ( self :Union[str, Any] ) -> Tuple: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1_0_0_0 ) def __UpperCAmelCase ( self :Tuple ) -> Optional[Any]: '''simple docstring''' if not self.test_rust_tokenizer: return _a : Tuple =self.get_tokenizer() _a : List[str] =self.get_rust_tokenizer() _a : List[Any] ="""I was born in 92000, and this is falsé.""" _a : Union[str, Any] =tokenizer.tokenize(SCREAMING_SNAKE_CASE ) _a : str =rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) _a : Dict =tokenizer.encode(SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =rust_tokenizer.encode(SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) _a : str =self.get_rust_tokenizer() _a : int =tokenizer.encode(SCREAMING_SNAKE_CASE ) _a : Optional[int] =rust_tokenizer.encode(SCREAMING_SNAKE_CASE ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :int , SCREAMING_SNAKE_CASE :str=1_5 ) -> Union[str, Any]: '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})" ): _a : Dict =self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) # Simple input _a : List[Any] ="""This is a simple input""" _a : Union[str, Any] =["""This is a simple input 1""", """This is a simple input 2"""] _a : Tuple =("""This is a simple input""", """This is a pair""") _a : str =[ ("""This is a simple input 1""", """This is a simple input 2"""), ("""This is a simple pair 1""", """This is a simple pair 2"""), ] # Simple input tests self.assertRaises(SCREAMING_SNAKE_CASE , tokenizer_r.encode , SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE , padding="""max_length""" ) # Simple input self.assertRaises(SCREAMING_SNAKE_CASE , tokenizer_r.encode_plus , SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE , padding="""max_length""" ) # Simple input self.assertRaises( SCREAMING_SNAKE_CASE , tokenizer_r.batch_encode_plus , SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE , padding="""max_length""" , ) # Pair input self.assertRaises(SCREAMING_SNAKE_CASE , tokenizer_r.encode , SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE , padding="""max_length""" ) # Pair input self.assertRaises(SCREAMING_SNAKE_CASE , tokenizer_r.encode_plus , SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE , padding="""max_length""" ) # Pair input self.assertRaises( SCREAMING_SNAKE_CASE , tokenizer_r.batch_encode_plus , SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE , padding="""max_length""" , ) def __UpperCAmelCase ( self :Optional[int] ) -> Optional[int]: '''simple docstring''' pass def __UpperCAmelCase ( self :Any ) -> Union[str, Any]: '''simple docstring''' _a : List[str] =ReformerTokenizer(SCREAMING_SNAKE_CASE , keep_accents=SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =tokenizer.tokenize("""This is a test""" ) self.assertListEqual(SCREAMING_SNAKE_CASE , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE ) , [2_8_5, 4_6, 1_0, 1_7_0, 3_8_2] , ) _a : Tuple =tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( SCREAMING_SNAKE_CASE , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """9""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """é""", """.""", ] , ) _a : List[Any] =tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE ) self.assertListEqual( SCREAMING_SNAKE_CASE , [8, 2_1, 8_4, 5_5, 2_4, 1_9, 7, 0, 6_0_2, 3_4_7, 3_4_7, 3_4_7, 3, 1_2, 6_6, 4_6, 7_2, 8_0, 6, 0, 4] , ) _a : Union[str, Any] =tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE ) self.assertListEqual( SCREAMING_SNAKE_CASE , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """<unk>""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """<unk>""", """.""", ] , ) @cached_property def __UpperCAmelCase ( self :Optional[int] ) -> List[str]: '''simple docstring''' return ReformerTokenizer.from_pretrained("""google/reformer-crime-and-punishment""" ) @slow def __UpperCAmelCase ( self :Any ) -> int: '''simple docstring''' _a : Any ="""Hello World!""" _a : List[str] =[1_2_6, 3_2, 2_6_2, 1_5_2, 3_8, 7_2, 2_8_7] self.assertListEqual(SCREAMING_SNAKE_CASE , self.big_tokenizer.encode(SCREAMING_SNAKE_CASE ) ) @slow def __UpperCAmelCase ( self :Optional[Any] ) -> List[Any]: '''simple docstring''' _a : Tuple =( """This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) \" [ ] ! : - . Also we will""" """ add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth""" ) _a : Optional[Any] =[ 1_0_8, 2_6_5, 2_4, 1_1_1, 4, 2_5_8, 1_5_6, 3_5, 2_8, 2_7_5, 3, 2_5_9, 2_9_7, 2_6_0, 8_4, 4, 3_5, 1_1_0, 4_4, 8, 2_5_9, 9_1, 2_6_8, 2_1, 1_1, 2_0_9, 2_7_4, 1_0_9, 2_6_6, 2_7_7, 1_1_7, 8_6, 9_3, 3_1_5, 2_5_8, 2_7_8, 2_5_8, 2_7_7, 2_5_8, 0, 2_5_8, 2_8_8, 2_5_8, 3_1_9, 2_5_8, 0, 2_5_8, 0, 2_5_8, 0, 2_5_8, 0, 2_5_8, 2_8_7, 2_5_8, 3_1_5, 2_5_8, 2_8_9, 2_5_8, 2_7_8, 9_9, 2_6_9, 2_6_6, 2_6_2, 8, 2_5_9, 2_4_1, 4, 2_1_7, 2_3_0, 2_6_8, 2_6_6, 5_5, 1_6_8, 1_0_6, 7_5, 1_9_3, 2_6_6, 2_2_3, 2_7, 4_9, 2_6, 2_8_2, 2_5, 2_6_4, 2_9_9, 1_9, 2_6, 0, 2_5_8, 2_7_7, 1_1_7, 8_6, 9_3, 1_7_6, 1_8_3, 2_7_0, 1_1, 2_6_2, 4_2, 6_1, 2_6_5, ] self.assertListEqual(SCREAMING_SNAKE_CASE , self.big_tokenizer.encode(SCREAMING_SNAKE_CASE ) ) @require_torch @slow def __UpperCAmelCase ( self :str ) -> List[str]: '''simple docstring''' import torch from transformers import ReformerConfig, ReformerModel # Build sequence _a : Dict =list(self.big_tokenizer.get_vocab().keys() )[:1_0] _a : Dict =""" """.join(SCREAMING_SNAKE_CASE ) _a : Optional[int] =self.big_tokenizer.encode_plus(SCREAMING_SNAKE_CASE , return_tensors="""pt""" ) _a : Optional[int] =self.big_tokenizer.batch_encode_plus([sequence, sequence] , return_tensors="""pt""" ) _a : str =ReformerConfig() # The input gets padded during training so adjust the axial position encodings from the pretrained model value of (512, 1024) _a : Union[str, Any] =encoded_sequence["""input_ids"""].shape _a : List[str] =ReformerModel(SCREAMING_SNAKE_CASE ) # Reformer has config.vocab_size == tokenizer.vocab_size == len(tokenizer) - 1 = 320; len(tokenizer) is 321 (including a pad token with id 320) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**SCREAMING_SNAKE_CASE ) model(**SCREAMING_SNAKE_CASE ) @slow def __UpperCAmelCase ( self :int ) -> str: '''simple docstring''' # fmt: off _a : Any ={"""input_ids""": [[1_0_8, 2_6_5, 2_4, 1_1_1, 4, 2_5_8, 1_5_6, 7, 5_1, 2_7_9, 5_8, 7, 7_6, 2_5, 6_9, 2_7_8], [1_4_0, 2_4_3, 2_6_4, 1_3_4, 1_7, 2_6_7, 7_7, 2_6_3, 2_2, 2_6_2, 2_9_7, 2_5_8, 3_0_4, 1_7_7, 2_7_9, 2_6_6, 1_4, 8_9, 1_3, 3_5, 2_6_1, 2_9_9, 2_7_2, 1_3_7, 2_7_5, 2_7_8]], """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]]} # noqa: E501 # fmt: on # This tokenizer does not know some characters like ")". # That is the reason why we use very simple texts here. # Also see https://github.com/huggingface/transformers/pull/11737#issuecomment-850769064 _a : str =[ """This is a very simple sentence.""", """The quick brown fox jumps over the lazy dog.""", ] self.tokenizer_integration_test_util( expected_encoding=SCREAMING_SNAKE_CASE , model_name="""google/reformer-crime-and-punishment""" , revision="""0e6c3decb8211d49bf881013425dc8b0448b3f5a""" , padding=SCREAMING_SNAKE_CASE , sequences=SCREAMING_SNAKE_CASE , )
276
'''simple docstring''' from __future__ import annotations from typing import TypedDict class A__ ( UpperCAmelCase__ ): __UpperCamelCase : str __UpperCamelCase : int def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ) -> list[str]: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError("""The parameter s type must be str.""" ) return [s[i:] + s[:i] for i in range(len(_UpperCAmelCase ) )] def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ) -> BWTTransformDict: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError("""The parameter s type must be str.""" ) if not s: raise ValueError("""The parameter s must not be empty.""" ) _a : List[Any] =all_rotations(_UpperCAmelCase ) rotations.sort() # sort the list of rotations in alphabetically order # make a string composed of the last char of each rotation _a : BWTTransformDict ={ "bwt_string": "".join([word[-1] for word in rotations] ), "idx_original_string": rotations.index(_UpperCAmelCase ), } return response def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : int ) -> str: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError("""The parameter bwt_string type must be str.""" ) if not bwt_string: raise ValueError("""The parameter bwt_string must not be empty.""" ) try: _a : List[str] =int(_UpperCAmelCase ) except ValueError: raise TypeError( """The parameter idx_original_string type must be int or passive""" """ of cast to int.""" ) if idx_original_string < 0: raise ValueError("""The parameter idx_original_string must not be lower than 0.""" ) if idx_original_string >= len(_UpperCAmelCase ): raise ValueError( """The parameter idx_original_string must be lower than""" """ len(bwt_string).""" ) _a : Optional[int] =[""""""] * len(_UpperCAmelCase ) for _ in range(len(_UpperCAmelCase ) ): for i in range(len(_UpperCAmelCase ) ): _a : int =bwt_string[i] + ordered_rotations[i] ordered_rotations.sort() return ordered_rotations[idx_original_string] if __name__ == "__main__": A__: Any = '''Provide a string that I will generate its BWT transform: ''' A__: Union[str, Any] = input(entry_msg).strip() A__: Optional[int] = bwt_transform(s) print( F"Burrows Wheeler transform for string '{s}' results " F"in '{result['bwt_string']}'" ) A__: Union[str, Any] = reverse_bwt(result['''bwt_string'''], result['''idx_original_string''']) print( F"Reversing Burrows Wheeler transform for entry '{result['bwt_string']}' " F"we get original string '{original_string}'" )
276
1
'''simple docstring''' import argparse import gc import json import os import shutil import warnings import torch from transformers import LlamaConfig, LlamaForCausalLM, LlamaTokenizer try: from transformers import LlamaTokenizerFast except ImportError as e: warnings.warn(e) warnings.warn( '''The converted tokenizer will be the `slow` tokenizer. To use the fast, update your `tokenizers` library and re-run the tokenizer conversion''' ) A__: Dict = None A__: Tuple = { '''7B''': 1_1008, '''13B''': 1_3824, '''30B''': 1_7920, '''65B''': 2_2016, '''70B''': 2_8672, } A__: Any = { '''7B''': 1, '''7Bf''': 1, '''13B''': 2, '''13Bf''': 2, '''30B''': 4, '''65B''': 8, '''70B''': 8, '''70Bf''': 8, } def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Optional[int]=1 ,_UpperCAmelCase : List[str]=256 ) -> Dict: return multiple_of * ((int(ffn_dim_multiplier * int(8 * n / 3 ) ) + multiple_of - 1) // multiple_of) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[Any] ) -> List[str]: with open(_UpperCAmelCase ,"""r""" ) as f: return json.load(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : Optional[Any] ) -> Tuple: with open(_UpperCAmelCase ,"""w""" ) as f: json.dump(_UpperCAmelCase ,_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : int ,_UpperCAmelCase : List[Any]=True ) -> Union[str, Any]: os.makedirs(_UpperCAmelCase ,exist_ok=_UpperCAmelCase ) _a : Union[str, Any] =os.path.join(_UpperCAmelCase ,"""tmp""" ) os.makedirs(_UpperCAmelCase ,exist_ok=_UpperCAmelCase ) _a : int =read_json(os.path.join(_UpperCAmelCase ,"""params.json""" ) ) _a : int =NUM_SHARDS[model_size] _a : Dict =params["""n_layers"""] _a : Union[str, Any] =params["""n_heads"""] _a : List[str] =n_heads // num_shards _a : int =params["""dim"""] _a : Union[str, Any] =dim // n_heads _a : int =1_0_0_0_0.0 _a : str =1.0 / (base ** (torch.arange(0 ,_UpperCAmelCase ,2 ).float() / dims_per_head)) if "n_kv_heads" in params: _a : str =params["""n_kv_heads"""] # for GQA / MQA _a : Optional[Any] =n_heads_per_shard // num_key_value_heads _a : Optional[int] =dim // num_key_value_heads else: # compatibility with other checkpoints _a : str =n_heads _a : Any =n_heads_per_shard _a : str =dim # permute for sliced rotary def permute(_UpperCAmelCase : Tuple ,_UpperCAmelCase : Optional[int]=n_heads ,_UpperCAmelCase : Optional[int]=dim ,_UpperCAmelCase : List[str]=dim ): return w.view(_UpperCAmelCase ,dima // n_heads // 2 ,2 ,_UpperCAmelCase ).transpose(1 ,2 ).reshape(_UpperCAmelCase ,_UpperCAmelCase ) print(F"Fetching all parameters from the checkpoint at {input_base_path}." ) # Load weights if model_size == "7B": # Not sharded # (The sharded implementation would also work, but this is simpler.) _a : Any =torch.load(os.path.join(_UpperCAmelCase ,"""consolidated.00.pth""" ) ,map_location="""cpu""" ) else: # Sharded _a : List[Any] =[ torch.load(os.path.join(_UpperCAmelCase ,F"consolidated.{i:02d}.pth" ) ,map_location="""cpu""" ) for i in range(_UpperCAmelCase ) ] _a : Any =0 _a : Optional[int] ={"""weight_map""": {}} for layer_i in range(_UpperCAmelCase ): _a : List[str] =F"pytorch_model-{layer_i + 1}-of-{n_layers + 1}.bin" if model_size == "7B": # Unsharded _a : List[str] ={ F"model.layers.{layer_i}.self_attn.q_proj.weight": permute( loaded[F"layers.{layer_i}.attention.wq.weight"] ), F"model.layers.{layer_i}.self_attn.k_proj.weight": permute( loaded[F"layers.{layer_i}.attention.wk.weight"] ), F"model.layers.{layer_i}.self_attn.v_proj.weight": loaded[F"layers.{layer_i}.attention.wv.weight"], F"model.layers.{layer_i}.self_attn.o_proj.weight": loaded[F"layers.{layer_i}.attention.wo.weight"], F"model.layers.{layer_i}.mlp.gate_proj.weight": loaded[F"layers.{layer_i}.feed_forward.w1.weight"], F"model.layers.{layer_i}.mlp.down_proj.weight": loaded[F"layers.{layer_i}.feed_forward.w2.weight"], F"model.layers.{layer_i}.mlp.up_proj.weight": loaded[F"layers.{layer_i}.feed_forward.w3.weight"], F"model.layers.{layer_i}.input_layernorm.weight": loaded[F"layers.{layer_i}.attention_norm.weight"], F"model.layers.{layer_i}.post_attention_layernorm.weight": loaded[F"layers.{layer_i}.ffn_norm.weight"], } else: # Sharded # Note that attention.w{q,k,v,o}, feed_fordward.w[1,2,3], attention_norm.weight and ffn_norm.weight share # the same storage object, saving attention_norm and ffn_norm will save other weights too, which is # redundant as other weights will be stitched from multiple shards. To avoid that, they are cloned. _a : Tuple ={ F"model.layers.{layer_i}.input_layernorm.weight": loaded[0][ F"layers.{layer_i}.attention_norm.weight" ].clone(), F"model.layers.{layer_i}.post_attention_layernorm.weight": loaded[0][ F"layers.{layer_i}.ffn_norm.weight" ].clone(), } _a : str =permute( torch.cat( [ loaded[i][F"layers.{layer_i}.attention.wq.weight"].view(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) for i in range(_UpperCAmelCase ) ] ,dim=0 ,).reshape(_UpperCAmelCase ,_UpperCAmelCase ) ) _a : Tuple =permute( torch.cat( [ loaded[i][F"layers.{layer_i}.attention.wk.weight"].view( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) for i in range(_UpperCAmelCase ) ] ,dim=0 ,).reshape(_UpperCAmelCase ,_UpperCAmelCase ) ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,) _a : Any =torch.cat( [ loaded[i][F"layers.{layer_i}.attention.wv.weight"].view( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) for i in range(_UpperCAmelCase ) ] ,dim=0 ,).reshape(_UpperCAmelCase ,_UpperCAmelCase ) _a : List[str] =torch.cat( [loaded[i][F"layers.{layer_i}.attention.wo.weight"] for i in range(_UpperCAmelCase )] ,dim=1 ) _a : Union[str, Any] =torch.cat( [loaded[i][F"layers.{layer_i}.feed_forward.w1.weight"] for i in range(_UpperCAmelCase )] ,dim=0 ) _a : Tuple =torch.cat( [loaded[i][F"layers.{layer_i}.feed_forward.w2.weight"] for i in range(_UpperCAmelCase )] ,dim=1 ) _a : Union[str, Any] =torch.cat( [loaded[i][F"layers.{layer_i}.feed_forward.w3.weight"] for i in range(_UpperCAmelCase )] ,dim=0 ) _a : str =inv_freq for k, v in state_dict.items(): _a : Any =filename param_count += v.numel() torch.save(_UpperCAmelCase ,os.path.join(_UpperCAmelCase ,_UpperCAmelCase ) ) _a : Union[str, Any] =F"pytorch_model-{n_layers + 1}-of-{n_layers + 1}.bin" if model_size == "7B": # Unsharded _a : List[str] ={ """model.embed_tokens.weight""": loaded["""tok_embeddings.weight"""], """model.norm.weight""": loaded["""norm.weight"""], """lm_head.weight""": loaded["""output.weight"""], } else: _a : int ={ """model.norm.weight""": loaded[0]["""norm.weight"""], """model.embed_tokens.weight""": torch.cat( [loaded[i]["""tok_embeddings.weight"""] for i in range(_UpperCAmelCase )] ,dim=1 ), """lm_head.weight""": torch.cat([loaded[i]["""output.weight"""] for i in range(_UpperCAmelCase )] ,dim=0 ), } for k, v in state_dict.items(): _a : Dict =filename param_count += v.numel() torch.save(_UpperCAmelCase ,os.path.join(_UpperCAmelCase ,_UpperCAmelCase ) ) # Write configs _a : Tuple ={"""total_size""": param_count * 2} write_json(_UpperCAmelCase ,os.path.join(_UpperCAmelCase ,"""pytorch_model.bin.index.json""" ) ) _a : Optional[Any] =params["""ffn_dim_multiplier"""] if """ffn_dim_multiplier""" in params else 1 _a : int =params["""multiple_of"""] if """multiple_of""" in params else 256 _a : List[Any] =LlamaConfig( hidden_size=_UpperCAmelCase ,intermediate_size=compute_intermediate_size(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) ,num_attention_heads=params["""n_heads"""] ,num_hidden_layers=params["""n_layers"""] ,rms_norm_eps=params["""norm_eps"""] ,num_key_value_heads=_UpperCAmelCase ,) config.save_pretrained(_UpperCAmelCase ) # Make space so we can load the model properly now. del state_dict del loaded gc.collect() print("""Loading the checkpoint in a Llama model.""" ) _a : Any =LlamaForCausalLM.from_pretrained(_UpperCAmelCase ,torch_dtype=torch.floataa ,low_cpu_mem_usage=_UpperCAmelCase ) # Avoid saving this as part of the config. del model.config._name_or_path print("""Saving in the Transformers format.""" ) model.save_pretrained(_UpperCAmelCase ,safe_serialization=_UpperCAmelCase ) shutil.rmtree(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ,_UpperCAmelCase : int ) -> Optional[Any]: # Initialize the tokenizer based on the `spm` model _a : List[str] =LlamaTokenizer if LlamaTokenizerFast is None else LlamaTokenizerFast print(F"Saving a {tokenizer_class.__name__} to {tokenizer_path}." ) _a : List[Any] =tokenizer_class(_UpperCAmelCase ) tokenizer.save_pretrained(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( ) -> Union[str, Any]: _a : List[str] =argparse.ArgumentParser() parser.add_argument( """--input_dir""" ,help="""Location of LLaMA weights, which contains tokenizer.model and model folders""" ,) parser.add_argument( """--model_size""" ,choices=["""7B""", """7Bf""", """13B""", """13Bf""", """30B""", """65B""", """70B""", """70Bf""", """tokenizer_only"""] ,) parser.add_argument( """--output_dir""" ,help="""Location to write HF model and tokenizer""" ,) parser.add_argument("""--safe_serialization""" ,type=_UpperCAmelCase ,help="""Whether or not to save using `safetensors`.""" ) _a : Optional[Any] =parser.parse_args() if args.model_size != "tokenizer_only": write_model( model_path=args.output_dir ,input_base_path=os.path.join(args.input_dir ,args.model_size ) ,model_size=args.model_size ,safe_serialization=args.safe_serialization ,) _a : List[Any] =os.path.join(args.input_dir ,"""tokenizer.model""" ) write_tokenizer(args.output_dir ,_UpperCAmelCase ) if __name__ == "__main__": main()
276
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available A__: List[str] = { '''configuration_chinese_clip''': [ '''CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ChineseCLIPConfig''', '''ChineseCLIPOnnxConfig''', '''ChineseCLIPTextConfig''', '''ChineseCLIPVisionConfig''', ], '''processing_chinese_clip''': ['''ChineseCLIPProcessor'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Optional[int] = ['''ChineseCLIPFeatureExtractor'''] A__: Any = ['''ChineseCLIPImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Dict = [ '''CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ChineseCLIPModel''', '''ChineseCLIPPreTrainedModel''', '''ChineseCLIPTextModel''', '''ChineseCLIPVisionModel''', ] if TYPE_CHECKING: from .configuration_chinese_clip import ( CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, ChineseCLIPConfig, ChineseCLIPOnnxConfig, ChineseCLIPTextConfig, ChineseCLIPVisionConfig, ) from .processing_chinese_clip import ChineseCLIPProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_chinese_clip import ChineseCLIPFeatureExtractor, ChineseCLIPImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_chinese_clip import ( CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, ChineseCLIPModel, ChineseCLIPPreTrainedModel, ChineseCLIPTextModel, ChineseCLIPVisionModel, ) else: import sys A__: str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
276
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) A__: str = { '''configuration_albert''': ['''ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''AlbertConfig''', '''AlbertOnnxConfig'''], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Tuple = ['''AlbertTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Tuple = ['''AlbertTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Optional[int] = [ '''ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''AlbertForMaskedLM''', '''AlbertForMultipleChoice''', '''AlbertForPreTraining''', '''AlbertForQuestionAnswering''', '''AlbertForSequenceClassification''', '''AlbertForTokenClassification''', '''AlbertModel''', '''AlbertPreTrainedModel''', '''load_tf_weights_in_albert''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Union[str, Any] = [ '''TF_ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFAlbertForMaskedLM''', '''TFAlbertForMultipleChoice''', '''TFAlbertForPreTraining''', '''TFAlbertForQuestionAnswering''', '''TFAlbertForSequenceClassification''', '''TFAlbertForTokenClassification''', '''TFAlbertMainLayer''', '''TFAlbertModel''', '''TFAlbertPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Optional[int] = [ '''FlaxAlbertForMaskedLM''', '''FlaxAlbertForMultipleChoice''', '''FlaxAlbertForPreTraining''', '''FlaxAlbertForQuestionAnswering''', '''FlaxAlbertForSequenceClassification''', '''FlaxAlbertForTokenClassification''', '''FlaxAlbertModel''', '''FlaxAlbertPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_albert import ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, AlbertConfig, AlbertOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_albert import AlbertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_albert_fast import AlbertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_albert import ( ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST, AlbertForMaskedLM, AlbertForMultipleChoice, AlbertForPreTraining, AlbertForQuestionAnswering, AlbertForSequenceClassification, AlbertForTokenClassification, AlbertModel, AlbertPreTrainedModel, load_tf_weights_in_albert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_albert import ( TF_ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFAlbertForMaskedLM, TFAlbertForMultipleChoice, TFAlbertForPreTraining, TFAlbertForQuestionAnswering, TFAlbertForSequenceClassification, TFAlbertForTokenClassification, TFAlbertMainLayer, TFAlbertModel, TFAlbertPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_albert import ( FlaxAlbertForMaskedLM, FlaxAlbertForMultipleChoice, FlaxAlbertForPreTraining, FlaxAlbertForQuestionAnswering, FlaxAlbertForSequenceClassification, FlaxAlbertForTokenClassification, FlaxAlbertModel, FlaxAlbertPreTrainedModel, ) else: import sys A__: str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
276
'''simple docstring''' class A__ : def __init__( self :List[Any] ) -> None: '''simple docstring''' _a : dict[str, TrieNode] ={} # Mapping from char to TrieNode _a : List[str] =False def __UpperCAmelCase ( self :Tuple , SCREAMING_SNAKE_CASE :list[str] ) -> None: '''simple docstring''' for word in words: self.insert(SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :str ) -> None: '''simple docstring''' _a : str =self for char in word: if char not in curr.nodes: _a : Dict =TrieNode() _a : List[Any] =curr.nodes[char] _a : int =True def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :str ) -> bool: '''simple docstring''' _a : int =self for char in word: if char not in curr.nodes: return False _a : List[Any] =curr.nodes[char] return curr.is_leaf def __UpperCAmelCase ( self :Dict , SCREAMING_SNAKE_CASE :str ) -> None: '''simple docstring''' def _delete(SCREAMING_SNAKE_CASE :TrieNode , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :int ) -> bool: if index == len(SCREAMING_SNAKE_CASE ): # If word does not exist if not curr.is_leaf: return False _a : Any =False return len(curr.nodes ) == 0 _a : int =word[index] _a : int =curr.nodes.get(SCREAMING_SNAKE_CASE ) # If char not in current trie node if not char_node: return False # Flag to check if node can be deleted _a : List[Any] =_delete(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , index + 1 ) if delete_curr: del curr.nodes[char] return len(curr.nodes ) == 0 return delete_curr _delete(self , SCREAMING_SNAKE_CASE , 0 ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : TrieNode ,_UpperCAmelCase : str ) -> None: if node.is_leaf: print(_UpperCAmelCase ,end=""" """ ) for key, value in node.nodes.items(): print_words(_UpperCAmelCase ,word + key ) def SCREAMING_SNAKE_CASE_ ( ) -> bool: _a : List[str] ="""banana bananas bandana band apple all beast""".split() _a : List[Any] =TrieNode() root.insert_many(_UpperCAmelCase ) # print_words(root, "") assert all(root.find(_UpperCAmelCase ) for word in words ) assert root.find("""banana""" ) assert not root.find("""bandanas""" ) assert not root.find("""apps""" ) assert root.find("""apple""" ) assert root.find("""all""" ) root.delete("""all""" ) assert not root.find("""all""" ) root.delete("""banana""" ) assert not root.find("""banana""" ) assert root.find("""bananas""" ) return True def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : bool ) -> None: print(str(_UpperCAmelCase ) ,"""works!""" if passes else """doesn't work :(""" ) def SCREAMING_SNAKE_CASE_ ( ) -> None: assert test_trie() def SCREAMING_SNAKE_CASE_ ( ) -> None: print_results("""Testing trie functionality""" ,test_trie() ) if __name__ == "__main__": main()
276
1
'''simple docstring''' import os # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_doctest_list.py A__: List[Any] = '''.''' if __name__ == "__main__": A__: List[str] = os.path.join(REPO_PATH, '''utils/documentation_tests.txt''') A__: Any = [] A__: int = [] with open(doctest_file_path) as fp: for line in fp: A__: Dict = line.strip() A__: Optional[int] = os.path.join(REPO_PATH, line) if not (os.path.isfile(path) or os.path.isdir(path)): non_existent_paths.append(line) all_paths.append(path) if len(non_existent_paths) > 0: A__: str = '''\n'''.join(non_existent_paths) raise ValueError(F"`utils/documentation_tests.txt` contains non-existent paths:\n{non_existent_paths}") if all_paths != sorted(all_paths): raise ValueError('''Files in `utils/documentation_tests.txt` are not in alphabetical order.''')
276
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available A__: str = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Tuple = ['''GPTSw3Tokenizer'''] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_swa import GPTSwaTokenizer else: import sys A__: str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
276
1
'''simple docstring''' import numpy as np def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : np.ndarray ,_UpperCAmelCase : float ) -> np.ndarray: return np.where(vector > 0 ,_UpperCAmelCase ,(alpha * (np.exp(_UpperCAmelCase ) - 1)) ) if __name__ == "__main__": import doctest doctest.testmod()
276
'''simple docstring''' import importlib.metadata import warnings from copy import deepcopy from packaging import version from ..utils import logging from .import_utils import is_accelerate_available, is_bitsandbytes_available if is_bitsandbytes_available(): import bitsandbytes as bnb import torch import torch.nn as nn from ..pytorch_utils import ConvaD if is_accelerate_available(): from accelerate import init_empty_weights from accelerate.utils import find_tied_parameters A__: str = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[Any] ,_UpperCAmelCase : List[str] ,_UpperCAmelCase : int ,_UpperCAmelCase : int=None ,_UpperCAmelCase : Optional[Any]=None ) -> Optional[Any]: # Recurse if needed if "." in tensor_name: _a : Union[str, Any] =tensor_name.split(""".""" ) for split in splits[:-1]: _a : Optional[Any] =getattr(_UpperCAmelCase ,_UpperCAmelCase ) if new_module is None: raise ValueError(F"{module} has no attribute {split}." ) _a : Optional[int] =new_module _a : Optional[int] =splits[-1] if tensor_name not in module._parameters and tensor_name not in module._buffers: raise ValueError(F"{module} does not have a parameter or a buffer named {tensor_name}." ) _a : Optional[Any] =tensor_name in module._buffers _a : str =getattr(_UpperCAmelCase ,_UpperCAmelCase ) if old_value.device == torch.device("""meta""" ) and device not in ["meta", torch.device("""meta""" )] and value is None: raise ValueError(F"{tensor_name} is on the meta device, we need a `value` to put in on {device}." ) _a : int =False _a : Tuple =False if is_buffer or not is_bitsandbytes_available(): _a : str =False _a : Optional[Any] =False else: _a : int =hasattr(bnb.nn ,"""Params4bit""" ) and isinstance(module._parameters[tensor_name] ,bnb.nn.Paramsabit ) _a : int =isinstance(module._parameters[tensor_name] ,bnb.nn.IntaParams ) if is_abit or is_abit: _a : Any =module._parameters[tensor_name] if param.device.type != "cuda": if value is None: _a : int =old_value.to(_UpperCAmelCase ) elif isinstance(_UpperCAmelCase ,torch.Tensor ): _a : str =value.to("""cpu""" ) if value.dtype == torch.inta: _a : int =version.parse(importlib.metadata.version("""bitsandbytes""" ) ) > version.parse( """0.37.2""" ) if not is_abit_serializable: raise ValueError( """Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. """ """Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`.""" ) else: _a : Dict =torch.tensor(_UpperCAmelCase ,device="""cpu""" ) # Support models using `Conv1D` in place of `nn.Linear` (e.g. gpt2) by transposing the weight matrix prior to quantization. # Since weights are saved in the correct "orientation", we skip transposing when loading. if issubclass(module.source_cls ,_UpperCAmelCase ) and fpaa_statistics is None: _a : int =new_value.T _a : Any =old_value.__dict__ if is_abit: _a : Any =bnb.nn.IntaParams(_UpperCAmelCase ,requires_grad=_UpperCAmelCase ,**_UpperCAmelCase ).to(_UpperCAmelCase ) elif is_abit: _a : Union[str, Any] =bnb.nn.Paramsabit(_UpperCAmelCase ,requires_grad=_UpperCAmelCase ,**_UpperCAmelCase ).to(_UpperCAmelCase ) _a : List[Any] =new_value if fpaa_statistics is not None: setattr(module.weight ,"""SCB""" ,fpaa_statistics.to(_UpperCAmelCase ) ) else: if value is None: _a : str =old_value.to(_UpperCAmelCase ) elif isinstance(_UpperCAmelCase ,torch.Tensor ): _a : Any =value.to(_UpperCAmelCase ) else: _a : str =torch.tensor(_UpperCAmelCase ,device=_UpperCAmelCase ) if is_buffer: _a : Optional[int] =new_value else: _a : Optional[Any] =nn.Parameter(_UpperCAmelCase ,requires_grad=old_value.requires_grad ) _a : Tuple =new_value def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : Union[str, Any]=None ,_UpperCAmelCase : List[Any]=None ,_UpperCAmelCase : str=None ,_UpperCAmelCase : Union[str, Any]=False ) -> Dict: for name, module in model.named_children(): if current_key_name is None: _a : Optional[int] =[] current_key_name.append(_UpperCAmelCase ) if (isinstance(_UpperCAmelCase ,nn.Linear ) or isinstance(_UpperCAmelCase ,_UpperCAmelCase )) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` if not any(key in """.""".join(_UpperCAmelCase ) for key in modules_to_not_convert ): with init_empty_weights(): if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): _a , _a : int =module.weight.shape else: _a : List[str] =module.in_features _a : Tuple =module.out_features if quantization_config.quantization_method() == "llm_int8": _a : Optional[Any] =bnb.nn.LinearabitLt( _UpperCAmelCase ,_UpperCAmelCase ,module.bias is not None ,has_fpaa_weights=quantization_config.llm_inta_has_fpaa_weight ,threshold=quantization_config.llm_inta_threshold ,) _a : Optional[Any] =True else: if ( quantization_config.llm_inta_skip_modules is not None and name in quantization_config.llm_inta_skip_modules ): pass else: _a : Dict =bnb.nn.Linearabit( _UpperCAmelCase ,_UpperCAmelCase ,module.bias is not None ,quantization_config.bnb_abit_compute_dtype ,compress_statistics=quantization_config.bnb_abit_use_double_quant ,quant_type=quantization_config.bnb_abit_quant_type ,) _a : List[Any] =True # Store the module class in case we need to transpose the weight later _a : int =type(_UpperCAmelCase ) # Force requires grad to False to avoid unexpected errors model._modules[name].requires_grad_(_UpperCAmelCase ) if len(list(module.children() ) ) > 0: _a , _a : List[Any] =_replace_with_bnb_linear( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,has_been_replaced=_UpperCAmelCase ,) # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : int=None ,_UpperCAmelCase : Union[str, Any]=None ,_UpperCAmelCase : Any=None ) -> Tuple: _a : Dict =["""lm_head"""] if modules_to_not_convert is None else modules_to_not_convert _a , _a : List[Any] =_replace_with_bnb_linear( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) 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.""" """ Please double check your model architecture, or submit an issue on github if you think this is""" """ a bug.""" ) return model def SCREAMING_SNAKE_CASE_ ( *_UpperCAmelCase : Any ,**_UpperCAmelCase : Any ) -> str: warnings.warn( """`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead""" ,_UpperCAmelCase ,) return replace_with_bnb_linear(*_UpperCAmelCase ,**_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( *_UpperCAmelCase : str ,**_UpperCAmelCase : Optional[int] ) -> Optional[int]: warnings.warn( """`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead""" ,_UpperCAmelCase ,) return set_module_quantized_tensor_to_device(*_UpperCAmelCase ,**_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ) -> Union[str, Any]: _a : Any =deepcopy(_UpperCAmelCase ) # this has 0 cost since it is done inside `init_empty_weights` context manager` tied_model.tie_weights() _a : List[Any] =find_tied_parameters(_UpperCAmelCase ) # For compatibility with Accelerate < 0.18 if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): _a : str =sum(list(tied_params.values() ) ,[] ) + list(tied_params.keys() ) else: _a : Optional[int] =sum(_UpperCAmelCase ,[] ) _a : List[Any] =len(_UpperCAmelCase ) > 0 # Check if it is a base model _a : Tuple =not hasattr(_UpperCAmelCase ,model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head _a : List[Any] =list(model.named_children() ) _a : Dict =[list_modules[-1][0]] # add last module together with tied weights _a : List[str] =set(_UpperCAmelCase ) - set(_UpperCAmelCase ) _a : str =list(set(_UpperCAmelCase ) ) + list(_UpperCAmelCase ) # remove ".weight" from the keys _a : List[Any] =[""".weight""", """.bias"""] _a : Any =[] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: _a : Any =name.replace(_UpperCAmelCase ,"""""" ) filtered_module_names.append(_UpperCAmelCase ) return filtered_module_names
276
1
'''simple docstring''' def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ,_UpperCAmelCase : int ) -> float: return base * power(_UpperCAmelCase ,(exponent - 1) ) if exponent else 1 if __name__ == "__main__": print('''Raise base to the power of exponent using recursion...''') A__: Optional[int] = int(input('''Enter the base: ''').strip()) A__: Any = int(input('''Enter the exponent: ''').strip()) A__: Union[str, Any] = power(base, abs(exponent)) if exponent < 0: # power() does not properly deal w/ negative exponents A__: int = 1 / result print(F"{base} to the power of {exponent} is {result}")
276
'''simple docstring''' import logging import os from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union from filelock import FileLock from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available A__: int = logging.getLogger(__name__) @dataclass class A__ : __UpperCamelCase : str __UpperCamelCase : List[str] __UpperCamelCase : Optional[List[str]] @dataclass class A__ : __UpperCamelCase : List[int] __UpperCamelCase : List[int] __UpperCamelCase : Optional[List[int]] = None __UpperCamelCase : Optional[List[int]] = None class A__ ( UpperCAmelCase__ ): __UpperCamelCase : str = "train" __UpperCamelCase : Tuple = "dev" __UpperCamelCase : str = "test" class A__ : @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :Union[Split, str] ) -> List[InputExample]: '''simple docstring''' raise NotImplementedError @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :str ) -> List[str]: '''simple docstring''' raise NotImplementedError @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :List[InputExample] , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :PreTrainedTokenizer , SCREAMING_SNAKE_CASE :str=False , SCREAMING_SNAKE_CASE :Optional[Any]="[CLS]" , SCREAMING_SNAKE_CASE :Optional[int]=1 , SCREAMING_SNAKE_CASE :Any="[SEP]" , SCREAMING_SNAKE_CASE :List[Any]=False , SCREAMING_SNAKE_CASE :Union[str, Any]=False , SCREAMING_SNAKE_CASE :List[str]=0 , SCREAMING_SNAKE_CASE :str=0 , SCREAMING_SNAKE_CASE :Dict=-1_0_0 , SCREAMING_SNAKE_CASE :Optional[int]=0 , SCREAMING_SNAKE_CASE :Tuple=True , ) -> List[InputFeatures]: '''simple docstring''' _a : str ={label: i for i, label in enumerate(SCREAMING_SNAKE_CASE )} _a : Tuple =[] for ex_index, example in enumerate(SCREAMING_SNAKE_CASE ): if ex_index % 1_0_0_0_0 == 0: logger.info("""Writing example %d of %d""" , SCREAMING_SNAKE_CASE , len(SCREAMING_SNAKE_CASE ) ) _a : Optional[Any] =[] _a : List[Any] =[] for word, label in zip(example.words , example.labels ): _a : Optional[int] =tokenizer.tokenize(SCREAMING_SNAKE_CASE ) # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space. if len(SCREAMING_SNAKE_CASE ) > 0: tokens.extend(SCREAMING_SNAKE_CASE ) # Use the real label id for the first token of the word, and padding ids for the remaining tokens label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(SCREAMING_SNAKE_CASE ) - 1) ) # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa. _a : Optional[int] =tokenizer.num_special_tokens_to_add() if len(SCREAMING_SNAKE_CASE ) > max_seq_length - special_tokens_count: _a : List[Any] =tokens[: (max_seq_length - special_tokens_count)] _a : Tuple =label_ids[: (max_seq_length - special_tokens_count)] # The convention in BERT is: # (a) For sequence pairs: # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP] # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1 # (b) For single sequences: # tokens: [CLS] the dog is hairy . [SEP] # type_ids: 0 0 0 0 0 0 0 # # Where "type_ids" are used to indicate whether this is the first # sequence or the second sequence. The embedding vectors for `type=0` and # `type=1` were learned during pre-training and are added to the wordpiece # embedding vector (and position vector). This is not *strictly* necessary # since the [SEP] token unambiguously separates the sequences, but it makes # it easier for the model to learn the concept of sequences. # # For classification tasks, the first vector (corresponding to [CLS]) is # used as the "sentence vector". Note that this only makes sense because # the entire model is fine-tuned. tokens += [sep_token] label_ids += [pad_token_label_id] if sep_token_extra: # roberta uses an extra separator b/w pairs of sentences tokens += [sep_token] label_ids += [pad_token_label_id] _a : Dict =[sequence_a_segment_id] * len(SCREAMING_SNAKE_CASE ) if cls_token_at_end: tokens += [cls_token] label_ids += [pad_token_label_id] segment_ids += [cls_token_segment_id] else: _a : Any =[cls_token] + tokens _a : Dict =[pad_token_label_id] + label_ids _a : Union[str, Any] =[cls_token_segment_id] + segment_ids _a : List[str] =tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE ) # The mask has 1 for real tokens and 0 for padding tokens. Only real # tokens are attended to. _a : Optional[int] =[1 if mask_padding_with_zero else 0] * len(SCREAMING_SNAKE_CASE ) # Zero-pad up to the sequence length. _a : Union[str, Any] =max_seq_length - len(SCREAMING_SNAKE_CASE ) if pad_on_left: _a : Optional[Any] =([pad_token] * padding_length) + input_ids _a : Optional[int] =([0 if mask_padding_with_zero else 1] * padding_length) + input_mask _a : Union[str, Any] =([pad_token_segment_id] * padding_length) + segment_ids _a : Dict =([pad_token_label_id] * padding_length) + label_ids else: input_ids += [pad_token] * padding_length input_mask += [0 if mask_padding_with_zero else 1] * padding_length segment_ids += [pad_token_segment_id] * padding_length label_ids += [pad_token_label_id] * padding_length assert len(SCREAMING_SNAKE_CASE ) == max_seq_length assert len(SCREAMING_SNAKE_CASE ) == max_seq_length assert len(SCREAMING_SNAKE_CASE ) == max_seq_length assert len(SCREAMING_SNAKE_CASE ) == max_seq_length if ex_index < 5: logger.info("""*** Example ***""" ) logger.info("""guid: %s""" , example.guid ) logger.info("""tokens: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in tokens] ) ) logger.info("""input_ids: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in input_ids] ) ) logger.info("""input_mask: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in input_mask] ) ) logger.info("""segment_ids: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in segment_ids] ) ) logger.info("""label_ids: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in label_ids] ) ) if "token_type_ids" not in tokenizer.model_input_names: _a : Tuple =None features.append( InputFeatures( input_ids=SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , token_type_ids=SCREAMING_SNAKE_CASE , label_ids=SCREAMING_SNAKE_CASE ) ) return features if is_torch_available(): import torch from torch import nn from torch.utils.data import Dataset class A__ ( UpperCAmelCase__ ): __UpperCamelCase : List[InputFeatures] __UpperCamelCase : int = nn.CrossEntropyLoss().ignore_index def __init__( self :Dict , SCREAMING_SNAKE_CASE :TokenClassificationTask , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :PreTrainedTokenizer , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Optional[int] = None , SCREAMING_SNAKE_CASE :int=False , SCREAMING_SNAKE_CASE :Split = Split.train , ) -> List[str]: '''simple docstring''' # Load data features from cache or dataset file _a : Optional[Any] =os.path.join( SCREAMING_SNAKE_CASE , """cached_{}_{}_{}""".format(mode.value , tokenizer.__class__.__name__ , str(SCREAMING_SNAKE_CASE ) ) , ) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. _a : List[str] =cached_features_file + """.lock""" with FileLock(SCREAMING_SNAKE_CASE ): if os.path.exists(SCREAMING_SNAKE_CASE ) and not overwrite_cache: logger.info(f"Loading features from cached file {cached_features_file}" ) _a : Any =torch.load(SCREAMING_SNAKE_CASE ) else: logger.info(f"Creating features from dataset file at {data_dir}" ) _a : Any =token_classification_task.read_examples_from_file(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # TODO clean up all this to leverage built-in features of tokenizers _a : List[str] =token_classification_task.convert_examples_to_features( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , cls_token_at_end=bool(model_type in ["""xlnet"""] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ["""xlnet"""] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=SCREAMING_SNAKE_CASE , pad_on_left=bool(tokenizer.padding_side == """left""" ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info(f"Saving features into cached file {cached_features_file}" ) torch.save(self.features , SCREAMING_SNAKE_CASE ) def __len__( self :Optional[int] ) -> Union[str, Any]: '''simple docstring''' return len(self.features ) def __getitem__( self :Dict , SCREAMING_SNAKE_CASE :int ) -> InputFeatures: '''simple docstring''' return self.features[i] if is_tf_available(): import tensorflow as tf class A__ : __UpperCamelCase : List[InputFeatures] __UpperCamelCase : int = -100 def __init__( self :str , SCREAMING_SNAKE_CASE :TokenClassificationTask , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :PreTrainedTokenizer , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Optional[int] = None , SCREAMING_SNAKE_CASE :str=False , SCREAMING_SNAKE_CASE :Split = Split.train , ) -> Any: '''simple docstring''' _a : Tuple =token_classification_task.read_examples_from_file(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # TODO clean up all this to leverage built-in features of tokenizers _a : List[Any] =token_classification_task.convert_examples_to_features( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , cls_token_at_end=bool(model_type in ["""xlnet"""] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ["""xlnet"""] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=SCREAMING_SNAKE_CASE , pad_on_left=bool(tokenizer.padding_side == """left""" ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) def gen(): for ex in self.features: if ex.token_type_ids is None: yield ( {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask}, ex.label_ids, ) else: yield ( { "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label_ids, ) if "token_type_ids" not in tokenizer.model_input_names: _a : Union[str, Any] =tf.data.Dataset.from_generator( SCREAMING_SNAKE_CASE , ({"""input_ids""": tf.intaa, """attention_mask""": tf.intaa}, tf.intaa) , ( {"""input_ids""": tf.TensorShape([None] ), """attention_mask""": tf.TensorShape([None] )}, tf.TensorShape([None] ), ) , ) else: _a : Union[str, Any] =tf.data.Dataset.from_generator( SCREAMING_SNAKE_CASE , ({"""input_ids""": tf.intaa, """attention_mask""": tf.intaa, """token_type_ids""": tf.intaa}, tf.intaa) , ( { """input_ids""": tf.TensorShape([None] ), """attention_mask""": tf.TensorShape([None] ), """token_type_ids""": tf.TensorShape([None] ), }, tf.TensorShape([None] ), ) , ) def __UpperCAmelCase ( self :Tuple ) -> Any: '''simple docstring''' _a : List[Any] =self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features ) ) ) return self.dataset def __len__( self :str ) -> Optional[int]: '''simple docstring''' return len(self.features ) def __getitem__( self :int , SCREAMING_SNAKE_CASE :str ) -> InputFeatures: '''simple docstring''' return self.features[i]
276
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) A__: List[str] = {'''configuration_opt''': ['''OPT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''OPTConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Dict = [ '''OPT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''OPTForCausalLM''', '''OPTModel''', '''OPTPreTrainedModel''', '''OPTForSequenceClassification''', '''OPTForQuestionAnswering''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: List[Any] = ['''TFOPTForCausalLM''', '''TFOPTModel''', '''TFOPTPreTrainedModel'''] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: str = [ '''FlaxOPTForCausalLM''', '''FlaxOPTModel''', '''FlaxOPTPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_opt import OPT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPTConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_opt import ( OPT_PRETRAINED_MODEL_ARCHIVE_LIST, OPTForCausalLM, OPTForQuestionAnswering, OPTForSequenceClassification, OPTModel, OPTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_opt import TFOPTForCausalLM, TFOPTModel, TFOPTPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_opt import FlaxOPTForCausalLM, FlaxOPTModel, FlaxOPTPreTrainedModel else: import sys A__: Any = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
276
'''simple docstring''' from __future__ import annotations class A__ : def __init__( self :Union[str, Any] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :str ) -> Optional[int]: '''simple docstring''' _a , _a : List[str] =text, pattern _a , _a : Union[str, Any] =len(SCREAMING_SNAKE_CASE ), len(SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Optional[int] , SCREAMING_SNAKE_CASE :str ) -> int: '''simple docstring''' for i in range(self.patLen - 1 , -1 , -1 ): if char == self.pattern[i]: return i return -1 def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :int ) -> int: '''simple docstring''' for i in range(self.patLen - 1 , -1 , -1 ): if self.pattern[i] != self.text[current_pos + i]: return current_pos + i return -1 def __UpperCAmelCase ( self :Union[str, Any] ) -> list[int]: '''simple docstring''' # searches pattern in text and returns index positions _a : Union[str, Any] =[] for i in range(self.textLen - self.patLen + 1 ): _a : Any =self.mismatch_in_text(SCREAMING_SNAKE_CASE ) if mismatch_index == -1: positions.append(SCREAMING_SNAKE_CASE ) else: _a : int =self.match_in_pattern(self.text[mismatch_index] ) _a : List[str] =( mismatch_index - match_index ) # shifting index lgtm [py/multiple-definition] return positions A__: Any = '''ABAABA''' A__: int = '''AB''' A__: Optional[int] = BoyerMooreSearch(text, pattern) A__: Optional[Any] = bms.bad_character_heuristic() if len(positions) == 0: print('''No match found''') else: print('''Pattern found in following positions: ''') print(positions)
276
1
'''simple docstring''' from arguments import InitializationArguments from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, HfArgumentParser # Configuration A__: Dict = HfArgumentParser(InitializationArguments) A__: int = parser.parse_args() # Load codeparrot tokenizer trained for Python code tokenization A__: Optional[int] = AutoTokenizer.from_pretrained(args.tokenizer_name) # Config: "scale_attn_by_layer_idx" and "reorder_and_upcast_attn" are Mistral stability tweaks A__: str = { '''vocab_size''': len(tokenizer), '''scale_attn_by_inverse_layer_idx''': True, '''reorder_and_upcast_attn''': True, } # Load model config (GPT-2 large in this case) A__: Optional[Any] = AutoConfig.from_pretrained(args.config_name, **config_kwargs) # Initialize new model with config A__: List[str] = AutoModelForCausalLM.from_config(config) # Save model to the hub model.save_pretrained(args.model_name, push_to_hub=args.push_to_hub)
276
'''simple docstring''' import argparse import gc import json import os import shutil import warnings import torch from transformers import LlamaConfig, LlamaForCausalLM, LlamaTokenizer try: from transformers import LlamaTokenizerFast except ImportError as e: warnings.warn(e) warnings.warn( '''The converted tokenizer will be the `slow` tokenizer. To use the fast, update your `tokenizers` library and re-run the tokenizer conversion''' ) A__: Dict = None A__: Tuple = { '''7B''': 1_1008, '''13B''': 1_3824, '''30B''': 1_7920, '''65B''': 2_2016, '''70B''': 2_8672, } A__: Any = { '''7B''': 1, '''7Bf''': 1, '''13B''': 2, '''13Bf''': 2, '''30B''': 4, '''65B''': 8, '''70B''': 8, '''70Bf''': 8, } def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Optional[int]=1 ,_UpperCAmelCase : List[str]=256 ) -> Dict: return multiple_of * ((int(ffn_dim_multiplier * int(8 * n / 3 ) ) + multiple_of - 1) // multiple_of) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[Any] ) -> List[str]: with open(_UpperCAmelCase ,"""r""" ) as f: return json.load(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : Optional[Any] ) -> Tuple: with open(_UpperCAmelCase ,"""w""" ) as f: json.dump(_UpperCAmelCase ,_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : int ,_UpperCAmelCase : List[Any]=True ) -> Union[str, Any]: os.makedirs(_UpperCAmelCase ,exist_ok=_UpperCAmelCase ) _a : Union[str, Any] =os.path.join(_UpperCAmelCase ,"""tmp""" ) os.makedirs(_UpperCAmelCase ,exist_ok=_UpperCAmelCase ) _a : int =read_json(os.path.join(_UpperCAmelCase ,"""params.json""" ) ) _a : int =NUM_SHARDS[model_size] _a : Dict =params["""n_layers"""] _a : Union[str, Any] =params["""n_heads"""] _a : List[str] =n_heads // num_shards _a : int =params["""dim"""] _a : Union[str, Any] =dim // n_heads _a : int =1_0_0_0_0.0 _a : str =1.0 / (base ** (torch.arange(0 ,_UpperCAmelCase ,2 ).float() / dims_per_head)) if "n_kv_heads" in params: _a : str =params["""n_kv_heads"""] # for GQA / MQA _a : Optional[Any] =n_heads_per_shard // num_key_value_heads _a : Optional[int] =dim // num_key_value_heads else: # compatibility with other checkpoints _a : str =n_heads _a : Any =n_heads_per_shard _a : str =dim # permute for sliced rotary def permute(_UpperCAmelCase : Tuple ,_UpperCAmelCase : Optional[int]=n_heads ,_UpperCAmelCase : Optional[int]=dim ,_UpperCAmelCase : List[str]=dim ): return w.view(_UpperCAmelCase ,dima // n_heads // 2 ,2 ,_UpperCAmelCase ).transpose(1 ,2 ).reshape(_UpperCAmelCase ,_UpperCAmelCase ) print(F"Fetching all parameters from the checkpoint at {input_base_path}." ) # Load weights if model_size == "7B": # Not sharded # (The sharded implementation would also work, but this is simpler.) _a : Any =torch.load(os.path.join(_UpperCAmelCase ,"""consolidated.00.pth""" ) ,map_location="""cpu""" ) else: # Sharded _a : List[Any] =[ torch.load(os.path.join(_UpperCAmelCase ,F"consolidated.{i:02d}.pth" ) ,map_location="""cpu""" ) for i in range(_UpperCAmelCase ) ] _a : Any =0 _a : Optional[int] ={"""weight_map""": {}} for layer_i in range(_UpperCAmelCase ): _a : List[str] =F"pytorch_model-{layer_i + 1}-of-{n_layers + 1}.bin" if model_size == "7B": # Unsharded _a : List[str] ={ F"model.layers.{layer_i}.self_attn.q_proj.weight": permute( loaded[F"layers.{layer_i}.attention.wq.weight"] ), F"model.layers.{layer_i}.self_attn.k_proj.weight": permute( loaded[F"layers.{layer_i}.attention.wk.weight"] ), F"model.layers.{layer_i}.self_attn.v_proj.weight": loaded[F"layers.{layer_i}.attention.wv.weight"], F"model.layers.{layer_i}.self_attn.o_proj.weight": loaded[F"layers.{layer_i}.attention.wo.weight"], F"model.layers.{layer_i}.mlp.gate_proj.weight": loaded[F"layers.{layer_i}.feed_forward.w1.weight"], F"model.layers.{layer_i}.mlp.down_proj.weight": loaded[F"layers.{layer_i}.feed_forward.w2.weight"], F"model.layers.{layer_i}.mlp.up_proj.weight": loaded[F"layers.{layer_i}.feed_forward.w3.weight"], F"model.layers.{layer_i}.input_layernorm.weight": loaded[F"layers.{layer_i}.attention_norm.weight"], F"model.layers.{layer_i}.post_attention_layernorm.weight": loaded[F"layers.{layer_i}.ffn_norm.weight"], } else: # Sharded # Note that attention.w{q,k,v,o}, feed_fordward.w[1,2,3], attention_norm.weight and ffn_norm.weight share # the same storage object, saving attention_norm and ffn_norm will save other weights too, which is # redundant as other weights will be stitched from multiple shards. To avoid that, they are cloned. _a : Tuple ={ F"model.layers.{layer_i}.input_layernorm.weight": loaded[0][ F"layers.{layer_i}.attention_norm.weight" ].clone(), F"model.layers.{layer_i}.post_attention_layernorm.weight": loaded[0][ F"layers.{layer_i}.ffn_norm.weight" ].clone(), } _a : str =permute( torch.cat( [ loaded[i][F"layers.{layer_i}.attention.wq.weight"].view(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) for i in range(_UpperCAmelCase ) ] ,dim=0 ,).reshape(_UpperCAmelCase ,_UpperCAmelCase ) ) _a : Tuple =permute( torch.cat( [ loaded[i][F"layers.{layer_i}.attention.wk.weight"].view( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) for i in range(_UpperCAmelCase ) ] ,dim=0 ,).reshape(_UpperCAmelCase ,_UpperCAmelCase ) ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,) _a : Any =torch.cat( [ loaded[i][F"layers.{layer_i}.attention.wv.weight"].view( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) for i in range(_UpperCAmelCase ) ] ,dim=0 ,).reshape(_UpperCAmelCase ,_UpperCAmelCase ) _a : List[str] =torch.cat( [loaded[i][F"layers.{layer_i}.attention.wo.weight"] for i in range(_UpperCAmelCase )] ,dim=1 ) _a : Union[str, Any] =torch.cat( [loaded[i][F"layers.{layer_i}.feed_forward.w1.weight"] for i in range(_UpperCAmelCase )] ,dim=0 ) _a : Tuple =torch.cat( [loaded[i][F"layers.{layer_i}.feed_forward.w2.weight"] for i in range(_UpperCAmelCase )] ,dim=1 ) _a : Union[str, Any] =torch.cat( [loaded[i][F"layers.{layer_i}.feed_forward.w3.weight"] for i in range(_UpperCAmelCase )] ,dim=0 ) _a : str =inv_freq for k, v in state_dict.items(): _a : Any =filename param_count += v.numel() torch.save(_UpperCAmelCase ,os.path.join(_UpperCAmelCase ,_UpperCAmelCase ) ) _a : Union[str, Any] =F"pytorch_model-{n_layers + 1}-of-{n_layers + 1}.bin" if model_size == "7B": # Unsharded _a : List[str] ={ """model.embed_tokens.weight""": loaded["""tok_embeddings.weight"""], """model.norm.weight""": loaded["""norm.weight"""], """lm_head.weight""": loaded["""output.weight"""], } else: _a : int ={ """model.norm.weight""": loaded[0]["""norm.weight"""], """model.embed_tokens.weight""": torch.cat( [loaded[i]["""tok_embeddings.weight"""] for i in range(_UpperCAmelCase )] ,dim=1 ), """lm_head.weight""": torch.cat([loaded[i]["""output.weight"""] for i in range(_UpperCAmelCase )] ,dim=0 ), } for k, v in state_dict.items(): _a : Dict =filename param_count += v.numel() torch.save(_UpperCAmelCase ,os.path.join(_UpperCAmelCase ,_UpperCAmelCase ) ) # Write configs _a : Tuple ={"""total_size""": param_count * 2} write_json(_UpperCAmelCase ,os.path.join(_UpperCAmelCase ,"""pytorch_model.bin.index.json""" ) ) _a : Optional[Any] =params["""ffn_dim_multiplier"""] if """ffn_dim_multiplier""" in params else 1 _a : int =params["""multiple_of"""] if """multiple_of""" in params else 256 _a : List[Any] =LlamaConfig( hidden_size=_UpperCAmelCase ,intermediate_size=compute_intermediate_size(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) ,num_attention_heads=params["""n_heads"""] ,num_hidden_layers=params["""n_layers"""] ,rms_norm_eps=params["""norm_eps"""] ,num_key_value_heads=_UpperCAmelCase ,) config.save_pretrained(_UpperCAmelCase ) # Make space so we can load the model properly now. del state_dict del loaded gc.collect() print("""Loading the checkpoint in a Llama model.""" ) _a : Any =LlamaForCausalLM.from_pretrained(_UpperCAmelCase ,torch_dtype=torch.floataa ,low_cpu_mem_usage=_UpperCAmelCase ) # Avoid saving this as part of the config. del model.config._name_or_path print("""Saving in the Transformers format.""" ) model.save_pretrained(_UpperCAmelCase ,safe_serialization=_UpperCAmelCase ) shutil.rmtree(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ,_UpperCAmelCase : int ) -> Optional[Any]: # Initialize the tokenizer based on the `spm` model _a : List[str] =LlamaTokenizer if LlamaTokenizerFast is None else LlamaTokenizerFast print(F"Saving a {tokenizer_class.__name__} to {tokenizer_path}." ) _a : List[Any] =tokenizer_class(_UpperCAmelCase ) tokenizer.save_pretrained(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( ) -> Union[str, Any]: _a : List[str] =argparse.ArgumentParser() parser.add_argument( """--input_dir""" ,help="""Location of LLaMA weights, which contains tokenizer.model and model folders""" ,) parser.add_argument( """--model_size""" ,choices=["""7B""", """7Bf""", """13B""", """13Bf""", """30B""", """65B""", """70B""", """70Bf""", """tokenizer_only"""] ,) parser.add_argument( """--output_dir""" ,help="""Location to write HF model and tokenizer""" ,) parser.add_argument("""--safe_serialization""" ,type=_UpperCAmelCase ,help="""Whether or not to save using `safetensors`.""" ) _a : Optional[Any] =parser.parse_args() if args.model_size != "tokenizer_only": write_model( model_path=args.output_dir ,input_base_path=os.path.join(args.input_dir ,args.model_size ) ,model_size=args.model_size ,safe_serialization=args.safe_serialization ,) _a : List[Any] =os.path.join(args.input_dir ,"""tokenizer.model""" ) write_tokenizer(args.output_dir ,_UpperCAmelCase ) if __name__ == "__main__": main()
276
1