code
stringlengths
81
54k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
import argparse import requests import torch # pip3 install salesforce-lavis # I'm actually installing a slightly modified version: pip3 install git+https://github.com/nielsrogge/LAVIS.git@fix_lavis from lavis.models import load_model_and_preprocess from PIL import Image from transformers import ( AutoTokenizer, BlipaConfig, BlipaForConditionalGeneration, BlipaProcessor, BlipaVisionConfig, BlipImageProcessor, OPTConfig, TaConfig, ) from transformers.utils.constants import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD def A ( ): SCREAMING_SNAKE_CASE : Dict = """https://storage.googleapis.com/sfr-vision-language-research/LAVIS/assets/merlion.png""" SCREAMING_SNAKE_CASE : Optional[int] = Image.open(requests.get(__UpperCamelCase , stream=__UpperCamelCase ).raw ).convert('''RGB''' ) return image def A ( _lowercase ): SCREAMING_SNAKE_CASE : Optional[int] = [] # fmt: off # vision encoder rename_keys.append(('''visual_encoder.cls_token''', '''vision_model.embeddings.class_embedding''') ) rename_keys.append(('''visual_encoder.pos_embed''', '''vision_model.embeddings.position_embedding''') ) rename_keys.append(('''visual_encoder.patch_embed.proj.weight''', '''vision_model.embeddings.patch_embedding.weight''') ) rename_keys.append(('''visual_encoder.patch_embed.proj.bias''', '''vision_model.embeddings.patch_embedding.bias''') ) rename_keys.append(('''ln_vision.weight''', '''vision_model.post_layernorm.weight''') ) rename_keys.append(('''ln_vision.bias''', '''vision_model.post_layernorm.bias''') ) for i in range(config.vision_config.num_hidden_layers ): rename_keys.append((f"""visual_encoder.blocks.{i}.norm1.weight""", f"""vision_model.encoder.layers.{i}.layer_norm1.weight""") ) rename_keys.append((f"""visual_encoder.blocks.{i}.norm1.bias""", f"""vision_model.encoder.layers.{i}.layer_norm1.bias""") ) rename_keys.append((f"""visual_encoder.blocks.{i}.norm2.weight""", f"""vision_model.encoder.layers.{i}.layer_norm2.weight""") ) rename_keys.append((f"""visual_encoder.blocks.{i}.norm2.bias""", f"""vision_model.encoder.layers.{i}.layer_norm2.bias""") ) rename_keys.append((f"""visual_encoder.blocks.{i}.attn.qkv.weight""", f"""vision_model.encoder.layers.{i}.self_attn.qkv.weight""") ) rename_keys.append((f"""visual_encoder.blocks.{i}.attn.proj.weight""", f"""vision_model.encoder.layers.{i}.self_attn.projection.weight""",) ) rename_keys.append((f"""visual_encoder.blocks.{i}.attn.proj.bias""", f"""vision_model.encoder.layers.{i}.self_attn.projection.bias""") ) rename_keys.append((f"""visual_encoder.blocks.{i}.mlp.fc1.weight""", f"""vision_model.encoder.layers.{i}.mlp.fc1.weight""") ) rename_keys.append((f"""visual_encoder.blocks.{i}.mlp.fc1.bias""", f"""vision_model.encoder.layers.{i}.mlp.fc1.bias""") ) rename_keys.append((f"""visual_encoder.blocks.{i}.mlp.fc2.weight""", f"""vision_model.encoder.layers.{i}.mlp.fc2.weight""") ) rename_keys.append((f"""visual_encoder.blocks.{i}.mlp.fc2.bias""", f"""vision_model.encoder.layers.{i}.mlp.fc2.bias""") ) # QFormer rename_keys.append(('''Qformer.bert.embeddings.LayerNorm.weight''', '''qformer.layernorm.weight''') ) rename_keys.append(('''Qformer.bert.embeddings.LayerNorm.bias''', '''qformer.layernorm.bias''') ) # fmt: on return rename_keys def A ( _lowercase , _lowercase , _lowercase ): SCREAMING_SNAKE_CASE : str = dct.pop(__UpperCamelCase ) SCREAMING_SNAKE_CASE : Optional[int] = val def A ( _lowercase , _lowercase ): for i in range(config.vision_config.num_hidden_layers ): # read in original q and v biases SCREAMING_SNAKE_CASE : Tuple = state_dict.pop(f"""visual_encoder.blocks.{i}.attn.q_bias""" ) SCREAMING_SNAKE_CASE : Optional[int] = state_dict.pop(f"""visual_encoder.blocks.{i}.attn.v_bias""" ) # next, set bias in the state dict SCREAMING_SNAKE_CASE : Any = torch.cat((q_bias, torch.zeros_like(__UpperCamelCase , requires_grad=__UpperCamelCase ), v_bias) ) SCREAMING_SNAKE_CASE : Optional[Any] = qkv_bias def A ( _lowercase , _lowercase ): SCREAMING_SNAKE_CASE : Optional[Any] = 364 if """coco""" in model_name else 224 SCREAMING_SNAKE_CASE : List[Any] = BlipaVisionConfig(image_size=__UpperCamelCase ).to_dict() # make sure the models have proper bos_token_id and eos_token_id set (important for generation) # seems like flan-T5 models don't have bos_token_id properly set? if "opt-2.7b" in model_name: SCREAMING_SNAKE_CASE : str = OPTConfig.from_pretrained('''facebook/opt-2.7b''' , eos_token_id=__UpperCamelCase ).to_dict() elif "opt-6.7b" in model_name: SCREAMING_SNAKE_CASE : str = OPTConfig.from_pretrained('''facebook/opt-6.7b''' , eos_token_id=__UpperCamelCase ).to_dict() elif "t5-xl" in model_name: SCREAMING_SNAKE_CASE : Optional[Any] = TaConfig.from_pretrained('''google/flan-t5-xl''' , dense_act_fn='''gelu''' , bos_token_id=1 ).to_dict() elif "t5-xxl" in model_name: SCREAMING_SNAKE_CASE : Any = TaConfig.from_pretrained('''google/flan-t5-xxl''' , dense_act_fn='''gelu''' , bos_token_id=1 ).to_dict() SCREAMING_SNAKE_CASE : Tuple = BlipaConfig(vision_config=__UpperCamelCase , text_config=__UpperCamelCase ) return config, image_size @torch.no_grad() def A ( _lowercase , _lowercase=None , _lowercase=False ): SCREAMING_SNAKE_CASE : Dict = ( AutoTokenizer.from_pretrained('''facebook/opt-2.7b''' ) if """opt""" in model_name else AutoTokenizer.from_pretrained('''google/flan-t5-xl''' ) ) SCREAMING_SNAKE_CASE : Dict = tokenizer('''\n''' , add_special_tokens=__UpperCamelCase ).input_ids[0] SCREAMING_SNAKE_CASE : List[str] = get_blipa_config(__UpperCamelCase , eos_token_id=__UpperCamelCase ) SCREAMING_SNAKE_CASE : Tuple = BlipaForConditionalGeneration(__UpperCamelCase ).eval() SCREAMING_SNAKE_CASE : Any = { """blip2-opt-2.7b""": ("""blip2_opt""", """pretrain_opt2.7b"""), """blip2-opt-6.7b""": ("""blip2_opt""", """pretrain_opt6.7b"""), """blip2-opt-2.7b-coco""": ("""blip2_opt""", """caption_coco_opt2.7b"""), """blip2-opt-6.7b-coco""": ("""blip2_opt""", """caption_coco_opt6.7b"""), """blip2-flan-t5-xl""": ("""blip2_t5""", """pretrain_flant5xl"""), """blip2-flan-t5-xl-coco""": ("""blip2_t5""", """caption_coco_flant5xl"""), """blip2-flan-t5-xxl""": ("""blip2_t5""", """pretrain_flant5xxl"""), } SCREAMING_SNAKE_CASE : List[str] = model_name_to_original[model_name] # load original model print('''Loading original model...''' ) SCREAMING_SNAKE_CASE : Optional[Any] = """cuda""" if torch.cuda.is_available() else """cpu""" SCREAMING_SNAKE_CASE : List[Any] = load_model_and_preprocess( name=__UpperCamelCase , model_type=__UpperCamelCase , is_eval=__UpperCamelCase , device=__UpperCamelCase ) original_model.eval() print('''Done!''' ) # update state dict keys SCREAMING_SNAKE_CASE : Any = original_model.state_dict() SCREAMING_SNAKE_CASE : List[str] = create_rename_keys(__UpperCamelCase ) for src, dest in rename_keys: rename_key(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) # some keys can be renamed efficiently for key, val in state_dict.copy().items(): SCREAMING_SNAKE_CASE : Any = state_dict.pop(__UpperCamelCase ) if key.startswith('''Qformer.bert''' ): SCREAMING_SNAKE_CASE : Any = key.replace('''Qformer.bert''' , '''qformer''' ) if "attention.self" in key: SCREAMING_SNAKE_CASE : List[Any] = key.replace('''self''' , '''attention''' ) if "opt_proj" in key: SCREAMING_SNAKE_CASE : str = key.replace('''opt_proj''' , '''language_projection''' ) if "t5_proj" in key: SCREAMING_SNAKE_CASE : Tuple = key.replace('''t5_proj''' , '''language_projection''' ) if key.startswith('''opt''' ): SCREAMING_SNAKE_CASE : Dict = key.replace('''opt''' , '''language''' ) if key.startswith('''t5''' ): SCREAMING_SNAKE_CASE : Any = key.replace('''t5''' , '''language''' ) SCREAMING_SNAKE_CASE : Optional[int] = val # read in qv biases read_in_q_v_bias(__UpperCamelCase , __UpperCamelCase ) SCREAMING_SNAKE_CASE : Any = hf_model.load_state_dict(__UpperCamelCase , strict=__UpperCamelCase ) assert len(__UpperCamelCase ) == 0 assert unexpected_keys == ["qformer.embeddings.position_ids"] SCREAMING_SNAKE_CASE : List[str] = load_demo_image() SCREAMING_SNAKE_CASE : Any = vis_processors["""eval"""](__UpperCamelCase ).unsqueeze(0 ).to(__UpperCamelCase ) SCREAMING_SNAKE_CASE : Dict = tokenizer(['''\n'''] , return_tensors='''pt''' ).input_ids.to(__UpperCamelCase ) # create processor SCREAMING_SNAKE_CASE : int = BlipImageProcessor( size={'''height''': image_size, '''width''': image_size} , image_mean=__UpperCamelCase , image_std=__UpperCamelCase ) SCREAMING_SNAKE_CASE : List[str] = BlipaProcessor(image_processor=__UpperCamelCase , tokenizer=__UpperCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = processor(images=__UpperCamelCase , return_tensors='''pt''' ).pixel_values.to(__UpperCamelCase ) # make sure processor creates exact same pixel values assert torch.allclose(__UpperCamelCase , __UpperCamelCase ) original_model.to(__UpperCamelCase ) hf_model.to(__UpperCamelCase ) with torch.no_grad(): if "opt" in model_name: SCREAMING_SNAKE_CASE : List[Any] = original_model({'''image''': original_pixel_values, '''text_input''': ['''''']} ).logits SCREAMING_SNAKE_CASE : Any = hf_model(__UpperCamelCase , __UpperCamelCase ).logits else: SCREAMING_SNAKE_CASE : Tuple = original_model( {'''image''': original_pixel_values, '''text_input''': ['''\n'''], '''text_output''': ['''\n''']} ).logits SCREAMING_SNAKE_CASE : List[Any] = input_ids.masked_fill(input_ids == tokenizer.pad_token_id , -100 ) SCREAMING_SNAKE_CASE : int = hf_model(__UpperCamelCase , __UpperCamelCase , labels=__UpperCamelCase ).logits assert original_logits.shape == logits.shape print('''First values of original logits:''' , original_logits[0, :3, :3] ) print('''First values of HF logits:''' , logits[0, :3, :3] ) # assert values if model_name == "blip2-flan-t5-xl": SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor( [[-41.5850, -4.4440, -8.9922], [-47.4322, -5.9143, -1.7340]] , device=__UpperCamelCase ) assert torch.allclose(logits[0, :3, :3] , __UpperCamelCase , atol=1e-4 ) elif model_name == "blip2-flan-t5-xl-coco": SCREAMING_SNAKE_CASE : Any = torch.tensor( [[-57.0109, -9.8967, -12.6280], [-68.6578, -12.7191, -10.5065]] , device=__UpperCamelCase ) else: # cast to same type SCREAMING_SNAKE_CASE : List[Any] = logits.dtype assert torch.allclose(original_logits.to(__UpperCamelCase ) , __UpperCamelCase , atol=1e-2 ) print('''Looks ok!''' ) print('''Generating a caption...''' ) SCREAMING_SNAKE_CASE : Optional[int] = """""" SCREAMING_SNAKE_CASE : int = tokenizer(__UpperCamelCase , return_tensors='''pt''' ).input_ids.to(__UpperCamelCase ) SCREAMING_SNAKE_CASE : Any = original_model.generate({'''image''': original_pixel_values} ) SCREAMING_SNAKE_CASE : Optional[int] = hf_model.generate( __UpperCamelCase , __UpperCamelCase , do_sample=__UpperCamelCase , num_beams=5 , max_length=30 , min_length=1 , top_p=0.9 , repetition_penalty=1.0 , length_penalty=1.0 , temperature=1 , ) print('''Original generation:''' , __UpperCamelCase ) SCREAMING_SNAKE_CASE : Optional[int] = input_ids.shape[1] SCREAMING_SNAKE_CASE : Union[str, Any] = processor.batch_decode(outputs[:, prompt_length:] , skip_special_tokens=__UpperCamelCase ) SCREAMING_SNAKE_CASE : Union[str, Any] = [text.strip() for text in output_text] print('''HF generation:''' , __UpperCamelCase ) if pytorch_dump_folder_path is not None: processor.save_pretrained(__UpperCamelCase ) hf_model.save_pretrained(__UpperCamelCase ) if push_to_hub: processor.push_to_hub(f"""nielsr/{model_name}""" ) hf_model.push_to_hub(f"""nielsr/{model_name}""" ) if __name__ == "__main__": __UpperCamelCase : List[str] = argparse.ArgumentParser() __UpperCamelCase : Optional[Any] = [ '''blip2-opt-2.7b''', '''blip2-opt-6.7b''', '''blip2-opt-2.7b-coco''', '''blip2-opt-6.7b-coco''', '''blip2-flan-t5-xl''', '''blip2-flan-t5-xl-coco''', '''blip2-flan-t5-xxl''', ] parser.add_argument( '--model_name', default='blip2-opt-2.7b', choices=choices, type=str, help='Path to hf config.json of model to convert', ) parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument( '--push_to_hub', action='store_true', help='Whether to push the model and processor to the hub after converting', ) __UpperCamelCase : Any = parser.parse_args() convert_blipa_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
721
from __future__ import annotations from typing import Any class lowercase__ ( UpperCamelCase_): pass class lowercase__ : def __init__( self : Union[str, Any] , UpperCamelCase__ : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = data SCREAMING_SNAKE_CASE : Node | None = None def __iter__( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = self SCREAMING_SNAKE_CASE : Tuple = [] while node: if node in visited: raise ContainsLoopError visited.append(UpperCamelCase__ ) yield node.data SCREAMING_SNAKE_CASE : Dict = node.next_node @property def __A ( self : Optional[int] ): '''simple docstring''' try: list(self ) return False except ContainsLoopError: return True if __name__ == "__main__": __UpperCamelCase : List[Any] = Node(1) __UpperCamelCase : str = Node(2) __UpperCamelCase : Dict = Node(3) __UpperCamelCase : List[Any] = Node(4) print(root_node.has_loop) # False __UpperCamelCase : int = root_node.next_node print(root_node.has_loop) # True __UpperCamelCase : Union[str, Any] = Node(5) __UpperCamelCase : Union[str, Any] = Node(6) __UpperCamelCase : List[Any] = Node(5) __UpperCamelCase : List[str] = Node(6) print(root_node.has_loop) # False __UpperCamelCase : List[Any] = Node(1) print(root_node.has_loop) # False
34
0
from dataclasses import dataclass, field from typing import Optional from transformers import AutoConfig, AutoImageProcessor, AutoTokenizer, FlaxVisionEncoderDecoderModel, HfArgumentParser @dataclass class lowercase__ : UpperCamelCase_ = field( metadata={"""help""": """The output directory where the model will be written."""} , ) UpperCamelCase_ = field( metadata={ """help""": ( """The encoder model checkpoint for weights initialization.""" """Don\'t set if you want to train an encoder model from scratch.""" ) } , ) UpperCamelCase_ = field( metadata={ """help""": ( """The decoder model checkpoint for weights initialization.""" """Don\'t set if you want to train a decoder model from scratch.""" ) } , ) UpperCamelCase_ = field( default=_lowercase , metadata={"""help""": """Pretrained encoder config name or path if not the same as encoder_model_name"""}) UpperCamelCase_ = field( default=_lowercase , metadata={"""help""": """Pretrained decoder config name or path if not the same as decoder_model_name"""}) def A ( ): SCREAMING_SNAKE_CASE : Tuple = HfArgumentParser((ModelArguments,) ) ((SCREAMING_SNAKE_CASE ) , ) : Optional[int] = parser.parse_args_into_dataclasses() # Load pretrained model and tokenizer # Use explicit specified encoder config if model_args.encoder_config_name: SCREAMING_SNAKE_CASE : Optional[Any] = AutoConfig.from_pretrained(model_args.encoder_config_name ) # Use pretrained encoder model's config else: SCREAMING_SNAKE_CASE : Any = AutoConfig.from_pretrained(model_args.encoder_model_name_or_path ) # Use explicit specified decoder config if model_args.decoder_config_name: SCREAMING_SNAKE_CASE : Dict = AutoConfig.from_pretrained(model_args.decoder_config_name ) # Use pretrained decoder model's config else: SCREAMING_SNAKE_CASE : Dict = AutoConfig.from_pretrained(model_args.decoder_model_name_or_path ) # necessary for `from_encoder_decoder_pretrained` when `decoder_config` is passed SCREAMING_SNAKE_CASE : str = True SCREAMING_SNAKE_CASE : Tuple = True SCREAMING_SNAKE_CASE : str = FlaxVisionEncoderDecoderModel.from_encoder_decoder_pretrained( encoder_pretrained_model_name_or_path=model_args.encoder_model_name_or_path , decoder_pretrained_model_name_or_path=model_args.decoder_model_name_or_path , encoder_config=snake_case__ , decoder_config=snake_case__ , ) # GPT2 only has bos/eos tokens but not decoder_start/pad tokens SCREAMING_SNAKE_CASE : Optional[Any] = decoder_config.decoder_start_token_id SCREAMING_SNAKE_CASE : Tuple = decoder_config.pad_token_id if decoder_start_token_id is None: SCREAMING_SNAKE_CASE : Any = decoder_config.bos_token_id if pad_token_id is None: SCREAMING_SNAKE_CASE : Any = decoder_config.eos_token_id # This is necessary to make Flax's generate() work SCREAMING_SNAKE_CASE : Tuple = decoder_config.eos_token_id SCREAMING_SNAKE_CASE : Dict = decoder_start_token_id SCREAMING_SNAKE_CASE : Optional[Any] = pad_token_id SCREAMING_SNAKE_CASE : Any = AutoImageProcessor.from_pretrained(model_args.encoder_model_name_or_path ) SCREAMING_SNAKE_CASE : Optional[Any] = AutoTokenizer.from_pretrained(model_args.decoder_model_name_or_path ) SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer.convert_ids_to_tokens(model.config.pad_token_id ) model.save_pretrained(model_args.output_dir ) image_processor.save_pretrained(model_args.output_dir ) tokenizer.save_pretrained(model_args.output_dir ) if __name__ == "__main__": main()
700
import copy from typing import Any, Dict, List, Optional, Union import numpy as np import torch from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import TensorType, logging __UpperCamelCase : Union[str, Any] = logging.get_logger(__name__) class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = ["""input_features""", """is_longer"""] def __init__( self : Optional[Any] , UpperCamelCase__ : Dict=64 , UpperCamelCase__ : Optional[Any]=4_8000 , UpperCamelCase__ : Tuple=480 , UpperCamelCase__ : Union[str, Any]=10 , UpperCamelCase__ : List[Any]=1024 , UpperCamelCase__ : Tuple=0.0 , UpperCamelCase__ : int=False , UpperCamelCase__ : float = 0 , UpperCamelCase__ : float = 1_4000 , UpperCamelCase__ : int = None , UpperCamelCase__ : str = "fusion" , UpperCamelCase__ : str = "repeatpad" , **UpperCamelCase__ : Union[str, Any] , ): '''simple docstring''' super().__init__( feature_size=UpperCamelCase__ , sampling_rate=UpperCamelCase__ , padding_value=UpperCamelCase__ , return_attention_mask=UpperCamelCase__ , **UpperCamelCase__ , ) SCREAMING_SNAKE_CASE : Union[str, Any] = top_db SCREAMING_SNAKE_CASE : Union[str, Any] = truncation SCREAMING_SNAKE_CASE : str = padding SCREAMING_SNAKE_CASE : List[Any] = fft_window_size SCREAMING_SNAKE_CASE : Tuple = (fft_window_size >> 1) + 1 SCREAMING_SNAKE_CASE : List[str] = hop_length SCREAMING_SNAKE_CASE : List[Any] = max_length_s SCREAMING_SNAKE_CASE : Tuple = max_length_s * sampling_rate SCREAMING_SNAKE_CASE : List[Any] = sampling_rate SCREAMING_SNAKE_CASE : List[str] = frequency_min SCREAMING_SNAKE_CASE : Any = frequency_max SCREAMING_SNAKE_CASE : List[Any] = mel_filter_bank( num_frequency_bins=self.nb_frequency_bins , num_mel_filters=UpperCamelCase__ , min_frequency=UpperCamelCase__ , max_frequency=UpperCamelCase__ , sampling_rate=UpperCamelCase__ , norm=UpperCamelCase__ , mel_scale='''htk''' , ) SCREAMING_SNAKE_CASE : Optional[Any] = mel_filter_bank( num_frequency_bins=self.nb_frequency_bins , num_mel_filters=UpperCamelCase__ , min_frequency=UpperCamelCase__ , max_frequency=UpperCamelCase__ , sampling_rate=UpperCamelCase__ , norm='''slaney''' , mel_scale='''slaney''' , ) def __A ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE : Optional[Any] = self.__class__.__name__ if "mel_filters" in output: del output["mel_filters"] if "mel_filters_slaney" in output: del output["mel_filters_slaney"] return output def __A ( self : Optional[int] , UpperCamelCase__ : np.array , UpperCamelCase__ : Optional[np.array] = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = spectrogram( UpperCamelCase__ , window_function(self.fft_window_size , '''hann''' ) , frame_length=self.fft_window_size , hop_length=self.hop_length , power=2.0 , mel_filters=UpperCamelCase__ , log_mel='''dB''' , ) return log_mel_spectrogram.T def __A ( self : Union[str, Any] , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Dict , UpperCamelCase__ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = np.array_split(list(range(0 , total_frames - chunk_frames + 1 ) ) , 3 ) if len(ranges[1] ) == 0: # if the audio is too short, we just use the first chunk SCREAMING_SNAKE_CASE : int = [0] if len(ranges[2] ) == 0: # if the audio is too short, we just use the first chunk SCREAMING_SNAKE_CASE : Any = [0] # randomly choose index for each part SCREAMING_SNAKE_CASE : Union[str, Any] = np.random.choice(ranges[0] ) SCREAMING_SNAKE_CASE : List[Any] = np.random.choice(ranges[1] ) SCREAMING_SNAKE_CASE : int = np.random.choice(ranges[2] ) SCREAMING_SNAKE_CASE : Optional[int] = mel[idx_front : idx_front + chunk_frames, :] SCREAMING_SNAKE_CASE : Optional[Any] = mel[idx_middle : idx_middle + chunk_frames, :] SCREAMING_SNAKE_CASE : Tuple = mel[idx_back : idx_back + chunk_frames, :] SCREAMING_SNAKE_CASE : str = torch.tensor(mel[None, None, :] ) SCREAMING_SNAKE_CASE : Optional[int] = torch.nn.functional.interpolate( UpperCamelCase__ , size=[chunk_frames, 64] , mode='''bilinear''' , align_corners=UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[Any] = mel_shrink[0][0].numpy() SCREAMING_SNAKE_CASE : Union[str, Any] = np.stack([mel_shrink, mel_chunk_front, mel_chunk_middle, mel_chunk_back] , axis=0 ) return mel_fusion def __A ( self : Dict , UpperCamelCase__ : np.array , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Dict , UpperCamelCase__ : List[str] ): '''simple docstring''' if waveform.shape[0] > max_length: if truncation == "rand_trunc": SCREAMING_SNAKE_CASE : Optional[Any] = True # random crop to max_length (for compatibility) -> this should be handled by self.pad SCREAMING_SNAKE_CASE : List[Any] = len(UpperCamelCase__ ) - max_length SCREAMING_SNAKE_CASE : Dict = np.random.randint(0 , overflow + 1 ) SCREAMING_SNAKE_CASE : Optional[Any] = waveform[idx : idx + max_length] SCREAMING_SNAKE_CASE : Any = self._np_extract_fbank_features(UpperCamelCase__ , self.mel_filters_slaney )[None, :] elif truncation == "fusion": SCREAMING_SNAKE_CASE : Any = self._np_extract_fbank_features(UpperCamelCase__ , self.mel_filters ) SCREAMING_SNAKE_CASE : List[str] = max_length // self.hop_length + 1 # the +1 related to how the spectrogram is computed SCREAMING_SNAKE_CASE : List[Any] = mel.shape[0] if chunk_frames == total_frames: # there is a corner case where the audio length is larger than max_length but smaller than max_length+hop_length. # In this case, we just use the whole audio. SCREAMING_SNAKE_CASE : Optional[Any] = np.stack([mel, mel, mel, mel] , axis=0 ) SCREAMING_SNAKE_CASE : Tuple = False else: SCREAMING_SNAKE_CASE : str = self._random_mel_fusion(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[int] = True else: raise NotImplementedError(f"""data_truncating {truncation} not implemented""" ) else: SCREAMING_SNAKE_CASE : List[str] = False # only use repeat as a new possible value for padding. you repeat the audio before applying the usual max_length padding if waveform.shape[0] < max_length: if padding == "repeat": SCREAMING_SNAKE_CASE : Tuple = int(max_length / len(UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE : Any = np.stack(np.tile(UpperCamelCase__ , n_repeat + 1 ) )[:max_length] if padding == "repeatpad": SCREAMING_SNAKE_CASE : List[Any] = int(max_length / len(UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE : Dict = np.stack(np.tile(UpperCamelCase__ , UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE : Dict = np.pad(UpperCamelCase__ , (0, max_length - waveform.shape[0]) , mode='''constant''' , constant_values=0 ) if truncation == "fusion": SCREAMING_SNAKE_CASE : List[Any] = self._np_extract_fbank_features(UpperCamelCase__ , self.mel_filters ) SCREAMING_SNAKE_CASE : Union[str, Any] = np.stack([input_mel, input_mel, input_mel, input_mel] , axis=0 ) else: SCREAMING_SNAKE_CASE : List[str] = self._np_extract_fbank_features(UpperCamelCase__ , self.mel_filters_slaney )[None, :] return input_mel, longer def __call__( self : Union[str, Any] , UpperCamelCase__ : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , UpperCamelCase__ : str = None , UpperCamelCase__ : Optional[str] = None , UpperCamelCase__ : Optional[int] = None , UpperCamelCase__ : Optional[int] = None , UpperCamelCase__ : Optional[Union[str, TensorType]] = None , **UpperCamelCase__ : Any , ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = truncation if truncation is not None else self.truncation SCREAMING_SNAKE_CASE : List[str] = padding if padding else self.padding if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f"""The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a""" f""" sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input""" f""" was sampled with {self.sampling_rate} and not {sampling_rate}.""" ) else: logger.warning( '''It is strongly recommended to pass the `sampling_rate` argument to this function. ''' '''Failing to do so can result in silent errors that might be hard to debug.''' ) SCREAMING_SNAKE_CASE : List[str] = isinstance(UpperCamelCase__ , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f"""Only mono-channel audio is supported for input to {self}""" ) SCREAMING_SNAKE_CASE : int = is_batched_numpy or ( isinstance(UpperCamelCase__ , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: SCREAMING_SNAKE_CASE : Any = [np.asarray(UpperCamelCase__ , dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(UpperCamelCase__ , np.ndarray ): SCREAMING_SNAKE_CASE : List[Any] = np.asarray(UpperCamelCase__ , dtype=np.floataa ) elif isinstance(UpperCamelCase__ , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): SCREAMING_SNAKE_CASE : Union[str, Any] = raw_speech.astype(np.floataa ) # always return batch if not is_batched: SCREAMING_SNAKE_CASE : List[str] = [np.asarray(UpperCamelCase__ )] # convert to mel spectrogram, truncate and pad if needed. SCREAMING_SNAKE_CASE : int = [ self._get_input_mel(UpperCamelCase__ , max_length if max_length else self.nb_max_samples , UpperCamelCase__ , UpperCamelCase__ ) for waveform in raw_speech ] SCREAMING_SNAKE_CASE : str = [] SCREAMING_SNAKE_CASE : List[str] = [] for mel, longer in padded_inputs: input_mel.append(UpperCamelCase__ ) is_longer.append(UpperCamelCase__ ) if truncation == "fusion" and sum(UpperCamelCase__ ) == 0: # if no audio is longer than 10s, then randomly select one audio to be longer SCREAMING_SNAKE_CASE : Union[str, Any] = np.random.randint(0 , len(UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE : Optional[Any] = True if isinstance(input_mel[0] , UpperCamelCase__ ): SCREAMING_SNAKE_CASE : Union[str, Any] = [np.asarray(UpperCamelCase__ , dtype=np.floataa ) for feature in input_mel] # is_longer is a list of bool SCREAMING_SNAKE_CASE : Optional[Any] = [[longer] for longer in is_longer] SCREAMING_SNAKE_CASE : Union[str, Any] = {'''input_features''': input_mel, '''is_longer''': is_longer} SCREAMING_SNAKE_CASE : int = BatchFeature(UpperCamelCase__ ) if return_tensors is not None: SCREAMING_SNAKE_CASE : int = input_features.convert_to_tensors(UpperCamelCase__ ) return input_features
34
0
# Function to print upper half of diamond (pyramid) def A ( _lowercase ): for i in range(0 , __SCREAMING_SNAKE_CASE ): for _ in range(0 , n - i - 1 ): # printing spaces print(''' ''' , end='''''' ) for _ in range(0 , i + 1 ): # printing stars print('''* ''' , end='''''' ) print() def A ( _lowercase ): for i in range(__SCREAMING_SNAKE_CASE , 0 , -1 ): for _ in range(__SCREAMING_SNAKE_CASE , 0 , -1 ): # printing stars print('''* ''' , end='''''' ) print() for _ in range(n - i + 1 , 0 , -1 ): # printing spaces print(''' ''' , end='''''' ) def A ( _lowercase ): if n <= 0: print(''' ... .... nothing printing :(''' ) return floyd(__SCREAMING_SNAKE_CASE ) # upper half reverse_floyd(__SCREAMING_SNAKE_CASE ) # lower half if __name__ == "__main__": print(R'| /\ | |- | |- |--| |\ /| |-') print(R'|/ \| |- |_ |_ |__| | \/ | |_') __UpperCamelCase : Union[str, Any] = 1 while K: __UpperCamelCase : Optional[Any] = int(input('enter the number and , and see the magic : ')) print() pretty_print(user_number) __UpperCamelCase : Optional[int] = int(input('press 0 to exit... and 1 to continue...')) print('Good Bye...')
701
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...utils import logging if TYPE_CHECKING: from ...processing_utils import ProcessorMixin from ...utils import TensorType __UpperCamelCase : str = logging.get_logger(__name__) __UpperCamelCase : str = { 'microsoft/layoutlmv3-base': 'https://huggingface.co/microsoft/layoutlmv3-base/resolve/main/config.json', } class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = """layoutlmv3""" def __init__( self : Optional[int] , UpperCamelCase__ : Union[str, Any]=5_0265 , UpperCamelCase__ : List[Any]=768 , UpperCamelCase__ : Union[str, Any]=12 , UpperCamelCase__ : Union[str, Any]=12 , UpperCamelCase__ : Tuple=3072 , UpperCamelCase__ : List[Any]="gelu" , UpperCamelCase__ : List[Any]=0.1 , UpperCamelCase__ : List[str]=0.1 , UpperCamelCase__ : Any=512 , UpperCamelCase__ : List[Any]=2 , UpperCamelCase__ : List[Any]=0.02 , UpperCamelCase__ : Optional[Any]=1E-5 , UpperCamelCase__ : List[str]=1 , UpperCamelCase__ : int=0 , UpperCamelCase__ : str=2 , UpperCamelCase__ : List[str]=1024 , UpperCamelCase__ : str=128 , UpperCamelCase__ : str=128 , UpperCamelCase__ : Tuple=True , UpperCamelCase__ : Optional[int]=32 , UpperCamelCase__ : Any=128 , UpperCamelCase__ : Optional[Any]=64 , UpperCamelCase__ : Dict=256 , UpperCamelCase__ : List[Any]=True , UpperCamelCase__ : str=True , UpperCamelCase__ : Dict=True , UpperCamelCase__ : Dict=224 , UpperCamelCase__ : Optional[Any]=3 , UpperCamelCase__ : Any=16 , UpperCamelCase__ : Any=None , **UpperCamelCase__ : Optional[Any] , ): '''simple docstring''' super().__init__( vocab_size=UpperCamelCase__ , hidden_size=UpperCamelCase__ , num_hidden_layers=UpperCamelCase__ , num_attention_heads=UpperCamelCase__ , intermediate_size=UpperCamelCase__ , hidden_act=UpperCamelCase__ , hidden_dropout_prob=UpperCamelCase__ , attention_probs_dropout_prob=UpperCamelCase__ , max_position_embeddings=UpperCamelCase__ , type_vocab_size=UpperCamelCase__ , initializer_range=UpperCamelCase__ , layer_norm_eps=UpperCamelCase__ , pad_token_id=UpperCamelCase__ , bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ , **UpperCamelCase__ , ) SCREAMING_SNAKE_CASE : Union[str, Any] = max_ad_position_embeddings SCREAMING_SNAKE_CASE : List[Any] = coordinate_size SCREAMING_SNAKE_CASE : List[str] = shape_size SCREAMING_SNAKE_CASE : Optional[int] = has_relative_attention_bias SCREAMING_SNAKE_CASE : List[Any] = rel_pos_bins SCREAMING_SNAKE_CASE : str = max_rel_pos SCREAMING_SNAKE_CASE : Any = has_spatial_attention_bias SCREAMING_SNAKE_CASE : Union[str, Any] = rel_ad_pos_bins SCREAMING_SNAKE_CASE : Union[str, Any] = max_rel_ad_pos SCREAMING_SNAKE_CASE : Union[str, Any] = text_embed SCREAMING_SNAKE_CASE : List[str] = visual_embed SCREAMING_SNAKE_CASE : Optional[Any] = input_size SCREAMING_SNAKE_CASE : Optional[Any] = num_channels SCREAMING_SNAKE_CASE : List[Any] = patch_size SCREAMING_SNAKE_CASE : List[Any] = classifier_dropout class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = version.parse("""1.12""") @property def __A ( self : str ): '''simple docstring''' if self.task in ["question-answering", "sequence-classification"]: return OrderedDict( [ ('''input_ids''', {0: '''batch''', 1: '''sequence'''}), ('''attention_mask''', {0: '''batch''', 1: '''sequence'''}), ('''bbox''', {0: '''batch''', 1: '''sequence'''}), ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) else: return OrderedDict( [ ('''input_ids''', {0: '''batch''', 1: '''sequence'''}), ('''bbox''', {0: '''batch''', 1: '''sequence'''}), ('''attention_mask''', {0: '''batch''', 1: '''sequence'''}), ('''pixel_values''', {0: '''batch''', 1: '''num_channels'''}), ] ) @property def __A ( self : int ): '''simple docstring''' return 1E-5 @property def __A ( self : Union[str, Any] ): '''simple docstring''' return 12 def __A ( self : Optional[Any] , UpperCamelCase__ : "ProcessorMixin" , UpperCamelCase__ : int = -1 , UpperCamelCase__ : int = -1 , UpperCamelCase__ : bool = False , UpperCamelCase__ : Optional["TensorType"] = None , UpperCamelCase__ : int = 3 , UpperCamelCase__ : int = 40 , UpperCamelCase__ : int = 40 , ): '''simple docstring''' setattr(processor.image_processor , '''apply_ocr''' , UpperCamelCase__ ) # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX SCREAMING_SNAKE_CASE : Any = compute_effective_axis_dimension( UpperCamelCase__ , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX SCREAMING_SNAKE_CASE : List[Any] = processor.tokenizer.num_special_tokens_to_add(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Tuple = compute_effective_axis_dimension( UpperCamelCase__ , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=UpperCamelCase__ ) # Generate dummy inputs according to compute batch and sequence SCREAMING_SNAKE_CASE : Union[str, Any] = [[''' '''.join([processor.tokenizer.unk_token] ) * seq_length]] * batch_size # Generate dummy bounding boxes SCREAMING_SNAKE_CASE : Any = [[[48, 84, 73, 128]]] * batch_size # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX # batch_size = compute_effective_axis_dimension(batch_size, fixed_dimension=OnnxConfig.default_fixed_batch) SCREAMING_SNAKE_CASE : List[Any] = self._generate_dummy_images(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[int] = dict( processor( UpperCamelCase__ , text=UpperCamelCase__ , boxes=UpperCamelCase__ , return_tensors=UpperCamelCase__ , ) ) return inputs
34
0
from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast from ...utils import logging __UpperCamelCase : List[Any] = logging.get_logger(__name__) __UpperCamelCase : Any = { 'EleutherAI/gpt-neo-1.3B': 'https://huggingface.co/EleutherAI/gpt-neo-1.3B/resolve/main/config.json', # See all GPTNeo models at https://huggingface.co/models?filter=gpt_neo } class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = """gpt_neo""" UpperCamelCase_ = ["""past_key_values"""] UpperCamelCase_ = {"""num_attention_heads""": """num_heads""", """num_hidden_layers""": """num_layers"""} def __init__( self : str , UpperCamelCase__ : Optional[int]=5_0257 , UpperCamelCase__ : int=2048 , UpperCamelCase__ : int=2048 , UpperCamelCase__ : List[Any]=24 , UpperCamelCase__ : int=[[["global", "local"], 12]] , UpperCamelCase__ : int=16 , UpperCamelCase__ : List[str]=None , UpperCamelCase__ : Union[str, Any]=256 , UpperCamelCase__ : Optional[int]="gelu_new" , UpperCamelCase__ : List[str]=0.0 , UpperCamelCase__ : Union[str, Any]=0.0 , UpperCamelCase__ : str=0.0 , UpperCamelCase__ : int=0.1 , UpperCamelCase__ : Tuple=1E-5 , UpperCamelCase__ : Optional[int]=0.02 , UpperCamelCase__ : Optional[Any]=True , UpperCamelCase__ : Any=5_0256 , UpperCamelCase__ : List[Any]=5_0256 , **UpperCamelCase__ : List[Any] , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = vocab_size SCREAMING_SNAKE_CASE : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE : Optional[int] = hidden_size SCREAMING_SNAKE_CASE : List[Any] = num_layers SCREAMING_SNAKE_CASE : str = num_heads SCREAMING_SNAKE_CASE : Any = intermediate_size SCREAMING_SNAKE_CASE : Optional[int] = window_size SCREAMING_SNAKE_CASE : int = activation_function SCREAMING_SNAKE_CASE : Any = resid_dropout SCREAMING_SNAKE_CASE : List[str] = embed_dropout SCREAMING_SNAKE_CASE : Optional[int] = attention_dropout SCREAMING_SNAKE_CASE : Any = classifier_dropout SCREAMING_SNAKE_CASE : str = layer_norm_epsilon SCREAMING_SNAKE_CASE : Optional[Any] = initializer_range SCREAMING_SNAKE_CASE : Union[str, Any] = use_cache SCREAMING_SNAKE_CASE : Any = bos_token_id SCREAMING_SNAKE_CASE : Tuple = eos_token_id SCREAMING_SNAKE_CASE : List[str] = attention_types SCREAMING_SNAKE_CASE : Tuple = self.expand_attention_types_params(UpperCamelCase__ ) if len(self.attention_layers ) != self.num_layers: raise ValueError( '''Configuration for convolutional module is incorrect. ''' '''It is required that `len(config.attention_layers)` == `config.num_layers` ''' f"""but is `len(config.attention_layers) = {len(self.attention_layers )}`, """ f"""`config.num_layers = {self.num_layers}`. """ '''`config.attention_layers` is prepared using `config.attention_types`. ''' '''Please verify the value of `config.attention_types` argument.''' ) super().__init__(bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ , **UpperCamelCase__ ) @staticmethod def __A ( UpperCamelCase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = [] for item in attention_types: for _ in range(item[1] ): attentions.extend(item[0] ) return attentions def A ( _lowercase , _lowercase , _lowercase , _lowercase ): import torch SCREAMING_SNAKE_CASE : int = input.size() SCREAMING_SNAKE_CASE : Dict = len(_lowercase ) SCREAMING_SNAKE_CASE : Dict = shape[dimension] SCREAMING_SNAKE_CASE : Any = torch.arange(0 , _lowercase , _lowercase ) SCREAMING_SNAKE_CASE : Any = torch.div(sizedim - size , _lowercase , rounding_mode='''floor''' ) + 1 SCREAMING_SNAKE_CASE : List[str] = torch.arange(_lowercase ) + low_indices[:min_length][:, None] SCREAMING_SNAKE_CASE : Dict = [slice(_lowercase )] * rank SCREAMING_SNAKE_CASE : Optional[int] = indices SCREAMING_SNAKE_CASE : int = input[s] SCREAMING_SNAKE_CASE : Union[str, Any] = list(range(0 , rank + 1 ) ) perm.append(perm.pop(dimension + 1 ) ) return sliced.permute(_lowercase ) def A ( _lowercase , _lowercase ): import torch SCREAMING_SNAKE_CASE : List[str] = torch.arange(1 , _lowercase ) SCREAMING_SNAKE_CASE : str = torch.remainder(_lowercase , _lowercase ) SCREAMING_SNAKE_CASE : Union[str, Any] = remainders == 0 SCREAMING_SNAKE_CASE : Dict = candidates[divisor_indices] SCREAMING_SNAKE_CASE : Optional[Any] = torch.max(_lowercase ) return largest_divisor, torch.div(_lowercase , _lowercase , rounding_mode='''floor''' ) class lowercase__ ( UpperCamelCase_): @property def __A ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = OrderedDict({'''input_ids''': {0: '''batch''', 1: '''sequence'''}} ) if self.use_past: self.fill_with_past_key_values_(UpperCamelCase__ , direction='''inputs''' ) SCREAMING_SNAKE_CASE : Union[str, Any] = {0: '''batch''', 1: '''past_sequence + sequence'''} else: SCREAMING_SNAKE_CASE : Optional[int] = {0: '''batch''', 1: '''sequence'''} return common_inputs @property def __A ( self : List[str] ): '''simple docstring''' return self._config.num_heads def __A ( self : Union[str, Any] , UpperCamelCase__ : int , UpperCamelCase__ : str = -1 , UpperCamelCase__ : Any = -1 , UpperCamelCase__ : Dict = False , UpperCamelCase__ : Any = None , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = super(UpperCamelCase__ , self ).generate_dummy_inputs( UpperCamelCase__ , batch_size=UpperCamelCase__ , seq_length=UpperCamelCase__ , is_pair=UpperCamelCase__ , framework=UpperCamelCase__ ) # We need to order the input in the way they appears in the forward() SCREAMING_SNAKE_CASE : Dict = OrderedDict({'''input_ids''': common_inputs['''input_ids''']} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError('''Cannot generate dummy past_keys inputs without PyTorch installed.''' ) else: import torch SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = common_inputs['''input_ids'''].shape # Not using the same length for past_key_values SCREAMING_SNAKE_CASE : str = seqlen + 2 SCREAMING_SNAKE_CASE : Optional[Any] = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) SCREAMING_SNAKE_CASE : Dict = [ (torch.zeros(UpperCamelCase__ ), torch.zeros(UpperCamelCase__ )) for _ in range(self.num_layers ) ] SCREAMING_SNAKE_CASE : Tuple = common_inputs['''attention_mask'''] if self.use_past: SCREAMING_SNAKE_CASE : Optional[int] = ordered_inputs['''attention_mask'''].dtype SCREAMING_SNAKE_CASE : Union[str, Any] = torch.cat( [ordered_inputs['''attention_mask'''], torch.ones(UpperCamelCase__ , UpperCamelCase__ , dtype=UpperCamelCase__ )] , dim=1 ) return ordered_inputs @property def __A ( self : Optional[Any] ): '''simple docstring''' return 13
702
import os import unittest from transformers import FunnelTokenizer, FunnelTokenizerFast from transformers.models.funnel.tokenization_funnel import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowercase__ ( UpperCamelCase_ , unittest.TestCase): UpperCamelCase_ = FunnelTokenizer UpperCamelCase_ = FunnelTokenizerFast UpperCamelCase_ = True UpperCamelCase_ = True def __A ( self : Union[str, Any] ): '''simple docstring''' super().setUp() SCREAMING_SNAKE_CASE : Optional[Any] = [ '''<unk>''', '''<cls>''', '''<sep>''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] SCREAMING_SNAKE_CASE : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) def __A ( self : int , **UpperCamelCase__ : List[Any] ): '''simple docstring''' return FunnelTokenizer.from_pretrained(self.tmpdirname , **UpperCamelCase__ ) def __A ( self : int , **UpperCamelCase__ : List[Any] ): '''simple docstring''' return FunnelTokenizerFast.from_pretrained(self.tmpdirname , **UpperCamelCase__ ) def __A ( self : Any , UpperCamelCase__ : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = '''UNwant\u00E9d,running''' SCREAMING_SNAKE_CASE : int = '''unwanted, running''' return input_text, output_text def __A ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = self.tokenizer_class(self.vocab_file ) SCREAMING_SNAKE_CASE : int = tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(UpperCamelCase__ , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCamelCase__ ) , [7, 4, 5, 10, 8, 9] ) def __A ( self : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self.get_tokenizers(do_lower_case=UpperCamelCase__ ) for tokenizer in tokenizers: SCREAMING_SNAKE_CASE : int = tokenizer('''UNwant\u00E9d,running''' ) SCREAMING_SNAKE_CASE : Optional[Any] = len(inputs['''input_ids'''] ) - 1 self.assertListEqual(inputs['''token_type_ids'''] , [2] + [0] * sentence_len ) SCREAMING_SNAKE_CASE : List[Any] = tokenizer('''UNwant\u00E9d,running''' , '''UNwant\u00E9d,running''' ) self.assertListEqual(inputs['''token_type_ids'''] , [2] + [0] * sentence_len + [1] * sentence_len )
34
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __UpperCamelCase : List[Any] = { """configuration_swinv2""": ["""SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Swinv2Config"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : str = [ """SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST""", """Swinv2ForImageClassification""", """Swinv2ForMaskedImageModeling""", """Swinv2Model""", """Swinv2PreTrainedModel""", ] if TYPE_CHECKING: from .configuration_swinva import SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP, SwinvaConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_swinva import ( SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST, SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel, SwinvaPreTrainedModel, ) else: import sys __UpperCamelCase : List[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
703
import numpy as np import torch from torch.utils.data import Dataset, IterableDataset from ..utils.generic import ModelOutput class lowercase__ ( UpperCamelCase_): def __init__( self : str , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = dataset SCREAMING_SNAKE_CASE : Optional[Any] = process SCREAMING_SNAKE_CASE : Union[str, Any] = params def __len__( self : Tuple ): '''simple docstring''' return len(self.dataset ) def __getitem__( self : List[str] , UpperCamelCase__ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = self.dataset[i] SCREAMING_SNAKE_CASE : Optional[int] = self.process(UpperCamelCase__ , **self.params ) return processed class lowercase__ ( UpperCamelCase_): def __init__( self : Dict , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Dict , UpperCamelCase__ : List[Any]=None ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = loader SCREAMING_SNAKE_CASE : List[Any] = infer SCREAMING_SNAKE_CASE : int = params if loader_batch_size == 1: # Let's spare some time by deactivating altogether SCREAMING_SNAKE_CASE : Optional[int] = None SCREAMING_SNAKE_CASE : List[str] = loader_batch_size # Internal bookkeeping SCREAMING_SNAKE_CASE : Optional[int] = None SCREAMING_SNAKE_CASE : int = None def __len__( self : int ): '''simple docstring''' return len(self.loader ) def __iter__( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = iter(self.loader ) return self def __A ( self : List[str] ): '''simple docstring''' if isinstance(self._loader_batch_data , torch.Tensor ): # Batch data is simple tensor, just fetch the slice SCREAMING_SNAKE_CASE : Optional[Any] = self._loader_batch_data[self._loader_batch_index] else: # Batch data is assumed to be BaseModelOutput (or dict) SCREAMING_SNAKE_CASE : Union[str, Any] = {} for k, element in self._loader_batch_data.items(): if isinstance(UpperCamelCase__ , UpperCamelCase__ ): # Convert ModelOutput to tuple first SCREAMING_SNAKE_CASE : Dict = element.to_tuple() if isinstance(element[0] , torch.Tensor ): SCREAMING_SNAKE_CASE : Dict = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element ) elif isinstance(element[0] , np.ndarray ): SCREAMING_SNAKE_CASE : Union[str, Any] = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element ) continue if k in {"hidden_states", "past_key_values", "attentions"} and isinstance(UpperCamelCase__ , UpperCamelCase__ ): # Those are stored as lists of tensors so need specific unbatching. if isinstance(element[0] , torch.Tensor ): SCREAMING_SNAKE_CASE : Union[str, Any] = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element ) elif isinstance(element[0] , np.ndarray ): SCREAMING_SNAKE_CASE : List[str] = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element ) continue if element is None: # This can happen for optional data that get passed around SCREAMING_SNAKE_CASE : int = None elif isinstance(element[self._loader_batch_index] , torch.Tensor ): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers SCREAMING_SNAKE_CASE : Union[str, Any] = element[self._loader_batch_index].unsqueeze(0 ) elif isinstance(element[self._loader_batch_index] , np.ndarray ): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers SCREAMING_SNAKE_CASE : Tuple = np.expand_dims(element[self._loader_batch_index] , 0 ) else: # This is typically a list, so no need to `unsqueeze`. SCREAMING_SNAKE_CASE : Tuple = element[self._loader_batch_index] # Recreate the element by reusing the original class to make it look # batch_size=1 SCREAMING_SNAKE_CASE : Any = self._loader_batch_data.__class__(UpperCamelCase__ ) self._loader_batch_index += 1 return result def __A ( self : Union[str, Any] ): '''simple docstring''' if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: # We are currently unrolling a batch so we just need to return # the current item within a batch return self.loader_batch_item() # We're out of items within a batch SCREAMING_SNAKE_CASE : Tuple = next(self.iterator ) SCREAMING_SNAKE_CASE : List[Any] = self.infer(UpperCamelCase__ , **self.params ) # We now have a batch of "inferred things". if self.loader_batch_size is not None: # Try to infer the size of the batch if isinstance(UpperCamelCase__ , torch.Tensor ): SCREAMING_SNAKE_CASE : Optional[int] = processed else: SCREAMING_SNAKE_CASE : int = list(processed.keys() )[0] SCREAMING_SNAKE_CASE : int = processed[key] if isinstance(UpperCamelCase__ , UpperCamelCase__ ): SCREAMING_SNAKE_CASE : List[Any] = len(UpperCamelCase__ ) else: SCREAMING_SNAKE_CASE : Dict = first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. SCREAMING_SNAKE_CASE : List[Any] = observed_batch_size # Setting internal index to unwrap the batch SCREAMING_SNAKE_CASE : List[Any] = processed SCREAMING_SNAKE_CASE : int = 0 return self.loader_batch_item() else: # We're not unrolling batches return processed class lowercase__ ( UpperCamelCase_): def __init__( self : str , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Union[str, Any]=None ): '''simple docstring''' super().__init__(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) def __iter__( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = iter(self.loader ) SCREAMING_SNAKE_CASE : List[Any] = None return self def __A ( self : List[str] ): '''simple docstring''' if self.subiterator is None: SCREAMING_SNAKE_CASE : Dict = self.infer(next(self.iterator ) , **self.params ) try: # Try to return next item SCREAMING_SNAKE_CASE : Any = next(self.subiterator ) except StopIteration: # When a preprocess iterator ends, we can start lookig at the next item # ChunkIterator will keep feeding until ALL elements of iterator # all have created their subiterator and have been iterating against. # # Another way to look at it, is we're basically flattening lists of lists # into a single list, but with generators SCREAMING_SNAKE_CASE : Optional[Any] = self.infer(next(self.iterator ) , **self.params ) SCREAMING_SNAKE_CASE : Union[str, Any] = next(self.subiterator ) return processed class lowercase__ ( UpperCamelCase_): def __iter__( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = iter(self.loader ) return self def __A ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = False SCREAMING_SNAKE_CASE : Optional[int] = [] if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: while self._loader_batch_index < self.loader_batch_size: SCREAMING_SNAKE_CASE : Tuple = self.loader_batch_item() SCREAMING_SNAKE_CASE : Any = item.pop('''is_last''' ) accumulator.append(UpperCamelCase__ ) if is_last: return accumulator while not is_last: SCREAMING_SNAKE_CASE : Any = self.infer(next(self.iterator ) , **self.params ) if self.loader_batch_size is not None: if isinstance(UpperCamelCase__ , torch.Tensor ): SCREAMING_SNAKE_CASE : Tuple = processed else: SCREAMING_SNAKE_CASE : Union[str, Any] = list(processed.keys() )[0] SCREAMING_SNAKE_CASE : List[str] = processed[key] if isinstance(UpperCamelCase__ , UpperCamelCase__ ): SCREAMING_SNAKE_CASE : List[Any] = len(UpperCamelCase__ ) else: SCREAMING_SNAKE_CASE : int = first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. SCREAMING_SNAKE_CASE : List[str] = observed_batch_size SCREAMING_SNAKE_CASE : List[Any] = processed SCREAMING_SNAKE_CASE : str = 0 while self._loader_batch_index < self.loader_batch_size: SCREAMING_SNAKE_CASE : Any = self.loader_batch_item() SCREAMING_SNAKE_CASE : List[Any] = item.pop('''is_last''' ) accumulator.append(UpperCamelCase__ ) if is_last: return accumulator else: SCREAMING_SNAKE_CASE : int = processed SCREAMING_SNAKE_CASE : List[str] = item.pop('''is_last''' ) accumulator.append(UpperCamelCase__ ) return accumulator class lowercase__ ( UpperCamelCase_): def __init__( self : Optional[Any] , UpperCamelCase__ : Dataset , UpperCamelCase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = dataset SCREAMING_SNAKE_CASE : Dict = key def __len__( self : Optional[int] ): '''simple docstring''' return len(self.dataset ) def __getitem__( self : Dict , UpperCamelCase__ : Tuple ): '''simple docstring''' return self.dataset[i][self.key] class lowercase__ ( UpperCamelCase_): def __init__( self : List[Any] , UpperCamelCase__ : Dataset , UpperCamelCase__ : str , UpperCamelCase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = dataset SCREAMING_SNAKE_CASE : List[str] = keya SCREAMING_SNAKE_CASE : Tuple = keya def __len__( self : List[str] ): '''simple docstring''' return len(self.dataset ) def __getitem__( self : Union[str, Any] , UpperCamelCase__ : Any ): '''simple docstring''' return {"text": self.dataset[i][self.keya], "text_pair": self.dataset[i][self.keya]}
34
0
import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DiffusionPipeline, EulerDiscreteScheduler, StableDiffusionXLImgaImgPipeline, UNetaDConditionModel, ) from diffusers.utils import floats_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowercase__ ( lowercase__ , lowercase__ , unittest.TestCase): UpperCamelCase_ = StableDiffusionXLImgaImgPipeline UpperCamelCase_ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"""height""", """width"""} UpperCamelCase_ = PipelineTesterMixin.required_optional_params - {"""latents"""} UpperCamelCase_ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS UpperCamelCase_ = IMAGE_TO_IMAGE_IMAGE_PARAMS UpperCamelCase_ = IMAGE_TO_IMAGE_IMAGE_PARAMS def __A ( self : Union[str, Any] ): '''simple docstring''' torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : List[Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') , attention_head_dim=(2, 4) , use_linear_projection=UpperCamelCase__ , addition_embed_type='''text_time''' , addition_time_embed_dim=8 , transformer_layers_per_block=(1, 2) , projection_class_embeddings_input_dim=80 , cross_attention_dim=64 , ) SCREAMING_SNAKE_CASE : str = EulerDiscreteScheduler( beta_start=0.0_0085 , beta_end=0.012 , steps_offset=1 , beta_schedule='''scaled_linear''' , timestep_spacing='''leading''' , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Tuple = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : int = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act='''gelu''' , projection_dim=32 , ) SCREAMING_SNAKE_CASE : Tuple = CLIPTextModel(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' , local_files_only=UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPTextModelWithProjection(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : str = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' , local_files_only=UpperCamelCase__ ) SCREAMING_SNAKE_CASE : str = { "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "text_encoder_2": text_encoder_a, "tokenizer_2": tokenizer_a, # "safety_checker": None, # "feature_extractor": None, } return components def __A ( self : Dict , UpperCamelCase__ : Any , UpperCamelCase__ : Union[str, Any]=0 ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = floats_tensor((1, 3, 32, 32) , rng=random.Random(UpperCamelCase__ ) ).to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[int] = image / 2 + 0.5 if str(UpperCamelCase__ ).startswith('''mps''' ): SCREAMING_SNAKE_CASE : Tuple = torch.manual_seed(UpperCamelCase__ ) else: SCREAMING_SNAKE_CASE : Optional[Any] = torch.Generator(device=UpperCamelCase__ ).manual_seed(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : int = { "prompt": "A painting of a squirrel eating a burger", "image": image, "generator": generator, "num_inference_steps": 2, "guidance_scale": 5.0, "output_type": "numpy", "strength": 0.75, } return inputs def __A ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = "cpu" # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE : int = self.get_dummy_components() SCREAMING_SNAKE_CASE : str = StableDiffusionXLImgaImgPipeline(**UpperCamelCase__ ) SCREAMING_SNAKE_CASE : str = sd_pipe.to(UpperCamelCase__ ) sd_pipe.set_progress_bar_config(disable=UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[int] = self.get_dummy_inputs(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Union[str, Any] = sd_pipe(**UpperCamelCase__ ).images SCREAMING_SNAKE_CASE : Tuple = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE : List[Any] = np.array([0.4656, 0.4840, 0.4439, 0.6698, 0.5574, 0.4524, 0.5799, 0.5943, 0.5165] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def __A ( self : Tuple ): '''simple docstring''' super().test_attention_slicing_forward_pass(expected_max_diff=3E-3 ) def __A ( self : Any ): '''simple docstring''' super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) def __A ( self : Dict ): '''simple docstring''' pass def __A ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = self.get_dummy_components() SCREAMING_SNAKE_CASE : Optional[int] = StableDiffusionXLImgaImgPipeline(**UpperCamelCase__ ) SCREAMING_SNAKE_CASE : str = sd_pipe.to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[Any] = sd_pipe.to(UpperCamelCase__ ) sd_pipe.set_progress_bar_config(disable=UpperCamelCase__ ) # forward without prompt embeds SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_dummy_inputs(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Any = 3 * ["this is a negative prompt"] SCREAMING_SNAKE_CASE : Dict = negative_prompt SCREAMING_SNAKE_CASE : str = 3 * [inputs["prompt"]] SCREAMING_SNAKE_CASE : Optional[int] = sd_pipe(**UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Union[str, Any] = output.images[0, -3:, -3:, -1] # forward with prompt embeds SCREAMING_SNAKE_CASE : List[str] = self.get_dummy_inputs(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[Any] = 3 * ["this is a negative prompt"] SCREAMING_SNAKE_CASE : List[str] = 3 * [inputs.pop('''prompt''' )] ( SCREAMING_SNAKE_CASE ) : Optional[Any] = sd_pipe.encode_prompt(UpperCamelCase__ , negative_prompt=UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Tuple = sd_pipe( **UpperCamelCase__ , prompt_embeds=UpperCamelCase__ , negative_prompt_embeds=UpperCamelCase__ , pooled_prompt_embeds=UpperCamelCase__ , negative_pooled_prompt_embeds=UpperCamelCase__ , ) SCREAMING_SNAKE_CASE : Union[str, Any] = output.images[0, -3:, -3:, -1] # make sure that it's equal assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1E-4 @slow @require_torch_gpu class lowercase__ ( unittest.TestCase): def __A ( self : Optional[int] ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def __A ( self : int , UpperCamelCase__ : Tuple , UpperCamelCase__ : Dict="cpu" , UpperCamelCase__ : Tuple=torch.floataa , UpperCamelCase__ : List[str]=0 ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = torch.Generator(device=UpperCamelCase__ ).manual_seed(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : str = np.random.RandomState(UpperCamelCase__ ).standard_normal((1, 4, 64, 64) ) SCREAMING_SNAKE_CASE : Optional[int] = torch.from_numpy(UpperCamelCase__ ).to(device=UpperCamelCase__ , dtype=UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Any = { "prompt": "a photograph of an astronaut riding a horse", "latents": latents, "generator": generator, "num_inference_steps": 3, "guidance_scale": 7.5, "output_type": "numpy", } return inputs def __A ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = DiffusionPipeline.from_pretrained('''stabilityai/stable-diffusion-2-base''' ) pipe.to(UpperCamelCase__ ) pipe.set_progress_bar_config(disable=UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[str] = self.get_inputs(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[Any] = pipe(**UpperCamelCase__ ).images SCREAMING_SNAKE_CASE : str = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE : Union[str, Any] = np.array([0.4_9493, 0.4_7896, 0.4_0798, 0.5_4214, 0.5_3212, 0.4_8202, 0.4_7656, 0.4_6329, 0.4_8506] ) assert np.abs(image_slice - expected_slice ).max() < 7E-3
704
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging if TYPE_CHECKING: from ... import FeatureExtractionMixin, PreTrainedTokenizerBase, TensorType __UpperCamelCase : Optional[Any] = logging.get_logger(__name__) __UpperCamelCase : Optional[Any] = { 'microsoft/deberta-v2-xlarge': 'https://huggingface.co/microsoft/deberta-v2-xlarge/resolve/main/config.json', 'microsoft/deberta-v2-xxlarge': 'https://huggingface.co/microsoft/deberta-v2-xxlarge/resolve/main/config.json', 'microsoft/deberta-v2-xlarge-mnli': ( 'https://huggingface.co/microsoft/deberta-v2-xlarge-mnli/resolve/main/config.json' ), 'microsoft/deberta-v2-xxlarge-mnli': ( 'https://huggingface.co/microsoft/deberta-v2-xxlarge-mnli/resolve/main/config.json' ), } class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = """deberta-v2""" def __init__( self : Optional[Any] , UpperCamelCase__ : Any=12_8100 , UpperCamelCase__ : Optional[int]=1536 , UpperCamelCase__ : Dict=24 , UpperCamelCase__ : List[str]=24 , UpperCamelCase__ : Tuple=6144 , UpperCamelCase__ : List[Any]="gelu" , UpperCamelCase__ : Optional[int]=0.1 , UpperCamelCase__ : List[str]=0.1 , UpperCamelCase__ : Optional[int]=512 , UpperCamelCase__ : Optional[Any]=0 , UpperCamelCase__ : Union[str, Any]=0.02 , UpperCamelCase__ : List[Any]=1E-7 , UpperCamelCase__ : List[str]=False , UpperCamelCase__ : str=-1 , UpperCamelCase__ : List[Any]=0 , UpperCamelCase__ : List[Any]=True , UpperCamelCase__ : Optional[Any]=None , UpperCamelCase__ : Tuple=0 , UpperCamelCase__ : str="gelu" , **UpperCamelCase__ : Optional[int] , ): '''simple docstring''' super().__init__(**UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[Any] = hidden_size SCREAMING_SNAKE_CASE : int = num_hidden_layers SCREAMING_SNAKE_CASE : Union[str, Any] = num_attention_heads SCREAMING_SNAKE_CASE : List[Any] = intermediate_size SCREAMING_SNAKE_CASE : Any = hidden_act SCREAMING_SNAKE_CASE : Dict = hidden_dropout_prob SCREAMING_SNAKE_CASE : Optional[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : str = max_position_embeddings SCREAMING_SNAKE_CASE : Dict = type_vocab_size SCREAMING_SNAKE_CASE : str = initializer_range SCREAMING_SNAKE_CASE : Optional[Any] = relative_attention SCREAMING_SNAKE_CASE : Optional[Any] = max_relative_positions SCREAMING_SNAKE_CASE : Optional[int] = pad_token_id SCREAMING_SNAKE_CASE : Optional[Any] = position_biased_input # Backwards compatibility if type(UpperCamelCase__ ) == str: SCREAMING_SNAKE_CASE : Optional[int] = [x.strip() for x in pos_att_type.lower().split('''|''' )] SCREAMING_SNAKE_CASE : Any = pos_att_type SCREAMING_SNAKE_CASE : int = vocab_size SCREAMING_SNAKE_CASE : Dict = layer_norm_eps SCREAMING_SNAKE_CASE : Tuple = kwargs.get('''pooler_hidden_size''' , UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Any = pooler_dropout SCREAMING_SNAKE_CASE : Union[str, Any] = pooler_hidden_act class lowercase__ ( UpperCamelCase_): @property def __A ( self : Union[str, Any] ): '''simple docstring''' if self.task == "multiple-choice": SCREAMING_SNAKE_CASE : Optional[int] = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: SCREAMING_SNAKE_CASE : Optional[Any] = {0: '''batch''', 1: '''sequence'''} if self._config.type_vocab_size > 0: return OrderedDict( [('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ('''token_type_ids''', dynamic_axis)] ) else: return OrderedDict([('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis)] ) @property def __A ( self : Union[str, Any] ): '''simple docstring''' return 12 def __A ( self : Dict , UpperCamelCase__ : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , UpperCamelCase__ : int = -1 , UpperCamelCase__ : int = -1 , UpperCamelCase__ : int = -1 , UpperCamelCase__ : bool = False , UpperCamelCase__ : Optional["TensorType"] = None , UpperCamelCase__ : int = 3 , UpperCamelCase__ : int = 40 , UpperCamelCase__ : int = 40 , UpperCamelCase__ : "PreTrainedTokenizerBase" = None , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = super().generate_dummy_inputs(preprocessor=UpperCamelCase__ , framework=UpperCamelCase__ ) if self._config.type_vocab_size == 0 and "token_type_ids" in dummy_inputs: del dummy_inputs["token_type_ids"] return dummy_inputs
34
0
import collections.abc from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithNoAttention, ImageClassifierOutputWithNoAttention from ...modeling_utils import PreTrainedModel from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging from .configuration_poolformer import PoolFormerConfig __UpperCamelCase : Dict = logging.get_logger(__name__) # General docstring __UpperCamelCase : Optional[Any] = 'PoolFormerConfig' # Base docstring __UpperCamelCase : List[str] = 'sail/poolformer_s12' __UpperCamelCase : Any = [1, 512, 7, 7] # Image classification docstring __UpperCamelCase : Dict = 'sail/poolformer_s12' __UpperCamelCase : int = 'tabby, tabby cat' __UpperCamelCase : Tuple = [ 'sail/poolformer_s12', # See all PoolFormer models at https://huggingface.co/models?filter=poolformer ] def A ( _lowercase , _lowercase = 0.0 , _lowercase = False ): if drop_prob == 0.0 or not training: return input SCREAMING_SNAKE_CASE : int = 1 - drop_prob SCREAMING_SNAKE_CASE : str = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets SCREAMING_SNAKE_CASE : int = keep_prob + torch.rand(_lowercase , dtype=input.dtype , device=input.device ) random_tensor.floor_() # binarize SCREAMING_SNAKE_CASE : List[Any] = input.div(_lowercase ) * random_tensor return output class lowercase__ ( nn.Module): def __init__( self : Tuple , UpperCamelCase__ : Optional[float] = None ): '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE : str = drop_prob def __A ( self : Union[str, Any] , UpperCamelCase__ : torch.Tensor ): '''simple docstring''' return drop_path(_a , self.drop_prob , self.training ) def __A ( self : Dict ): '''simple docstring''' return "p={}".format(self.drop_prob ) class lowercase__ ( nn.Module): def __init__( self : Any , UpperCamelCase__ : Dict , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Any , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Tuple , UpperCamelCase__ : str=None ): '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE : str = patch_size if isinstance(_a , collections.abc.Iterable ) else (patch_size, patch_size) SCREAMING_SNAKE_CASE : Dict = stride if isinstance(_a , collections.abc.Iterable ) else (stride, stride) SCREAMING_SNAKE_CASE : Any = padding if isinstance(_a , collections.abc.Iterable ) else (padding, padding) SCREAMING_SNAKE_CASE : List[Any] = nn.Convad(_a , _a , kernel_size=_a , stride=_a , padding=_a ) SCREAMING_SNAKE_CASE : Dict = norm_layer(_a ) if norm_layer else nn.Identity() def __A ( self : List[str] , UpperCamelCase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = self.projection(_a ) SCREAMING_SNAKE_CASE : Tuple = self.norm(_a ) return embeddings class lowercase__ ( nn.GroupNorm): def __init__( self : Union[str, Any] , UpperCamelCase__ : Optional[int] , **UpperCamelCase__ : Dict ): '''simple docstring''' super().__init__(1 , _a , **_a ) class lowercase__ ( nn.Module): def __init__( self : Optional[Any] , UpperCamelCase__ : int ): '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE : Tuple = nn.AvgPoolad(_a , stride=1 , padding=pool_size // 2 , count_include_pad=_a ) def __A ( self : Dict , UpperCamelCase__ : Optional[int] ): '''simple docstring''' return self.pool(_a ) - hidden_states class lowercase__ ( nn.Module): def __init__( self : Any , UpperCamelCase__ : List[str] , UpperCamelCase__ : Any , UpperCamelCase__ : int , UpperCamelCase__ : int ): '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE : Dict = nn.Convad(_a , _a , 1 ) SCREAMING_SNAKE_CASE : Union[str, Any] = nn.Convad(_a , _a , 1 ) SCREAMING_SNAKE_CASE : Optional[Any] = PoolFormerDropPath(_a ) if isinstance(config.hidden_act , _a ): SCREAMING_SNAKE_CASE : Union[str, Any] = ACTaFN[config.hidden_act] else: SCREAMING_SNAKE_CASE : Dict = config.hidden_act def __A ( self : str , UpperCamelCase__ : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = self.conva(_a ) SCREAMING_SNAKE_CASE : str = self.act_fn(_a ) SCREAMING_SNAKE_CASE : Optional[int] = self.drop(_a ) SCREAMING_SNAKE_CASE : List[str] = self.conva(_a ) SCREAMING_SNAKE_CASE : List[str] = self.drop(_a ) return hidden_states class lowercase__ ( nn.Module): def __init__( self : List[Any] , UpperCamelCase__ : Any , UpperCamelCase__ : Tuple , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Tuple , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : List[Any] ): '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE : List[Any] = PoolFormerPooling(_a ) SCREAMING_SNAKE_CASE : str = PoolFormerOutput(_a , _a , _a , _a ) SCREAMING_SNAKE_CASE : List[Any] = PoolFormerGroupNorm(_a ) SCREAMING_SNAKE_CASE : Optional[Any] = PoolFormerGroupNorm(_a ) # Useful for training neural nets SCREAMING_SNAKE_CASE : Optional[int] = PoolFormerDropPath(_a ) if drop_path > 0.0 else nn.Identity() SCREAMING_SNAKE_CASE : Any = config.use_layer_scale if config.use_layer_scale: SCREAMING_SNAKE_CASE : Optional[int] = nn.Parameter( config.layer_scale_init_value * torch.ones((_a) ) , requires_grad=_a ) SCREAMING_SNAKE_CASE : Union[str, Any] = nn.Parameter( config.layer_scale_init_value * torch.ones((_a) ) , requires_grad=_a ) def __A ( self : Optional[int] , UpperCamelCase__ : Any ): '''simple docstring''' if self.use_layer_scale: SCREAMING_SNAKE_CASE : Optional[Any] = self.pooling(self.before_norm(_a ) ) SCREAMING_SNAKE_CASE : str = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * pooling_output # First residual connection SCREAMING_SNAKE_CASE : Optional[int] = hidden_states + self.drop_path(_a ) SCREAMING_SNAKE_CASE : Optional[Any] = () SCREAMING_SNAKE_CASE : List[Any] = self.output(self.after_norm(_a ) ) SCREAMING_SNAKE_CASE : str = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * layer_output # Second residual connection SCREAMING_SNAKE_CASE : Union[str, Any] = hidden_states + self.drop_path(_a ) SCREAMING_SNAKE_CASE : Dict = (output,) + outputs return outputs else: SCREAMING_SNAKE_CASE : Union[str, Any] = self.drop_path(self.pooling(self.before_norm(_a ) ) ) # First residual connection SCREAMING_SNAKE_CASE : Any = pooling_output + hidden_states SCREAMING_SNAKE_CASE : List[str] = () # Second residual connection inside the PoolFormerOutput block SCREAMING_SNAKE_CASE : List[Any] = self.drop_path(self.output(self.after_norm(_a ) ) ) SCREAMING_SNAKE_CASE : str = hidden_states + layer_output SCREAMING_SNAKE_CASE : Optional[Any] = (output,) + outputs return outputs class lowercase__ ( nn.Module): def __init__( self : Tuple , UpperCamelCase__ : Optional[Any] ): '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE : Any = config # stochastic depth decay rule SCREAMING_SNAKE_CASE : Dict = [x.item() for x in torch.linspace(0 , config.drop_path_rate , sum(config.depths ) )] # patch embeddings SCREAMING_SNAKE_CASE : Tuple = [] for i in range(config.num_encoder_blocks ): embeddings.append( PoolFormerEmbeddings( patch_size=config.patch_sizes[i] , stride=config.strides[i] , padding=config.padding[i] , num_channels=config.num_channels if i == 0 else config.hidden_sizes[i - 1] , hidden_size=config.hidden_sizes[i] , ) ) SCREAMING_SNAKE_CASE : Optional[Any] = nn.ModuleList(_a ) # Transformer blocks SCREAMING_SNAKE_CASE : Tuple = [] SCREAMING_SNAKE_CASE : int = 0 for i in range(config.num_encoder_blocks ): # each block consists of layers SCREAMING_SNAKE_CASE : str = [] if i != 0: cur += config.depths[i - 1] for j in range(config.depths[i] ): layers.append( PoolFormerLayer( _a , num_channels=config.hidden_sizes[i] , pool_size=config.pool_size , hidden_size=config.hidden_sizes[i] , intermediate_size=int(config.hidden_sizes[i] * config.mlp_ratio ) , drop_path=dpr[cur + j] , ) ) blocks.append(nn.ModuleList(_a ) ) SCREAMING_SNAKE_CASE : List[Any] = nn.ModuleList(_a ) def __A ( self : Tuple , UpperCamelCase__ : List[str] , UpperCamelCase__ : List[Any]=False , UpperCamelCase__ : Dict=True ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = () if output_hidden_states else None SCREAMING_SNAKE_CASE : str = pixel_values for idx, layers in enumerate(zip(self.patch_embeddings , self.block ) ): SCREAMING_SNAKE_CASE : List[str] = layers # Get patch embeddings from hidden_states SCREAMING_SNAKE_CASE : Any = embedding_layer(_a ) # Send the embeddings through the blocks for _, blk in enumerate(_a ): SCREAMING_SNAKE_CASE : Tuple = blk(_a ) SCREAMING_SNAKE_CASE : List[str] = layer_outputs[0] if output_hidden_states: SCREAMING_SNAKE_CASE : Union[str, Any] = all_hidden_states + (hidden_states,) if not return_dict: return tuple(v for v in [hidden_states, all_hidden_states] if v is not None ) return BaseModelOutputWithNoAttention(last_hidden_state=_a , hidden_states=_a ) class lowercase__ ( __SCREAMING_SNAKE_CASE): UpperCamelCase_ = PoolFormerConfig UpperCamelCase_ = """poolformer""" UpperCamelCase_ = """pixel_values""" UpperCamelCase_ = True def __A ( self : int , UpperCamelCase__ : List[str] ): '''simple docstring''' if isinstance(_a , (nn.Linear, nn.Convad) ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() elif isinstance(_a , nn.LayerNorm ): module.bias.data.zero_() module.weight.data.fill_(1.0 ) def __A ( self : Any , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : List[str]=False ): '''simple docstring''' if isinstance(_a , _a ): SCREAMING_SNAKE_CASE : int = value __UpperCamelCase : Dict = R'\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use\n it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n\n Parameters:\n config ([`PoolFormerConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n' __UpperCamelCase : Optional[Any] = R'\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`PoolFormerImageProcessor.__call__`] for details.\n' @add_start_docstrings( """The bare PoolFormer Model transformer outputting raw hidden-states without any specific head on top.""" , __SCREAMING_SNAKE_CASE , ) class lowercase__ ( __SCREAMING_SNAKE_CASE): def __init__( self : str , UpperCamelCase__ : str ): '''simple docstring''' super().__init__(_a ) SCREAMING_SNAKE_CASE : List[str] = config SCREAMING_SNAKE_CASE : Optional[Any] = PoolFormerEncoder(_a ) # Initialize weights and apply final processing self.post_init() def __A ( self : Optional[int] ): '''simple docstring''' return self.embeddings.patch_embeddings @add_start_docstrings_to_model_forward(_a ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=_a , config_class=_CONFIG_FOR_DOC , modality='''vision''' , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def __A ( self : List[str] , UpperCamelCase__ : Optional[torch.FloatTensor] = None , UpperCamelCase__ : Optional[bool] = None , UpperCamelCase__ : Optional[bool] = None , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) SCREAMING_SNAKE_CASE : Union[str, Any] = return_dict if return_dict is not None else self.config.use_return_dict if pixel_values is None: raise ValueError('''You have to specify pixel_values''' ) SCREAMING_SNAKE_CASE : List[Any] = self.encoder( _a , output_hidden_states=_a , return_dict=_a , ) SCREAMING_SNAKE_CASE : int = encoder_outputs[0] if not return_dict: return (sequence_output, None) + encoder_outputs[1:] return BaseModelOutputWithNoAttention( last_hidden_state=_a , hidden_states=encoder_outputs.hidden_states , ) class lowercase__ ( nn.Module): def __init__( self : Optional[int] , UpperCamelCase__ : str ): '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE : Optional[int] = nn.Linear(config.hidden_size , config.hidden_size ) def __A ( self : str , UpperCamelCase__ : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = self.dense(_a ) return output @add_start_docstrings( """ PoolFormer Model transformer with an image classification head on top """ , __SCREAMING_SNAKE_CASE , ) class lowercase__ ( __SCREAMING_SNAKE_CASE): def __init__( self : int , UpperCamelCase__ : List[str] ): '''simple docstring''' super().__init__(_a ) SCREAMING_SNAKE_CASE : List[str] = config.num_labels SCREAMING_SNAKE_CASE : str = PoolFormerModel(_a ) # Final norm SCREAMING_SNAKE_CASE : Union[str, Any] = PoolFormerGroupNorm(config.hidden_sizes[-1] ) # Classifier head SCREAMING_SNAKE_CASE : Optional[Any] = ( nn.Linear(config.hidden_sizes[-1] , config.num_labels ) if config.num_labels > 0 else nn.Identity() ) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(_a ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=_a , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def __A ( self : str , UpperCamelCase__ : Optional[torch.FloatTensor] = None , UpperCamelCase__ : Optional[torch.LongTensor] = None , UpperCamelCase__ : Optional[bool] = None , UpperCamelCase__ : Optional[bool] = None , ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = return_dict if return_dict is not None else self.config.use_return_dict SCREAMING_SNAKE_CASE : Tuple = self.poolformer( _a , output_hidden_states=_a , return_dict=_a , ) SCREAMING_SNAKE_CASE : Optional[Any] = outputs[0] SCREAMING_SNAKE_CASE : Optional[int] = self.classifier(self.norm(_a ).mean([-2, -1] ) ) SCREAMING_SNAKE_CASE : Tuple = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: SCREAMING_SNAKE_CASE : Optional[Any] = """regression""" elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): SCREAMING_SNAKE_CASE : List[Any] = """single_label_classification""" else: SCREAMING_SNAKE_CASE : int = """multi_label_classification""" if self.config.problem_type == "regression": SCREAMING_SNAKE_CASE : Optional[Any] = MSELoss() if self.num_labels == 1: SCREAMING_SNAKE_CASE : Optional[int] = loss_fct(logits.squeeze() , labels.squeeze() ) else: SCREAMING_SNAKE_CASE : List[Any] = loss_fct(_a , _a ) elif self.config.problem_type == "single_label_classification": SCREAMING_SNAKE_CASE : List[str] = CrossEntropyLoss() SCREAMING_SNAKE_CASE : List[str] = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": SCREAMING_SNAKE_CASE : Dict = BCEWithLogitsLoss() SCREAMING_SNAKE_CASE : List[str] = loss_fct(_a , _a ) if not return_dict: SCREAMING_SNAKE_CASE : List[Any] = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=_a , logits=_a , hidden_states=outputs.hidden_states )
705
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from timm import create_model from timm.data import resolve_data_config from timm.data.transforms_factory import create_transform from transformers import BitConfig, BitForImageClassification, BitImageProcessor from transformers.image_utils import PILImageResampling from transformers.utils import logging logging.set_verbosity_info() __UpperCamelCase : str = logging.get_logger(__name__) def A ( _lowercase ): SCREAMING_SNAKE_CASE : Any = '''huggingface/label-files''' SCREAMING_SNAKE_CASE : Any = '''imagenet-1k-id2label.json''' SCREAMING_SNAKE_CASE : Any = json.load(open(hf_hub_download(_lowercase , _lowercase , repo_type='''dataset''' ) , '''r''' ) ) SCREAMING_SNAKE_CASE : Union[str, Any] = {int(_lowercase ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE : Dict = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE : str = '''std_conv''' if '''bit''' in model_name else False # note that when using BiT as backbone for ViT-hybrid checkpoints, # one needs to additionally set config.layer_type = "bottleneck", config.stem_type = "same", # config.conv_layer = "std_conv_same" SCREAMING_SNAKE_CASE : Optional[int] = BitConfig( conv_layer=_lowercase , num_labels=1_000 , idalabel=_lowercase , labelaid=_lowercase , ) return config def A ( _lowercase ): if "stem.conv" in name: SCREAMING_SNAKE_CASE : Optional[int] = name.replace('''stem.conv''' , '''bit.embedder.convolution''' ) if "blocks" in name: SCREAMING_SNAKE_CASE : Tuple = name.replace('''blocks''' , '''layers''' ) if "head.fc" in name: SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace('''head.fc''' , '''classifier.1''' ) if name.startswith('''norm''' ): SCREAMING_SNAKE_CASE : str = '''bit.''' + name if "bit" not in name and "classifier" not in name: SCREAMING_SNAKE_CASE : Union[str, Any] = '''bit.encoder.''' + name return name def A ( ): SCREAMING_SNAKE_CASE : Any = '''http://images.cocodataset.org/val2017/000000039769.jpg''' SCREAMING_SNAKE_CASE : List[str] = Image.open(requests.get(_lowercase , stream=_lowercase ).raw ) return im @torch.no_grad() def A ( _lowercase , _lowercase , _lowercase=False ): SCREAMING_SNAKE_CASE : List[Any] = get_config(_lowercase ) # load original model from timm SCREAMING_SNAKE_CASE : Optional[Any] = create_model(_lowercase , pretrained=_lowercase ) timm_model.eval() # load state_dict of original model SCREAMING_SNAKE_CASE : Optional[int] = timm_model.state_dict() for key in state_dict.copy().keys(): SCREAMING_SNAKE_CASE : Dict = state_dict.pop(_lowercase ) SCREAMING_SNAKE_CASE : Optional[int] = val.squeeze() if '''head''' in key else val # load HuggingFace model SCREAMING_SNAKE_CASE : str = BitForImageClassification(_lowercase ) model.eval() model.load_state_dict(_lowercase ) # create image processor SCREAMING_SNAKE_CASE : Optional[Any] = create_transform(**resolve_data_config({} , model=_lowercase ) ) SCREAMING_SNAKE_CASE : List[str] = transform.transforms SCREAMING_SNAKE_CASE : Union[str, Any] = { '''bilinear''': PILImageResampling.BILINEAR, '''bicubic''': PILImageResampling.BICUBIC, '''nearest''': PILImageResampling.NEAREST, } SCREAMING_SNAKE_CASE : Tuple = BitImageProcessor( do_resize=_lowercase , size={'''shortest_edge''': timm_transforms[0].size} , resample=pillow_resamplings[timm_transforms[0].interpolation.value] , do_center_crop=_lowercase , crop_size={'''height''': timm_transforms[1].size[0], '''width''': timm_transforms[1].size[1]} , do_normalize=_lowercase , image_mean=timm_transforms[-1].mean.tolist() , image_std=timm_transforms[-1].std.tolist() , ) SCREAMING_SNAKE_CASE : Any = prepare_img() SCREAMING_SNAKE_CASE : Union[str, Any] = transform(_lowercase ).unsqueeze(0 ) SCREAMING_SNAKE_CASE : Optional[int] = processor(_lowercase , return_tensors='''pt''' ).pixel_values # verify pixel values assert torch.allclose(_lowercase , _lowercase ) # verify logits with torch.no_grad(): SCREAMING_SNAKE_CASE : Dict = model(_lowercase ) SCREAMING_SNAKE_CASE : Optional[Any] = outputs.logits print('''Logits:''' , logits[0, :3] ) print('''Predicted class:''' , model.config.idalabel[logits.argmax(-1 ).item()] ) SCREAMING_SNAKE_CASE : List[Any] = timm_model(_lowercase ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(_lowercase , outputs.logits , atol=1e-3 ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: Path(_lowercase ).mkdir(exist_ok=_lowercase ) print(f"""Saving model {model_name} and processor to {pytorch_dump_folder_path}""" ) model.save_pretrained(_lowercase ) processor.save_pretrained(_lowercase ) if push_to_hub: print(f"""Pushing model {model_name} and processor to the hub""" ) model.push_to_hub(f"""ybelkada/{model_name}""" ) processor.push_to_hub(f"""ybelkada/{model_name}""" ) if __name__ == "__main__": __UpperCamelCase : Any = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='resnetv2_50x1_bitm', type=str, help='Name of the BiT 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.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether to push the model to the hub.', ) __UpperCamelCase : Optional[int] = parser.parse_args() convert_bit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
34
0
from typing import TYPE_CHECKING from ...utils import _LazyModule __UpperCamelCase : List[str] = {'tokenization_wav2vec2_phoneme': ['Wav2Vec2PhonemeCTCTokenizer']} if TYPE_CHECKING: from .tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizer else: import sys __UpperCamelCase : Optional[int] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
706
import argparse import json import logging import os import sys from unittest.mock import patch from transformers.testing_utils import TestCasePlus, get_gpu_count, slow __UpperCamelCase : str = [ os.path.join(os.path.dirname(__file__), dirname) for dirname in [ 'text-classification', 'language-modeling', 'summarization', 'token-classification', 'question-answering', ] ] sys.path.extend(SRC_DIRS) if SRC_DIRS is not None: import run_clm_flax import run_flax_glue import run_flax_ner import run_mlm_flax import run_qa import run_summarization_flax import run_ta_mlm_flax logging.basicConfig(level=logging.DEBUG) __UpperCamelCase : int = logging.getLogger() def A ( ): SCREAMING_SNAKE_CASE : str = argparse.ArgumentParser() parser.add_argument('''-f''' ) SCREAMING_SNAKE_CASE : List[str] = parser.parse_args() return args.f def A ( _lowercase , _lowercase="eval" ): SCREAMING_SNAKE_CASE : Dict = os.path.join(_lowercase , f"""{split}_results.json""" ) if os.path.exists(_lowercase ): with open(_lowercase , '''r''' ) as f: return json.load(_lowercase ) raise ValueError(f"""can't find {path}""" ) __UpperCamelCase : Optional[Any] = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class lowercase__ ( UpperCamelCase_): def __A ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE : Tuple = f""" run_glue.py --model_name_or_path distilbert-base-uncased --output_dir {tmp_dir} --train_file ./tests/fixtures/tests_samples/MRPC/train.csv --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --learning_rate=1e-4 --eval_steps=2 --warmup_steps=2 --seed=42 --max_seq_length=128 """.split() with patch.object(UpperCamelCase__ , '''argv''' , UpperCamelCase__ ): run_flax_glue.main() SCREAMING_SNAKE_CASE : Union[str, Any] = get_results(UpperCamelCase__ ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 ) @slow def __A ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE : str = f""" run_clm_flax.py --model_name_or_path distilgpt2 --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --do_train --do_eval --block_size 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --num_train_epochs 2 --logging_steps 2 --eval_steps 2 --output_dir {tmp_dir} --overwrite_output_dir """.split() with patch.object(UpperCamelCase__ , '''argv''' , UpperCamelCase__ ): run_clm_flax.main() SCREAMING_SNAKE_CASE : Dict = get_results(UpperCamelCase__ ) self.assertLess(result['''eval_perplexity'''] , 100 ) @slow def __A ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE : Union[str, Any] = f""" run_summarization.py --model_name_or_path t5-small --train_file tests/fixtures/tests_samples/xsum/sample.json --validation_file tests/fixtures/tests_samples/xsum/sample.json --test_file tests/fixtures/tests_samples/xsum/sample.json --output_dir {tmp_dir} --overwrite_output_dir --num_train_epochs=3 --warmup_steps=8 --do_train --do_eval --do_predict --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --predict_with_generate """.split() with patch.object(UpperCamelCase__ , '''argv''' , UpperCamelCase__ ): run_summarization_flax.main() SCREAMING_SNAKE_CASE : Union[str, Any] = get_results(UpperCamelCase__ , split='''test''' ) self.assertGreaterEqual(result['''test_rouge1'''] , 10 ) self.assertGreaterEqual(result['''test_rouge2'''] , 2 ) self.assertGreaterEqual(result['''test_rougeL'''] , 7 ) self.assertGreaterEqual(result['''test_rougeLsum'''] , 7 ) @slow def __A ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE : Dict = f""" run_mlm.py --model_name_or_path distilroberta-base --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --output_dir {tmp_dir} --overwrite_output_dir --max_seq_length 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --logging_steps 2 --eval_steps 2 --do_train --do_eval --num_train_epochs=1 """.split() with patch.object(UpperCamelCase__ , '''argv''' , UpperCamelCase__ ): run_mlm_flax.main() SCREAMING_SNAKE_CASE : List[Any] = get_results(UpperCamelCase__ ) self.assertLess(result['''eval_perplexity'''] , 42 ) @slow def __A ( self : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE : Union[str, Any] = f""" run_t5_mlm_flax.py --model_name_or_path t5-small --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --do_train --do_eval --max_seq_length 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --num_train_epochs 2 --logging_steps 2 --eval_steps 2 --output_dir {tmp_dir} --overwrite_output_dir """.split() with patch.object(UpperCamelCase__ , '''argv''' , UpperCamelCase__ ): run_ta_mlm_flax.main() SCREAMING_SNAKE_CASE : Optional[int] = get_results(UpperCamelCase__ ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.42 ) @slow def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = 7 if get_gpu_count() > 1 else 2 SCREAMING_SNAKE_CASE : Dict = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE : Any = f""" run_flax_ner.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/conll/sample.json --validation_file tests/fixtures/tests_samples/conll/sample.json --output_dir {tmp_dir} --overwrite_output_dir --do_train --do_eval --warmup_steps=2 --learning_rate=2e-4 --logging_steps 2 --eval_steps 2 --per_device_train_batch_size=2 --per_device_eval_batch_size=2 --num_train_epochs={epochs} --seed 7 """.split() with patch.object(UpperCamelCase__ , '''argv''' , UpperCamelCase__ ): run_flax_ner.main() SCREAMING_SNAKE_CASE : List[str] = get_results(UpperCamelCase__ ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 ) self.assertGreaterEqual(result['''eval_f1'''] , 0.3 ) @slow def __A ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE : Union[str, Any] = f""" run_qa.py --model_name_or_path bert-base-uncased --version_2_with_negative --train_file tests/fixtures/tests_samples/SQUAD/sample.json --validation_file tests/fixtures/tests_samples/SQUAD/sample.json --output_dir {tmp_dir} --overwrite_output_dir --num_train_epochs=3 --warmup_steps=2 --do_train --do_eval --logging_steps 2 --eval_steps 2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 """.split() with patch.object(UpperCamelCase__ , '''argv''' , UpperCamelCase__ ): run_qa.main() SCREAMING_SNAKE_CASE : str = get_results(UpperCamelCase__ ) self.assertGreaterEqual(result['''eval_f1'''] , 30 ) self.assertGreaterEqual(result['''eval_exact'''] , 30 )
34
0
from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCamelCase : int = logging.get_logger(__name__) __UpperCamelCase : Optional[Any] = { 'google/realm-cc-news-pretrained-embedder': ( 'https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/config.json' ), 'google/realm-cc-news-pretrained-encoder': ( 'https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/config.json' ), 'google/realm-cc-news-pretrained-scorer': ( 'https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/config.json' ), 'google/realm-cc-news-pretrained-openqa': ( 'https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/config.json' ), 'google/realm-orqa-nq-openqa': 'https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/config.json', 'google/realm-orqa-nq-reader': 'https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/config.json', 'google/realm-orqa-wq-openqa': 'https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/config.json', 'google/realm-orqa-wq-reader': 'https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/config.json', # See all REALM models at https://huggingface.co/models?filter=realm } class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = """realm""" def __init__( self : Optional[Any] , UpperCamelCase__ : Tuple=3_0522 , UpperCamelCase__ : str=768 , UpperCamelCase__ : List[str]=128 , UpperCamelCase__ : Any=12 , UpperCamelCase__ : Optional[int]=12 , UpperCamelCase__ : Optional[int]=8 , UpperCamelCase__ : Dict=3072 , UpperCamelCase__ : Any="gelu_new" , UpperCamelCase__ : List[str]=0.1 , UpperCamelCase__ : Optional[Any]=0.1 , UpperCamelCase__ : Optional[Any]=512 , UpperCamelCase__ : List[str]=2 , UpperCamelCase__ : List[str]=0.02 , UpperCamelCase__ : Union[str, Any]=1E-12 , UpperCamelCase__ : Any=256 , UpperCamelCase__ : Optional[int]=10 , UpperCamelCase__ : Optional[int]=1E-3 , UpperCamelCase__ : Union[str, Any]=5 , UpperCamelCase__ : Optional[Any]=320 , UpperCamelCase__ : Tuple=1335_3718 , UpperCamelCase__ : Tuple=5000 , UpperCamelCase__ : List[Any]=1 , UpperCamelCase__ : Union[str, Any]=0 , UpperCamelCase__ : Dict=2 , **UpperCamelCase__ : str , ): '''simple docstring''' super().__init__(pad_token_id=__lowerCAmelCase , bos_token_id=__lowerCAmelCase , eos_token_id=__lowerCAmelCase , **__lowerCAmelCase ) # Common config SCREAMING_SNAKE_CASE : Optional[Any] = vocab_size SCREAMING_SNAKE_CASE : int = max_position_embeddings SCREAMING_SNAKE_CASE : List[str] = hidden_size SCREAMING_SNAKE_CASE : List[str] = retriever_proj_size SCREAMING_SNAKE_CASE : Dict = num_hidden_layers SCREAMING_SNAKE_CASE : Optional[int] = num_attention_heads SCREAMING_SNAKE_CASE : Any = num_candidates SCREAMING_SNAKE_CASE : Union[str, Any] = intermediate_size SCREAMING_SNAKE_CASE : List[Any] = hidden_act SCREAMING_SNAKE_CASE : Union[str, Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE : Union[str, Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : List[str] = initializer_range SCREAMING_SNAKE_CASE : Union[str, Any] = type_vocab_size SCREAMING_SNAKE_CASE : int = layer_norm_eps # Reader config SCREAMING_SNAKE_CASE : Optional[int] = span_hidden_size SCREAMING_SNAKE_CASE : str = max_span_width SCREAMING_SNAKE_CASE : int = reader_layer_norm_eps SCREAMING_SNAKE_CASE : Tuple = reader_beam_size SCREAMING_SNAKE_CASE : Tuple = reader_seq_len # Retrieval config SCREAMING_SNAKE_CASE : Tuple = num_block_records SCREAMING_SNAKE_CASE : str = searcher_beam_size
707
import itertools import os import random import tempfile import unittest import numpy as np from transformers import TvltFeatureExtractor, is_datasets_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_torch_available(): import torch if is_datasets_available(): from datasets import load_dataset __UpperCamelCase : Dict = random.Random() def A ( _lowercase , _lowercase=1.0 , _lowercase=None , _lowercase=None ): if rng is None: SCREAMING_SNAKE_CASE : Any = global_rng SCREAMING_SNAKE_CASE : int = [] 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 : List[Any] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : str=7 , UpperCamelCase__ : Any=400 , UpperCamelCase__ : List[str]=2000 , UpperCamelCase__ : List[Any]=2048 , UpperCamelCase__ : Any=128 , UpperCamelCase__ : Union[str, Any]=1 , UpperCamelCase__ : List[Any]=512 , UpperCamelCase__ : str=30 , UpperCamelCase__ : Tuple=4_4100 , ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = parent SCREAMING_SNAKE_CASE : str = batch_size SCREAMING_SNAKE_CASE : str = min_seq_length SCREAMING_SNAKE_CASE : Dict = max_seq_length SCREAMING_SNAKE_CASE : Optional[int] = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) SCREAMING_SNAKE_CASE : Optional[Any] = spectrogram_length SCREAMING_SNAKE_CASE : Optional[int] = feature_size SCREAMING_SNAKE_CASE : Tuple = num_audio_channels SCREAMING_SNAKE_CASE : Union[str, Any] = hop_length SCREAMING_SNAKE_CASE : List[Any] = chunk_length SCREAMING_SNAKE_CASE : str = sampling_rate def __A ( self : Optional[Any] ): '''simple docstring''' return { "spectrogram_length": self.spectrogram_length, "feature_size": self.feature_size, "num_audio_channels": self.num_audio_channels, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "sampling_rate": self.sampling_rate, } def __A ( self : Tuple , UpperCamelCase__ : List[str]=False , UpperCamelCase__ : Optional[int]=False ): '''simple docstring''' def _flatten(UpperCamelCase__ : str ): return list(itertools.chain(*UpperCamelCase__ ) ) if equal_length: SCREAMING_SNAKE_CASE : List[str] = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE : int = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE : Optional[Any] = [np.asarray(UpperCamelCase__ ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class lowercase__ ( UpperCamelCase_ , unittest.TestCase): UpperCamelCase_ = TvltFeatureExtractor def __A ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = TvltFeatureExtractionTester(self ) def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = self.feature_extraction_class(**self.feat_extract_dict ) self.assertTrue(hasattr(UpperCamelCase__ , '''spectrogram_length''' ) ) self.assertTrue(hasattr(UpperCamelCase__ , '''feature_size''' ) ) self.assertTrue(hasattr(UpperCamelCase__ , '''num_audio_channels''' ) ) self.assertTrue(hasattr(UpperCamelCase__ , '''hop_length''' ) ) self.assertTrue(hasattr(UpperCamelCase__ , '''chunk_length''' ) ) self.assertTrue(hasattr(UpperCamelCase__ , '''sampling_rate''' ) ) def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE : Optional[Any] = feat_extract_first.save_pretrained(UpperCamelCase__ )[0] check_json_file_has_correct_format(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[Any] = self.feature_extraction_class.from_pretrained(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[Any] = feat_extract_first.to_dict() SCREAMING_SNAKE_CASE : str = feat_extract_second.to_dict() SCREAMING_SNAKE_CASE : Optional[int] = dict_first.pop('''mel_filters''' ) SCREAMING_SNAKE_CASE : Optional[int] = dict_second.pop('''mel_filters''' ) self.assertTrue(np.allclose(UpperCamelCase__ , UpperCamelCase__ ) ) self.assertEqual(UpperCamelCase__ , UpperCamelCase__ ) def __A ( self : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE : Tuple = os.path.join(UpperCamelCase__ , '''feat_extract.json''' ) feat_extract_first.to_json_file(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[str] = self.feature_extraction_class.from_json_file(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Any = feat_extract_first.to_dict() SCREAMING_SNAKE_CASE : str = feat_extract_second.to_dict() SCREAMING_SNAKE_CASE : int = dict_first.pop('''mel_filters''' ) SCREAMING_SNAKE_CASE : Any = dict_second.pop('''mel_filters''' ) self.assertTrue(np.allclose(UpperCamelCase__ , UpperCamelCase__ ) ) self.assertEqual(UpperCamelCase__ , UpperCamelCase__ ) def __A ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = self.feature_extraction_class(**self.feat_extract_dict ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE : List[Any] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE : Optional[int] = [np.asarray(UpperCamelCase__ ) for speech_input in speech_inputs] # Test not batched input SCREAMING_SNAKE_CASE : List[Any] = feature_extractor(np_speech_inputs[0] , return_tensors='''np''' , sampling_rate=4_4100 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test batched SCREAMING_SNAKE_CASE : Optional[Any] = feature_extractor(UpperCamelCase__ , return_tensors='''np''' , sampling_rate=4_4100 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test audio masking SCREAMING_SNAKE_CASE : List[str] = feature_extractor( UpperCamelCase__ , return_tensors='''np''' , sampling_rate=4_4100 , mask_audio=UpperCamelCase__ ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test 2-D numpy arrays are batched. SCREAMING_SNAKE_CASE : Optional[Any] = [floats_list((1, x) )[0] for x in (800, 800, 800)] SCREAMING_SNAKE_CASE : Dict = np.asarray(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : str = feature_extractor(UpperCamelCase__ , return_tensors='''np''' , sampling_rate=4_4100 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) def __A ( self : Optional[int] , UpperCamelCase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = load_dataset('''hf-internal-testing/librispeech_asr_dummy''' , '''clean''' , split='''validation''' ) # automatic decoding with librispeech SCREAMING_SNAKE_CASE : Dict = ds.sort('''id''' ).select(range(UpperCamelCase__ ) )[:num_samples]['''audio'''] return [x["array"] for x in speech_samples] def __A ( self : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE : int = TvltFeatureExtractor() SCREAMING_SNAKE_CASE : List[Any] = feature_extractor(UpperCamelCase__ , return_tensors='''pt''' ).audio_values self.assertEquals(audio_values.shape , (1, 1, 192, 128) ) SCREAMING_SNAKE_CASE : str = torch.tensor([[-0.3032, -0.2708], [-0.4434, -0.4007]] ) self.assertTrue(torch.allclose(audio_values[0, 0, :2, :2] , UpperCamelCase__ , atol=1E-4 ) )
34
0
import sacrebleu as scb from packaging import version from sacrebleu import TER import datasets __UpperCamelCase : Optional[Any] = "\\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 : int = "\\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 : str = "\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 lowercase__ ( datasets.Metric): def __A ( self : int ): '''simple docstring''' 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 __A ( self : Tuple , UpperCamelCase__ : int , UpperCamelCase__ : int , UpperCamelCase__ : bool = False , UpperCamelCase__ : bool = False , UpperCamelCase__ : bool = False , UpperCamelCase__ : bool = False , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = len(references[0] ) if any(len(lowercase_ ) != references_per_prediction for refs in references ): raise ValueError('''Sacrebleu requires the same number of references for each prediction''' ) SCREAMING_SNAKE_CASE : str = [[refs[i] for refs in references] for i in range(lowercase_ )] SCREAMING_SNAKE_CASE : int = TER( normalized=lowercase_ , no_punct=lowercase_ , asian_support=lowercase_ , case_sensitive=lowercase_ , ) SCREAMING_SNAKE_CASE : List[str] = sb_ter.corpus_score(lowercase_ , lowercase_ ) return {"score": output.score, "num_edits": output.num_edits, "ref_length": output.ref_length}
708
import math from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import SchedulerMixin, SchedulerOutput class lowercase__ ( UpperCamelCase_ , UpperCamelCase_): UpperCamelCase_ = 1 @register_to_config def __init__( self : List[str] , UpperCamelCase__ : int = 1000 , UpperCamelCase__ : Optional[Union[np.ndarray, List[float]]] = None ): '''simple docstring''' self.set_timesteps(UpperCamelCase__ ) # standard deviation of the initial noise distribution SCREAMING_SNAKE_CASE : str = 1.0 # For now we only support F-PNDM, i.e. the runge-kutta method # For more information on the algorithm please take a look at the paper: https://arxiv.org/pdf/2202.09778.pdf # mainly at formula (9), (12), (13) and the Algorithm 2. SCREAMING_SNAKE_CASE : Tuple = 4 # running values SCREAMING_SNAKE_CASE : int = [] def __A ( self : Dict , UpperCamelCase__ : int , UpperCamelCase__ : Union[str, torch.device] = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = num_inference_steps SCREAMING_SNAKE_CASE : Union[str, Any] = torch.linspace(1 , 0 , num_inference_steps + 1 )[:-1] SCREAMING_SNAKE_CASE : Tuple = torch.cat([steps, torch.tensor([0.0] )] ) if self.config.trained_betas is not None: SCREAMING_SNAKE_CASE : int = torch.tensor(self.config.trained_betas , dtype=torch.floataa ) else: SCREAMING_SNAKE_CASE : Optional[Any] = torch.sin(steps * math.pi / 2 ) ** 2 SCREAMING_SNAKE_CASE : Dict = (1.0 - self.betas**2) ** 0.5 SCREAMING_SNAKE_CASE : Optional[Any] = (torch.atana(self.betas , self.alphas ) / math.pi * 2)[:-1] SCREAMING_SNAKE_CASE : List[str] = timesteps.to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Any = [] def __A ( self : Tuple , UpperCamelCase__ : torch.FloatTensor , UpperCamelCase__ : int , UpperCamelCase__ : torch.FloatTensor , UpperCamelCase__ : bool = True , ): '''simple docstring''' if self.num_inference_steps is None: raise ValueError( '''Number of inference steps is \'None\', you need to run \'set_timesteps\' after creating the scheduler''' ) SCREAMING_SNAKE_CASE : Optional[int] = (self.timesteps == timestep).nonzero().item() SCREAMING_SNAKE_CASE : Union[str, Any] = timestep_index + 1 SCREAMING_SNAKE_CASE : int = sample * self.betas[timestep_index] + model_output * self.alphas[timestep_index] self.ets.append(UpperCamelCase__ ) if len(self.ets ) == 1: SCREAMING_SNAKE_CASE : Dict = self.ets[-1] elif len(self.ets ) == 2: SCREAMING_SNAKE_CASE : Optional[int] = (3 * self.ets[-1] - self.ets[-2]) / 2 elif len(self.ets ) == 3: SCREAMING_SNAKE_CASE : str = (23 * self.ets[-1] - 16 * self.ets[-2] + 5 * self.ets[-3]) / 12 else: SCREAMING_SNAKE_CASE : Optional[Any] = (1 / 24) * (55 * self.ets[-1] - 59 * self.ets[-2] + 37 * self.ets[-3] - 9 * self.ets[-4]) SCREAMING_SNAKE_CASE : Optional[int] = self._get_prev_sample(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=UpperCamelCase__ ) def __A ( self : Optional[Any] , UpperCamelCase__ : torch.FloatTensor , *UpperCamelCase__ : List[str] , **UpperCamelCase__ : Optional[Any] ): '''simple docstring''' return sample def __A ( self : Union[str, Any] , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Any , UpperCamelCase__ : Tuple , UpperCamelCase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = self.alphas[timestep_index] SCREAMING_SNAKE_CASE : List[str] = self.betas[timestep_index] SCREAMING_SNAKE_CASE : Union[str, Any] = self.alphas[prev_timestep_index] SCREAMING_SNAKE_CASE : Tuple = self.betas[prev_timestep_index] SCREAMING_SNAKE_CASE : Dict = (sample - sigma * ets) / max(UpperCamelCase__ , 1E-8 ) SCREAMING_SNAKE_CASE : Optional[Any] = next_alpha * pred + ets * next_sigma return prev_sample def __len__( self : int ): '''simple docstring''' return self.config.num_train_timesteps
34
0
def A ( _lowercase = 10 , _lowercase = 22 ): SCREAMING_SNAKE_CASE : Optional[Any] = range(1 , _lowercase ) SCREAMING_SNAKE_CASE : Tuple = range(1 , _lowercase ) return sum( 1 for power in powers for base in bases if len(str(base**power ) ) == power ) if __name__ == "__main__": print(f"""{solution(10, 22) = }""")
709
import gc import random import unittest import torch from diffusers import ( IFImgaImgPipeline, IFImgaImgSuperResolutionPipeline, IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline, IFPipeline, IFSuperResolutionPipeline, ) from diffusers.models.attention_processor import AttnAddedKVProcessor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import floats_tensor, load_numpy, require_torch_gpu, skip_mps, slow, torch_device from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference from . import IFPipelineTesterMixin @skip_mps class lowercase__ ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): UpperCamelCase_ = IFPipeline UpperCamelCase_ = TEXT_TO_IMAGE_PARAMS - {"""width""", """height""", """latents"""} UpperCamelCase_ = TEXT_TO_IMAGE_BATCH_PARAMS UpperCamelCase_ = PipelineTesterMixin.required_optional_params - {"""latents"""} def __A ( self : Tuple ): '''simple docstring''' return self._get_dummy_components() def __A ( self : int , UpperCamelCase__ : Dict , UpperCamelCase__ : int=0 ): '''simple docstring''' if str(UpperCamelCase__ ).startswith('''mps''' ): SCREAMING_SNAKE_CASE : Tuple = torch.manual_seed(UpperCamelCase__ ) else: SCREAMING_SNAKE_CASE : Dict = torch.Generator(device=UpperCamelCase__ ).manual_seed(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : int = { '''prompt''': '''A painting of a squirrel eating a burger''', '''generator''': generator, '''num_inference_steps''': 2, '''output_type''': '''numpy''', } return inputs def __A ( self : List[str] ): '''simple docstring''' self._test_save_load_optional_components() @unittest.skipIf(torch_device != '''cuda''' , reason='''float16 requires CUDA''' ) def __A ( self : Any ): '''simple docstring''' super().test_save_load_floataa(expected_max_diff=1E-1 ) def __A ( self : Union[str, Any] ): '''simple docstring''' self._test_attention_slicing_forward_pass(expected_max_diff=1E-2 ) def __A ( self : List[Any] ): '''simple docstring''' self._test_save_load_local() def __A ( self : List[str] ): '''simple docstring''' self._test_inference_batch_single_identical( expected_max_diff=1E-2 , ) @unittest.skipIf( torch_device != '''cuda''' or not is_xformers_available() , reason='''XFormers attention is only available with CUDA and `xformers` installed''' , ) def __A ( self : Tuple ): '''simple docstring''' self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 ) @slow @require_torch_gpu class lowercase__ ( unittest.TestCase): def __A ( self : Optional[Any] ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = IFPipeline.from_pretrained('''DeepFloyd/IF-I-XL-v1.0''' , variant='''fp16''' , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE : str = IFSuperResolutionPipeline.from_pretrained( '''DeepFloyd/IF-II-L-v1.0''' , variant='''fp16''' , torch_dtype=torch.floataa , text_encoder=UpperCamelCase__ , tokenizer=UpperCamelCase__ ) # pre compute text embeddings and remove T5 to save memory pipe_a.text_encoder.to('''cuda''' ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Dict = pipe_a.encode_prompt('''anime turtle''' , device='''cuda''' ) del pipe_a.tokenizer del pipe_a.text_encoder gc.collect() SCREAMING_SNAKE_CASE : Tuple = None SCREAMING_SNAKE_CASE : str = None pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) pipe_a.remove_all_hooks() pipe_a.remove_all_hooks() # img2img SCREAMING_SNAKE_CASE : Optional[int] = IFImgaImgPipeline(**pipe_a.components ) SCREAMING_SNAKE_CASE : Optional[int] = IFImgaImgSuperResolutionPipeline(**pipe_a.components ) pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if_imgaimg(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) pipe_a.remove_all_hooks() pipe_a.remove_all_hooks() # inpainting SCREAMING_SNAKE_CASE : Tuple = IFInpaintingPipeline(**pipe_a.components ) SCREAMING_SNAKE_CASE : Optional[int] = IFInpaintingSuperResolutionPipeline(**pipe_a.components ) pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if_inpainting(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) def __A ( self : Tuple , UpperCamelCase__ : int , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Dict ): '''simple docstring''' _start_torch_memory_measurement() SCREAMING_SNAKE_CASE : List[str] = torch.Generator(device='''cpu''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[Any] = pipe_a( prompt_embeds=UpperCamelCase__ , negative_prompt_embeds=UpperCamelCase__ , num_inference_steps=2 , generator=UpperCamelCase__ , output_type='''np''' , ) SCREAMING_SNAKE_CASE : Optional[int] = output.images[0] assert image.shape == (64, 64, 3) SCREAMING_SNAKE_CASE : Tuple = torch.cuda.max_memory_allocated() assert mem_bytes < 13 * 10**9 SCREAMING_SNAKE_CASE : Optional[Any] = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if.npy''' ) assert_mean_pixel_difference(UpperCamelCase__ , UpperCamelCase__ ) # pipeline 2 _start_torch_memory_measurement() SCREAMING_SNAKE_CASE : Tuple = torch.Generator(device='''cpu''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE : int = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Any = pipe_a( prompt_embeds=UpperCamelCase__ , negative_prompt_embeds=UpperCamelCase__ , image=UpperCamelCase__ , generator=UpperCamelCase__ , num_inference_steps=2 , output_type='''np''' , ) SCREAMING_SNAKE_CASE : Tuple = output.images[0] assert image.shape == (256, 256, 3) SCREAMING_SNAKE_CASE : Union[str, Any] = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 SCREAMING_SNAKE_CASE : int = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_superresolution_stage_II.npy''' ) assert_mean_pixel_difference(UpperCamelCase__ , UpperCamelCase__ ) def __A ( self : Optional[int] , UpperCamelCase__ : str , UpperCamelCase__ : int , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : str ): '''simple docstring''' _start_torch_memory_measurement() SCREAMING_SNAKE_CASE : Tuple = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Any = torch.Generator(device='''cpu''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE : List[Any] = pipe_a( prompt_embeds=UpperCamelCase__ , negative_prompt_embeds=UpperCamelCase__ , image=UpperCamelCase__ , num_inference_steps=2 , generator=UpperCamelCase__ , output_type='''np''' , ) SCREAMING_SNAKE_CASE : int = output.images[0] assert image.shape == (64, 64, 3) SCREAMING_SNAKE_CASE : Optional[int] = torch.cuda.max_memory_allocated() assert mem_bytes < 10 * 10**9 SCREAMING_SNAKE_CASE : Tuple = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img.npy''' ) assert_mean_pixel_difference(UpperCamelCase__ , UpperCamelCase__ ) # pipeline 2 _start_torch_memory_measurement() SCREAMING_SNAKE_CASE : Union[str, Any] = torch.Generator(device='''cpu''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[Any] = floats_tensor((1, 3, 256, 256) , rng=random.Random(0 ) ).to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[Any] = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : str = pipe_a( prompt_embeds=UpperCamelCase__ , negative_prompt_embeds=UpperCamelCase__ , image=UpperCamelCase__ , original_image=UpperCamelCase__ , generator=UpperCamelCase__ , num_inference_steps=2 , output_type='''np''' , ) SCREAMING_SNAKE_CASE : Optional[int] = output.images[0] assert image.shape == (256, 256, 3) SCREAMING_SNAKE_CASE : List[Any] = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 SCREAMING_SNAKE_CASE : Optional[Any] = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img_superresolution_stage_II.npy''' ) assert_mean_pixel_difference(UpperCamelCase__ , UpperCamelCase__ ) def __A ( self : List[str] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Optional[Any] ): '''simple docstring''' _start_torch_memory_measurement() SCREAMING_SNAKE_CASE : str = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Union[str, Any] = floats_tensor((1, 3, 64, 64) , rng=random.Random(1 ) ).to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[int] = torch.Generator(device='''cpu''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE : int = pipe_a( prompt_embeds=UpperCamelCase__ , negative_prompt_embeds=UpperCamelCase__ , image=UpperCamelCase__ , mask_image=UpperCamelCase__ , num_inference_steps=2 , generator=UpperCamelCase__ , output_type='''np''' , ) SCREAMING_SNAKE_CASE : Any = output.images[0] assert image.shape == (64, 64, 3) SCREAMING_SNAKE_CASE : Any = torch.cuda.max_memory_allocated() assert mem_bytes < 10 * 10**9 SCREAMING_SNAKE_CASE : List[Any] = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting.npy''' ) assert_mean_pixel_difference(UpperCamelCase__ , UpperCamelCase__ ) # pipeline 2 _start_torch_memory_measurement() SCREAMING_SNAKE_CASE : str = torch.Generator(device='''cpu''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE : List[str] = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : int = floats_tensor((1, 3, 256, 256) , rng=random.Random(0 ) ).to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[int] = floats_tensor((1, 3, 256, 256) , rng=random.Random(1 ) ).to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Dict = pipe_a( prompt_embeds=UpperCamelCase__ , negative_prompt_embeds=UpperCamelCase__ , image=UpperCamelCase__ , mask_image=UpperCamelCase__ , original_image=UpperCamelCase__ , generator=UpperCamelCase__ , num_inference_steps=2 , output_type='''np''' , ) SCREAMING_SNAKE_CASE : Optional[Any] = output.images[0] assert image.shape == (256, 256, 3) SCREAMING_SNAKE_CASE : Any = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 SCREAMING_SNAKE_CASE : Tuple = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting_superresolution_stage_II.npy''' ) assert_mean_pixel_difference(UpperCamelCase__ , UpperCamelCase__ ) def A ( ): torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats()
34
0
import unittest from transformers import ( MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, Pipeline, ZeroShotClassificationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow from .test_pipelines_common import ANY # These 2 model types require different inputs than those of the usual text models. __UpperCamelCase : List[str] = {'''LayoutLMv2Config''', '''LayoutLMv3Config'''} @is_pipeline_test class lowercase__ ( unittest.TestCase): UpperCamelCase_ = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING UpperCamelCase_ = TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if model_mapping is not None: UpperCamelCase_ = {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP} if tf_model_mapping is not None: UpperCamelCase_ = { config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP } def __A ( self : str , UpperCamelCase__ : Dict , UpperCamelCase__ : int , UpperCamelCase__ : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = ZeroShotClassificationPipeline( model=__lowerCAmelCase , tokenizer=__lowerCAmelCase , candidate_labels=['''polics''', '''health'''] ) return classifier, ["Who are you voting for in 2020?", "My stomach hurts."] def __A ( self : List[Any] , UpperCamelCase__ : Any , UpperCamelCase__ : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = classifier('''Who are you voting for in 2020?''' , candidate_labels='''politics''' ) self.assertEqual(__lowerCAmelCase , {'''sequence''': ANY(__lowerCAmelCase ), '''labels''': [ANY(__lowerCAmelCase )], '''scores''': [ANY(__lowerCAmelCase )]} ) # No kwarg SCREAMING_SNAKE_CASE : Any = classifier('''Who are you voting for in 2020?''' , ['''politics'''] ) self.assertEqual(__lowerCAmelCase , {'''sequence''': ANY(__lowerCAmelCase ), '''labels''': [ANY(__lowerCAmelCase )], '''scores''': [ANY(__lowerCAmelCase )]} ) SCREAMING_SNAKE_CASE : List[Any] = classifier('''Who are you voting for in 2020?''' , candidate_labels=['''politics'''] ) self.assertEqual(__lowerCAmelCase , {'''sequence''': ANY(__lowerCAmelCase ), '''labels''': [ANY(__lowerCAmelCase )], '''scores''': [ANY(__lowerCAmelCase )]} ) SCREAMING_SNAKE_CASE : str = classifier('''Who are you voting for in 2020?''' , candidate_labels='''politics, public health''' ) self.assertEqual( __lowerCAmelCase , {'''sequence''': ANY(__lowerCAmelCase ), '''labels''': [ANY(__lowerCAmelCase ), ANY(__lowerCAmelCase )], '''scores''': [ANY(__lowerCAmelCase ), ANY(__lowerCAmelCase )]} ) self.assertAlmostEqual(sum(nested_simplify(outputs['''scores'''] ) ) , 1.0 ) SCREAMING_SNAKE_CASE : int = classifier('''Who are you voting for in 2020?''' , candidate_labels=['''politics''', '''public health'''] ) self.assertEqual( __lowerCAmelCase , {'''sequence''': ANY(__lowerCAmelCase ), '''labels''': [ANY(__lowerCAmelCase ), ANY(__lowerCAmelCase )], '''scores''': [ANY(__lowerCAmelCase ), ANY(__lowerCAmelCase )]} ) self.assertAlmostEqual(sum(nested_simplify(outputs['''scores'''] ) ) , 1.0 ) SCREAMING_SNAKE_CASE : List[Any] = classifier( '''Who are you voting for in 2020?''' , candidate_labels='''politics''' , hypothesis_template='''This text is about {}''' ) self.assertEqual(__lowerCAmelCase , {'''sequence''': ANY(__lowerCAmelCase ), '''labels''': [ANY(__lowerCAmelCase )], '''scores''': [ANY(__lowerCAmelCase )]} ) # https://github.com/huggingface/transformers/issues/13846 SCREAMING_SNAKE_CASE : str = classifier(['''I am happy'''] , ['''positive''', '''negative'''] ) self.assertEqual( __lowerCAmelCase , [ {'''sequence''': ANY(__lowerCAmelCase ), '''labels''': [ANY(__lowerCAmelCase ), ANY(__lowerCAmelCase )], '''scores''': [ANY(__lowerCAmelCase ), ANY(__lowerCAmelCase )]} for i in range(1 ) ] , ) SCREAMING_SNAKE_CASE : Any = classifier(['''I am happy''', '''I am sad'''] , ['''positive''', '''negative'''] ) self.assertEqual( __lowerCAmelCase , [ {'''sequence''': ANY(__lowerCAmelCase ), '''labels''': [ANY(__lowerCAmelCase ), ANY(__lowerCAmelCase )], '''scores''': [ANY(__lowerCAmelCase ), ANY(__lowerCAmelCase )]} for i in range(2 ) ] , ) with self.assertRaises(__lowerCAmelCase ): classifier('''''' , candidate_labels='''politics''' ) with self.assertRaises(__lowerCAmelCase ): classifier(__lowerCAmelCase , candidate_labels='''politics''' ) with self.assertRaises(__lowerCAmelCase ): classifier('''Who are you voting for in 2020?''' , candidate_labels='''''' ) with self.assertRaises(__lowerCAmelCase ): classifier('''Who are you voting for in 2020?''' , candidate_labels=__lowerCAmelCase ) with self.assertRaises(__lowerCAmelCase ): classifier( '''Who are you voting for in 2020?''' , candidate_labels='''politics''' , hypothesis_template='''Not formatting template''' , ) with self.assertRaises(__lowerCAmelCase ): classifier( '''Who are you voting for in 2020?''' , candidate_labels='''politics''' , hypothesis_template=__lowerCAmelCase , ) self.run_entailment_id(__lowerCAmelCase ) def __A ( self : List[str] , UpperCamelCase__ : Pipeline ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = zero_shot_classifier.model.config SCREAMING_SNAKE_CASE : Tuple = config.labelaid SCREAMING_SNAKE_CASE : List[str] = zero_shot_classifier.entailment_id SCREAMING_SNAKE_CASE : str = {'''LABEL_0''': 0, '''LABEL_1''': 1, '''LABEL_2''': 2} self.assertEqual(zero_shot_classifier.entailment_id , -1 ) SCREAMING_SNAKE_CASE : str = {'''entailment''': 0, '''neutral''': 1, '''contradiction''': 2} self.assertEqual(zero_shot_classifier.entailment_id , 0 ) SCREAMING_SNAKE_CASE : int = {'''ENTAIL''': 0, '''NON-ENTAIL''': 1} self.assertEqual(zero_shot_classifier.entailment_id , 0 ) SCREAMING_SNAKE_CASE : Optional[int] = {'''ENTAIL''': 2, '''NEUTRAL''': 1, '''CONTR''': 0} self.assertEqual(zero_shot_classifier.entailment_id , 2 ) SCREAMING_SNAKE_CASE : List[Any] = original_labelaid self.assertEqual(__lowerCAmelCase , zero_shot_classifier.entailment_id ) @require_torch def __A ( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = pipeline( '''zero-shot-classification''' , model='''sshleifer/tiny-distilbert-base-cased-distilled-squad''' , framework='''pt''' , ) # There was a regression in 4.10 for this # Adding a test so we don't make the mistake again. # https://github.com/huggingface/transformers/issues/13381#issuecomment-912343499 zero_shot_classifier( '''Who are you voting for in 2020?''' * 100 , candidate_labels=['''politics''', '''public health''', '''science'''] ) @require_torch def __A ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = pipeline( '''zero-shot-classification''' , model='''sshleifer/tiny-distilbert-base-cased-distilled-squad''' , framework='''pt''' , ) SCREAMING_SNAKE_CASE : List[Any] = zero_shot_classifier( '''Who are you voting for in 2020?''' , candidate_labels=['''politics''', '''public health''', '''science'''] ) self.assertEqual( nested_simplify(__lowerCAmelCase ) , { '''sequence''': '''Who are you voting for in 2020?''', '''labels''': ['''science''', '''public health''', '''politics'''], '''scores''': [0.333, 0.333, 0.333], } , ) @require_tf def __A ( self : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = pipeline( '''zero-shot-classification''' , model='''sshleifer/tiny-distilbert-base-cased-distilled-squad''' , framework='''tf''' , ) SCREAMING_SNAKE_CASE : List[Any] = zero_shot_classifier( '''Who are you voting for in 2020?''' , candidate_labels=['''politics''', '''public health''', '''science'''] ) self.assertEqual( nested_simplify(__lowerCAmelCase ) , { '''sequence''': '''Who are you voting for in 2020?''', '''labels''': ['''science''', '''public health''', '''politics'''], '''scores''': [0.333, 0.333, 0.333], } , ) @slow @require_torch def __A ( self : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = pipeline('''zero-shot-classification''' , model='''roberta-large-mnli''' , framework='''pt''' ) SCREAMING_SNAKE_CASE : Tuple = zero_shot_classifier( '''Who are you voting for in 2020?''' , candidate_labels=['''politics''', '''public health''', '''science'''] ) self.assertEqual( nested_simplify(__lowerCAmelCase ) , { '''sequence''': '''Who are you voting for in 2020?''', '''labels''': ['''politics''', '''public health''', '''science'''], '''scores''': [0.976, 0.015, 0.009], } , ) SCREAMING_SNAKE_CASE : List[Any] = zero_shot_classifier( '''The dominant sequence transduction models are based on complex recurrent or convolutional neural networks''' ''' in an encoder-decoder configuration. The best performing models also connect the encoder and decoder''' ''' through an attention mechanism. We propose a new simple network architecture, the Transformer, based''' ''' solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two''' ''' machine translation tasks show these models to be superior in quality while being more parallelizable''' ''' and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014''' ''' English-to-German translation task, improving over the existing best results, including ensembles by''' ''' over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new''' ''' single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small''' ''' fraction of the training costs of the best models from the literature. We show that the Transformer''' ''' generalizes well to other tasks by applying it successfully to English constituency parsing both with''' ''' large and limited training data.''' , candidate_labels=['''machine learning''', '''statistics''', '''translation''', '''vision'''] , multi_label=__lowerCAmelCase , ) self.assertEqual( nested_simplify(__lowerCAmelCase ) , { '''sequence''': ( '''The dominant sequence transduction models are based on complex recurrent or convolutional neural''' ''' networks in an encoder-decoder configuration. The best performing models also connect the''' ''' encoder and decoder through an attention mechanism. We propose a new simple network''' ''' architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence''' ''' and convolutions entirely. Experiments on two machine translation tasks show these models to be''' ''' superior in quality while being more parallelizable and requiring significantly less time to''' ''' train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,''' ''' improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014''' ''' English-to-French translation task, our model establishes a new single-model state-of-the-art''' ''' BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training''' ''' costs of the best models from the literature. We show that the Transformer generalizes well to''' ''' other tasks by applying it successfully to English constituency parsing both with large and''' ''' limited training data.''' ), '''labels''': ['''translation''', '''machine learning''', '''vision''', '''statistics'''], '''scores''': [0.817, 0.713, 0.018, 0.018], } , ) @slow @require_tf def __A ( self : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = pipeline('''zero-shot-classification''' , model='''roberta-large-mnli''' , framework='''tf''' ) SCREAMING_SNAKE_CASE : Optional[int] = zero_shot_classifier( '''Who are you voting for in 2020?''' , candidate_labels=['''politics''', '''public health''', '''science'''] ) self.assertEqual( nested_simplify(__lowerCAmelCase ) , { '''sequence''': '''Who are you voting for in 2020?''', '''labels''': ['''politics''', '''public health''', '''science'''], '''scores''': [0.976, 0.015, 0.009], } , ) SCREAMING_SNAKE_CASE : List[str] = zero_shot_classifier( '''The dominant sequence transduction models are based on complex recurrent or convolutional neural networks''' ''' in an encoder-decoder configuration. The best performing models also connect the encoder and decoder''' ''' through an attention mechanism. We propose a new simple network architecture, the Transformer, based''' ''' solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two''' ''' machine translation tasks show these models to be superior in quality while being more parallelizable''' ''' and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014''' ''' English-to-German translation task, improving over the existing best results, including ensembles by''' ''' over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new''' ''' single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small''' ''' fraction of the training costs of the best models from the literature. We show that the Transformer''' ''' generalizes well to other tasks by applying it successfully to English constituency parsing both with''' ''' large and limited training data.''' , candidate_labels=['''machine learning''', '''statistics''', '''translation''', '''vision'''] , multi_label=__lowerCAmelCase , ) self.assertEqual( nested_simplify(__lowerCAmelCase ) , { '''sequence''': ( '''The dominant sequence transduction models are based on complex recurrent or convolutional neural''' ''' networks in an encoder-decoder configuration. The best performing models also connect the''' ''' encoder and decoder through an attention mechanism. We propose a new simple network''' ''' architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence''' ''' and convolutions entirely. Experiments on two machine translation tasks show these models to be''' ''' superior in quality while being more parallelizable and requiring significantly less time to''' ''' train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,''' ''' improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014''' ''' English-to-French translation task, our model establishes a new single-model state-of-the-art''' ''' BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training''' ''' costs of the best models from the literature. We show that the Transformer generalizes well to''' ''' other tasks by applying it successfully to English constituency parsing both with large and''' ''' limited training data.''' ), '''labels''': ['''translation''', '''machine learning''', '''vision''', '''statistics'''], '''scores''': [0.817, 0.713, 0.018, 0.018], } , )
710
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 : int = logging.get_logger(__name__) def A ( _lowercase , _lowercase , _lowercase , _lowercase ): def constraint_to_multiple_of(_lowercase , _lowercase , _lowercase=0 , _lowercase=None ): SCREAMING_SNAKE_CASE : int = round(val / multiple ) * multiple if max_val is not None and x > max_val: SCREAMING_SNAKE_CASE : Dict = math.floor(val / multiple ) * multiple if x < min_val: SCREAMING_SNAKE_CASE : Optional[Any] = math.ceil(val / multiple ) * multiple return x SCREAMING_SNAKE_CASE : Optional[Any] = (output_size, output_size) if isinstance(_lowercase , _lowercase ) else output_size SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = get_image_size(_lowercase ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = output_size # determine new height and width SCREAMING_SNAKE_CASE : Dict = output_height / input_height SCREAMING_SNAKE_CASE : Optional[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 SCREAMING_SNAKE_CASE : List[Any] = scale_width else: # fit height SCREAMING_SNAKE_CASE : List[Any] = scale_height SCREAMING_SNAKE_CASE : List[str] = constraint_to_multiple_of(scale_height * input_height , multiple=_lowercase ) SCREAMING_SNAKE_CASE : Optional[int] = constraint_to_multiple_of(scale_width * input_width , multiple=_lowercase ) return (new_height, new_width) class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = ["""pixel_values"""] def __init__( self : int , UpperCamelCase__ : bool = True , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : PILImageResampling = PILImageResampling.BILINEAR , UpperCamelCase__ : bool = False , UpperCamelCase__ : int = 1 , UpperCamelCase__ : bool = True , UpperCamelCase__ : Union[int, float] = 1 / 255 , UpperCamelCase__ : bool = True , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , **UpperCamelCase__ : Optional[int] , ): '''simple docstring''' super().__init__(**UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[str] = size if size is not None else {'''height''': 384, '''width''': 384} SCREAMING_SNAKE_CASE : Any = get_size_dict(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Dict = do_resize SCREAMING_SNAKE_CASE : Any = size SCREAMING_SNAKE_CASE : str = keep_aspect_ratio SCREAMING_SNAKE_CASE : List[str] = ensure_multiple_of SCREAMING_SNAKE_CASE : int = resample SCREAMING_SNAKE_CASE : Any = do_rescale SCREAMING_SNAKE_CASE : List[Any] = rescale_factor SCREAMING_SNAKE_CASE : Optional[int] = do_normalize SCREAMING_SNAKE_CASE : str = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN SCREAMING_SNAKE_CASE : Union[str, Any] = image_std if image_std is not None else IMAGENET_STANDARD_STD def __A ( self : Optional[Any] , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Dict[str, int] , UpperCamelCase__ : bool = False , UpperCamelCase__ : int = 1 , UpperCamelCase__ : PILImageResampling = PILImageResampling.BICUBIC , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : Union[str, Any] , ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = get_size_dict(UpperCamelCase__ ) 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()}""" ) SCREAMING_SNAKE_CASE : Any = get_resize_output_image_size( UpperCamelCase__ , output_size=(size['''height'''], size['''width''']) , keep_aspect_ratio=UpperCamelCase__ , multiple=UpperCamelCase__ , ) return resize(UpperCamelCase__ , size=UpperCamelCase__ , resample=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def __A ( self : Dict , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Union[int, float] , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : str , ): '''simple docstring''' return rescale(UpperCamelCase__ , scale=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def __A ( self : Any , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Union[float, List[float]] , UpperCamelCase__ : Union[float, List[float]] , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : List[str] , ): '''simple docstring''' return normalize(UpperCamelCase__ , mean=UpperCamelCase__ , std=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def __A ( self : Optional[Any] , UpperCamelCase__ : ImageInput , UpperCamelCase__ : bool = None , UpperCamelCase__ : int = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : int = None , UpperCamelCase__ : PILImageResampling = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : float = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : Optional[Union[str, TensorType]] = None , UpperCamelCase__ : ChannelDimension = ChannelDimension.FIRST , **UpperCamelCase__ : Optional[int] , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE : Optional[Any] = size if size is not None else self.size SCREAMING_SNAKE_CASE : Union[str, Any] = get_size_dict(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[Any] = keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio SCREAMING_SNAKE_CASE : List[str] = ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of SCREAMING_SNAKE_CASE : Tuple = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE : Optional[Any] = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE : Union[str, Any] = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE : str = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE : List[Any] = image_mean if image_mean is not None else self.image_mean SCREAMING_SNAKE_CASE : List[Any] = image_std if image_std is not None else self.image_std SCREAMING_SNAKE_CASE : Dict = make_list_of_images(UpperCamelCase__ ) if not valid_images(UpperCamelCase__ ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None or resample is None: raise ValueError('''Size and resample must be specified if do_resize is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('''Image mean and std must be specified if do_normalize is True.''' ) # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE : Tuple = [to_numpy_array(UpperCamelCase__ ) for image in images] if do_resize: SCREAMING_SNAKE_CASE : Dict = [self.resize(image=UpperCamelCase__ , size=UpperCamelCase__ , resample=UpperCamelCase__ ) for image in images] if do_rescale: SCREAMING_SNAKE_CASE : Any = [self.rescale(image=UpperCamelCase__ , scale=UpperCamelCase__ ) for image in images] if do_normalize: SCREAMING_SNAKE_CASE : Any = [self.normalize(image=UpperCamelCase__ , mean=UpperCamelCase__ , std=UpperCamelCase__ ) for image in images] SCREAMING_SNAKE_CASE : Optional[int] = [to_channel_dimension_format(UpperCamelCase__ , UpperCamelCase__ ) for image in images] SCREAMING_SNAKE_CASE : Tuple = {'''pixel_values''': images} return BatchFeature(data=UpperCamelCase__ , tensor_type=UpperCamelCase__ ) def __A ( self : Tuple , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : List[Tuple] = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(UpperCamelCase__ ) != len(UpperCamelCase__ ): raise ValueError( '''Make sure that you pass in as many target sizes as the batch dimension of the logits''' ) if is_torch_tensor(UpperCamelCase__ ): SCREAMING_SNAKE_CASE : List[Any] = target_sizes.numpy() SCREAMING_SNAKE_CASE : Optional[int] = [] for idx in range(len(UpperCamelCase__ ) ): SCREAMING_SNAKE_CASE : List[str] = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode='''bilinear''' , align_corners=UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Dict = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(UpperCamelCase__ ) else: SCREAMING_SNAKE_CASE : List[Any] = logits.argmax(dim=1 ) SCREAMING_SNAKE_CASE : List[Any] = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
34
0
import numpy as np def A ( _lowercase ): return 1 / (1 + np.exp(-vector )) def A ( _lowercase ): return vector * sigmoid(_snake_case ) if __name__ == "__main__": import doctest doctest.testmod()
711
import random def A ( _lowercase , _lowercase ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = [], [], [] for element in data: if element < pivot: less.append(_lowercase ) elif element > pivot: greater.append(_lowercase ) else: equal.append(_lowercase ) return less, equal, greater def A ( _lowercase , _lowercase ): # index = len(items) // 2 when trying to find the median # (value of index when items is sorted) # invalid input if index >= len(_lowercase ) or index < 0: return None SCREAMING_SNAKE_CASE : Dict = items[random.randint(0 , len(_lowercase ) - 1 )] SCREAMING_SNAKE_CASE : int = 0 SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = _partition(_lowercase , _lowercase ) SCREAMING_SNAKE_CASE : List[Any] = len(_lowercase ) SCREAMING_SNAKE_CASE : Optional[Any] = len(_lowercase ) # index is the pivot if m <= index < m + count: return pivot # must be in smaller elif m > index: return quick_select(_lowercase , _lowercase ) # must be in larger else: return quick_select(_lowercase , index - (m + count) )
34
0
def A ( _lowercase = 100 ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = (n * (n + 1) // 2) ** 2 SCREAMING_SNAKE_CASE : List[str] = n * (n + 1) * (2 * n + 1) // 6 return sum_cubes - sum_squares if __name__ == "__main__": print(f"""{solution() = }""")
712
from dataclasses import asdict, dataclass from typing import Optional from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCamelCase : Tuple = logging.get_logger(__name__) # TODO Update this __UpperCamelCase : List[str] = { 'facebook/esm-1b': 'https://huggingface.co/facebook/esm-1b/resolve/main/config.json', # See all ESM models at https://huggingface.co/models?filter=esm } class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = """esm""" def __init__( self : Tuple , UpperCamelCase__ : Optional[Any]=None , UpperCamelCase__ : int=None , UpperCamelCase__ : List[str]=None , UpperCamelCase__ : Any=768 , UpperCamelCase__ : Optional[Any]=12 , UpperCamelCase__ : str=12 , UpperCamelCase__ : Optional[int]=3072 , UpperCamelCase__ : Optional[Any]=0.1 , UpperCamelCase__ : Any=0.1 , UpperCamelCase__ : Union[str, Any]=1026 , UpperCamelCase__ : Dict=0.02 , UpperCamelCase__ : Any=1E-12 , UpperCamelCase__ : Dict="absolute" , UpperCamelCase__ : Optional[Any]=True , UpperCamelCase__ : int=None , UpperCamelCase__ : Optional[int]=False , UpperCamelCase__ : Tuple=False , UpperCamelCase__ : List[str]=None , UpperCamelCase__ : Optional[Any]=None , **UpperCamelCase__ : Any , ): '''simple docstring''' super().__init__(pad_token_id=UpperCamelCase__ , mask_token_id=UpperCamelCase__ , **UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[Any] = vocab_size SCREAMING_SNAKE_CASE : Any = hidden_size SCREAMING_SNAKE_CASE : Union[str, Any] = num_hidden_layers SCREAMING_SNAKE_CASE : Dict = num_attention_heads SCREAMING_SNAKE_CASE : Any = intermediate_size SCREAMING_SNAKE_CASE : str = hidden_dropout_prob SCREAMING_SNAKE_CASE : List[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : str = max_position_embeddings SCREAMING_SNAKE_CASE : Tuple = initializer_range SCREAMING_SNAKE_CASE : Optional[int] = layer_norm_eps SCREAMING_SNAKE_CASE : Dict = position_embedding_type SCREAMING_SNAKE_CASE : Any = use_cache SCREAMING_SNAKE_CASE : Dict = emb_layer_norm_before SCREAMING_SNAKE_CASE : List[str] = token_dropout SCREAMING_SNAKE_CASE : List[Any] = is_folding_model if is_folding_model: if esmfold_config is None: logger.info('''No esmfold_config supplied for folding model, using default values.''' ) SCREAMING_SNAKE_CASE : List[Any] = EsmFoldConfig() elif isinstance(UpperCamelCase__ , UpperCamelCase__ ): SCREAMING_SNAKE_CASE : Union[str, Any] = EsmFoldConfig(**UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[Any] = esmfold_config if vocab_list is None: logger.warning('''No vocab_list supplied for folding model, assuming the ESM-2 vocabulary!''' ) SCREAMING_SNAKE_CASE : Optional[int] = get_default_vocab_list() else: SCREAMING_SNAKE_CASE : Optional[Any] = vocab_list else: SCREAMING_SNAKE_CASE : str = None SCREAMING_SNAKE_CASE : int = None if self.esmfold_config is not None and getattr(self.esmfold_config , '''use_esm_attn_map''' , UpperCamelCase__ ): raise ValueError('''The HuggingFace port of ESMFold does not support use_esm_attn_map at this time!''' ) def __A ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = super().to_dict() if isinstance(self.esmfold_config , UpperCamelCase__ ): SCREAMING_SNAKE_CASE : Optional[Any] = self.esmfold_config.to_dict() return output @dataclass class lowercase__ : UpperCamelCase_ = None UpperCamelCase_ = True UpperCamelCase_ = False UpperCamelCase_ = False UpperCamelCase_ = False UpperCamelCase_ = 0 UpperCamelCase_ = True UpperCamelCase_ = False UpperCamelCase_ = 128 UpperCamelCase_ = None def __A ( self : Optional[int] ): '''simple docstring''' if self.trunk is None: SCREAMING_SNAKE_CASE : Optional[Any] = TrunkConfig() elif isinstance(self.trunk , UpperCamelCase__ ): SCREAMING_SNAKE_CASE : Tuple = TrunkConfig(**self.trunk ) def __A ( self : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = asdict(self ) SCREAMING_SNAKE_CASE : Tuple = self.trunk.to_dict() return output @dataclass class lowercase__ : UpperCamelCase_ = 48 UpperCamelCase_ = 1_024 UpperCamelCase_ = 128 UpperCamelCase_ = 32 UpperCamelCase_ = 32 UpperCamelCase_ = 32 UpperCamelCase_ = 0 UpperCamelCase_ = 0 UpperCamelCase_ = False UpperCamelCase_ = 4 UpperCamelCase_ = 128 UpperCamelCase_ = None def __A ( self : Any ): '''simple docstring''' if self.structure_module is None: SCREAMING_SNAKE_CASE : Optional[int] = StructureModuleConfig() elif isinstance(self.structure_module , UpperCamelCase__ ): SCREAMING_SNAKE_CASE : Optional[Any] = StructureModuleConfig(**self.structure_module ) if self.max_recycles <= 0: raise ValueError(f"""`max_recycles` should be positive, got {self.max_recycles}.""" ) if self.sequence_state_dim % self.sequence_state_dim != 0: raise ValueError( '''`sequence_state_dim` should be a round multiple of `sequence_state_dim`, got''' f""" {self.sequence_state_dim} and {self.sequence_state_dim}.""" ) if self.pairwise_state_dim % self.pairwise_state_dim != 0: raise ValueError( '''`pairwise_state_dim` should be a round multiple of `pairwise_state_dim`, got''' f""" {self.pairwise_state_dim} and {self.pairwise_state_dim}.""" ) SCREAMING_SNAKE_CASE : Dict = self.sequence_state_dim // self.sequence_head_width SCREAMING_SNAKE_CASE : Tuple = self.pairwise_state_dim // self.pairwise_head_width if self.sequence_state_dim != sequence_num_heads * self.sequence_head_width: raise ValueError( '''`sequence_state_dim` should be equal to `sequence_num_heads * sequence_head_width, got''' f""" {self.sequence_state_dim} != {sequence_num_heads} * {self.sequence_head_width}.""" ) if self.pairwise_state_dim != pairwise_num_heads * self.pairwise_head_width: raise ValueError( '''`pairwise_state_dim` should be equal to `pairwise_num_heads * pairwise_head_width, got''' f""" {self.pairwise_state_dim} != {pairwise_num_heads} * {self.pairwise_head_width}.""" ) if self.pairwise_state_dim % 2 != 0: raise ValueError(f"""`pairwise_state_dim` should be even, got {self.pairwise_state_dim}.""" ) if self.dropout >= 0.4: raise ValueError(f"""`dropout` should not be greater than 0.4, got {self.dropout}.""" ) def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = asdict(self ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.structure_module.to_dict() return output @dataclass class lowercase__ : UpperCamelCase_ = 384 UpperCamelCase_ = 128 UpperCamelCase_ = 16 UpperCamelCase_ = 128 UpperCamelCase_ = 12 UpperCamelCase_ = 4 UpperCamelCase_ = 8 UpperCamelCase_ = 0.1 UpperCamelCase_ = 8 UpperCamelCase_ = 1 UpperCamelCase_ = 2 UpperCamelCase_ = 7 UpperCamelCase_ = 10 UpperCamelCase_ = 1E-8 UpperCamelCase_ = 1E5 def __A ( self : Dict ): '''simple docstring''' return asdict(self ) def A ( ): return ( "<cls>", "<pad>", "<eos>", "<unk>", "L", "A", "G", "V", "S", "E", "R", "T", "I", "D", "P", "K", "Q", "N", "F", "Y", "M", "H", "W", "C", "X", "B", "U", "Z", "O", ".", "-", "<null_1>", "<mask>", )
34
0
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices __UpperCamelCase : List[Any] = logging.get_logger(__name__) __UpperCamelCase : Optional[Any] = { 'shi-labs/nat-mini-in1k-224': 'https://huggingface.co/shi-labs/nat-mini-in1k-224/resolve/main/config.json', # See all Nat models at https://huggingface.co/models?filter=nat } class lowercase__ ( UpperCAmelCase__ , UpperCAmelCase__): UpperCamelCase_ = 'nat' UpperCamelCase_ = { 'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers', } def __init__( self : Optional[Any] , UpperCamelCase__ : Optional[int]=4 , UpperCamelCase__ : int=3 , UpperCamelCase__ : Any=64 , UpperCamelCase__ : Union[str, Any]=[3, 4, 6, 5] , UpperCamelCase__ : Optional[Any]=[2, 4, 8, 16] , UpperCamelCase__ : Any=7 , UpperCamelCase__ : int=3.0 , UpperCamelCase__ : Optional[int]=True , UpperCamelCase__ : Optional[int]=0.0 , UpperCamelCase__ : int=0.0 , UpperCamelCase__ : List[Any]=0.1 , UpperCamelCase__ : Dict="gelu" , UpperCamelCase__ : Dict=0.02 , UpperCamelCase__ : Optional[Any]=1E-5 , UpperCamelCase__ : str=0.0 , UpperCamelCase__ : Dict=None , UpperCamelCase__ : Dict=None , **UpperCamelCase__ : str , ): '''simple docstring''' super().__init__(**UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Dict = patch_size SCREAMING_SNAKE_CASE : Any = num_channels SCREAMING_SNAKE_CASE : List[Any] = embed_dim SCREAMING_SNAKE_CASE : List[str] = depths SCREAMING_SNAKE_CASE : str = len(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[str] = num_heads SCREAMING_SNAKE_CASE : List[str] = kernel_size SCREAMING_SNAKE_CASE : Dict = mlp_ratio SCREAMING_SNAKE_CASE : Tuple = qkv_bias SCREAMING_SNAKE_CASE : Any = hidden_dropout_prob SCREAMING_SNAKE_CASE : List[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : List[str] = drop_path_rate SCREAMING_SNAKE_CASE : List[Any] = hidden_act SCREAMING_SNAKE_CASE : Union[str, Any] = layer_norm_eps SCREAMING_SNAKE_CASE : Optional[int] = initializer_range # we set the hidden_size attribute in order to make Nat work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model SCREAMING_SNAKE_CASE : List[str] = int(embed_dim * 2 ** (len(UpperCamelCase__ ) - 1) ) SCREAMING_SNAKE_CASE : Any = layer_scale_init_value SCREAMING_SNAKE_CASE : Any = ["""stem"""] + [f"""stage{idx}""" for idx in range(1 , len(UpperCamelCase__ ) + 1 )] SCREAMING_SNAKE_CASE : Optional[int] = get_aligned_output_features_output_indices( out_features=UpperCamelCase__ , out_indices=UpperCamelCase__ , stage_names=self.stage_names )
713
import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv("""TEST_SAGEMAKER""" , """False""")) is not True , reason="""Skipping test because should only be run when releasing minor transformers version""" , ) @pytest.mark.usefixtures("""sm_env""") @parameterized_class( [ { """framework""": """pytorch""", """script""": """run_glue.py""", """model_name_or_path""": """distilbert-base-cased""", """instance_type""": """ml.p3.16xlarge""", """results""": {"""train_runtime""": 650, """eval_accuracy""": 0.7, """eval_loss""": 0.6}, }, { """framework""": """pytorch""", """script""": """run_ddp.py""", """model_name_or_path""": """distilbert-base-cased""", """instance_type""": """ml.p3.16xlarge""", """results""": {"""train_runtime""": 600, """eval_accuracy""": 0.7, """eval_loss""": 0.6}, }, { """framework""": """tensorflow""", """script""": """run_tf_dist.py""", """model_name_or_path""": """distilbert-base-cased""", """instance_type""": """ml.p3.16xlarge""", """results""": {"""train_runtime""": 600, """eval_accuracy""": 0.6, """eval_loss""": 0.7}, }, ]) class lowercase__ ( unittest.TestCase): def __A ( self : Any ): '''simple docstring''' if self.framework == "pytorch": subprocess.run( f"""cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py""".split() , encoding='''utf-8''' , check=UpperCamelCase__ , ) assert hasattr(self , '''env''' ) def __A ( self : str , UpperCamelCase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = f"""{self.env.base_job_name}-{instance_count}-{'ddp' if 'ddp' in self.script else 'smd'}""" # distributed data settings SCREAMING_SNAKE_CASE : Any = {'''smdistributed''': {'''dataparallel''': {'''enabled''': True}}} if self.script != '''run_ddp.py''' else None # creates estimator return HuggingFace( entry_point=self.script , source_dir=self.env.test_path , role=self.env.role , image_uri=self.env.image_uri , base_job_name=UpperCamelCase__ , instance_count=UpperCamelCase__ , instance_type=self.instance_type , debugger_hook_config=UpperCamelCase__ , hyperparameters={**self.env.distributed_hyperparameters, '''model_name_or_path''': self.model_name_or_path} , metric_definitions=self.env.metric_definitions , distribution=UpperCamelCase__ , py_version='''py36''' , ) def __A ( self : Optional[Any] , UpperCamelCase__ : List[str] ): '''simple docstring''' TrainingJobAnalytics(UpperCamelCase__ ).export_csv(f"""{self.env.test_path}/{job_name}_metrics.csv""" ) @parameterized.expand([(2,)] ) def __A ( self : Tuple , UpperCamelCase__ : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = self.create_estimator(UpperCamelCase__ ) # run training estimator.fit() # result dataframe SCREAMING_SNAKE_CASE : Optional[Any] = TrainingJobAnalytics(estimator.latest_training_job.name ).dataframe() # extract kpis SCREAMING_SNAKE_CASE : List[str] = list(result_metrics_df[result_metrics_df.metric_name == '''eval_accuracy''']['''value'''] ) SCREAMING_SNAKE_CASE : Dict = list(result_metrics_df[result_metrics_df.metric_name == '''eval_loss''']['''value'''] ) # get train time from SageMaker job, this includes starting, preprocessing, stopping SCREAMING_SNAKE_CASE : List[Any] = ( Session().describe_training_job(estimator.latest_training_job.name ).get('''TrainingTimeInSeconds''' , 99_9999 ) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results['''eval_accuracy'''] for t in eval_accuracy ) assert all(t <= self.results['''eval_loss'''] for t in eval_loss ) # dump tests result into json file to share in PR with open(f"""{estimator.latest_training_job.name}.json""" , '''w''' ) as outfile: json.dump({'''train_time''': train_runtime, '''eval_accuracy''': eval_accuracy, '''eval_loss''': eval_loss} , UpperCamelCase__ )
34
0
class lowercase__ : def __init__( self : Optional[Any] , UpperCamelCase__ : str = "" , UpperCamelCase__ : bool = False ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = {} # A node will be a leaf if the tree contains its word SCREAMING_SNAKE_CASE : Any = is_leaf SCREAMING_SNAKE_CASE : str = prefix def __A ( self : Union[str, Any] , UpperCamelCase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = 0 for q, w in zip(self.prefix , __lowercase ): if q != w: break x += 1 return self.prefix[:x], self.prefix[x:], word[x:] def __A ( self : Optional[int] , UpperCamelCase__ : list[str] ): '''simple docstring''' for word in words: self.insert(__lowercase ) def __A ( self : Optional[Any] , UpperCamelCase__ : str ): '''simple docstring''' if self.prefix == word: SCREAMING_SNAKE_CASE : List[str] = True # Case 2: The node has no edges that have a prefix to the word # Solution: We create an edge from the current node to a new one # containing the word elif word[0] not in self.nodes: SCREAMING_SNAKE_CASE : Tuple = RadixNode(prefix=__lowercase , is_leaf=__lowercase ) else: SCREAMING_SNAKE_CASE : Optional[Any] = self.nodes[word[0]] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = incoming_node.match( __lowercase ) # Case 3: The node prefix is equal to the matching # Solution: We insert remaining word on the next node if remaining_prefix == "": self.nodes[matching_string[0]].insert(__lowercase ) # Case 4: The word is greater equal to the matching # Solution: Create a node in between both nodes, change # prefixes and add the new node for the remaining word else: SCREAMING_SNAKE_CASE : Optional[Any] = remaining_prefix SCREAMING_SNAKE_CASE : List[str] = self.nodes[matching_string[0]] SCREAMING_SNAKE_CASE : str = RadixNode(__lowercase , __lowercase ) SCREAMING_SNAKE_CASE : int = aux_node if remaining_word == "": SCREAMING_SNAKE_CASE : Tuple = True else: self.nodes[matching_string[0]].insert(__lowercase ) def __A ( self : Optional[Any] , UpperCamelCase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = self.nodes.get(word[0] , __lowercase ) if not incoming_node: return False else: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = incoming_node.match( __lowercase ) # If there is remaining prefix, the word can't be on the tree if remaining_prefix != "": return False # This applies when the word and the prefix are equal elif remaining_word == "": return incoming_node.is_leaf # We have word remaining so we check the next node else: return incoming_node.find(__lowercase ) def __A ( self : List[Any] , UpperCamelCase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = self.nodes.get(word[0] , __lowercase ) if not incoming_node: return False else: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = incoming_node.match( __lowercase ) # If there is remaining prefix, the word can't be on the tree if remaining_prefix != "": return False # We have word remaining so we check the next node elif remaining_word != "": return incoming_node.delete(__lowercase ) else: # If it is not a leaf, we don't have to delete if not incoming_node.is_leaf: return False else: # We delete the nodes if no edges go from it if len(incoming_node.nodes ) == 0: del self.nodes[word[0]] # We merge the current node with its only child if len(self.nodes ) == 1 and not self.is_leaf: SCREAMING_SNAKE_CASE : str = list(self.nodes.values() )[0] SCREAMING_SNAKE_CASE : Tuple = merging_node.is_leaf self.prefix += merging_node.prefix SCREAMING_SNAKE_CASE : Optional[int] = merging_node.nodes # If there is more than 1 edge, we just mark it as non-leaf elif len(incoming_node.nodes ) > 1: SCREAMING_SNAKE_CASE : Union[str, Any] = False # If there is 1 edge, we merge it with its child else: SCREAMING_SNAKE_CASE : Any = list(incoming_node.nodes.values() )[0] SCREAMING_SNAKE_CASE : Tuple = merging_node.is_leaf incoming_node.prefix += merging_node.prefix SCREAMING_SNAKE_CASE : Optional[Any] = merging_node.nodes return True def __A ( self : int , UpperCamelCase__ : int = 0 ): '''simple docstring''' if self.prefix != "": print('''-''' * height , self.prefix , ''' (leaf)''' if self.is_leaf else '''''' ) for value in self.nodes.values(): value.print_tree(height + 1 ) def A ( ): SCREAMING_SNAKE_CASE : Any = '''banana bananas bandana band apple all beast'''.split() SCREAMING_SNAKE_CASE : int = RadixNode() root.insert_many(SCREAMING_SNAKE_CASE_ ) assert all(root.find(SCREAMING_SNAKE_CASE_ ) for word in words ) assert not root.find('''bandanas''' ) assert not root.find('''apps''' ) root.delete('''all''' ) assert not root.find('''all''' ) root.delete('''banana''' ) assert not root.find('''banana''' ) assert root.find('''bananas''' ) return True def A ( ): assert test_trie() def A ( ): SCREAMING_SNAKE_CASE : Optional[Any] = RadixNode() SCREAMING_SNAKE_CASE : Optional[Any] = '''banana bananas bandanas bandana band apple all beast'''.split() root.insert_many(SCREAMING_SNAKE_CASE_ ) print('''Words:''' , SCREAMING_SNAKE_CASE_ ) print('''Tree:''' ) root.print_tree() if __name__ == "__main__": main()
714
import os try: from .build_directory_md import good_file_paths except ImportError: from build_directory_md import good_file_paths # type: ignore __UpperCamelCase : Dict = list(good_file_paths()) assert filepaths, "good_file_paths() failed!" __UpperCamelCase : Tuple = [file for file in filepaths if file != file.lower()] if upper_files: print(f"""{len(upper_files)} files contain uppercase characters:""") print('\n'.join(upper_files) + '\n') __UpperCamelCase : List[Any] = [file for file in filepaths if ' ' in file] if space_files: print(f"""{len(space_files)} files contain space characters:""") print('\n'.join(space_files) + '\n') __UpperCamelCase : List[Any] = [file for file in filepaths if '-' in file] if hyphen_files: print(f"""{len(hyphen_files)} files contain hyphen characters:""") print('\n'.join(hyphen_files) + '\n') __UpperCamelCase : List[Any] = [file for file in filepaths if os.sep not in file] if nodir_files: print(f"""{len(nodir_files)} files are not in a directory:""") print('\n'.join(nodir_files) + '\n') __UpperCamelCase : Optional[Any] = len(upper_files + space_files + hyphen_files + nodir_files) if bad_files: import sys sys.exit(bad_files)
34
0
from __future__ import annotations def A ( _lowercase ): SCREAMING_SNAKE_CASE : Optional[Any] = [True] * limit SCREAMING_SNAKE_CASE : Optional[Any] = False SCREAMING_SNAKE_CASE : List[str] = False SCREAMING_SNAKE_CASE : Tuple = True for i in range(3 , int(limit**0.5 + 1 ) , 2 ): SCREAMING_SNAKE_CASE : Optional[Any] = i * 2 while index < limit: SCREAMING_SNAKE_CASE : int = False SCREAMING_SNAKE_CASE : Optional[int] = index + i SCREAMING_SNAKE_CASE : Any = [2] for i in range(3 , _lowerCAmelCase , 2 ): if is_prime[i]: primes.append(_lowerCAmelCase ) return primes def A ( _lowercase = 1_000_000 ): SCREAMING_SNAKE_CASE : Union[str, Any] = prime_sieve(_lowerCAmelCase ) SCREAMING_SNAKE_CASE : List[str] = 0 SCREAMING_SNAKE_CASE : Union[str, Any] = 0 for i in range(len(_lowerCAmelCase ) ): for j in range(i + length , len(_lowerCAmelCase ) ): SCREAMING_SNAKE_CASE : Dict = sum(primes[i:j] ) if sol >= ceiling: break if sol in primes: SCREAMING_SNAKE_CASE : int = j - i SCREAMING_SNAKE_CASE : Dict = sol return largest if __name__ == "__main__": print(f"""{solution() = }""")
715
import os import re import warnings from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_ta import TaTokenizer else: __UpperCamelCase : Dict = None __UpperCamelCase : Tuple = logging.get_logger(__name__) __UpperCamelCase : Optional[int] = {'vocab_file': 'spiece.model', 'tokenizer_file': 'tokenizer.json'} __UpperCamelCase : Optional[int] = { 'vocab_file': { 't5-small': 'https://huggingface.co/t5-small/resolve/main/spiece.model', 't5-base': 'https://huggingface.co/t5-base/resolve/main/spiece.model', 't5-large': 'https://huggingface.co/t5-large/resolve/main/spiece.model', 't5-3b': 'https://huggingface.co/t5-3b/resolve/main/spiece.model', 't5-11b': 'https://huggingface.co/t5-11b/resolve/main/spiece.model', }, 'tokenizer_file': { 't5-small': 'https://huggingface.co/t5-small/resolve/main/tokenizer.json', 't5-base': 'https://huggingface.co/t5-base/resolve/main/tokenizer.json', 't5-large': 'https://huggingface.co/t5-large/resolve/main/tokenizer.json', 't5-3b': 'https://huggingface.co/t5-3b/resolve/main/tokenizer.json', 't5-11b': 'https://huggingface.co/t5-11b/resolve/main/tokenizer.json', }, } # TODO(PVP) - this should be removed in Transformers v5 __UpperCamelCase : Union[str, Any] = { 't5-small': 512, 't5-base': 512, 't5-large': 512, 't5-3b': 512, 't5-11b': 512, } class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = VOCAB_FILES_NAMES UpperCamelCase_ = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase_ = ["""input_ids""", """attention_mask"""] UpperCamelCase_ = TaTokenizer UpperCamelCase_ = [] def __init__( self : str , UpperCamelCase__ : Optional[int]=None , UpperCamelCase__ : Dict=None , UpperCamelCase__ : str="</s>" , UpperCamelCase__ : str="<unk>" , UpperCamelCase__ : Optional[int]="<pad>" , UpperCamelCase__ : Optional[Any]=100 , UpperCamelCase__ : List[Any]=None , **UpperCamelCase__ : str , ): '''simple docstring''' if extra_ids > 0 and additional_special_tokens is None: SCREAMING_SNAKE_CASE : List[str] = [f"""<extra_id_{i}>""" for i in range(UpperCamelCase__ )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra special tokens SCREAMING_SNAKE_CASE : int = len(set(filter(lambda UpperCamelCase__ : bool('''extra_id_''' in str(UpperCamelCase__ ) ) , UpperCamelCase__ ) ) ) if extra_tokens != extra_ids: raise ValueError( f"""Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are""" ''' provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids''' ''' tokens''' ) super().__init__( UpperCamelCase__ , tokenizer_file=UpperCamelCase__ , eos_token=UpperCamelCase__ , unk_token=UpperCamelCase__ , pad_token=UpperCamelCase__ , extra_ids=UpperCamelCase__ , additional_special_tokens=UpperCamelCase__ , **UpperCamelCase__ , ) SCREAMING_SNAKE_CASE : str = vocab_file SCREAMING_SNAKE_CASE : int = False if not self.vocab_file else True SCREAMING_SNAKE_CASE : str = extra_ids @staticmethod def __A ( UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Optional[Any] ): '''simple docstring''' if pretrained_model_name_or_path in TaTokenizerFast.max_model_input_sizes: SCREAMING_SNAKE_CASE : List[str] = TaTokenizerFast.max_model_input_sizes[pretrained_model_name_or_path] if init_max_model_length is not None and init_max_model_length != max_model_length: return init_max_model_length elif init_max_model_length is None: warnings.warn( '''This tokenizer was incorrectly instantiated with a model max length of''' f""" {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this""" ''' behavior is kept to avoid breaking backwards compatibility when padding/encoding with''' ''' `truncation is True`.\n- Be aware that you SHOULD NOT rely on''' f""" {pretrained_model_name_or_path} automatically truncating your input to""" f""" {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences""" f""" longer than {deprecated_max_model_length} you can either instantiate this tokenizer with""" ''' `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please''' ''' instantiate this tokenizer with `model_max_length` set to your preferred value.''' , UpperCamelCase__ , ) return max_model_length def __A ( self : Tuple , UpperCamelCase__ : str , UpperCamelCase__ : Optional[str] = None ): '''simple docstring''' if not self.can_save_slow_tokenizer: raise ValueError( '''Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ''' '''tokenizer.''' ) if not os.path.isdir(UpperCamelCase__ ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return SCREAMING_SNAKE_CASE : Any = os.path.join( UpperCamelCase__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCamelCase__ ): copyfile(self.vocab_file , UpperCamelCase__ ) logger.info(f"""Copy vocab file to {out_vocab_file}""" ) return (out_vocab_file,) def __A ( self : Optional[Any] , UpperCamelCase__ : List[int] , UpperCamelCase__ : Optional[List[int]] = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = token_ids_a + [self.eos_token_id] if token_ids_a is None: return self.prefix_tokens + token_ids_a else: SCREAMING_SNAKE_CASE : Tuple = token_ids_a + [self.eos_token_id] return self.prefix_tokens + token_ids_a + token_ids_a def __A ( self : Any , UpperCamelCase__ : List[int] , UpperCamelCase__ : Optional[List[int]] = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def __A ( self : Dict ): '''simple docstring''' return list( set(filter(lambda UpperCamelCase__ : bool(re.search(r'''<extra_id_\d+>''' , UpperCamelCase__ ) ) is not None , self.additional_special_tokens ) ) ) def __A ( self : List[Any] ): '''simple docstring''' return [self.convert_tokens_to_ids(UpperCamelCase__ ) for token in self.get_sentinel_tokens()]
34
0
import math from typing import Union import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import randn_tensor from .scheduling_utils import SchedulerMixin class lowercase__ ( UpperCamelCase__ , UpperCamelCase__): UpperCamelCase_ = 1 @register_to_config def __init__( self : Union[str, Any] , UpperCamelCase__ : Optional[Any]=2000 , UpperCamelCase__ : int=0.1 , UpperCamelCase__ : Dict=20 , UpperCamelCase__ : Dict=1E-3 ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = None SCREAMING_SNAKE_CASE : Optional[Any] = None SCREAMING_SNAKE_CASE : List[Any] = None def __A ( self : Any , UpperCamelCase__ : int , UpperCamelCase__ : Any = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = torch.linspace(1 , self.config.sampling_eps , UpperCamelCase__ , device=UpperCamelCase__ ) def __A ( self : Optional[int] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Any , UpperCamelCase__ : Dict , UpperCamelCase__ : Union[str, Any]=None ): '''simple docstring''' if self.timesteps is None: raise ValueError( '''`self.timesteps` is not set, you need to run \'set_timesteps\' after creating the scheduler''' ) # TODO(Patrick) better comments + non-PyTorch # postprocess model score SCREAMING_SNAKE_CASE : List[str] = ( -0.25 * t**2 * (self.config.beta_max - self.config.beta_min) - 0.5 * t * self.config.beta_min ) SCREAMING_SNAKE_CASE : Optional[int] = torch.sqrt(1.0 - torch.exp(2.0 * log_mean_coeff ) ) SCREAMING_SNAKE_CASE : int = std.flatten() while len(std.shape ) < len(score.shape ): SCREAMING_SNAKE_CASE : Union[str, Any] = std.unsqueeze(-1 ) SCREAMING_SNAKE_CASE : Union[str, Any] = -score / std # compute SCREAMING_SNAKE_CASE : Optional[int] = -1.0 / len(self.timesteps ) SCREAMING_SNAKE_CASE : Tuple = self.config.beta_min + t * (self.config.beta_max - self.config.beta_min) SCREAMING_SNAKE_CASE : str = beta_t.flatten() while len(beta_t.shape ) < len(x.shape ): SCREAMING_SNAKE_CASE : Any = beta_t.unsqueeze(-1 ) SCREAMING_SNAKE_CASE : List[Any] = -0.5 * beta_t * x SCREAMING_SNAKE_CASE : str = torch.sqrt(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Dict = drift - diffusion**2 * score SCREAMING_SNAKE_CASE : List[str] = x + drift * dt # add noise SCREAMING_SNAKE_CASE : Any = randn_tensor(x.shape , layout=x.layout , generator=UpperCamelCase__ , device=x.device , dtype=x.dtype ) SCREAMING_SNAKE_CASE : Optional[Any] = x_mean + diffusion * math.sqrt(-dt ) * noise return x, x_mean def __len__( self : Dict ): '''simple docstring''' return self.config.num_train_timesteps
716
import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionPipeline from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device __UpperCamelCase : str = False class lowercase__ ( unittest.TestCase): pass @nightly @require_torch_gpu class lowercase__ ( unittest.TestCase): def __A ( self : Union[str, Any] ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = VersatileDiffusionPipeline.from_pretrained('''shi-labs/versatile-diffusion''' , torch_dtype=torch.floataa ) pipe.to(UpperCamelCase__ ) pipe.set_progress_bar_config(disable=UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[Any] = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg''' ) SCREAMING_SNAKE_CASE : Optional[Any] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Dict = pipe.dual_guided( prompt='''first prompt''' , image=UpperCamelCase__ , text_to_image_strength=0.75 , generator=UpperCamelCase__ , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' , ).images with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[Any] = VersatileDiffusionPipeline.from_pretrained(UpperCamelCase__ , torch_dtype=torch.floataa ) pipe.to(UpperCamelCase__ ) pipe.set_progress_bar_config(disable=UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[Any] = generator.manual_seed(0 ) SCREAMING_SNAKE_CASE : int = pipe.dual_guided( prompt='''first prompt''' , image=UpperCamelCase__ , text_to_image_strength=0.75 , generator=UpperCamelCase__ , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' , ).images assert np.abs(image - new_image ).sum() < 1E-5, "Models don't have the same forward pass" def __A ( self : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = VersatileDiffusionPipeline.from_pretrained('''shi-labs/versatile-diffusion''' , torch_dtype=torch.floataa ) pipe.to(UpperCamelCase__ ) pipe.set_progress_bar_config(disable=UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[int] = '''cyberpunk 2077''' SCREAMING_SNAKE_CASE : Tuple = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg''' ) SCREAMING_SNAKE_CASE : List[Any] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Tuple = pipe.dual_guided( prompt=UpperCamelCase__ , image=UpperCamelCase__ , text_to_image_strength=0.75 , generator=UpperCamelCase__ , guidance_scale=7.5 , num_inference_steps=50 , output_type='''numpy''' , ).images SCREAMING_SNAKE_CASE : Tuple = image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE : int = np.array([0.1448, 0.1619, 0.1741, 0.1086, 0.1147, 0.1128, 0.1199, 0.1165, 0.1001] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 SCREAMING_SNAKE_CASE : Optional[Any] = '''A painting of a squirrel eating a burger ''' SCREAMING_SNAKE_CASE : Optional[Any] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Any = pipe.text_to_image( prompt=UpperCamelCase__ , generator=UpperCamelCase__ , guidance_scale=7.5 , num_inference_steps=50 , output_type='''numpy''' ).images SCREAMING_SNAKE_CASE : List[str] = image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE : Any = np.array([0.3367, 0.3169, 0.2656, 0.3870, 0.4790, 0.3796, 0.4009, 0.4878, 0.4778] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 SCREAMING_SNAKE_CASE : Optional[Any] = pipe.image_variation(UpperCamelCase__ , generator=UpperCamelCase__ , output_type='''numpy''' ).images SCREAMING_SNAKE_CASE : Optional[int] = image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE : Union[str, Any] = np.array([0.3076, 0.3123, 0.3284, 0.3782, 0.3770, 0.3894, 0.4297, 0.4331, 0.4456] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1
34
0
'''simple docstring''' import unittest from transformers import ( MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING, TextGenerationPipeline, logging, pipeline, ) from transformers.testing_utils import ( CaptureLogger, is_pipeline_test, require_accelerate, require_tf, require_torch, require_torch_gpu, require_torch_or_tf, ) from .test_pipelines_common import ANY @is_pipeline_test @require_torch_or_tf class lowercase__ ( unittest.TestCase): UpperCamelCase_ = MODEL_FOR_CAUSAL_LM_MAPPING UpperCamelCase_ = TF_MODEL_FOR_CAUSAL_LM_MAPPING @require_torch def __A ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = pipeline(task='''text-generation''' , model='''sshleifer/tiny-ctrl''' , framework='''pt''' ) # Using `do_sample=False` to force deterministic output SCREAMING_SNAKE_CASE : Any = text_generator('''This is a test''' , do_sample=lowerCamelCase__ ) self.assertEqual( lowerCamelCase__ , [ { '''generated_text''': ( '''This is a test ☃ ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy oscope.''' ''' oscope. FiliFili@@''' ) } ] , ) SCREAMING_SNAKE_CASE : Dict = text_generator(['''This is a test''', '''This is a second test'''] ) self.assertEqual( lowerCamelCase__ , [ [ { '''generated_text''': ( '''This is a test ☃ ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy oscope.''' ''' oscope. FiliFili@@''' ) } ], [ { '''generated_text''': ( '''This is a second test ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy''' ''' oscope. oscope. FiliFili@@''' ) } ], ] , ) SCREAMING_SNAKE_CASE : int = text_generator('''This is a test''' , do_sample=lowerCamelCase__ , num_return_sequences=2 , return_tensors=lowerCamelCase__ ) self.assertEqual( lowerCamelCase__ , [ {'''generated_token_ids''': ANY(lowerCamelCase__ )}, {'''generated_token_ids''': ANY(lowerCamelCase__ )}, ] , ) SCREAMING_SNAKE_CASE : Any = text_generator.model.config.eos_token_id SCREAMING_SNAKE_CASE : List[Any] = "<pad>" SCREAMING_SNAKE_CASE : Union[str, Any] = text_generator( ['''This is a test''', '''This is a second test'''] , do_sample=lowerCamelCase__ , num_return_sequences=2 , batch_size=2 , return_tensors=lowerCamelCase__ , ) self.assertEqual( lowerCamelCase__ , [ [ {'''generated_token_ids''': ANY(lowerCamelCase__ )}, {'''generated_token_ids''': ANY(lowerCamelCase__ )}, ], [ {'''generated_token_ids''': ANY(lowerCamelCase__ )}, {'''generated_token_ids''': ANY(lowerCamelCase__ )}, ], ] , ) @require_tf def __A ( self : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = pipeline(task='''text-generation''' , model='''sshleifer/tiny-ctrl''' , framework='''tf''' ) # Using `do_sample=False` to force deterministic output SCREAMING_SNAKE_CASE : Dict = text_generator('''This is a test''' , do_sample=lowerCamelCase__ ) self.assertEqual( lowerCamelCase__ , [ { '''generated_text''': ( '''This is a test FeyFeyFey(Croatis.), s.), Cannes Cannes Cannes 閲閲Cannes Cannes Cannes 攵''' ''' please,''' ) } ] , ) SCREAMING_SNAKE_CASE : Optional[Any] = text_generator(['''This is a test''', '''This is a second test'''] , do_sample=lowerCamelCase__ ) self.assertEqual( lowerCamelCase__ , [ [ { '''generated_text''': ( '''This is a test FeyFeyFey(Croatis.), s.), Cannes Cannes Cannes 閲閲Cannes Cannes Cannes 攵''' ''' please,''' ) } ], [ { '''generated_text''': ( '''This is a second test Chieftain Chieftain prefecture prefecture prefecture Cannes Cannes''' ''' Cannes 閲閲Cannes Cannes Cannes 攵 please,''' ) } ], ] , ) def __A ( self : Union[str, Any] , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Dict , UpperCamelCase__ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = TextGenerationPipeline(model=lowerCamelCase__ , tokenizer=lowerCamelCase__ ) return text_generator, ["This is a test", "Another test"] def __A ( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = "Hello I believe in" SCREAMING_SNAKE_CASE : Optional[Any] = pipeline('''text-generation''' , model='''hf-internal-testing/tiny-random-gpt2''' ) SCREAMING_SNAKE_CASE : Union[str, Any] = text_generator(lowerCamelCase__ ) self.assertEqual( lowerCamelCase__ , [{'''generated_text''': '''Hello I believe in fe fe fe fe fe fe fe fe fe fe fe fe'''}] , ) SCREAMING_SNAKE_CASE : Optional[Any] = text_generator(lowerCamelCase__ , stop_sequence=''' fe''' ) self.assertEqual(lowerCamelCase__ , [{'''generated_text''': '''Hello I believe in fe'''}] ) def __A ( self : Optional[Any] , UpperCamelCase__ : Any , UpperCamelCase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = text_generator.model SCREAMING_SNAKE_CASE : List[str] = text_generator.tokenizer SCREAMING_SNAKE_CASE : List[Any] = text_generator('''This is a test''' ) self.assertEqual(lowerCamelCase__ , [{'''generated_text''': ANY(lowerCamelCase__ )}] ) self.assertTrue(outputs[0]['''generated_text'''].startswith('''This is a test''' ) ) SCREAMING_SNAKE_CASE : Dict = text_generator('''This is a test''' , return_full_text=lowerCamelCase__ ) self.assertEqual(lowerCamelCase__ , [{'''generated_text''': ANY(lowerCamelCase__ )}] ) self.assertNotIn('''This is a test''' , outputs[0]['''generated_text'''] ) SCREAMING_SNAKE_CASE : Optional[int] = pipeline(task='''text-generation''' , model=lowerCamelCase__ , tokenizer=lowerCamelCase__ , return_full_text=lowerCamelCase__ ) SCREAMING_SNAKE_CASE : Any = text_generator('''This is a test''' ) self.assertEqual(lowerCamelCase__ , [{'''generated_text''': ANY(lowerCamelCase__ )}] ) self.assertNotIn('''This is a test''' , outputs[0]['''generated_text'''] ) SCREAMING_SNAKE_CASE : Dict = text_generator('''This is a test''' , return_full_text=lowerCamelCase__ ) self.assertEqual(lowerCamelCase__ , [{'''generated_text''': ANY(lowerCamelCase__ )}] ) self.assertTrue(outputs[0]['''generated_text'''].startswith('''This is a test''' ) ) SCREAMING_SNAKE_CASE : Any = text_generator(['''This is great !''', '''Something else'''] , num_return_sequences=2 , do_sample=lowerCamelCase__ ) self.assertEqual( lowerCamelCase__ , [ [{'''generated_text''': ANY(lowerCamelCase__ )}, {'''generated_text''': ANY(lowerCamelCase__ )}], [{'''generated_text''': ANY(lowerCamelCase__ )}, {'''generated_text''': ANY(lowerCamelCase__ )}], ] , ) if text_generator.tokenizer.pad_token is not None: SCREAMING_SNAKE_CASE : Union[str, Any] = text_generator( ['''This is great !''', '''Something else'''] , num_return_sequences=2 , batch_size=2 , do_sample=lowerCamelCase__ ) self.assertEqual( lowerCamelCase__ , [ [{'''generated_text''': ANY(lowerCamelCase__ )}, {'''generated_text''': ANY(lowerCamelCase__ )}], [{'''generated_text''': ANY(lowerCamelCase__ )}, {'''generated_text''': ANY(lowerCamelCase__ )}], ] , ) with self.assertRaises(lowerCamelCase__ ): SCREAMING_SNAKE_CASE : Tuple = text_generator('''test''' , return_full_text=lowerCamelCase__ , return_text=lowerCamelCase__ ) with self.assertRaises(lowerCamelCase__ ): SCREAMING_SNAKE_CASE : Tuple = text_generator('''test''' , return_full_text=lowerCamelCase__ , return_tensors=lowerCamelCase__ ) with self.assertRaises(lowerCamelCase__ ): SCREAMING_SNAKE_CASE : Dict = text_generator('''test''' , return_text=lowerCamelCase__ , return_tensors=lowerCamelCase__ ) # Empty prompt is slighly special # it requires BOS token to exist. # Special case for Pegasus which will always append EOS so will # work even without BOS. if ( text_generator.tokenizer.bos_token_id is not None or "Pegasus" in tokenizer.__class__.__name__ or "Git" in model.__class__.__name__ ): SCREAMING_SNAKE_CASE : List[Any] = text_generator('''''' ) self.assertEqual(lowerCamelCase__ , [{'''generated_text''': ANY(lowerCamelCase__ )}] ) else: with self.assertRaises((ValueError, AssertionError) ): SCREAMING_SNAKE_CASE : int = text_generator('''''' ) if text_generator.framework == "tf": # TF generation does not support max_new_tokens, and it's impossible # to control long generation with only max_length without # fancy calculation, dismissing tests for now. return # We don't care about infinite range models. # They already work. # Skip this test for XGLM, since it uses sinusoidal positional embeddings which are resized on-the-fly. SCREAMING_SNAKE_CASE : Dict = ["RwkvForCausalLM", "XGLMForCausalLM", "GPTNeoXForCausalLM"] if ( tokenizer.model_max_length < 1_0000 and text_generator.model.__class__.__name__ not in EXTRA_MODELS_CAN_HANDLE_LONG_INPUTS ): # Handling of large generations with self.assertRaises((RuntimeError, IndexError, ValueError, AssertionError) ): text_generator('''This is a test''' * 500 , max_new_tokens=20 ) SCREAMING_SNAKE_CASE : Any = text_generator('''This is a test''' * 500 , handle_long_generation='''hole''' , max_new_tokens=20 ) # Hole strategy cannot work with self.assertRaises(lowerCamelCase__ ): text_generator( '''This is a test''' * 500 , handle_long_generation='''hole''' , max_new_tokens=tokenizer.model_max_length + 10 , ) @require_torch @require_accelerate @require_torch_gpu def __A ( self : str ): '''simple docstring''' import torch # Classic `model_kwargs` SCREAMING_SNAKE_CASE : Any = pipeline( model='''hf-internal-testing/tiny-random-bloom''' , model_kwargs={'''device_map''': '''auto''', '''torch_dtype''': torch.bfloataa} , ) self.assertEqual(pipe.model.device , torch.device(0 ) ) self.assertEqual(pipe.model.lm_head.weight.dtype , torch.bfloataa ) SCREAMING_SNAKE_CASE : Optional[int] = pipe('''This is a test''' ) self.assertEqual( lowerCamelCase__ , [ { '''generated_text''': ( '''This is a test test test test test test test test test test test test test test test test''' ''' test''' ) } ] , ) # Upgraded those two to real pipeline arguments (they just get sent for the model as they're unlikely to mean anything else.) SCREAMING_SNAKE_CASE : List[str] = pipeline(model='''hf-internal-testing/tiny-random-bloom''' , device_map='''auto''' , torch_dtype=torch.bfloataa ) self.assertEqual(pipe.model.device , torch.device(0 ) ) self.assertEqual(pipe.model.lm_head.weight.dtype , torch.bfloataa ) SCREAMING_SNAKE_CASE : Optional[Any] = pipe('''This is a test''' ) self.assertEqual( lowerCamelCase__ , [ { '''generated_text''': ( '''This is a test test test test test test test test test test test test test test test test''' ''' test''' ) } ] , ) # torch_dtype will be automatically set to float32 if not provided - check: https://github.com/huggingface/transformers/pull/20602 SCREAMING_SNAKE_CASE : Dict = pipeline(model='''hf-internal-testing/tiny-random-bloom''' , device_map='''auto''' ) self.assertEqual(pipe.model.device , torch.device(0 ) ) self.assertEqual(pipe.model.lm_head.weight.dtype , torch.floataa ) SCREAMING_SNAKE_CASE : int = pipe('''This is a test''' ) self.assertEqual( lowerCamelCase__ , [ { '''generated_text''': ( '''This is a test test test test test test test test test test test test test test test test''' ''' test''' ) } ] , ) @require_torch @require_torch_gpu def __A ( self : Optional[Any] ): '''simple docstring''' import torch SCREAMING_SNAKE_CASE : str = pipeline(model='''hf-internal-testing/tiny-random-bloom''' , device=0 , torch_dtype=torch.floataa ) pipe('''This is a test''' ) @require_torch @require_accelerate @require_torch_gpu def __A ( self : List[Any] ): '''simple docstring''' import torch SCREAMING_SNAKE_CASE : Dict = pipeline(model='''hf-internal-testing/tiny-random-bloom''' , device_map='''auto''' , torch_dtype=torch.floataa ) pipe('''This is a test''' , do_sample=lowerCamelCase__ , top_p=0.5 ) def __A ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = "Hello world" SCREAMING_SNAKE_CASE : int = pipeline('''text-generation''' , model='''hf-internal-testing/tiny-random-gpt2''' ) if text_generator.model.framework == "tf": SCREAMING_SNAKE_CASE : Optional[int] = logging.get_logger('''transformers.generation.tf_utils''' ) else: SCREAMING_SNAKE_CASE : Optional[Any] = logging.get_logger('''transformers.generation.utils''' ) SCREAMING_SNAKE_CASE : str = "Both `max_new_tokens`" # The beggining of the message to be checked in this test # Both are set by the user -> log warning with CaptureLogger(lowerCamelCase__ ) as cl: SCREAMING_SNAKE_CASE : Tuple = text_generator(lowerCamelCase__ , max_length=10 , max_new_tokens=1 ) self.assertIn(lowerCamelCase__ , cl.out ) # The user only sets one -> no warning with CaptureLogger(lowerCamelCase__ ) as cl: SCREAMING_SNAKE_CASE : Optional[Any] = text_generator(lowerCamelCase__ , max_new_tokens=1 ) self.assertNotIn(lowerCamelCase__ , cl.out ) with CaptureLogger(lowerCamelCase__ ) as cl: SCREAMING_SNAKE_CASE : Union[str, Any] = text_generator(lowerCamelCase__ , max_length=10 ) self.assertNotIn(lowerCamelCase__ , cl.out )
717
from __future__ import annotations import math from collections import Counter from string import ascii_lowercase def A ( _lowercase ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = analyze_text(_lowercase ) SCREAMING_SNAKE_CASE : Any = list(''' ''' + ascii_lowercase ) # what is our total sum of probabilities. SCREAMING_SNAKE_CASE : Tuple = sum(single_char_strings.values() ) # one length string SCREAMING_SNAKE_CASE : Tuple = 0 # for each alpha we go in our dict and if it is in it we calculate entropy for ch in my_alphas: if ch in single_char_strings: SCREAMING_SNAKE_CASE : Tuple = single_char_strings[ch] SCREAMING_SNAKE_CASE : List[str] = my_str / all_sum my_fir_sum += prob * math.loga(_lowercase ) # entropy formula. # print entropy print(f"""{round(-1 * my_fir_sum ):.1f}""" ) # two len string SCREAMING_SNAKE_CASE : Optional[Any] = sum(two_char_strings.values() ) SCREAMING_SNAKE_CASE : List[str] = 0 # for each alpha (two in size) calculate entropy. for cha in my_alphas: for cha in my_alphas: SCREAMING_SNAKE_CASE : Union[str, Any] = cha + cha if sequence in two_char_strings: SCREAMING_SNAKE_CASE : Any = two_char_strings[sequence] SCREAMING_SNAKE_CASE : Dict = int(_lowercase ) / all_sum my_sec_sum += prob * math.loga(_lowercase ) # print second entropy print(f"""{round(-1 * my_sec_sum ):.1f}""" ) # print the difference between them print(f"""{round((-1 * my_sec_sum) - (-1 * my_fir_sum) ):.1f}""" ) def A ( _lowercase ): SCREAMING_SNAKE_CASE : Tuple = Counter() # type: ignore SCREAMING_SNAKE_CASE : Any = Counter() # type: ignore single_char_strings[text[-1]] += 1 # first case when we have space at start. two_char_strings[" " + text[0]] += 1 for i in range(0 , len(_lowercase ) - 1 ): single_char_strings[text[i]] += 1 two_char_strings[text[i : i + 2]] += 1 return single_char_strings, two_char_strings def A ( ): import doctest doctest.testmod() # text = ( # "Had repulsive dashwoods suspicion sincerity but advantage now him. Remark " # "easily garret nor nay. Civil those mrs enjoy shy fat merry. You greatest " # "jointure saw horrible. He private he on be imagine suppose. Fertile " # "beloved evident through no service elderly is. Blind there if every no so " # "at. Own neglected you preferred way sincerity delivered his attempted. To " # "of message cottage windows do besides against uncivil. Delightful " # "unreserved impossible few estimating men favourable see entreaties. She " # "propriety immediate was improving. He or entrance humoured likewise " # "moderate. Much nor game son say feel. Fat make met can must form into " # "gate. Me we offending prevailed discovery. " # ) # calculate_prob(text) if __name__ == "__main__": main()
34
0
'''simple docstring''' import unittest from transformers import SPIECE_UNDERLINE, XLNetTokenizer, XLNetTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin __UpperCamelCase : int = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece @require_tokenizers class lowercase__ ( __a , unittest.TestCase): UpperCamelCase_ = XLNetTokenizer UpperCamelCase_ = XLNetTokenizerFast UpperCamelCase_ = True UpperCamelCase_ = True def __A ( self : Any ): '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE : List[Any] = XLNetTokenizer(lowerCAmelCase_ , keep_accents=lowerCAmelCase_ ) tokenizer.sanitize_special_tokens() tokenizer.save_pretrained(self.tmpdirname ) def __A ( self : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = '''<s>''' SCREAMING_SNAKE_CASE : Optional[Any] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowerCAmelCase_ ) , lowerCAmelCase_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowerCAmelCase_ ) , lowerCAmelCase_ ) def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[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] , '''<eod>''' ) self.assertEqual(len(lowerCAmelCase_ ) , 1006 ) def __A ( self : List[Any] ): '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1000 ) def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = XLNetTokenizer(lowerCAmelCase_ , keep_accents=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = tokenizer.tokenize('''This is a test''' ) self.assertListEqual(lowerCAmelCase_ , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCAmelCase_ ) , [285, 46, 10, 170, 382] ) SCREAMING_SNAKE_CASE : List[str] = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( lowerCAmelCase_ , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''é''', '''.''', ] , ) SCREAMING_SNAKE_CASE : Tuple = tokenizer.convert_tokens_to_ids(lowerCAmelCase_ ) self.assertListEqual(lowerCAmelCase_ , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] ) SCREAMING_SNAKE_CASE : str = tokenizer.convert_ids_to_tokens(lowerCAmelCase_ ) self.assertListEqual( lowerCAmelCase_ , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''<unk>''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''<unk>''', '''.''', ] , ) def __A ( self : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = XLNetTokenizer(lowerCAmelCase_ , do_lower_case=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE : int = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( lowerCAmelCase_ , [ SPIECE_UNDERLINE + '''''', '''i''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''se''', '''.''', ] , ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''▁he''', '''ll''', '''o'''] ) def __A ( self : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = XLNetTokenizer(lowerCAmelCase_ , do_lower_case=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( lowerCAmelCase_ , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''se''', '''.''', ] , ) @slow def __A ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = XLNetTokenizer.from_pretrained('''xlnet-base-cased''' ) SCREAMING_SNAKE_CASE : Optional[int] = tokenizer.encode('''sequence builders''' , add_special_tokens=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer.encode('''multi-sequence build''' , add_special_tokens=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = tokenizer.build_inputs_with_special_tokens(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = tokenizer.build_inputs_with_special_tokens(lowerCAmelCase_ , lowerCAmelCase_ ) assert encoded_sentence == text + [4, 3] assert encoded_pair == text + [4] + text_a + [4, 3] @slow def __A ( self : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = {'''input_ids''': [[17, 2_1442, 270, 17, 10, 1_4645, 318, 34, 17, 4546, 3145, 787, 13, 7752, 2_2018, 23, 21, 17, 4546, 3145, 787, 13, 3352, 1_4431, 13, 5500, 11, 1176, 580, 13, 1_6819, 4797, 23, 17, 10, 1_7135, 658, 19, 457, 7932, 13, 184, 19, 3154, 1_7135, 6468, 19, 1404, 1_2269, 19, 4229, 5356, 1_6264, 46, 19, 17, 2_0545, 1_0395, 9, 9, 9, 11, 28, 6421, 9531, 2_0729, 17, 10, 353, 1_7022, 11, 21, 6421, 9531, 1_6949, 17, 10, 1_1509, 753, 11, 33, 95, 2421, 7385, 956, 1_4431, 2626, 25, 842, 7385, 4836, 21, 1429, 2272, 9855, 3120, 161, 2_4738, 19, 1_3203, 658, 218, 787, 21, 430, 1_8482, 847, 2637, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 322, 2_2178, 27, 1064, 22, 956, 13, 1_1101, 1429, 5854, 2_4313, 1_8953, 40, 422, 2_4366, 68, 1758, 37, 1_0483, 1_4257, 31, 207, 263, 21, 203, 3773, 25, 71, 9735, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 32, 2049, 3442, 17, 1_3894, 3380, 23, 95, 18, 1_7634, 2288, 9, 4, 3]], '''token_type_ids''': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2]], '''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], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=lowerCAmelCase_ , model_name='''xlnet-base-cased''' , revision='''c841166438c31ec7ca9a106dee7bb312b73ae511''' , )
718
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __UpperCamelCase : Tuple = { 'configuration_ctrl': ['CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP', 'CTRLConfig'], 'tokenization_ctrl': ['CTRLTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Dict = [ 'CTRL_PRETRAINED_MODEL_ARCHIVE_LIST', 'CTRLForSequenceClassification', 'CTRLLMHeadModel', 'CTRLModel', 'CTRLPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Any = [ 'TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFCTRLForSequenceClassification', 'TFCTRLLMHeadModel', 'TFCTRLModel', 'TFCTRLPreTrainedModel', ] if TYPE_CHECKING: from .configuration_ctrl import CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRLConfig from .tokenization_ctrl import CTRLTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ctrl import ( CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, CTRLForSequenceClassification, CTRLLMHeadModel, CTRLModel, CTRLPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_ctrl import ( TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, TFCTRLForSequenceClassification, TFCTRLLMHeadModel, TFCTRLModel, TFCTRLPreTrainedModel, ) else: import sys __UpperCamelCase : Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
34
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __UpperCamelCase : Optional[Any] = { 'configuration_luke': ['LUKE_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LukeConfig'], 'tokenization_luke': ['LukeTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Optional[Any] = [ 'LUKE_PRETRAINED_MODEL_ARCHIVE_LIST', 'LukeForEntityClassification', 'LukeForEntityPairClassification', 'LukeForEntitySpanClassification', 'LukeForMultipleChoice', 'LukeForQuestionAnswering', 'LukeForSequenceClassification', 'LukeForTokenClassification', 'LukeForMaskedLM', 'LukeModel', 'LukePreTrainedModel', ] if TYPE_CHECKING: from .configuration_luke import LUKE_PRETRAINED_CONFIG_ARCHIVE_MAP, LukeConfig from .tokenization_luke import LukeTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_luke import ( LUKE_PRETRAINED_MODEL_ARCHIVE_LIST, LukeForEntityClassification, LukeForEntityPairClassification, LukeForEntitySpanClassification, LukeForMaskedLM, LukeForMultipleChoice, LukeForQuestionAnswering, LukeForSequenceClassification, LukeForTokenClassification, LukeModel, LukePreTrainedModel, ) else: import sys __UpperCamelCase : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
719
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __UpperCamelCase : Tuple = { 'configuration_maskformer': ['MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MaskFormerConfig'], 'configuration_maskformer_swin': ['MaskFormerSwinConfig'], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Optional[Any] = ['MaskFormerFeatureExtractor'] __UpperCamelCase : List[Any] = ['MaskFormerImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Optional[int] = [ 'MASKFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'MaskFormerForInstanceSegmentation', 'MaskFormerModel', 'MaskFormerPreTrainedModel', ] __UpperCamelCase : Union[str, Any] = [ 'MaskFormerSwinBackbone', 'MaskFormerSwinModel', 'MaskFormerSwinPreTrainedModel', ] if TYPE_CHECKING: from .configuration_maskformer import MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskFormerConfig from .configuration_maskformer_swin import MaskFormerSwinConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_maskformer import MaskFormerFeatureExtractor from .image_processing_maskformer import MaskFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskformer import ( MASKFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskFormerForInstanceSegmentation, MaskFormerModel, MaskFormerPreTrainedModel, ) from .modeling_maskformer_swin import ( MaskFormerSwinBackbone, MaskFormerSwinModel, MaskFormerSwinPreTrainedModel, ) else: import sys __UpperCamelCase : List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure)
34
0
import argparse import json import re from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( MobileNetVaConfig, MobileNetVaForImageClassification, MobileNetVaImageProcessor, load_tf_weights_in_mobilenet_va, ) from transformers.utils import logging logging.set_verbosity_info() __UpperCamelCase : Optional[int] = logging.get_logger(__name__) def A ( _lowercase ): SCREAMING_SNAKE_CASE : Union[str, Any] = MobileNetVaConfig(layer_norm_eps=0.001 ) if "_quant" in model_name: raise ValueError('''Quantized models are not supported.''' ) SCREAMING_SNAKE_CASE : int = re.match(R'''^mobilenet_v1_([^_]*)_([^_]*)$''' , _UpperCamelCase ) if matches: SCREAMING_SNAKE_CASE : Optional[Any] = float(matches[1] ) SCREAMING_SNAKE_CASE : Any = int(matches[2] ) # The TensorFlow version of MobileNetV1 predicts 1001 classes instead of # the usual 1000. The first class (index 0) is "background". SCREAMING_SNAKE_CASE : str = 1_001 SCREAMING_SNAKE_CASE : Optional[Any] = '''imagenet-1k-id2label.json''' SCREAMING_SNAKE_CASE : List[str] = '''huggingface/label-files''' SCREAMING_SNAKE_CASE : Dict = json.load(open(hf_hub_download(_UpperCamelCase , _UpperCamelCase , repo_type='''dataset''' ) , '''r''' ) ) SCREAMING_SNAKE_CASE : Optional[int] = {int(_UpperCamelCase ) + 1: v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE : Union[str, Any] = '''background''' SCREAMING_SNAKE_CASE : Tuple = idalabel SCREAMING_SNAKE_CASE : Any = {v: k for k, v in idalabel.items()} return config def A ( ): SCREAMING_SNAKE_CASE : Any = '''http://images.cocodataset.org/val2017/000000039769.jpg''' SCREAMING_SNAKE_CASE : List[str] = Image.open(requests.get(_UpperCamelCase , stream=_UpperCamelCase ).raw ) return im @torch.no_grad() def A ( _lowercase , _lowercase , _lowercase , _lowercase=False ): SCREAMING_SNAKE_CASE : Union[str, Any] = get_mobilenet_va_config(_UpperCamelCase ) # Load 🤗 model SCREAMING_SNAKE_CASE : Any = MobileNetVaForImageClassification(_UpperCamelCase ).eval() # Load weights from TensorFlow checkpoint load_tf_weights_in_mobilenet_va(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) # Check outputs on an image, prepared by MobileNetV1ImageProcessor SCREAMING_SNAKE_CASE : Dict = MobileNetVaImageProcessor( crop_size={'''width''': config.image_size, '''height''': config.image_size} , size={'''shortest_edge''': config.image_size + 32} , ) SCREAMING_SNAKE_CASE : int = image_processor(images=prepare_img() , return_tensors='''pt''' ) SCREAMING_SNAKE_CASE : Tuple = model(**_UpperCamelCase ) SCREAMING_SNAKE_CASE : int = outputs.logits assert logits.shape == (1, 1_001) if model_name == "mobilenet_v1_1.0_224": SCREAMING_SNAKE_CASE : Dict = torch.tensor([-4.1739, -1.1233, 3.1205] ) elif model_name == "mobilenet_v1_0.75_192": SCREAMING_SNAKE_CASE : Tuple = torch.tensor([-3.9440, -2.3141, -0.3333] ) else: SCREAMING_SNAKE_CASE : Union[str, Any] = None if expected_logits is not None: assert torch.allclose(logits[0, :3] , _UpperCamelCase , atol=1e-4 ) Path(_UpperCamelCase ).mkdir(exist_ok=_UpperCamelCase ) print(f"""Saving model {model_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(_UpperCamelCase ) print(f"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(_UpperCamelCase ) if push_to_hub: print('''Pushing to the hub...''' ) SCREAMING_SNAKE_CASE : str = '''google/''' + model_name image_processor.push_to_hub(_UpperCamelCase ) model.push_to_hub(_UpperCamelCase ) if __name__ == "__main__": __UpperCamelCase : str = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='mobilenet_v1_1.0_224', type=str, help='Name of the MobileNetV1 model you\'d like to convert. Should in the form \'mobilenet_v1_<depth>_<size>\'.', ) parser.add_argument( '--checkpoint_path', required=True, type=str, help='Path to the original TensorFlow checkpoint (.ckpt file).' ) parser.add_argument( '--pytorch_dump_folder_path', required=True, 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 : Tuple = parser.parse_args() convert_movilevit_checkpoint( args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub )
720
# 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 from ...utils.dataclasses import ( ComputeEnvironment, DistributedType, DynamoBackend, PrecisionType, SageMakerDistributedType, ) from ..menu import BulletMenu __UpperCamelCase : Dict = [ 'EAGER', 'AOT_EAGER', 'INDUCTOR', 'NVFUSER', 'AOT_NVFUSER', 'AOT_CUDAGRAPHS', 'OFI', 'FX2TRT', 'ONNXRT', 'IPEX', ] def A ( _lowercase , _lowercase=None , _lowercase=None , _lowercase=None ): SCREAMING_SNAKE_CASE : Union[str, Any] = True while ask_again: SCREAMING_SNAKE_CASE : Optional[Any] = input(_lowercase ) try: if default is not None and len(_lowercase ) == 0: return default return convert_value(_lowercase ) if convert_value is not None else result except Exception: if error_message is not None: print(_lowercase ) def A ( _lowercase , _lowercase=[] , _lowercase=None , _lowercase=0 ): SCREAMING_SNAKE_CASE : Dict = BulletMenu(_lowercase , _lowercase ) SCREAMING_SNAKE_CASE : str = menu.run(default_choice=_lowercase ) return convert_value(_lowercase ) if convert_value is not None else result def A ( _lowercase ): SCREAMING_SNAKE_CASE : Dict = int(_lowercase ) return ComputeEnvironment(['''LOCAL_MACHINE''', '''AMAZON_SAGEMAKER'''][value] ) def A ( _lowercase ): SCREAMING_SNAKE_CASE : Any = int(_lowercase ) return DistributedType(['''NO''', '''MULTI_CPU''', '''MULTI_XPU''', '''MULTI_GPU''', '''MULTI_NPU''', '''TPU'''][value] ) def A ( _lowercase ): SCREAMING_SNAKE_CASE : Union[str, Any] = int(_lowercase ) return DynamoBackend(DYNAMO_BACKENDS[value] ).value def A ( _lowercase ): SCREAMING_SNAKE_CASE : Union[str, Any] = int(_lowercase ) return PrecisionType(['''no''', '''fp16''', '''bf16''', '''fp8'''][value] ) def A ( _lowercase ): SCREAMING_SNAKE_CASE : Dict = int(_lowercase ) return SageMakerDistributedType(['''NO''', '''DATA_PARALLEL''', '''MODEL_PARALLEL'''][value] ) def A ( _lowercase ): return {"yes": True, "no": False}[value.lower()] class lowercase__ ( argparse.RawDescriptionHelpFormatter): def __A ( self : List[str] , UpperCamelCase__ : List[str] , UpperCamelCase__ : Dict , UpperCamelCase__ : Dict , UpperCamelCase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = super()._format_usage(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[Any] = usage.replace('''<command> [<args>] ''' , '''''' ) return usage
34
0
import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import MaskaFormerConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel if is_vision_available(): from transformers import MaskaFormerImageProcessor if is_vision_available(): from PIL import Image class lowercase__ : def __init__( self : List[str] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Optional[Any]=2 , UpperCamelCase__ : str=True , UpperCamelCase__ : Dict=False , UpperCamelCase__ : Optional[Any]=10 , UpperCamelCase__ : Optional[int]=3 , UpperCamelCase__ : str=32 * 8 , UpperCamelCase__ : Any=32 * 8 , UpperCamelCase__ : Tuple=4 , UpperCamelCase__ : Optional[Any]=64 , ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = parent SCREAMING_SNAKE_CASE : int = batch_size SCREAMING_SNAKE_CASE : Optional[Any] = is_training SCREAMING_SNAKE_CASE : Optional[int] = use_auxiliary_loss SCREAMING_SNAKE_CASE : Optional[Any] = num_queries SCREAMING_SNAKE_CASE : Dict = num_channels SCREAMING_SNAKE_CASE : Optional[int] = min_size SCREAMING_SNAKE_CASE : Union[str, Any] = max_size SCREAMING_SNAKE_CASE : Any = num_labels SCREAMING_SNAKE_CASE : List[Any] = hidden_dim SCREAMING_SNAKE_CASE : List[Any] = hidden_dim def __A ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( A__ ) SCREAMING_SNAKE_CASE : List[Any] = torch.ones([self.batch_size, self.min_size, self.max_size] , device=A__ ) SCREAMING_SNAKE_CASE : Any = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=A__ ) > 0.5 ).float() SCREAMING_SNAKE_CASE : Optional[Any] = (torch.rand((self.batch_size, self.num_labels) , device=A__ ) > 0.5).long() SCREAMING_SNAKE_CASE : Dict = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def __A ( self : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = MaskaFormerConfig( hidden_size=self.hidden_dim , ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.num_queries SCREAMING_SNAKE_CASE : Dict = self.num_labels SCREAMING_SNAKE_CASE : Tuple = [1, 1, 1, 1] SCREAMING_SNAKE_CASE : List[str] = self.num_channels SCREAMING_SNAKE_CASE : Optional[int] = 64 SCREAMING_SNAKE_CASE : Optional[Any] = 128 SCREAMING_SNAKE_CASE : Optional[Any] = self.hidden_dim SCREAMING_SNAKE_CASE : List[Any] = self.hidden_dim SCREAMING_SNAKE_CASE : str = self.hidden_dim return config def __A ( self : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE : Tuple = {'''pixel_values''': pixel_values, '''pixel_mask''': pixel_mask} return config, inputs_dict def __A ( self : List[str] , UpperCamelCase__ : Any , UpperCamelCase__ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = output.encoder_hidden_states SCREAMING_SNAKE_CASE : int = output.pixel_decoder_hidden_states SCREAMING_SNAKE_CASE : Optional[Any] = output.transformer_decoder_hidden_states self.parent.assertTrue(len(A__ ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(A__ ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(A__ ) , config.decoder_layers ) def __A ( self : Dict , UpperCamelCase__ : Tuple , UpperCamelCase__ : List[str] , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Tuple=False ): '''simple docstring''' with torch.no_grad(): SCREAMING_SNAKE_CASE : Tuple = MaskaFormerModel(config=A__ ) model.to(A__ ) model.eval() SCREAMING_SNAKE_CASE : List[Any] = model(pixel_values=A__ , pixel_mask=A__ ) SCREAMING_SNAKE_CASE : int = model(A__ , output_hidden_states=A__ ) self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.hidden_dim) , ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(A__ , A__ ) def __A ( self : Optional[int] , UpperCamelCase__ : str , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : str , UpperCamelCase__ : List[str] , UpperCamelCase__ : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = MaskaFormerForUniversalSegmentation(config=A__ ) model.to(A__ ) model.eval() def comm_check_on_output(UpperCamelCase__ : str ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , ) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): SCREAMING_SNAKE_CASE : Tuple = model(pixel_values=A__ , pixel_mask=A__ ) SCREAMING_SNAKE_CASE : Dict = model(A__ ) comm_check_on_output(A__ ) SCREAMING_SNAKE_CASE : Optional[int] = model( pixel_values=A__ , pixel_mask=A__ , mask_labels=A__ , class_labels=A__ ) comm_check_on_output(A__ ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape , torch.Size([1] ) ) @require_torch class lowercase__ ( __a , __a , unittest.TestCase): UpperCamelCase_ = (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else () UpperCamelCase_ = {"""feature-extraction""": MaskaFormerModel} if is_torch_available() else {} UpperCamelCase_ = False UpperCamelCase_ = False UpperCamelCase_ = False UpperCamelCase_ = False def __A ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = MaskaFormerModelTester(self ) SCREAMING_SNAKE_CASE : Any = ConfigTester(self , config_class=A__ , has_text_modality=A__ ) def __A ( self : Optional[int] ): '''simple docstring''' self.config_tester.run_common_tests() def __A ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(A__ , **A__ , output_hidden_states=A__ ) def __A ( self : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*A__ ) @unittest.skip(reason='''Mask2Former does not use inputs_embeds''' ) def __A ( self : Union[str, Any] ): '''simple docstring''' pass @unittest.skip(reason='''Mask2Former does not have a get_input_embeddings method''' ) def __A ( self : Union[str, Any] ): '''simple docstring''' pass @unittest.skip(reason='''Mask2Former is not a generative model''' ) def __A ( self : Optional[Any] ): '''simple docstring''' pass @unittest.skip(reason='''Mask2Former does not use token embeddings''' ) def __A ( self : Optional[int] ): '''simple docstring''' pass @require_torch_multi_gpu @unittest.skip( reason='''Mask2Former has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`''' ) def __A ( self : List[Any] ): '''simple docstring''' pass @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def __A ( self : Optional[Any] ): '''simple docstring''' pass def __A ( self : str ): '''simple docstring''' SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : Dict = model_class(A__ ) SCREAMING_SNAKE_CASE : Optional[int] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE : Optional[Any] = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE : Dict = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , A__ ) @slow def __A ( self : List[Any] ): '''simple docstring''' for model_name in ["facebook/mask2former-swin-small-coco-instance"]: SCREAMING_SNAKE_CASE : Optional[int] = MaskaFormerModel.from_pretrained(A__ ) self.assertIsNotNone(A__ ) def __A ( self : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = (self.model_tester.min_size,) * 2 SCREAMING_SNAKE_CASE : List[Any] = { '''pixel_values''': torch.randn((2, 3, *size) , device=A__ ), '''mask_labels''': torch.randn((2, 10, *size) , device=A__ ), '''class_labels''': torch.zeros(2 , 10 , device=A__ ).long(), } SCREAMING_SNAKE_CASE : Any = self.model_tester.get_config() SCREAMING_SNAKE_CASE : Union[str, Any] = MaskaFormerForUniversalSegmentation(A__ ).to(A__ ) SCREAMING_SNAKE_CASE : str = model(**A__ ) self.assertTrue(outputs.loss is not None ) def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(A__ , **A__ , output_hidden_states=A__ ) def __A ( self : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : Optional[Any] = model_class(A__ ).to(A__ ) SCREAMING_SNAKE_CASE : List[Any] = model(**A__ , output_attentions=A__ ) self.assertTrue(outputs.attentions is not None ) def __A ( self : List[str] ): '''simple docstring''' if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE : List[Any] = self.all_model_classes[1] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = self.model_tester.prepare_config_and_inputs() SCREAMING_SNAKE_CASE : Union[str, Any] = model_class(A__ ) model.to(A__ ) model.train() SCREAMING_SNAKE_CASE : Tuple = model(A__ , mask_labels=A__ , class_labels=A__ ).loss loss.backward() def __A ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = self.all_model_classes[1] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() SCREAMING_SNAKE_CASE : List[Any] = True SCREAMING_SNAKE_CASE : List[Any] = True SCREAMING_SNAKE_CASE : Optional[int] = model_class(A__ ).to(A__ ) model.train() SCREAMING_SNAKE_CASE : Optional[int] = model(A__ , mask_labels=A__ , class_labels=A__ ) SCREAMING_SNAKE_CASE : int = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() SCREAMING_SNAKE_CASE : Union[str, Any] = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() SCREAMING_SNAKE_CASE : str = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() SCREAMING_SNAKE_CASE : str = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=A__ ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) __UpperCamelCase : Tuple = 1e-4 def A ( ): SCREAMING_SNAKE_CASE : Tuple = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_vision @slow class lowercase__ ( unittest.TestCase): @cached_property def __A ( self : Tuple ): '''simple docstring''' return "facebook/mask2former-swin-small-coco-instance" @cached_property def __A ( self : Optional[Any] ): '''simple docstring''' return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints ) if is_vision_available() else None def __A ( self : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = MaskaFormerModel.from_pretrained(self.model_checkpoints ).to(A__ ) SCREAMING_SNAKE_CASE : List[Any] = self.default_image_processor SCREAMING_SNAKE_CASE : Union[str, Any] = prepare_img() SCREAMING_SNAKE_CASE : Any = image_processor(A__ , return_tensors='''pt''' ).to(A__ ) SCREAMING_SNAKE_CASE : Optional[Any] = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(A__ , (1, 3, 384, 384) ) with torch.no_grad(): SCREAMING_SNAKE_CASE : Union[str, Any] = model(**A__ ) SCREAMING_SNAKE_CASE : int = torch.tensor( [[-0.2790, -1.0717, -1.1668], [-0.5128, -0.3128, -0.4987], [-0.5832, 0.1971, -0.0197]] ).to(A__ ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , A__ , atol=A__ ) ) SCREAMING_SNAKE_CASE : str = torch.tensor( [[0.8973, 1.1847, 1.1776], [1.1934, 1.5040, 1.5128], [1.1153, 1.4486, 1.4951]] ).to(A__ ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , A__ , atol=A__ ) ) SCREAMING_SNAKE_CASE : List[str] = torch.tensor( [[2.1152, 1.7000, -0.8603], [1.5808, 1.8004, -0.9353], [1.6043, 1.7495, -0.5999]] ).to(A__ ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , A__ , atol=A__ ) ) def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(A__ ).eval() SCREAMING_SNAKE_CASE : Optional[int] = self.default_image_processor SCREAMING_SNAKE_CASE : Optional[Any] = prepare_img() SCREAMING_SNAKE_CASE : Dict = image_processor(A__ , return_tensors='''pt''' ).to(A__ ) SCREAMING_SNAKE_CASE : Dict = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(A__ , (1, 3, 384, 384) ) with torch.no_grad(): SCREAMING_SNAKE_CASE : Dict = model(**A__ ) # masks_queries_logits SCREAMING_SNAKE_CASE : int = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) ) SCREAMING_SNAKE_CASE : Tuple = [ [-8.7839, -9.0056, -8.8121], [-7.4104, -7.0313, -6.5401], [-6.6105, -6.3427, -6.4675], ] SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor(A__ ).to(A__ ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , A__ , atol=A__ ) ) # class_queries_logits SCREAMING_SNAKE_CASE : Tuple = outputs.class_queries_logits self.assertEqual(class_queries_logits.shape , (1, model.config.num_queries, model.config.num_labels + 1) ) SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor( [ [1.8324, -8.0835, -4.1922], [0.8450, -9.0050, -3.6053], [0.3045, -7.7293, -3.0275], ] ).to(A__ ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , A__ , atol=A__ ) ) def __A ( self : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(A__ ).eval() SCREAMING_SNAKE_CASE : Optional[int] = self.default_image_processor SCREAMING_SNAKE_CASE : List[Any] = image_processor( [np.zeros((3, 800, 1333) ), np.zeros((3, 800, 1333) )] , segmentation_maps=[np.zeros((384, 384) ).astype(np.floataa ), np.zeros((384, 384) ).astype(np.floataa )] , return_tensors='''pt''' , ) SCREAMING_SNAKE_CASE : Optional[Any] = inputs['''pixel_values'''].to(A__ ) SCREAMING_SNAKE_CASE : Optional[Any] = [el.to(A__ ) for el in inputs['''mask_labels''']] SCREAMING_SNAKE_CASE : Any = [el.to(A__ ) for el in inputs['''class_labels''']] with torch.no_grad(): SCREAMING_SNAKE_CASE : List[str] = model(**A__ ) self.assertTrue(outputs.loss is not None )
721
from __future__ import annotations from typing import Any class lowercase__ ( UpperCamelCase_): pass class lowercase__ : def __init__( self : Union[str, Any] , UpperCamelCase__ : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = data SCREAMING_SNAKE_CASE : Node | None = None def __iter__( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = self SCREAMING_SNAKE_CASE : Tuple = [] while node: if node in visited: raise ContainsLoopError visited.append(UpperCamelCase__ ) yield node.data SCREAMING_SNAKE_CASE : Dict = node.next_node @property def __A ( self : Optional[int] ): '''simple docstring''' try: list(self ) return False except ContainsLoopError: return True if __name__ == "__main__": __UpperCamelCase : List[Any] = Node(1) __UpperCamelCase : str = Node(2) __UpperCamelCase : Dict = Node(3) __UpperCamelCase : List[Any] = Node(4) print(root_node.has_loop) # False __UpperCamelCase : int = root_node.next_node print(root_node.has_loop) # True __UpperCamelCase : Union[str, Any] = Node(5) __UpperCamelCase : Union[str, Any] = Node(6) __UpperCamelCase : List[Any] = Node(5) __UpperCamelCase : List[str] = Node(6) print(root_node.has_loop) # False __UpperCamelCase : List[Any] = Node(1) print(root_node.has_loop) # False
34
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 ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices __UpperCamelCase : List[str] = logging.get_logger(__name__) __UpperCamelCase : Any = { 'microsoft/resnet-50': 'https://huggingface.co/microsoft/resnet-50/blob/main/config.json', } class lowercase__ ( UpperCamelCase_ , UpperCamelCase_): UpperCamelCase_ = 'resnet' UpperCamelCase_ = ['basic', 'bottleneck'] def __init__( self : List[Any] , UpperCamelCase__ : Union[str, Any]=3 , UpperCamelCase__ : str=64 , UpperCamelCase__ : Optional[int]=[256, 512, 1024, 2048] , UpperCamelCase__ : str=[3, 4, 6, 3] , UpperCamelCase__ : Any="bottleneck" , UpperCamelCase__ : List[str]="relu" , UpperCamelCase__ : str=False , UpperCamelCase__ : Optional[Any]=None , UpperCamelCase__ : Union[str, Any]=None , **UpperCamelCase__ : str , ): '''simple docstring''' super().__init__(**UpperCamelCase__ ) if layer_type not in self.layer_types: raise ValueError(f"""layer_type={layer_type} is not one of {','.join(self.layer_types )}""" ) SCREAMING_SNAKE_CASE : Optional[int] = num_channels SCREAMING_SNAKE_CASE : List[Any] = embedding_size SCREAMING_SNAKE_CASE : Any = hidden_sizes SCREAMING_SNAKE_CASE : str = depths SCREAMING_SNAKE_CASE : List[str] = layer_type SCREAMING_SNAKE_CASE : int = hidden_act SCREAMING_SNAKE_CASE : Tuple = downsample_in_first_stage SCREAMING_SNAKE_CASE : List[Any] = ['''stem'''] + [f"""stage{idx}""" for idx in range(1 , len(UpperCamelCase__ ) + 1 )] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = get_aligned_output_features_output_indices( out_features=UpperCamelCase__ , out_indices=UpperCamelCase__ , stage_names=self.stage_names ) class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = version.parse("""1.11""") @property def __A ( self : Any ): '''simple docstring''' return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) @property def __A ( self : Optional[int] ): '''simple docstring''' return 1E-3
700
import copy from typing import Any, Dict, List, Optional, Union import numpy as np import torch from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import TensorType, logging __UpperCamelCase : Union[str, Any] = logging.get_logger(__name__) class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = ["""input_features""", """is_longer"""] def __init__( self : Optional[Any] , UpperCamelCase__ : Dict=64 , UpperCamelCase__ : Optional[Any]=4_8000 , UpperCamelCase__ : Tuple=480 , UpperCamelCase__ : Union[str, Any]=10 , UpperCamelCase__ : List[Any]=1024 , UpperCamelCase__ : Tuple=0.0 , UpperCamelCase__ : int=False , UpperCamelCase__ : float = 0 , UpperCamelCase__ : float = 1_4000 , UpperCamelCase__ : int = None , UpperCamelCase__ : str = "fusion" , UpperCamelCase__ : str = "repeatpad" , **UpperCamelCase__ : Union[str, Any] , ): '''simple docstring''' super().__init__( feature_size=UpperCamelCase__ , sampling_rate=UpperCamelCase__ , padding_value=UpperCamelCase__ , return_attention_mask=UpperCamelCase__ , **UpperCamelCase__ , ) SCREAMING_SNAKE_CASE : Union[str, Any] = top_db SCREAMING_SNAKE_CASE : Union[str, Any] = truncation SCREAMING_SNAKE_CASE : str = padding SCREAMING_SNAKE_CASE : List[Any] = fft_window_size SCREAMING_SNAKE_CASE : Tuple = (fft_window_size >> 1) + 1 SCREAMING_SNAKE_CASE : List[str] = hop_length SCREAMING_SNAKE_CASE : List[Any] = max_length_s SCREAMING_SNAKE_CASE : Tuple = max_length_s * sampling_rate SCREAMING_SNAKE_CASE : List[Any] = sampling_rate SCREAMING_SNAKE_CASE : List[str] = frequency_min SCREAMING_SNAKE_CASE : Any = frequency_max SCREAMING_SNAKE_CASE : List[Any] = mel_filter_bank( num_frequency_bins=self.nb_frequency_bins , num_mel_filters=UpperCamelCase__ , min_frequency=UpperCamelCase__ , max_frequency=UpperCamelCase__ , sampling_rate=UpperCamelCase__ , norm=UpperCamelCase__ , mel_scale='''htk''' , ) SCREAMING_SNAKE_CASE : Optional[Any] = mel_filter_bank( num_frequency_bins=self.nb_frequency_bins , num_mel_filters=UpperCamelCase__ , min_frequency=UpperCamelCase__ , max_frequency=UpperCamelCase__ , sampling_rate=UpperCamelCase__ , norm='''slaney''' , mel_scale='''slaney''' , ) def __A ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE : Optional[Any] = self.__class__.__name__ if "mel_filters" in output: del output["mel_filters"] if "mel_filters_slaney" in output: del output["mel_filters_slaney"] return output def __A ( self : Optional[int] , UpperCamelCase__ : np.array , UpperCamelCase__ : Optional[np.array] = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = spectrogram( UpperCamelCase__ , window_function(self.fft_window_size , '''hann''' ) , frame_length=self.fft_window_size , hop_length=self.hop_length , power=2.0 , mel_filters=UpperCamelCase__ , log_mel='''dB''' , ) return log_mel_spectrogram.T def __A ( self : Union[str, Any] , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Dict , UpperCamelCase__ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = np.array_split(list(range(0 , total_frames - chunk_frames + 1 ) ) , 3 ) if len(ranges[1] ) == 0: # if the audio is too short, we just use the first chunk SCREAMING_SNAKE_CASE : int = [0] if len(ranges[2] ) == 0: # if the audio is too short, we just use the first chunk SCREAMING_SNAKE_CASE : Any = [0] # randomly choose index for each part SCREAMING_SNAKE_CASE : Union[str, Any] = np.random.choice(ranges[0] ) SCREAMING_SNAKE_CASE : List[Any] = np.random.choice(ranges[1] ) SCREAMING_SNAKE_CASE : int = np.random.choice(ranges[2] ) SCREAMING_SNAKE_CASE : Optional[int] = mel[idx_front : idx_front + chunk_frames, :] SCREAMING_SNAKE_CASE : Optional[Any] = mel[idx_middle : idx_middle + chunk_frames, :] SCREAMING_SNAKE_CASE : Tuple = mel[idx_back : idx_back + chunk_frames, :] SCREAMING_SNAKE_CASE : str = torch.tensor(mel[None, None, :] ) SCREAMING_SNAKE_CASE : Optional[int] = torch.nn.functional.interpolate( UpperCamelCase__ , size=[chunk_frames, 64] , mode='''bilinear''' , align_corners=UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[Any] = mel_shrink[0][0].numpy() SCREAMING_SNAKE_CASE : Union[str, Any] = np.stack([mel_shrink, mel_chunk_front, mel_chunk_middle, mel_chunk_back] , axis=0 ) return mel_fusion def __A ( self : Dict , UpperCamelCase__ : np.array , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Dict , UpperCamelCase__ : List[str] ): '''simple docstring''' if waveform.shape[0] > max_length: if truncation == "rand_trunc": SCREAMING_SNAKE_CASE : Optional[Any] = True # random crop to max_length (for compatibility) -> this should be handled by self.pad SCREAMING_SNAKE_CASE : List[Any] = len(UpperCamelCase__ ) - max_length SCREAMING_SNAKE_CASE : Dict = np.random.randint(0 , overflow + 1 ) SCREAMING_SNAKE_CASE : Optional[Any] = waveform[idx : idx + max_length] SCREAMING_SNAKE_CASE : Any = self._np_extract_fbank_features(UpperCamelCase__ , self.mel_filters_slaney )[None, :] elif truncation == "fusion": SCREAMING_SNAKE_CASE : Any = self._np_extract_fbank_features(UpperCamelCase__ , self.mel_filters ) SCREAMING_SNAKE_CASE : List[str] = max_length // self.hop_length + 1 # the +1 related to how the spectrogram is computed SCREAMING_SNAKE_CASE : List[Any] = mel.shape[0] if chunk_frames == total_frames: # there is a corner case where the audio length is larger than max_length but smaller than max_length+hop_length. # In this case, we just use the whole audio. SCREAMING_SNAKE_CASE : Optional[Any] = np.stack([mel, mel, mel, mel] , axis=0 ) SCREAMING_SNAKE_CASE : Tuple = False else: SCREAMING_SNAKE_CASE : str = self._random_mel_fusion(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[int] = True else: raise NotImplementedError(f"""data_truncating {truncation} not implemented""" ) else: SCREAMING_SNAKE_CASE : List[str] = False # only use repeat as a new possible value for padding. you repeat the audio before applying the usual max_length padding if waveform.shape[0] < max_length: if padding == "repeat": SCREAMING_SNAKE_CASE : Tuple = int(max_length / len(UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE : Any = np.stack(np.tile(UpperCamelCase__ , n_repeat + 1 ) )[:max_length] if padding == "repeatpad": SCREAMING_SNAKE_CASE : List[Any] = int(max_length / len(UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE : Dict = np.stack(np.tile(UpperCamelCase__ , UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE : Dict = np.pad(UpperCamelCase__ , (0, max_length - waveform.shape[0]) , mode='''constant''' , constant_values=0 ) if truncation == "fusion": SCREAMING_SNAKE_CASE : List[Any] = self._np_extract_fbank_features(UpperCamelCase__ , self.mel_filters ) SCREAMING_SNAKE_CASE : Union[str, Any] = np.stack([input_mel, input_mel, input_mel, input_mel] , axis=0 ) else: SCREAMING_SNAKE_CASE : List[str] = self._np_extract_fbank_features(UpperCamelCase__ , self.mel_filters_slaney )[None, :] return input_mel, longer def __call__( self : Union[str, Any] , UpperCamelCase__ : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , UpperCamelCase__ : str = None , UpperCamelCase__ : Optional[str] = None , UpperCamelCase__ : Optional[int] = None , UpperCamelCase__ : Optional[int] = None , UpperCamelCase__ : Optional[Union[str, TensorType]] = None , **UpperCamelCase__ : Any , ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = truncation if truncation is not None else self.truncation SCREAMING_SNAKE_CASE : List[str] = padding if padding else self.padding if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f"""The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a""" f""" sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input""" f""" was sampled with {self.sampling_rate} and not {sampling_rate}.""" ) else: logger.warning( '''It is strongly recommended to pass the `sampling_rate` argument to this function. ''' '''Failing to do so can result in silent errors that might be hard to debug.''' ) SCREAMING_SNAKE_CASE : List[str] = isinstance(UpperCamelCase__ , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f"""Only mono-channel audio is supported for input to {self}""" ) SCREAMING_SNAKE_CASE : int = is_batched_numpy or ( isinstance(UpperCamelCase__ , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: SCREAMING_SNAKE_CASE : Any = [np.asarray(UpperCamelCase__ , dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(UpperCamelCase__ , np.ndarray ): SCREAMING_SNAKE_CASE : List[Any] = np.asarray(UpperCamelCase__ , dtype=np.floataa ) elif isinstance(UpperCamelCase__ , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): SCREAMING_SNAKE_CASE : Union[str, Any] = raw_speech.astype(np.floataa ) # always return batch if not is_batched: SCREAMING_SNAKE_CASE : List[str] = [np.asarray(UpperCamelCase__ )] # convert to mel spectrogram, truncate and pad if needed. SCREAMING_SNAKE_CASE : int = [ self._get_input_mel(UpperCamelCase__ , max_length if max_length else self.nb_max_samples , UpperCamelCase__ , UpperCamelCase__ ) for waveform in raw_speech ] SCREAMING_SNAKE_CASE : str = [] SCREAMING_SNAKE_CASE : List[str] = [] for mel, longer in padded_inputs: input_mel.append(UpperCamelCase__ ) is_longer.append(UpperCamelCase__ ) if truncation == "fusion" and sum(UpperCamelCase__ ) == 0: # if no audio is longer than 10s, then randomly select one audio to be longer SCREAMING_SNAKE_CASE : Union[str, Any] = np.random.randint(0 , len(UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE : Optional[Any] = True if isinstance(input_mel[0] , UpperCamelCase__ ): SCREAMING_SNAKE_CASE : Union[str, Any] = [np.asarray(UpperCamelCase__ , dtype=np.floataa ) for feature in input_mel] # is_longer is a list of bool SCREAMING_SNAKE_CASE : Optional[Any] = [[longer] for longer in is_longer] SCREAMING_SNAKE_CASE : Union[str, Any] = {'''input_features''': input_mel, '''is_longer''': is_longer} SCREAMING_SNAKE_CASE : int = BatchFeature(UpperCamelCase__ ) if return_tensors is not None: SCREAMING_SNAKE_CASE : int = input_features.convert_to_tensors(UpperCamelCase__ ) return input_features
34
0
import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow if is_torch_available(): import torch from transformers import XLMRobertaModel @require_sentencepiece @require_tokenizers @require_torch class lowercase__ ( unittest.TestCase): @slow def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = XLMRobertaModel.from_pretrained('''xlm-roberta-base''' ) SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([[0, 581, 1_0269, 83, 9_9942, 136, 6_0742, 23, 70, 8_0583, 1_8276, 2]] ) # The dog is cute and lives in the garden house SCREAMING_SNAKE_CASE : Optional[Any] = torch.Size((1, 12, 768) ) # batch_size, sequence_length, embedding_vector_dim SCREAMING_SNAKE_CASE : str = torch.tensor( [[-0.0101, 0.1218, -0.0803, 0.0801, 0.1327, 0.0776, -0.1215, 0.2383, 0.3338, 0.3106, 0.0300, 0.0252]] ) # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.eval() # expected_output_values_last_dim = xlmr.extract_features(input_ids[0])[:, :, -1] with torch.no_grad(): SCREAMING_SNAKE_CASE : List[Any] = model(__UpperCamelCase )['''last_hidden_state'''].detach() self.assertEqual(output.shape , __UpperCamelCase ) # compare the actual values for a slice of last dim self.assertTrue(torch.allclose(output[:, :, -1] , __UpperCamelCase , atol=1E-3 ) ) @slow def __A ( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = XLMRobertaModel.from_pretrained('''xlm-roberta-large''' ) SCREAMING_SNAKE_CASE : int = torch.tensor([[0, 581, 1_0269, 83, 9_9942, 136, 6_0742, 23, 70, 8_0583, 1_8276, 2]] ) # The dog is cute and lives in the garden house SCREAMING_SNAKE_CASE : List[str] = torch.Size((1, 12, 1024) ) # batch_size, sequence_length, embedding_vector_dim SCREAMING_SNAKE_CASE : int = torch.tensor( [[-0.0699, -0.0318, 0.0705, -0.1241, 0.0999, -0.0520, 0.1004, -0.1838, -0.4704, 0.1437, 0.0821, 0.0126]] ) # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.large') # xlmr.eval() # expected_output_values_last_dim = xlmr.extract_features(input_ids[0])[:, :, -1] with torch.no_grad(): SCREAMING_SNAKE_CASE : List[Any] = model(__UpperCamelCase )['''last_hidden_state'''].detach() self.assertEqual(output.shape , __UpperCamelCase ) # compare the actual values for a slice of last dim self.assertTrue(torch.allclose(output[:, :, -1] , __UpperCamelCase , atol=1E-3 ) )
701
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...utils import logging if TYPE_CHECKING: from ...processing_utils import ProcessorMixin from ...utils import TensorType __UpperCamelCase : str = logging.get_logger(__name__) __UpperCamelCase : str = { 'microsoft/layoutlmv3-base': 'https://huggingface.co/microsoft/layoutlmv3-base/resolve/main/config.json', } class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = """layoutlmv3""" def __init__( self : Optional[int] , UpperCamelCase__ : Union[str, Any]=5_0265 , UpperCamelCase__ : List[Any]=768 , UpperCamelCase__ : Union[str, Any]=12 , UpperCamelCase__ : Union[str, Any]=12 , UpperCamelCase__ : Tuple=3072 , UpperCamelCase__ : List[Any]="gelu" , UpperCamelCase__ : List[Any]=0.1 , UpperCamelCase__ : List[str]=0.1 , UpperCamelCase__ : Any=512 , UpperCamelCase__ : List[Any]=2 , UpperCamelCase__ : List[Any]=0.02 , UpperCamelCase__ : Optional[Any]=1E-5 , UpperCamelCase__ : List[str]=1 , UpperCamelCase__ : int=0 , UpperCamelCase__ : str=2 , UpperCamelCase__ : List[str]=1024 , UpperCamelCase__ : str=128 , UpperCamelCase__ : str=128 , UpperCamelCase__ : Tuple=True , UpperCamelCase__ : Optional[int]=32 , UpperCamelCase__ : Any=128 , UpperCamelCase__ : Optional[Any]=64 , UpperCamelCase__ : Dict=256 , UpperCamelCase__ : List[Any]=True , UpperCamelCase__ : str=True , UpperCamelCase__ : Dict=True , UpperCamelCase__ : Dict=224 , UpperCamelCase__ : Optional[Any]=3 , UpperCamelCase__ : Any=16 , UpperCamelCase__ : Any=None , **UpperCamelCase__ : Optional[Any] , ): '''simple docstring''' super().__init__( vocab_size=UpperCamelCase__ , hidden_size=UpperCamelCase__ , num_hidden_layers=UpperCamelCase__ , num_attention_heads=UpperCamelCase__ , intermediate_size=UpperCamelCase__ , hidden_act=UpperCamelCase__ , hidden_dropout_prob=UpperCamelCase__ , attention_probs_dropout_prob=UpperCamelCase__ , max_position_embeddings=UpperCamelCase__ , type_vocab_size=UpperCamelCase__ , initializer_range=UpperCamelCase__ , layer_norm_eps=UpperCamelCase__ , pad_token_id=UpperCamelCase__ , bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ , **UpperCamelCase__ , ) SCREAMING_SNAKE_CASE : Union[str, Any] = max_ad_position_embeddings SCREAMING_SNAKE_CASE : List[Any] = coordinate_size SCREAMING_SNAKE_CASE : List[str] = shape_size SCREAMING_SNAKE_CASE : Optional[int] = has_relative_attention_bias SCREAMING_SNAKE_CASE : List[Any] = rel_pos_bins SCREAMING_SNAKE_CASE : str = max_rel_pos SCREAMING_SNAKE_CASE : Any = has_spatial_attention_bias SCREAMING_SNAKE_CASE : Union[str, Any] = rel_ad_pos_bins SCREAMING_SNAKE_CASE : Union[str, Any] = max_rel_ad_pos SCREAMING_SNAKE_CASE : Union[str, Any] = text_embed SCREAMING_SNAKE_CASE : List[str] = visual_embed SCREAMING_SNAKE_CASE : Optional[Any] = input_size SCREAMING_SNAKE_CASE : Optional[Any] = num_channels SCREAMING_SNAKE_CASE : List[Any] = patch_size SCREAMING_SNAKE_CASE : List[Any] = classifier_dropout class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = version.parse("""1.12""") @property def __A ( self : str ): '''simple docstring''' if self.task in ["question-answering", "sequence-classification"]: return OrderedDict( [ ('''input_ids''', {0: '''batch''', 1: '''sequence'''}), ('''attention_mask''', {0: '''batch''', 1: '''sequence'''}), ('''bbox''', {0: '''batch''', 1: '''sequence'''}), ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) else: return OrderedDict( [ ('''input_ids''', {0: '''batch''', 1: '''sequence'''}), ('''bbox''', {0: '''batch''', 1: '''sequence'''}), ('''attention_mask''', {0: '''batch''', 1: '''sequence'''}), ('''pixel_values''', {0: '''batch''', 1: '''num_channels'''}), ] ) @property def __A ( self : int ): '''simple docstring''' return 1E-5 @property def __A ( self : Union[str, Any] ): '''simple docstring''' return 12 def __A ( self : Optional[Any] , UpperCamelCase__ : "ProcessorMixin" , UpperCamelCase__ : int = -1 , UpperCamelCase__ : int = -1 , UpperCamelCase__ : bool = False , UpperCamelCase__ : Optional["TensorType"] = None , UpperCamelCase__ : int = 3 , UpperCamelCase__ : int = 40 , UpperCamelCase__ : int = 40 , ): '''simple docstring''' setattr(processor.image_processor , '''apply_ocr''' , UpperCamelCase__ ) # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX SCREAMING_SNAKE_CASE : Any = compute_effective_axis_dimension( UpperCamelCase__ , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX SCREAMING_SNAKE_CASE : List[Any] = processor.tokenizer.num_special_tokens_to_add(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Tuple = compute_effective_axis_dimension( UpperCamelCase__ , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=UpperCamelCase__ ) # Generate dummy inputs according to compute batch and sequence SCREAMING_SNAKE_CASE : Union[str, Any] = [[''' '''.join([processor.tokenizer.unk_token] ) * seq_length]] * batch_size # Generate dummy bounding boxes SCREAMING_SNAKE_CASE : Any = [[[48, 84, 73, 128]]] * batch_size # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX # batch_size = compute_effective_axis_dimension(batch_size, fixed_dimension=OnnxConfig.default_fixed_batch) SCREAMING_SNAKE_CASE : List[Any] = self._generate_dummy_images(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[int] = dict( processor( UpperCamelCase__ , text=UpperCamelCase__ , boxes=UpperCamelCase__ , return_tensors=UpperCamelCase__ , ) ) return inputs
34
0
print((lambda quine: quine % quine)('print((lambda quine: quine %% quine)(%r))'))
702
import os import unittest from transformers import FunnelTokenizer, FunnelTokenizerFast from transformers.models.funnel.tokenization_funnel import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowercase__ ( UpperCamelCase_ , unittest.TestCase): UpperCamelCase_ = FunnelTokenizer UpperCamelCase_ = FunnelTokenizerFast UpperCamelCase_ = True UpperCamelCase_ = True def __A ( self : Union[str, Any] ): '''simple docstring''' super().setUp() SCREAMING_SNAKE_CASE : Optional[Any] = [ '''<unk>''', '''<cls>''', '''<sep>''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] SCREAMING_SNAKE_CASE : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) def __A ( self : int , **UpperCamelCase__ : List[Any] ): '''simple docstring''' return FunnelTokenizer.from_pretrained(self.tmpdirname , **UpperCamelCase__ ) def __A ( self : int , **UpperCamelCase__ : List[Any] ): '''simple docstring''' return FunnelTokenizerFast.from_pretrained(self.tmpdirname , **UpperCamelCase__ ) def __A ( self : Any , UpperCamelCase__ : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = '''UNwant\u00E9d,running''' SCREAMING_SNAKE_CASE : int = '''unwanted, running''' return input_text, output_text def __A ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = self.tokenizer_class(self.vocab_file ) SCREAMING_SNAKE_CASE : int = tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(UpperCamelCase__ , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCamelCase__ ) , [7, 4, 5, 10, 8, 9] ) def __A ( self : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self.get_tokenizers(do_lower_case=UpperCamelCase__ ) for tokenizer in tokenizers: SCREAMING_SNAKE_CASE : int = tokenizer('''UNwant\u00E9d,running''' ) SCREAMING_SNAKE_CASE : Optional[Any] = len(inputs['''input_ids'''] ) - 1 self.assertListEqual(inputs['''token_type_ids'''] , [2] + [0] * sentence_len ) SCREAMING_SNAKE_CASE : List[Any] = tokenizer('''UNwant\u00E9d,running''' , '''UNwant\u00E9d,running''' ) self.assertListEqual(inputs['''token_type_ids'''] , [2] + [0] * sentence_len + [1] * sentence_len )
34
0
from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCamelCase : Any = logging.get_logger(__name__) class lowercase__ ( _UpperCAmelCase): UpperCamelCase_ = """timm_backbone""" def __init__( self : List[str] , UpperCamelCase__ : str=None , UpperCamelCase__ : List[Any]=3 , UpperCamelCase__ : List[str]=True , UpperCamelCase__ : Dict=True , UpperCamelCase__ : List[str]=None , **UpperCamelCase__ : Any , ): '''simple docstring''' super().__init__(**lowercase__ ) SCREAMING_SNAKE_CASE : int = backbone SCREAMING_SNAKE_CASE : Union[str, Any] = num_channels SCREAMING_SNAKE_CASE : Optional[Any] = features_only SCREAMING_SNAKE_CASE : str = use_pretrained_backbone SCREAMING_SNAKE_CASE : str = True SCREAMING_SNAKE_CASE : List[Any] = out_indices if out_indices is not None else (-1,)
703
import numpy as np import torch from torch.utils.data import Dataset, IterableDataset from ..utils.generic import ModelOutput class lowercase__ ( UpperCamelCase_): def __init__( self : str , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = dataset SCREAMING_SNAKE_CASE : Optional[Any] = process SCREAMING_SNAKE_CASE : Union[str, Any] = params def __len__( self : Tuple ): '''simple docstring''' return len(self.dataset ) def __getitem__( self : List[str] , UpperCamelCase__ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = self.dataset[i] SCREAMING_SNAKE_CASE : Optional[int] = self.process(UpperCamelCase__ , **self.params ) return processed class lowercase__ ( UpperCamelCase_): def __init__( self : Dict , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Dict , UpperCamelCase__ : List[Any]=None ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = loader SCREAMING_SNAKE_CASE : List[Any] = infer SCREAMING_SNAKE_CASE : int = params if loader_batch_size == 1: # Let's spare some time by deactivating altogether SCREAMING_SNAKE_CASE : Optional[int] = None SCREAMING_SNAKE_CASE : List[str] = loader_batch_size # Internal bookkeeping SCREAMING_SNAKE_CASE : Optional[int] = None SCREAMING_SNAKE_CASE : int = None def __len__( self : int ): '''simple docstring''' return len(self.loader ) def __iter__( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = iter(self.loader ) return self def __A ( self : List[str] ): '''simple docstring''' if isinstance(self._loader_batch_data , torch.Tensor ): # Batch data is simple tensor, just fetch the slice SCREAMING_SNAKE_CASE : Optional[Any] = self._loader_batch_data[self._loader_batch_index] else: # Batch data is assumed to be BaseModelOutput (or dict) SCREAMING_SNAKE_CASE : Union[str, Any] = {} for k, element in self._loader_batch_data.items(): if isinstance(UpperCamelCase__ , UpperCamelCase__ ): # Convert ModelOutput to tuple first SCREAMING_SNAKE_CASE : Dict = element.to_tuple() if isinstance(element[0] , torch.Tensor ): SCREAMING_SNAKE_CASE : Dict = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element ) elif isinstance(element[0] , np.ndarray ): SCREAMING_SNAKE_CASE : Union[str, Any] = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element ) continue if k in {"hidden_states", "past_key_values", "attentions"} and isinstance(UpperCamelCase__ , UpperCamelCase__ ): # Those are stored as lists of tensors so need specific unbatching. if isinstance(element[0] , torch.Tensor ): SCREAMING_SNAKE_CASE : Union[str, Any] = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element ) elif isinstance(element[0] , np.ndarray ): SCREAMING_SNAKE_CASE : List[str] = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element ) continue if element is None: # This can happen for optional data that get passed around SCREAMING_SNAKE_CASE : int = None elif isinstance(element[self._loader_batch_index] , torch.Tensor ): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers SCREAMING_SNAKE_CASE : Union[str, Any] = element[self._loader_batch_index].unsqueeze(0 ) elif isinstance(element[self._loader_batch_index] , np.ndarray ): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers SCREAMING_SNAKE_CASE : Tuple = np.expand_dims(element[self._loader_batch_index] , 0 ) else: # This is typically a list, so no need to `unsqueeze`. SCREAMING_SNAKE_CASE : Tuple = element[self._loader_batch_index] # Recreate the element by reusing the original class to make it look # batch_size=1 SCREAMING_SNAKE_CASE : Any = self._loader_batch_data.__class__(UpperCamelCase__ ) self._loader_batch_index += 1 return result def __A ( self : Union[str, Any] ): '''simple docstring''' if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: # We are currently unrolling a batch so we just need to return # the current item within a batch return self.loader_batch_item() # We're out of items within a batch SCREAMING_SNAKE_CASE : Tuple = next(self.iterator ) SCREAMING_SNAKE_CASE : List[Any] = self.infer(UpperCamelCase__ , **self.params ) # We now have a batch of "inferred things". if self.loader_batch_size is not None: # Try to infer the size of the batch if isinstance(UpperCamelCase__ , torch.Tensor ): SCREAMING_SNAKE_CASE : Optional[int] = processed else: SCREAMING_SNAKE_CASE : int = list(processed.keys() )[0] SCREAMING_SNAKE_CASE : int = processed[key] if isinstance(UpperCamelCase__ , UpperCamelCase__ ): SCREAMING_SNAKE_CASE : List[Any] = len(UpperCamelCase__ ) else: SCREAMING_SNAKE_CASE : Dict = first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. SCREAMING_SNAKE_CASE : List[Any] = observed_batch_size # Setting internal index to unwrap the batch SCREAMING_SNAKE_CASE : List[Any] = processed SCREAMING_SNAKE_CASE : int = 0 return self.loader_batch_item() else: # We're not unrolling batches return processed class lowercase__ ( UpperCamelCase_): def __init__( self : str , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Union[str, Any]=None ): '''simple docstring''' super().__init__(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) def __iter__( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = iter(self.loader ) SCREAMING_SNAKE_CASE : List[Any] = None return self def __A ( self : List[str] ): '''simple docstring''' if self.subiterator is None: SCREAMING_SNAKE_CASE : Dict = self.infer(next(self.iterator ) , **self.params ) try: # Try to return next item SCREAMING_SNAKE_CASE : Any = next(self.subiterator ) except StopIteration: # When a preprocess iterator ends, we can start lookig at the next item # ChunkIterator will keep feeding until ALL elements of iterator # all have created their subiterator and have been iterating against. # # Another way to look at it, is we're basically flattening lists of lists # into a single list, but with generators SCREAMING_SNAKE_CASE : Optional[Any] = self.infer(next(self.iterator ) , **self.params ) SCREAMING_SNAKE_CASE : Union[str, Any] = next(self.subiterator ) return processed class lowercase__ ( UpperCamelCase_): def __iter__( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = iter(self.loader ) return self def __A ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = False SCREAMING_SNAKE_CASE : Optional[int] = [] if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: while self._loader_batch_index < self.loader_batch_size: SCREAMING_SNAKE_CASE : Tuple = self.loader_batch_item() SCREAMING_SNAKE_CASE : Any = item.pop('''is_last''' ) accumulator.append(UpperCamelCase__ ) if is_last: return accumulator while not is_last: SCREAMING_SNAKE_CASE : Any = self.infer(next(self.iterator ) , **self.params ) if self.loader_batch_size is not None: if isinstance(UpperCamelCase__ , torch.Tensor ): SCREAMING_SNAKE_CASE : Tuple = processed else: SCREAMING_SNAKE_CASE : Union[str, Any] = list(processed.keys() )[0] SCREAMING_SNAKE_CASE : List[str] = processed[key] if isinstance(UpperCamelCase__ , UpperCamelCase__ ): SCREAMING_SNAKE_CASE : List[Any] = len(UpperCamelCase__ ) else: SCREAMING_SNAKE_CASE : int = first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. SCREAMING_SNAKE_CASE : List[str] = observed_batch_size SCREAMING_SNAKE_CASE : List[Any] = processed SCREAMING_SNAKE_CASE : str = 0 while self._loader_batch_index < self.loader_batch_size: SCREAMING_SNAKE_CASE : Any = self.loader_batch_item() SCREAMING_SNAKE_CASE : List[Any] = item.pop('''is_last''' ) accumulator.append(UpperCamelCase__ ) if is_last: return accumulator else: SCREAMING_SNAKE_CASE : int = processed SCREAMING_SNAKE_CASE : List[str] = item.pop('''is_last''' ) accumulator.append(UpperCamelCase__ ) return accumulator class lowercase__ ( UpperCamelCase_): def __init__( self : Optional[Any] , UpperCamelCase__ : Dataset , UpperCamelCase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = dataset SCREAMING_SNAKE_CASE : Dict = key def __len__( self : Optional[int] ): '''simple docstring''' return len(self.dataset ) def __getitem__( self : Dict , UpperCamelCase__ : Tuple ): '''simple docstring''' return self.dataset[i][self.key] class lowercase__ ( UpperCamelCase_): def __init__( self : List[Any] , UpperCamelCase__ : Dataset , UpperCamelCase__ : str , UpperCamelCase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = dataset SCREAMING_SNAKE_CASE : List[str] = keya SCREAMING_SNAKE_CASE : Tuple = keya def __len__( self : List[str] ): '''simple docstring''' return len(self.dataset ) def __getitem__( self : Union[str, Any] , UpperCamelCase__ : Any ): '''simple docstring''' return {"text": self.dataset[i][self.keya], "text_pair": self.dataset[i][self.keya]}
34
0
import numpy as np from transformers import BatchFeature from transformers.testing_utils import require_tf, require_torch from .test_feature_extraction_common import FeatureExtractionSavingTestMixin class lowercase__ ( __SCREAMING_SNAKE_CASE): # to overwrite at feature extractactor specific tests UpperCamelCase_ = None UpperCamelCase_ = None @property def __A ( self : Any ): '''simple docstring''' return self.feat_extract_tester.prepare_feat_extract_dict() def __A ( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self.feature_extraction_class(**self.feat_extract_dict ) self.assertTrue(hasattr(__snake_case , '''feature_size''' ) ) self.assertTrue(hasattr(__snake_case , '''sampling_rate''' ) ) self.assertTrue(hasattr(__snake_case , '''padding_value''' ) ) def __A ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE : Any = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE : str = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE : Optional[Any] = BatchFeature({input_name: speech_inputs} ) self.assertTrue(all(len(__snake_case ) == len(__snake_case ) for x, y in zip(__snake_case , processed_features[input_name] ) ) ) SCREAMING_SNAKE_CASE : Dict = self.feat_extract_tester.prepare_inputs_for_common(equal_length=__snake_case ) SCREAMING_SNAKE_CASE : List[str] = BatchFeature({input_name: speech_inputs} , tensor_type='''np''' ) SCREAMING_SNAKE_CASE : Dict = processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE : int = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) @require_torch def __A ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self.feat_extract_tester.prepare_inputs_for_common(equal_length=__snake_case ) SCREAMING_SNAKE_CASE : List[str] = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE : List[str] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE : Union[str, Any] = BatchFeature({input_name: speech_inputs} , tensor_type='''pt''' ) SCREAMING_SNAKE_CASE : Dict = processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE : List[str] = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) @require_tf def __A ( self : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = self.feat_extract_tester.prepare_inputs_for_common(equal_length=__snake_case ) SCREAMING_SNAKE_CASE : List[str] = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE : Tuple = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE : str = BatchFeature({input_name: speech_inputs} , tensor_type='''tf''' ) SCREAMING_SNAKE_CASE : List[Any] = processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE : Tuple = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) def __A ( self : Dict , UpperCamelCase__ : Tuple=False ): '''simple docstring''' def _inputs_have_equal_length(UpperCamelCase__ : int ): SCREAMING_SNAKE_CASE : Any = len(input[0] ) for input_slice in input[1:]: if len(__snake_case ) != length: return False return True def _inputs_are_equal(UpperCamelCase__ : Tuple , UpperCamelCase__ : Tuple ): if len(__snake_case ) != len(__snake_case ): return False for input_slice_a, input_slice_a in zip(__snake_case , __snake_case ): if not np.allclose(np.asarray(__snake_case ) , np.asarray(__snake_case ) , atol=1E-3 ): return False return True SCREAMING_SNAKE_CASE : List[Any] = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE : Tuple = self.feat_extract_tester.prepare_inputs_for_common(numpify=__snake_case ) SCREAMING_SNAKE_CASE : Any = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE : Tuple = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE : List[Any] = self.feat_extract_tester.seq_length_diff SCREAMING_SNAKE_CASE : List[str] = self.feat_extract_tester.max_seq_length + pad_diff SCREAMING_SNAKE_CASE : List[str] = self.feat_extract_tester.min_seq_length SCREAMING_SNAKE_CASE : Any = self.feat_extract_tester.batch_size SCREAMING_SNAKE_CASE : List[Any] = self.feat_extract_tester.feature_size # test padding for List[int] + numpy SCREAMING_SNAKE_CASE : Optional[int] = feat_extract.pad(__snake_case , padding=__snake_case ) SCREAMING_SNAKE_CASE : List[str] = input_a[input_name] SCREAMING_SNAKE_CASE : Union[str, Any] = feat_extract.pad(__snake_case , padding='''longest''' ) SCREAMING_SNAKE_CASE : Dict = input_a[input_name] SCREAMING_SNAKE_CASE : List[str] = feat_extract.pad(__snake_case , padding='''max_length''' , max_length=len(speech_inputs[-1] ) ) SCREAMING_SNAKE_CASE : List[Any] = input_a[input_name] SCREAMING_SNAKE_CASE : Tuple = feat_extract.pad(__snake_case , padding='''longest''' , return_tensors='''np''' ) SCREAMING_SNAKE_CASE : Optional[Any] = input_a[input_name] # max_length parameter has to be provided when setting `padding="max_length"` with self.assertRaises(__snake_case ): feat_extract.pad(__snake_case , padding='''max_length''' )[input_name] SCREAMING_SNAKE_CASE : Any = feat_extract.pad( __snake_case , padding='''max_length''' , max_length=__snake_case , return_tensors='''np''' ) SCREAMING_SNAKE_CASE : List[str] = input_a[input_name] self.assertFalse(_inputs_have_equal_length(__snake_case ) ) self.assertTrue(_inputs_have_equal_length(__snake_case ) ) self.assertTrue(_inputs_have_equal_length(__snake_case ) ) self.assertTrue(_inputs_are_equal(__snake_case , __snake_case ) ) self.assertTrue(len(input_a[0] ) == pad_min_length ) self.assertTrue(len(input_a[1] ) == pad_min_length + pad_diff ) self.assertTrue(input_a.shape[:2] == (batch_size, len(input_a[0] )) ) self.assertTrue(input_a.shape[:2] == (batch_size, pad_max_length) ) if feature_size > 1: self.assertTrue(input_a.shape[2] == input_a.shape[2] == feature_size ) # test padding for `pad_to_multiple_of` for List[int] + numpy SCREAMING_SNAKE_CASE : Tuple = feat_extract.pad(__snake_case , pad_to_multiple_of=10 ) SCREAMING_SNAKE_CASE : Union[str, Any] = input_a[input_name] SCREAMING_SNAKE_CASE : Dict = feat_extract.pad(__snake_case , padding='''longest''' , pad_to_multiple_of=10 ) SCREAMING_SNAKE_CASE : Optional[int] = input_a[input_name] SCREAMING_SNAKE_CASE : Tuple = feat_extract.pad( __snake_case , padding='''max_length''' , pad_to_multiple_of=10 , max_length=__snake_case ) SCREAMING_SNAKE_CASE : Optional[Any] = input_a[input_name] SCREAMING_SNAKE_CASE : Tuple = feat_extract.pad( __snake_case , padding='''max_length''' , pad_to_multiple_of=10 , max_length=__snake_case , return_tensors='''np''' , ) SCREAMING_SNAKE_CASE : str = input_a[input_name] self.assertTrue(all(len(__snake_case ) % 10 == 0 for x in input_a ) ) self.assertTrue(_inputs_are_equal(__snake_case , __snake_case ) ) SCREAMING_SNAKE_CASE : Optional[Any] = pad_max_length if pad_max_length % 10 == 0 else (pad_max_length // 10 + 1) * 10 self.assertTrue(all(len(__snake_case ) == expected_mult_pad_length for x in input_a ) ) self.assertEqual(input_a.shape[:2] , (batch_size, expected_mult_pad_length) ) if feature_size > 1: self.assertTrue(input_a.shape[2] == feature_size ) # Check padding value is correct SCREAMING_SNAKE_CASE : str = (np.ones(self.feat_extract_tester.feature_size ) * feat_extract.padding_value).sum() self.assertTrue( abs(np.asarray(input_a[0] )[pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length) ) < 1E-3 ) self.assertTrue( abs( np.asarray(input_a[1] )[pad_min_length + pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - pad_diff) ) < 1E-3 ) self.assertTrue( abs( np.asarray(input_a[2] )[pad_min_length + 2 * pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - 2 * pad_diff) ) < 1E-3 ) self.assertTrue( abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length) ) < 1E-3 ) self.assertTrue( abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (expected_mult_pad_length - pad_min_length) ) < 1E-3 ) def __A ( self : Dict , UpperCamelCase__ : Union[str, Any]=False ): '''simple docstring''' def _inputs_have_equal_length(UpperCamelCase__ : List[str] ): SCREAMING_SNAKE_CASE : str = len(input[0] ) for input_slice in input[1:]: if len(__snake_case ) != length: return False return True def _inputs_are_equal(UpperCamelCase__ : Dict , UpperCamelCase__ : List[str] ): if len(__snake_case ) != len(__snake_case ): return False for input_slice_a, input_slice_a in zip(__snake_case , __snake_case ): if not np.allclose(np.asarray(__snake_case ) , np.asarray(__snake_case ) , atol=1E-3 ): return False return True SCREAMING_SNAKE_CASE : str = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE : Any = self.feat_extract_tester.prepare_inputs_for_common(numpify=__snake_case ) SCREAMING_SNAKE_CASE : Tuple = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE : Optional[int] = BatchFeature({input_name: speech_inputs} ) # truncate to smallest SCREAMING_SNAKE_CASE : List[str] = feat_extract.pad( __snake_case , padding='''max_length''' , max_length=len(speech_inputs[0] ) , truncation=__snake_case ) SCREAMING_SNAKE_CASE : Optional[Any] = input_a[input_name] SCREAMING_SNAKE_CASE : List[Any] = feat_extract.pad(__snake_case , padding='''max_length''' , max_length=len(speech_inputs[0] ) ) SCREAMING_SNAKE_CASE : Any = input_a[input_name] self.assertTrue(_inputs_have_equal_length(__snake_case ) ) self.assertFalse(_inputs_have_equal_length(__snake_case ) ) # truncate to smallest with np SCREAMING_SNAKE_CASE : Optional[Any] = feat_extract.pad( __snake_case , padding='''max_length''' , max_length=len(speech_inputs[0] ) , return_tensors='''np''' , truncation=__snake_case , ) SCREAMING_SNAKE_CASE : int = input_a[input_name] SCREAMING_SNAKE_CASE : List[Any] = feat_extract.pad( __snake_case , padding='''max_length''' , max_length=len(speech_inputs[0] ) , return_tensors='''np''' ) SCREAMING_SNAKE_CASE : Optional[Any] = input_a[input_name] self.assertTrue(_inputs_have_equal_length(__snake_case ) ) self.assertTrue(input_a.shape[1] == len(speech_inputs[0] ) ) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(__snake_case ) ) # truncate to middle SCREAMING_SNAKE_CASE : Any = feat_extract.pad( __snake_case , padding='''max_length''' , max_length=len(speech_inputs[1] ) , truncation=__snake_case , return_tensors='''np''' , ) SCREAMING_SNAKE_CASE : Optional[int] = input_a[input_name] SCREAMING_SNAKE_CASE : Optional[int] = feat_extract.pad( __snake_case , padding='''max_length''' , max_length=len(speech_inputs[1] ) , truncation=__snake_case ) SCREAMING_SNAKE_CASE : Dict = input_a[input_name] SCREAMING_SNAKE_CASE : Optional[int] = feat_extract.pad( __snake_case , padding='''max_length''' , max_length=len(speech_inputs[1] ) , return_tensors='''np''' ) SCREAMING_SNAKE_CASE : List[Any] = input_a[input_name] self.assertTrue(input_a.shape[1] == len(speech_inputs[1] ) ) self.assertTrue(_inputs_have_equal_length(__snake_case ) ) self.assertTrue(_inputs_have_equal_length(__snake_case ) ) self.assertTrue(_inputs_are_equal(__snake_case , __snake_case ) ) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(__snake_case ) ) self.assertTrue(len(input_a[-1] ) == len(speech_inputs[-1] ) ) # padding has to be max_length when setting `truncation=True` with self.assertRaises(__snake_case ): feat_extract.pad(__snake_case , truncation=__snake_case )[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(__snake_case ): feat_extract.pad(__snake_case , padding='''longest''' , truncation=__snake_case )[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(__snake_case ): feat_extract.pad(__snake_case , padding='''longest''' , truncation=__snake_case )[input_name] # max_length parameter has to be provided when setting `truncation=True` and padding="max_length" with self.assertRaises(__snake_case ): feat_extract.pad(__snake_case , padding='''max_length''' , truncation=__snake_case )[input_name] # test truncation for `pad_to_multiple_of` for List[int] + numpy SCREAMING_SNAKE_CASE : Any = 12 SCREAMING_SNAKE_CASE : Dict = feat_extract.pad( __snake_case , padding='''max_length''' , max_length=len(speech_inputs[0] ) , pad_to_multiple_of=__snake_case , truncation=__snake_case , ) SCREAMING_SNAKE_CASE : List[str] = input_a[input_name] SCREAMING_SNAKE_CASE : Dict = feat_extract.pad( __snake_case , padding='''max_length''' , max_length=len(speech_inputs[0] ) , pad_to_multiple_of=__snake_case , ) SCREAMING_SNAKE_CASE : List[str] = input_a[input_name] # retrieve expected_length as multiple of pad_to_multiple_of SCREAMING_SNAKE_CASE : List[str] = len(speech_inputs[0] ) if expected_length % pad_to_multiple_of != 0: SCREAMING_SNAKE_CASE : List[Any] = ((len(speech_inputs[0] ) // pad_to_multiple_of) + 1) * pad_to_multiple_of self.assertTrue(len(input_a[0] ) == expected_length ) self.assertTrue(_inputs_have_equal_length(__snake_case ) ) self.assertFalse(_inputs_have_equal_length(__snake_case ) ) def __A ( self : Union[str, Any] ): '''simple docstring''' self._check_padding(numpify=__snake_case ) def __A ( self : int ): '''simple docstring''' self._check_padding(numpify=__snake_case ) def __A ( self : Union[str, Any] ): '''simple docstring''' self._check_truncation(numpify=__snake_case ) def __A ( self : str ): '''simple docstring''' self._check_truncation(numpify=__snake_case ) @require_torch def __A ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE : Optional[Any] = self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE : Dict = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE : Any = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE : Optional[Any] = feat_extract.pad(__snake_case , padding='''longest''' , return_tensors='''np''' )[input_name] SCREAMING_SNAKE_CASE : Dict = feat_extract.pad(__snake_case , padding='''longest''' , return_tensors='''pt''' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_pt.numpy().astype(np.floataa ).sum() ) < 1E-2 ) @require_tf def __A ( self : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE : Tuple = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE : int = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE : str = feat_extract.pad(__snake_case , padding='''longest''' , return_tensors='''np''' )[input_name] SCREAMING_SNAKE_CASE : List[Any] = feat_extract.pad(__snake_case , padding='''longest''' , return_tensors='''tf''' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_tf.numpy().astype(np.floataa ).sum() ) < 1E-2 ) def __A ( self : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = self.feat_extract_dict SCREAMING_SNAKE_CASE : Union[str, Any] = True SCREAMING_SNAKE_CASE : int = self.feature_extraction_class(**__snake_case ) SCREAMING_SNAKE_CASE : Optional[int] = self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE : Tuple = [len(__snake_case ) for x in speech_inputs] SCREAMING_SNAKE_CASE : Optional[int] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE : int = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE : int = feat_extract.pad(__snake_case , padding='''longest''' , return_tensors='''np''' ) self.assertIn('''attention_mask''' , __snake_case ) self.assertListEqual(list(processed.attention_mask.shape ) , list(processed[input_name].shape[:2] ) ) self.assertListEqual(processed.attention_mask.sum(-1 ).tolist() , __snake_case ) def __A ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = self.feat_extract_dict SCREAMING_SNAKE_CASE : Optional[int] = True SCREAMING_SNAKE_CASE : int = self.feature_extraction_class(**__snake_case ) SCREAMING_SNAKE_CASE : List[Any] = self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE : Optional[int] = [len(__snake_case ) for x in speech_inputs] SCREAMING_SNAKE_CASE : List[Any] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE : str = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE : str = min(__snake_case ) SCREAMING_SNAKE_CASE : List[str] = feat_extract.pad( __snake_case , padding='''max_length''' , max_length=__snake_case , truncation=__snake_case , return_tensors='''np''' ) self.assertIn('''attention_mask''' , __snake_case ) self.assertListEqual( list(processed_pad.attention_mask.shape ) , [processed_pad[input_name].shape[0], max_length] ) self.assertListEqual( processed_pad.attention_mask[:, :max_length].sum(-1 ).tolist() , [max_length for x in speech_inputs] )
704
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging if TYPE_CHECKING: from ... import FeatureExtractionMixin, PreTrainedTokenizerBase, TensorType __UpperCamelCase : Optional[Any] = logging.get_logger(__name__) __UpperCamelCase : Optional[Any] = { 'microsoft/deberta-v2-xlarge': 'https://huggingface.co/microsoft/deberta-v2-xlarge/resolve/main/config.json', 'microsoft/deberta-v2-xxlarge': 'https://huggingface.co/microsoft/deberta-v2-xxlarge/resolve/main/config.json', 'microsoft/deberta-v2-xlarge-mnli': ( 'https://huggingface.co/microsoft/deberta-v2-xlarge-mnli/resolve/main/config.json' ), 'microsoft/deberta-v2-xxlarge-mnli': ( 'https://huggingface.co/microsoft/deberta-v2-xxlarge-mnli/resolve/main/config.json' ), } class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = """deberta-v2""" def __init__( self : Optional[Any] , UpperCamelCase__ : Any=12_8100 , UpperCamelCase__ : Optional[int]=1536 , UpperCamelCase__ : Dict=24 , UpperCamelCase__ : List[str]=24 , UpperCamelCase__ : Tuple=6144 , UpperCamelCase__ : List[Any]="gelu" , UpperCamelCase__ : Optional[int]=0.1 , UpperCamelCase__ : List[str]=0.1 , UpperCamelCase__ : Optional[int]=512 , UpperCamelCase__ : Optional[Any]=0 , UpperCamelCase__ : Union[str, Any]=0.02 , UpperCamelCase__ : List[Any]=1E-7 , UpperCamelCase__ : List[str]=False , UpperCamelCase__ : str=-1 , UpperCamelCase__ : List[Any]=0 , UpperCamelCase__ : List[Any]=True , UpperCamelCase__ : Optional[Any]=None , UpperCamelCase__ : Tuple=0 , UpperCamelCase__ : str="gelu" , **UpperCamelCase__ : Optional[int] , ): '''simple docstring''' super().__init__(**UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[Any] = hidden_size SCREAMING_SNAKE_CASE : int = num_hidden_layers SCREAMING_SNAKE_CASE : Union[str, Any] = num_attention_heads SCREAMING_SNAKE_CASE : List[Any] = intermediate_size SCREAMING_SNAKE_CASE : Any = hidden_act SCREAMING_SNAKE_CASE : Dict = hidden_dropout_prob SCREAMING_SNAKE_CASE : Optional[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : str = max_position_embeddings SCREAMING_SNAKE_CASE : Dict = type_vocab_size SCREAMING_SNAKE_CASE : str = initializer_range SCREAMING_SNAKE_CASE : Optional[Any] = relative_attention SCREAMING_SNAKE_CASE : Optional[Any] = max_relative_positions SCREAMING_SNAKE_CASE : Optional[int] = pad_token_id SCREAMING_SNAKE_CASE : Optional[Any] = position_biased_input # Backwards compatibility if type(UpperCamelCase__ ) == str: SCREAMING_SNAKE_CASE : Optional[int] = [x.strip() for x in pos_att_type.lower().split('''|''' )] SCREAMING_SNAKE_CASE : Any = pos_att_type SCREAMING_SNAKE_CASE : int = vocab_size SCREAMING_SNAKE_CASE : Dict = layer_norm_eps SCREAMING_SNAKE_CASE : Tuple = kwargs.get('''pooler_hidden_size''' , UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Any = pooler_dropout SCREAMING_SNAKE_CASE : Union[str, Any] = pooler_hidden_act class lowercase__ ( UpperCamelCase_): @property def __A ( self : Union[str, Any] ): '''simple docstring''' if self.task == "multiple-choice": SCREAMING_SNAKE_CASE : Optional[int] = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: SCREAMING_SNAKE_CASE : Optional[Any] = {0: '''batch''', 1: '''sequence'''} if self._config.type_vocab_size > 0: return OrderedDict( [('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ('''token_type_ids''', dynamic_axis)] ) else: return OrderedDict([('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis)] ) @property def __A ( self : Union[str, Any] ): '''simple docstring''' return 12 def __A ( self : Dict , UpperCamelCase__ : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , UpperCamelCase__ : int = -1 , UpperCamelCase__ : int = -1 , UpperCamelCase__ : int = -1 , UpperCamelCase__ : bool = False , UpperCamelCase__ : Optional["TensorType"] = None , UpperCamelCase__ : int = 3 , UpperCamelCase__ : int = 40 , UpperCamelCase__ : int = 40 , UpperCamelCase__ : "PreTrainedTokenizerBase" = None , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = super().generate_dummy_inputs(preprocessor=UpperCamelCase__ , framework=UpperCamelCase__ ) if self._config.type_vocab_size == 0 and "token_type_ids" in dummy_inputs: del dummy_inputs["token_type_ids"] return dummy_inputs
34
0
import copy from typing import Any, Dict, List, Optional, Union import numpy as np import torch from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import TensorType, logging __UpperCamelCase : List[Any] = logging.get_logger(__name__) class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = ["input_features", "is_longer"] def __init__( self : Union[str, Any] , UpperCamelCase__ : int=64 , UpperCamelCase__ : int=4_8000 , UpperCamelCase__ : int=480 , UpperCamelCase__ : List[Any]=10 , UpperCamelCase__ : Dict=1024 , UpperCamelCase__ : Tuple=0.0 , UpperCamelCase__ : Dict=False , UpperCamelCase__ : float = 0 , UpperCamelCase__ : float = 1_4000 , UpperCamelCase__ : int = None , UpperCamelCase__ : str = "fusion" , UpperCamelCase__ : str = "repeatpad" , **UpperCamelCase__ : str , ): '''simple docstring''' super().__init__( feature_size=UpperCamelCase__ , sampling_rate=UpperCamelCase__ , padding_value=UpperCamelCase__ , return_attention_mask=UpperCamelCase__ , **UpperCamelCase__ , ) SCREAMING_SNAKE_CASE : str = top_db SCREAMING_SNAKE_CASE : Optional[Any] = truncation SCREAMING_SNAKE_CASE : List[Any] = padding SCREAMING_SNAKE_CASE : Any = fft_window_size SCREAMING_SNAKE_CASE : Tuple = (fft_window_size >> 1) + 1 SCREAMING_SNAKE_CASE : int = hop_length SCREAMING_SNAKE_CASE : str = max_length_s SCREAMING_SNAKE_CASE : Tuple = max_length_s * sampling_rate SCREAMING_SNAKE_CASE : Dict = sampling_rate SCREAMING_SNAKE_CASE : List[str] = frequency_min SCREAMING_SNAKE_CASE : Optional[int] = frequency_max SCREAMING_SNAKE_CASE : Optional[Any] = mel_filter_bank( num_frequency_bins=self.nb_frequency_bins , num_mel_filters=UpperCamelCase__ , min_frequency=UpperCamelCase__ , max_frequency=UpperCamelCase__ , sampling_rate=UpperCamelCase__ , norm=UpperCamelCase__ , mel_scale='''htk''' , ) SCREAMING_SNAKE_CASE : List[str] = mel_filter_bank( num_frequency_bins=self.nb_frequency_bins , num_mel_filters=UpperCamelCase__ , min_frequency=UpperCamelCase__ , max_frequency=UpperCamelCase__ , sampling_rate=UpperCamelCase__ , norm='''slaney''' , mel_scale='''slaney''' , ) def __A ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE : Optional[Any] = self.__class__.__name__ if "mel_filters" in output: del output["mel_filters"] if "mel_filters_slaney" in output: del output["mel_filters_slaney"] return output def __A ( self : List[str] , UpperCamelCase__ : np.array , UpperCamelCase__ : Optional[np.array] = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = spectrogram( UpperCamelCase__ , window_function(self.fft_window_size , '''hann''' ) , frame_length=self.fft_window_size , hop_length=self.hop_length , power=2.0 , mel_filters=UpperCamelCase__ , log_mel='''dB''' , ) return log_mel_spectrogram.T def __A ( self : Union[str, Any] , UpperCamelCase__ : Tuple , UpperCamelCase__ : List[str] , UpperCamelCase__ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = np.array_split(list(range(0 , total_frames - chunk_frames + 1 ) ) , 3 ) if len(ranges[1] ) == 0: # if the audio is too short, we just use the first chunk SCREAMING_SNAKE_CASE : str = [0] if len(ranges[2] ) == 0: # if the audio is too short, we just use the first chunk SCREAMING_SNAKE_CASE : Any = [0] # randomly choose index for each part SCREAMING_SNAKE_CASE : Dict = np.random.choice(ranges[0] ) SCREAMING_SNAKE_CASE : Optional[int] = np.random.choice(ranges[1] ) SCREAMING_SNAKE_CASE : Any = np.random.choice(ranges[2] ) SCREAMING_SNAKE_CASE : List[str] = mel[idx_front : idx_front + chunk_frames, :] SCREAMING_SNAKE_CASE : Tuple = mel[idx_middle : idx_middle + chunk_frames, :] SCREAMING_SNAKE_CASE : Tuple = mel[idx_back : idx_back + chunk_frames, :] SCREAMING_SNAKE_CASE : str = torch.tensor(mel[None, None, :] ) SCREAMING_SNAKE_CASE : Optional[int] = torch.nn.functional.interpolate( UpperCamelCase__ , size=[chunk_frames, 64] , mode='''bilinear''' , align_corners=UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[int] = mel_shrink[0][0].numpy() SCREAMING_SNAKE_CASE : Union[str, Any] = np.stack([mel_shrink, mel_chunk_front, mel_chunk_middle, mel_chunk_back] , axis=0 ) return mel_fusion def __A ( self : List[Any] , UpperCamelCase__ : np.array , UpperCamelCase__ : List[str] , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : Any ): '''simple docstring''' if waveform.shape[0] > max_length: if truncation == "rand_trunc": SCREAMING_SNAKE_CASE : Tuple = True # random crop to max_length (for compatibility) -> this should be handled by self.pad SCREAMING_SNAKE_CASE : int = len(UpperCamelCase__ ) - max_length SCREAMING_SNAKE_CASE : Union[str, Any] = np.random.randint(0 , overflow + 1 ) SCREAMING_SNAKE_CASE : List[str] = waveform[idx : idx + max_length] SCREAMING_SNAKE_CASE : str = self._np_extract_fbank_features(UpperCamelCase__ , self.mel_filters_slaney )[None, :] elif truncation == "fusion": SCREAMING_SNAKE_CASE : Optional[Any] = self._np_extract_fbank_features(UpperCamelCase__ , self.mel_filters ) SCREAMING_SNAKE_CASE : Optional[int] = max_length // self.hop_length + 1 # the +1 related to how the spectrogram is computed SCREAMING_SNAKE_CASE : Optional[int] = mel.shape[0] if chunk_frames == total_frames: # there is a corner case where the audio length is larger than max_length but smaller than max_length+hop_length. # In this case, we just use the whole audio. SCREAMING_SNAKE_CASE : Union[str, Any] = np.stack([mel, mel, mel, mel] , axis=0 ) SCREAMING_SNAKE_CASE : List[str] = False else: SCREAMING_SNAKE_CASE : Dict = self._random_mel_fusion(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[Any] = True else: raise NotImplementedError(f"""data_truncating {truncation} not implemented""" ) else: SCREAMING_SNAKE_CASE : Tuple = False # only use repeat as a new possible value for padding. you repeat the audio before applying the usual max_length padding if waveform.shape[0] < max_length: if padding == "repeat": SCREAMING_SNAKE_CASE : List[Any] = int(max_length / len(UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE : str = np.stack(np.tile(UpperCamelCase__ , n_repeat + 1 ) )[:max_length] if padding == "repeatpad": SCREAMING_SNAKE_CASE : List[str] = int(max_length / len(UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE : Optional[int] = np.stack(np.tile(UpperCamelCase__ , UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE : str = np.pad(UpperCamelCase__ , (0, max_length - waveform.shape[0]) , mode='''constant''' , constant_values=0 ) if truncation == "fusion": SCREAMING_SNAKE_CASE : Dict = self._np_extract_fbank_features(UpperCamelCase__ , self.mel_filters ) SCREAMING_SNAKE_CASE : Union[str, Any] = np.stack([input_mel, input_mel, input_mel, input_mel] , axis=0 ) else: SCREAMING_SNAKE_CASE : Optional[Any] = self._np_extract_fbank_features(UpperCamelCase__ , self.mel_filters_slaney )[None, :] return input_mel, longer def __call__( self : List[str] , UpperCamelCase__ : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , UpperCamelCase__ : str = None , UpperCamelCase__ : Optional[str] = None , UpperCamelCase__ : Optional[int] = None , UpperCamelCase__ : Optional[int] = None , UpperCamelCase__ : Optional[Union[str, TensorType]] = None , **UpperCamelCase__ : str , ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = truncation if truncation is not None else self.truncation SCREAMING_SNAKE_CASE : Union[str, Any] = padding if padding else self.padding if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f"""The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a""" f""" sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input""" f""" was sampled with {self.sampling_rate} and not {sampling_rate}.""" ) else: logger.warning( '''It is strongly recommended to pass the `sampling_rate` argument to this function. ''' '''Failing to do so can result in silent errors that might be hard to debug.''' ) SCREAMING_SNAKE_CASE : Union[str, Any] = isinstance(UpperCamelCase__ , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f"""Only mono-channel audio is supported for input to {self}""" ) SCREAMING_SNAKE_CASE : Dict = is_batched_numpy or ( isinstance(UpperCamelCase__ , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: SCREAMING_SNAKE_CASE : Union[str, Any] = [np.asarray(UpperCamelCase__ , dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(UpperCamelCase__ , np.ndarray ): SCREAMING_SNAKE_CASE : int = np.asarray(UpperCamelCase__ , dtype=np.floataa ) elif isinstance(UpperCamelCase__ , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): SCREAMING_SNAKE_CASE : Optional[int] = raw_speech.astype(np.floataa ) # always return batch if not is_batched: SCREAMING_SNAKE_CASE : Optional[int] = [np.asarray(UpperCamelCase__ )] # convert to mel spectrogram, truncate and pad if needed. SCREAMING_SNAKE_CASE : Tuple = [ self._get_input_mel(UpperCamelCase__ , max_length if max_length else self.nb_max_samples , UpperCamelCase__ , UpperCamelCase__ ) for waveform in raw_speech ] SCREAMING_SNAKE_CASE : List[str] = [] SCREAMING_SNAKE_CASE : Any = [] for mel, longer in padded_inputs: input_mel.append(UpperCamelCase__ ) is_longer.append(UpperCamelCase__ ) if truncation == "fusion" and sum(UpperCamelCase__ ) == 0: # if no audio is longer than 10s, then randomly select one audio to be longer SCREAMING_SNAKE_CASE : Any = np.random.randint(0 , len(UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE : List[str] = True if isinstance(input_mel[0] , UpperCamelCase__ ): SCREAMING_SNAKE_CASE : Any = [np.asarray(UpperCamelCase__ , dtype=np.floataa ) for feature in input_mel] # is_longer is a list of bool SCREAMING_SNAKE_CASE : int = [[longer] for longer in is_longer] SCREAMING_SNAKE_CASE : Union[str, Any] = {'''input_features''': input_mel, '''is_longer''': is_longer} SCREAMING_SNAKE_CASE : Optional[Any] = BatchFeature(UpperCamelCase__ ) if return_tensors is not None: SCREAMING_SNAKE_CASE : Any = input_features.convert_to_tensors(UpperCamelCase__ ) return input_features
705
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from timm import create_model from timm.data import resolve_data_config from timm.data.transforms_factory import create_transform from transformers import BitConfig, BitForImageClassification, BitImageProcessor from transformers.image_utils import PILImageResampling from transformers.utils import logging logging.set_verbosity_info() __UpperCamelCase : str = logging.get_logger(__name__) def A ( _lowercase ): SCREAMING_SNAKE_CASE : Any = '''huggingface/label-files''' SCREAMING_SNAKE_CASE : Any = '''imagenet-1k-id2label.json''' SCREAMING_SNAKE_CASE : Any = json.load(open(hf_hub_download(_lowercase , _lowercase , repo_type='''dataset''' ) , '''r''' ) ) SCREAMING_SNAKE_CASE : Union[str, Any] = {int(_lowercase ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE : Dict = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE : str = '''std_conv''' if '''bit''' in model_name else False # note that when using BiT as backbone for ViT-hybrid checkpoints, # one needs to additionally set config.layer_type = "bottleneck", config.stem_type = "same", # config.conv_layer = "std_conv_same" SCREAMING_SNAKE_CASE : Optional[int] = BitConfig( conv_layer=_lowercase , num_labels=1_000 , idalabel=_lowercase , labelaid=_lowercase , ) return config def A ( _lowercase ): if "stem.conv" in name: SCREAMING_SNAKE_CASE : Optional[int] = name.replace('''stem.conv''' , '''bit.embedder.convolution''' ) if "blocks" in name: SCREAMING_SNAKE_CASE : Tuple = name.replace('''blocks''' , '''layers''' ) if "head.fc" in name: SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace('''head.fc''' , '''classifier.1''' ) if name.startswith('''norm''' ): SCREAMING_SNAKE_CASE : str = '''bit.''' + name if "bit" not in name and "classifier" not in name: SCREAMING_SNAKE_CASE : Union[str, Any] = '''bit.encoder.''' + name return name def A ( ): SCREAMING_SNAKE_CASE : Any = '''http://images.cocodataset.org/val2017/000000039769.jpg''' SCREAMING_SNAKE_CASE : List[str] = Image.open(requests.get(_lowercase , stream=_lowercase ).raw ) return im @torch.no_grad() def A ( _lowercase , _lowercase , _lowercase=False ): SCREAMING_SNAKE_CASE : List[Any] = get_config(_lowercase ) # load original model from timm SCREAMING_SNAKE_CASE : Optional[Any] = create_model(_lowercase , pretrained=_lowercase ) timm_model.eval() # load state_dict of original model SCREAMING_SNAKE_CASE : Optional[int] = timm_model.state_dict() for key in state_dict.copy().keys(): SCREAMING_SNAKE_CASE : Dict = state_dict.pop(_lowercase ) SCREAMING_SNAKE_CASE : Optional[int] = val.squeeze() if '''head''' in key else val # load HuggingFace model SCREAMING_SNAKE_CASE : str = BitForImageClassification(_lowercase ) model.eval() model.load_state_dict(_lowercase ) # create image processor SCREAMING_SNAKE_CASE : Optional[Any] = create_transform(**resolve_data_config({} , model=_lowercase ) ) SCREAMING_SNAKE_CASE : List[str] = transform.transforms SCREAMING_SNAKE_CASE : Union[str, Any] = { '''bilinear''': PILImageResampling.BILINEAR, '''bicubic''': PILImageResampling.BICUBIC, '''nearest''': PILImageResampling.NEAREST, } SCREAMING_SNAKE_CASE : Tuple = BitImageProcessor( do_resize=_lowercase , size={'''shortest_edge''': timm_transforms[0].size} , resample=pillow_resamplings[timm_transforms[0].interpolation.value] , do_center_crop=_lowercase , crop_size={'''height''': timm_transforms[1].size[0], '''width''': timm_transforms[1].size[1]} , do_normalize=_lowercase , image_mean=timm_transforms[-1].mean.tolist() , image_std=timm_transforms[-1].std.tolist() , ) SCREAMING_SNAKE_CASE : Any = prepare_img() SCREAMING_SNAKE_CASE : Union[str, Any] = transform(_lowercase ).unsqueeze(0 ) SCREAMING_SNAKE_CASE : Optional[int] = processor(_lowercase , return_tensors='''pt''' ).pixel_values # verify pixel values assert torch.allclose(_lowercase , _lowercase ) # verify logits with torch.no_grad(): SCREAMING_SNAKE_CASE : Dict = model(_lowercase ) SCREAMING_SNAKE_CASE : Optional[Any] = outputs.logits print('''Logits:''' , logits[0, :3] ) print('''Predicted class:''' , model.config.idalabel[logits.argmax(-1 ).item()] ) SCREAMING_SNAKE_CASE : List[Any] = timm_model(_lowercase ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(_lowercase , outputs.logits , atol=1e-3 ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: Path(_lowercase ).mkdir(exist_ok=_lowercase ) print(f"""Saving model {model_name} and processor to {pytorch_dump_folder_path}""" ) model.save_pretrained(_lowercase ) processor.save_pretrained(_lowercase ) if push_to_hub: print(f"""Pushing model {model_name} and processor to the hub""" ) model.push_to_hub(f"""ybelkada/{model_name}""" ) processor.push_to_hub(f"""ybelkada/{model_name}""" ) if __name__ == "__main__": __UpperCamelCase : Any = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='resnetv2_50x1_bitm', type=str, help='Name of the BiT 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.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether to push the model to the hub.', ) __UpperCamelCase : Optional[int] = parser.parse_args() convert_bit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
34
0
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ViTConfig, ViTForImageClassification, ViTImageProcessor, ViTModel from transformers.utils import logging logging.set_verbosity_info() __UpperCamelCase : Optional[int] = logging.get_logger(__name__) def A ( _lowercase , _lowercase=False ): SCREAMING_SNAKE_CASE : Union[str, Any] = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f"""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'''), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" SCREAMING_SNAKE_CASE : List[str] = [(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 A ( _lowercase , _lowercase , _lowercase=False ): for i in range(config.num_hidden_layers ): if base_model: SCREAMING_SNAKE_CASE : Union[str, Any] = "" else: SCREAMING_SNAKE_CASE : Union[str, Any] = "vit." # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) SCREAMING_SNAKE_CASE : Any = state_dict.pop(f"""blocks.{i}.attn.qkv.weight""" ) SCREAMING_SNAKE_CASE : List[str] = state_dict.pop(f"""blocks.{i}.attn.qkv.bias""" ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE : List[Any] = in_proj_weight[ : config.hidden_size, : ] SCREAMING_SNAKE_CASE : Tuple = in_proj_bias[: config.hidden_size] SCREAMING_SNAKE_CASE : Any = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] SCREAMING_SNAKE_CASE : Optional[int] = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] SCREAMING_SNAKE_CASE : Dict = in_proj_weight[ -config.hidden_size :, : ] SCREAMING_SNAKE_CASE : Any = in_proj_bias[-config.hidden_size :] def A ( _lowercase ): SCREAMING_SNAKE_CASE : Optional[int] = ["head.weight", "head.bias"] for k in ignore_keys: state_dict.pop(lowercase_ , lowercase_ ) def A ( _lowercase , _lowercase , _lowercase ): SCREAMING_SNAKE_CASE : Dict = dct.pop(lowercase_ ) SCREAMING_SNAKE_CASE : List[str] = val def A ( ): SCREAMING_SNAKE_CASE : Union[str, Any] = "http://images.cocodataset.org/val2017/000000039769.jpg" SCREAMING_SNAKE_CASE : Any = Image.open(requests.get(lowercase_ , stream=lowercase_ ).raw ) return im @torch.no_grad() def A ( _lowercase , _lowercase , _lowercase=True ): SCREAMING_SNAKE_CASE : Union[str, Any] = ViTConfig() # patch_size if model_name[-1] == "8": SCREAMING_SNAKE_CASE : List[Any] = 8 # set labels if required if not base_model: SCREAMING_SNAKE_CASE : Tuple = 1_000 SCREAMING_SNAKE_CASE : Union[str, Any] = "huggingface/label-files" SCREAMING_SNAKE_CASE : Optional[Any] = "imagenet-1k-id2label.json" SCREAMING_SNAKE_CASE : int = json.load(open(hf_hub_download(lowercase_ , lowercase_ , repo_type='''dataset''' ) , '''r''' ) ) SCREAMING_SNAKE_CASE : int = {int(lowercase_ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE : int = idalabel SCREAMING_SNAKE_CASE : List[str] = {v: k for k, v in idalabel.items()} # size of the architecture if model_name in ["dino_vits8", "dino_vits16"]: SCREAMING_SNAKE_CASE : Dict = 384 SCREAMING_SNAKE_CASE : Any = 1_536 SCREAMING_SNAKE_CASE : List[Any] = 12 SCREAMING_SNAKE_CASE : Union[str, Any] = 6 # load original model from torch hub SCREAMING_SNAKE_CASE : List[str] = torch.hub.load('''facebookresearch/dino:main''' , lowercase_ ) original_model.eval() # load state_dict of original model, remove and rename some keys SCREAMING_SNAKE_CASE : int = original_model.state_dict() if base_model: remove_classification_head_(lowercase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = create_rename_keys(lowercase_ , base_model=lowercase_ ) for src, dest in rename_keys: rename_key(lowercase_ , lowercase_ , lowercase_ ) read_in_q_k_v(lowercase_ , lowercase_ , lowercase_ ) # load HuggingFace model if base_model: SCREAMING_SNAKE_CASE : Dict = ViTModel(lowercase_ , add_pooling_layer=lowercase_ ).eval() else: SCREAMING_SNAKE_CASE : List[str] = ViTForImageClassification(lowercase_ ).eval() model.load_state_dict(lowercase_ ) # Check outputs on an image, prepared by ViTImageProcessor SCREAMING_SNAKE_CASE : Tuple = ViTImageProcessor() SCREAMING_SNAKE_CASE : str = image_processor(images=prepare_img() , return_tensors='''pt''' ) SCREAMING_SNAKE_CASE : str = encoding["pixel_values"] SCREAMING_SNAKE_CASE : Union[str, Any] = model(lowercase_ ) if base_model: SCREAMING_SNAKE_CASE : Union[str, Any] = original_model(lowercase_ ) assert torch.allclose(lowercase_ , outputs.last_hidden_state[:, 0, :] , atol=1e-1 ) else: SCREAMING_SNAKE_CASE : str = original_model(lowercase_ ) assert logits.shape == outputs.logits.shape assert torch.allclose(lowercase_ , outputs.logits , atol=1e-3 ) Path(lowercase_ ).mkdir(exist_ok=lowercase_ ) print(f"""Saving model {model_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__": __UpperCamelCase : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='dino_vitb16', type=str, help='Name of the model trained with DINO 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( '--base_model', action='store_true', help='Whether to only convert the base model (no projection head weights).', ) parser.set_defaults(base_model=True) __UpperCamelCase : Optional[Any] = parser.parse_args() convert_vit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.base_model)
706
import argparse import json import logging import os import sys from unittest.mock import patch from transformers.testing_utils import TestCasePlus, get_gpu_count, slow __UpperCamelCase : str = [ os.path.join(os.path.dirname(__file__), dirname) for dirname in [ 'text-classification', 'language-modeling', 'summarization', 'token-classification', 'question-answering', ] ] sys.path.extend(SRC_DIRS) if SRC_DIRS is not None: import run_clm_flax import run_flax_glue import run_flax_ner import run_mlm_flax import run_qa import run_summarization_flax import run_ta_mlm_flax logging.basicConfig(level=logging.DEBUG) __UpperCamelCase : int = logging.getLogger() def A ( ): SCREAMING_SNAKE_CASE : str = argparse.ArgumentParser() parser.add_argument('''-f''' ) SCREAMING_SNAKE_CASE : List[str] = parser.parse_args() return args.f def A ( _lowercase , _lowercase="eval" ): SCREAMING_SNAKE_CASE : Dict = os.path.join(_lowercase , f"""{split}_results.json""" ) if os.path.exists(_lowercase ): with open(_lowercase , '''r''' ) as f: return json.load(_lowercase ) raise ValueError(f"""can't find {path}""" ) __UpperCamelCase : Optional[Any] = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class lowercase__ ( UpperCamelCase_): def __A ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE : Tuple = f""" run_glue.py --model_name_or_path distilbert-base-uncased --output_dir {tmp_dir} --train_file ./tests/fixtures/tests_samples/MRPC/train.csv --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --learning_rate=1e-4 --eval_steps=2 --warmup_steps=2 --seed=42 --max_seq_length=128 """.split() with patch.object(UpperCamelCase__ , '''argv''' , UpperCamelCase__ ): run_flax_glue.main() SCREAMING_SNAKE_CASE : Union[str, Any] = get_results(UpperCamelCase__ ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 ) @slow def __A ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE : str = f""" run_clm_flax.py --model_name_or_path distilgpt2 --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --do_train --do_eval --block_size 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --num_train_epochs 2 --logging_steps 2 --eval_steps 2 --output_dir {tmp_dir} --overwrite_output_dir """.split() with patch.object(UpperCamelCase__ , '''argv''' , UpperCamelCase__ ): run_clm_flax.main() SCREAMING_SNAKE_CASE : Dict = get_results(UpperCamelCase__ ) self.assertLess(result['''eval_perplexity'''] , 100 ) @slow def __A ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE : Union[str, Any] = f""" run_summarization.py --model_name_or_path t5-small --train_file tests/fixtures/tests_samples/xsum/sample.json --validation_file tests/fixtures/tests_samples/xsum/sample.json --test_file tests/fixtures/tests_samples/xsum/sample.json --output_dir {tmp_dir} --overwrite_output_dir --num_train_epochs=3 --warmup_steps=8 --do_train --do_eval --do_predict --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --predict_with_generate """.split() with patch.object(UpperCamelCase__ , '''argv''' , UpperCamelCase__ ): run_summarization_flax.main() SCREAMING_SNAKE_CASE : Union[str, Any] = get_results(UpperCamelCase__ , split='''test''' ) self.assertGreaterEqual(result['''test_rouge1'''] , 10 ) self.assertGreaterEqual(result['''test_rouge2'''] , 2 ) self.assertGreaterEqual(result['''test_rougeL'''] , 7 ) self.assertGreaterEqual(result['''test_rougeLsum'''] , 7 ) @slow def __A ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE : Dict = f""" run_mlm.py --model_name_or_path distilroberta-base --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --output_dir {tmp_dir} --overwrite_output_dir --max_seq_length 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --logging_steps 2 --eval_steps 2 --do_train --do_eval --num_train_epochs=1 """.split() with patch.object(UpperCamelCase__ , '''argv''' , UpperCamelCase__ ): run_mlm_flax.main() SCREAMING_SNAKE_CASE : List[Any] = get_results(UpperCamelCase__ ) self.assertLess(result['''eval_perplexity'''] , 42 ) @slow def __A ( self : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE : Union[str, Any] = f""" run_t5_mlm_flax.py --model_name_or_path t5-small --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --do_train --do_eval --max_seq_length 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --num_train_epochs 2 --logging_steps 2 --eval_steps 2 --output_dir {tmp_dir} --overwrite_output_dir """.split() with patch.object(UpperCamelCase__ , '''argv''' , UpperCamelCase__ ): run_ta_mlm_flax.main() SCREAMING_SNAKE_CASE : Optional[int] = get_results(UpperCamelCase__ ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.42 ) @slow def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = 7 if get_gpu_count() > 1 else 2 SCREAMING_SNAKE_CASE : Dict = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE : Any = f""" run_flax_ner.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/conll/sample.json --validation_file tests/fixtures/tests_samples/conll/sample.json --output_dir {tmp_dir} --overwrite_output_dir --do_train --do_eval --warmup_steps=2 --learning_rate=2e-4 --logging_steps 2 --eval_steps 2 --per_device_train_batch_size=2 --per_device_eval_batch_size=2 --num_train_epochs={epochs} --seed 7 """.split() with patch.object(UpperCamelCase__ , '''argv''' , UpperCamelCase__ ): run_flax_ner.main() SCREAMING_SNAKE_CASE : List[str] = get_results(UpperCamelCase__ ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 ) self.assertGreaterEqual(result['''eval_f1'''] , 0.3 ) @slow def __A ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE : Union[str, Any] = f""" run_qa.py --model_name_or_path bert-base-uncased --version_2_with_negative --train_file tests/fixtures/tests_samples/SQUAD/sample.json --validation_file tests/fixtures/tests_samples/SQUAD/sample.json --output_dir {tmp_dir} --overwrite_output_dir --num_train_epochs=3 --warmup_steps=2 --do_train --do_eval --logging_steps 2 --eval_steps 2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 """.split() with patch.object(UpperCamelCase__ , '''argv''' , UpperCamelCase__ ): run_qa.main() SCREAMING_SNAKE_CASE : str = get_results(UpperCamelCase__ ) self.assertGreaterEqual(result['''eval_f1'''] , 30 ) self.assertGreaterEqual(result['''eval_exact'''] , 30 )
34
0
from __future__ import annotations import os import tempfile import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import is_tensorflow_text_available, is_tf_available from transformers.testing_utils import require_tensorflow_text, require_tf, slow from ..test_modeling_tf_common import floats_tensor from .test_framework_agnostic import GenerationIntegrationTestsMixin if is_tf_available(): import tensorflow as tf from transformers import ( AutoTokenizer, TFAutoModelForCausalLM, TFAutoModelForSeqaSeqLM, TFAutoModelForSpeechSeqaSeq, TFAutoModelForVisionaSeq, TFBartForConditionalGeneration, TFLogitsProcessorList, TFMinLengthLogitsProcessor, tf_top_k_top_p_filtering, ) if is_tensorflow_text_available(): import tensorflow_text as text @require_tf class lowercase__ ( unittest.TestCase): def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = tf.convert_to_tensor( [ [ 8.222_0991, # 3rd highest value; idx. 0 -0.562_0044, 5.2322_9752, 4.038_6393, -6.879_8378, -0.5478_5802, -3.201_2153, 2.9277_7176, 1.8817_1953, 7.3534_1276, # 5th highest value; idx. 9 8.4320_7833, # 2nd highest value; idx. 10 -9.8571_1836, -5.9620_9236, -1.1303_9161, -7.111_5294, -0.836_9633, -5.318_6408, 7.0642_7407, 0.8136_9344, -0.8202_3817, -5.917_9796, 0.5881_3443, -6.9977_8438, 4.7155_1189, -0.1877_1637, 7.4402_0759, # 4th highest value; idx. 25 9.3845_0987, # 1st highest value; idx. 26 2.1266_2941, -9.3256_2038, 2.3565_2522, ], # cummulative prob of 5 highest values <= 0.6 [ 0.5842_5518, 4.5313_9238, -5.5751_0464, -6.2803_0699, -7.1952_9503, -4.0212_2551, 1.3933_7037, -6.0670_7057, 1.5948_0517, -9.64_3119, 0.0390_7799, 0.6723_1762, -8.8820_6726, 6.2711_5922, # 4th highest value; idx. 13 2.2852_0723, 4.8276_7506, 4.3042_1368, 8.827_5313, # 2nd highest value; idx. 17 5.4402_9958, # 5th highest value; idx. 18 -4.473_5794, 7.3857_9536, # 3rd highest value; idx. 20 -2.9105_1663, 2.6194_6077, -2.567_4762, -9.4895_9302, -4.0292_2645, -1.3541_6918, 9.6770_2323, # 1st highest value; idx. 27 -5.8947_8553, 1.8537_0467, ], # cummulative prob of 5 highest values <= 0.6 ] , dtype=tf.floataa , ) SCREAMING_SNAKE_CASE : Optional[int] = tf.convert_to_tensor( [[0, 0], [0, 9], [0, 10], [0, 25], [0, 26], [1, 13], [1, 17], [1, 18], [1, 20], [1, 27]] , dtype=tf.intaa , ) # expected non filtered idx as noted above SCREAMING_SNAKE_CASE : Optional[Any] = tf.convert_to_tensor( [8.22_2099, 7.353_4126, 8.43_2078, 7.440_2075, 9.3_8451, 6.27_1159, 8.82_7531, 5.440_2995, 7.385_7956, 9.67_7023] , dtype=tf.floataa , ) # expected non filtered values as noted above SCREAMING_SNAKE_CASE : List[str] = tf_top_k_top_p_filtering(_snake_case , top_k=10 , top_p=0.6 , min_tokens_to_keep=4 ) SCREAMING_SNAKE_CASE : Tuple = output[output != -float('''inf''' )] SCREAMING_SNAKE_CASE : Optional[int] = tf.cast( tf.where(tf.not_equal(_snake_case , tf.constant(-float('''inf''' ) , dtype=tf.floataa ) ) ) , dtype=tf.intaa , ) tf.debugging.assert_near(_snake_case , _snake_case , rtol=1E-12 ) tf.debugging.assert_equal(_snake_case , _snake_case ) @require_tf class lowercase__ ( unittest.TestCase , UpperCAmelCase_): if is_tf_available(): UpperCamelCase_ = { "AutoModelForCausalLM": TFAutoModelForCausalLM, "AutoModelForSpeechSeq2Seq": TFAutoModelForSpeechSeqaSeq, "AutoModelForSeq2SeqLM": TFAutoModelForSeqaSeqLM, "AutoModelForVision2Seq": TFAutoModelForVisionaSeq, "LogitsProcessorList": TFLogitsProcessorList, "MinLengthLogitsProcessor": TFMinLengthLogitsProcessor, "create_tensor_fn": tf.convert_to_tensor, "floats_tensor": floats_tensor, "return_tensors": "tf", } @slow def __A ( self : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = TFAutoModelForCausalLM.from_pretrained('''hf-internal-testing/tiny-random-gpt2''' ) SCREAMING_SNAKE_CASE : Tuple = 2 SCREAMING_SNAKE_CASE : List[str] = 2 class lowercase__ ( tf.Module): def __init__( self : Any , UpperCamelCase__ : str ): '''simple docstring''' super(_snake_case , self ).__init__() SCREAMING_SNAKE_CASE : Any = model @tf.function( input_signature=( tf.TensorSpec((None, input_length) , tf.intaa , name='''input_ids''' ), tf.TensorSpec((None, input_length) , tf.intaa , name='''attention_mask''' ), ) , jit_compile=_snake_case , ) def __A ( self : Optional[int] , UpperCamelCase__ : Dict , UpperCamelCase__ : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = self.model.generate( input_ids=_snake_case , attention_mask=_snake_case , max_new_tokens=_snake_case , return_dict_in_generate=_snake_case , ) return {"sequences": outputs["sequences"]} SCREAMING_SNAKE_CASE : Dict = [[2, 0], [102, 103]] SCREAMING_SNAKE_CASE : Tuple = [[1, 0], [1, 1]] SCREAMING_SNAKE_CASE : List[str] = DummyModel(model=_snake_case ) with tempfile.TemporaryDirectory() as tmp_dir: tf.saved_model.save(_snake_case , _snake_case , signatures={'''serving_default''': dummy_model.serving} ) SCREAMING_SNAKE_CASE : List[str] = tf.saved_model.load(_snake_case ).signatures['''serving_default'''] for batch_size in range(1 , len(_snake_case ) + 1 ): SCREAMING_SNAKE_CASE : List[Any] = { '''input_ids''': tf.constant(dummy_input_ids[:batch_size] ), '''attention_mask''': tf.constant(dummy_attention_masks[:batch_size] ), } SCREAMING_SNAKE_CASE : Optional[Any] = serving_func(**_snake_case )['''sequences'''] SCREAMING_SNAKE_CASE : List[str] = test_model.generate(**_snake_case , max_new_tokens=_snake_case ) tf.debugging.assert_equal(_snake_case , _snake_case ) @slow def __A ( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = TFAutoModelForCausalLM.from_pretrained('''hf-internal-testing/tiny-random-gpt2''' ) SCREAMING_SNAKE_CASE : List[Any] = 1 SCREAMING_SNAKE_CASE : Union[str, Any] = 2 class lowercase__ ( tf.Module): def __init__( self : Optional[int] , UpperCamelCase__ : Tuple ): '''simple docstring''' super(_snake_case , self ).__init__() SCREAMING_SNAKE_CASE : int = model @tf.function( input_signature=( tf.TensorSpec((batch_size, None) , tf.intaa , name='''input_ids''' ), tf.TensorSpec((batch_size, None) , tf.intaa , name='''attention_mask''' ), ) , jit_compile=_snake_case , ) def __A ( self : Tuple , UpperCamelCase__ : Any , UpperCamelCase__ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = self.model.generate( input_ids=_snake_case , attention_mask=_snake_case , max_new_tokens=_snake_case , return_dict_in_generate=_snake_case , ) return {"sequences": outputs["sequences"]} SCREAMING_SNAKE_CASE : Any = [[2], [102, 103]] SCREAMING_SNAKE_CASE : Any = [[1], [1, 1]] SCREAMING_SNAKE_CASE : Dict = DummyModel(model=_snake_case ) with tempfile.TemporaryDirectory() as tmp_dir: tf.saved_model.save(_snake_case , _snake_case , signatures={'''serving_default''': dummy_model.serving} ) SCREAMING_SNAKE_CASE : Dict = tf.saved_model.load(_snake_case ).signatures['''serving_default'''] for input_row in range(len(_snake_case ) ): SCREAMING_SNAKE_CASE : Optional[Any] = { '''input_ids''': tf.constant([dummy_input_ids[input_row]] ), '''attention_mask''': tf.constant([dummy_attention_masks[input_row]] ), } SCREAMING_SNAKE_CASE : Optional[int] = serving_func(**_snake_case )['''sequences'''] SCREAMING_SNAKE_CASE : Optional[Any] = test_model.generate(**_snake_case , max_new_tokens=_snake_case ) tf.debugging.assert_equal(_snake_case , _snake_case ) @slow @require_tensorflow_text def __A ( self : Optional[Any] ): '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: # file needed to load the TF tokenizer hf_hub_download(repo_id='''google/flan-t5-small''' , filename='''spiece.model''' , local_dir=_snake_case ) class lowercase__ ( tf.keras.layers.Layer): def __init__( self : Dict ): '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE : List[Any] = text.SentencepieceTokenizer( model=tf.io.gfile.GFile(os.path.join(_snake_case , '''spiece.model''' ) , '''rb''' ).read() ) SCREAMING_SNAKE_CASE : Optional[int] = TFAutoModelForSeqaSeqLM.from_pretrained('''hf-internal-testing/tiny-random-t5''' ) def __A ( self : Any , UpperCamelCase__ : Tuple , *UpperCamelCase__ : Optional[Any] , **UpperCamelCase__ : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = self.tokenizer.tokenize(_snake_case ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = text.pad_model_inputs( _snake_case , max_seq_length=64 , pad_value=self.model.config.pad_token_id ) SCREAMING_SNAKE_CASE : Dict = self.model.generate(input_ids=_snake_case , attention_mask=_snake_case ) return self.tokenizer.detokenize(_snake_case ) SCREAMING_SNAKE_CASE : Optional[Any] = CompleteSentenceTransformer() SCREAMING_SNAKE_CASE : List[Any] = tf.keras.layers.Input(shape=(1,) , dtype=tf.string , name='''inputs''' ) SCREAMING_SNAKE_CASE : List[Any] = complete_model(_snake_case ) SCREAMING_SNAKE_CASE : Optional[int] = tf.keras.Model(_snake_case , _snake_case ) keras_model.save(_snake_case ) def __A ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = { '''do_sample''': True, '''num_beams''': 1, '''top_p''': 0.7, '''top_k''': 10, '''temperature''': 0.7, } SCREAMING_SNAKE_CASE : Optional[int] = 14 SCREAMING_SNAKE_CASE : int = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-gpt2''' ) SCREAMING_SNAKE_CASE : Tuple = '''Hello, my dog is cute and''' SCREAMING_SNAKE_CASE : int = tokenizer(_snake_case , return_tensors='''tf''' ) SCREAMING_SNAKE_CASE : List[str] = TFAutoModelForCausalLM.from_pretrained('''hf-internal-testing/tiny-random-gpt2''' ) SCREAMING_SNAKE_CASE : Dict = 638 # forces the generation to happen on CPU, to avoid GPU-related quirks with tf.device(''':/CPU:0''' ): tf.random.set_seed(0 ) SCREAMING_SNAKE_CASE : List[str] = model.generate(**_snake_case , eos_token_id=_snake_case , **_snake_case ) self.assertTrue(expectation == len(generated_tokens[0] ) ) SCREAMING_SNAKE_CASE : List[Any] = [638, 198] with tf.device(''':/CPU:0''' ): tf.random.set_seed(0 ) SCREAMING_SNAKE_CASE : Optional[int] = model.generate(**_snake_case , eos_token_id=_snake_case , **_snake_case ) self.assertTrue(expectation == len(generated_tokens[0] ) ) def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-bart''' ) SCREAMING_SNAKE_CASE : str = '''Hugging Face is a technology company based in New York and Paris.''' SCREAMING_SNAKE_CASE : int = bart_tokenizer(_snake_case , return_tensors='''tf''' ).input_ids SCREAMING_SNAKE_CASE : str = TFBartForConditionalGeneration.from_pretrained('''hf-internal-testing/tiny-random-bart''' ) SCREAMING_SNAKE_CASE : str = bart_model.generate(_snake_case ).numpy() class lowercase__ ( UpperCAmelCase_): def __A ( self : List[str] , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Dict=None , **UpperCamelCase__ : int ): '''simple docstring''' return super().call(_snake_case , **_snake_case ) SCREAMING_SNAKE_CASE : Any = FakeBart.from_pretrained('''hf-internal-testing/tiny-random-bart''' ) SCREAMING_SNAKE_CASE : Union[str, Any] = bart_model.generate(_snake_case , foo='''bar''' ).numpy() self.assertTrue(np.array_equal(_snake_case , _snake_case ) ) class lowercase__ ( bart_model.model.encoder.__class__): def __A ( self : str , UpperCamelCase__ : Tuple , **UpperCamelCase__ : str ): '''simple docstring''' return super().call(_snake_case , **_snake_case ) SCREAMING_SNAKE_CASE : Optional[int] = FakeEncoder(bart_model.config , bart_model.model.shared ) SCREAMING_SNAKE_CASE : Dict = fake_encoder # Normal generation still works (the output will be different because the encoder weights are different) SCREAMING_SNAKE_CASE : str = bart_model.generate(_snake_case ).numpy() with self.assertRaises(_snake_case ): # FakeEncoder.call() accepts **kwargs -> no filtering -> value error due to unexpected input "foo" bart_model.generate(_snake_case , foo='''bar''' )
707
import itertools import os import random import tempfile import unittest import numpy as np from transformers import TvltFeatureExtractor, is_datasets_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_torch_available(): import torch if is_datasets_available(): from datasets import load_dataset __UpperCamelCase : Dict = random.Random() def A ( _lowercase , _lowercase=1.0 , _lowercase=None , _lowercase=None ): if rng is None: SCREAMING_SNAKE_CASE : Any = global_rng SCREAMING_SNAKE_CASE : int = [] 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 : List[Any] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : str=7 , UpperCamelCase__ : Any=400 , UpperCamelCase__ : List[str]=2000 , UpperCamelCase__ : List[Any]=2048 , UpperCamelCase__ : Any=128 , UpperCamelCase__ : Union[str, Any]=1 , UpperCamelCase__ : List[Any]=512 , UpperCamelCase__ : str=30 , UpperCamelCase__ : Tuple=4_4100 , ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = parent SCREAMING_SNAKE_CASE : str = batch_size SCREAMING_SNAKE_CASE : str = min_seq_length SCREAMING_SNAKE_CASE : Dict = max_seq_length SCREAMING_SNAKE_CASE : Optional[int] = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) SCREAMING_SNAKE_CASE : Optional[Any] = spectrogram_length SCREAMING_SNAKE_CASE : Optional[int] = feature_size SCREAMING_SNAKE_CASE : Tuple = num_audio_channels SCREAMING_SNAKE_CASE : Union[str, Any] = hop_length SCREAMING_SNAKE_CASE : List[Any] = chunk_length SCREAMING_SNAKE_CASE : str = sampling_rate def __A ( self : Optional[Any] ): '''simple docstring''' return { "spectrogram_length": self.spectrogram_length, "feature_size": self.feature_size, "num_audio_channels": self.num_audio_channels, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "sampling_rate": self.sampling_rate, } def __A ( self : Tuple , UpperCamelCase__ : List[str]=False , UpperCamelCase__ : Optional[int]=False ): '''simple docstring''' def _flatten(UpperCamelCase__ : str ): return list(itertools.chain(*UpperCamelCase__ ) ) if equal_length: SCREAMING_SNAKE_CASE : List[str] = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE : int = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE : Optional[Any] = [np.asarray(UpperCamelCase__ ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class lowercase__ ( UpperCamelCase_ , unittest.TestCase): UpperCamelCase_ = TvltFeatureExtractor def __A ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = TvltFeatureExtractionTester(self ) def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = self.feature_extraction_class(**self.feat_extract_dict ) self.assertTrue(hasattr(UpperCamelCase__ , '''spectrogram_length''' ) ) self.assertTrue(hasattr(UpperCamelCase__ , '''feature_size''' ) ) self.assertTrue(hasattr(UpperCamelCase__ , '''num_audio_channels''' ) ) self.assertTrue(hasattr(UpperCamelCase__ , '''hop_length''' ) ) self.assertTrue(hasattr(UpperCamelCase__ , '''chunk_length''' ) ) self.assertTrue(hasattr(UpperCamelCase__ , '''sampling_rate''' ) ) def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE : Optional[Any] = feat_extract_first.save_pretrained(UpperCamelCase__ )[0] check_json_file_has_correct_format(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[Any] = self.feature_extraction_class.from_pretrained(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[Any] = feat_extract_first.to_dict() SCREAMING_SNAKE_CASE : str = feat_extract_second.to_dict() SCREAMING_SNAKE_CASE : Optional[int] = dict_first.pop('''mel_filters''' ) SCREAMING_SNAKE_CASE : Optional[int] = dict_second.pop('''mel_filters''' ) self.assertTrue(np.allclose(UpperCamelCase__ , UpperCamelCase__ ) ) self.assertEqual(UpperCamelCase__ , UpperCamelCase__ ) def __A ( self : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE : Tuple = os.path.join(UpperCamelCase__ , '''feat_extract.json''' ) feat_extract_first.to_json_file(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[str] = self.feature_extraction_class.from_json_file(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Any = feat_extract_first.to_dict() SCREAMING_SNAKE_CASE : str = feat_extract_second.to_dict() SCREAMING_SNAKE_CASE : int = dict_first.pop('''mel_filters''' ) SCREAMING_SNAKE_CASE : Any = dict_second.pop('''mel_filters''' ) self.assertTrue(np.allclose(UpperCamelCase__ , UpperCamelCase__ ) ) self.assertEqual(UpperCamelCase__ , UpperCamelCase__ ) def __A ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = self.feature_extraction_class(**self.feat_extract_dict ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE : List[Any] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE : Optional[int] = [np.asarray(UpperCamelCase__ ) for speech_input in speech_inputs] # Test not batched input SCREAMING_SNAKE_CASE : List[Any] = feature_extractor(np_speech_inputs[0] , return_tensors='''np''' , sampling_rate=4_4100 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test batched SCREAMING_SNAKE_CASE : Optional[Any] = feature_extractor(UpperCamelCase__ , return_tensors='''np''' , sampling_rate=4_4100 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test audio masking SCREAMING_SNAKE_CASE : List[str] = feature_extractor( UpperCamelCase__ , return_tensors='''np''' , sampling_rate=4_4100 , mask_audio=UpperCamelCase__ ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test 2-D numpy arrays are batched. SCREAMING_SNAKE_CASE : Optional[Any] = [floats_list((1, x) )[0] for x in (800, 800, 800)] SCREAMING_SNAKE_CASE : Dict = np.asarray(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : str = feature_extractor(UpperCamelCase__ , return_tensors='''np''' , sampling_rate=4_4100 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) def __A ( self : Optional[int] , UpperCamelCase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = load_dataset('''hf-internal-testing/librispeech_asr_dummy''' , '''clean''' , split='''validation''' ) # automatic decoding with librispeech SCREAMING_SNAKE_CASE : Dict = ds.sort('''id''' ).select(range(UpperCamelCase__ ) )[:num_samples]['''audio'''] return [x["array"] for x in speech_samples] def __A ( self : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE : int = TvltFeatureExtractor() SCREAMING_SNAKE_CASE : List[Any] = feature_extractor(UpperCamelCase__ , return_tensors='''pt''' ).audio_values self.assertEquals(audio_values.shape , (1, 1, 192, 128) ) SCREAMING_SNAKE_CASE : str = torch.tensor([[-0.3032, -0.2708], [-0.4434, -0.4007]] ) self.assertTrue(torch.allclose(audio_values[0, 0, :2, :2] , UpperCamelCase__ , atol=1E-4 ) )
34
0
import json import os import unittest from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES, BioGptTokenizer from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class lowercase__ ( _lowerCAmelCase , unittest.TestCase): UpperCamelCase_ = BioGptTokenizer UpperCamelCase_ = False def __A ( self : List[str] ): '''simple docstring''' super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt SCREAMING_SNAKE_CASE : Union[str, Any] = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''w</w>''', '''r</w>''', '''t</w>''', '''lo''', '''low''', '''er</w>''', '''low</w>''', '''lowest</w>''', '''newer</w>''', '''wider</w>''', '''<unk>''', ] SCREAMING_SNAKE_CASE : List[Any] = dict(zip(_lowerCAmelCase , range(len(_lowerCAmelCase ) ) ) ) SCREAMING_SNAKE_CASE : Any = ['''l o 123''', '''lo w 1456''', '''e r</w> 1789''', ''''''] SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) SCREAMING_SNAKE_CASE : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' ) as fp: fp.write(json.dumps(_lowerCAmelCase ) ) with open(self.merges_file , '''w''' ) as fp: fp.write('''\n'''.join(_lowerCAmelCase ) ) def __A ( self : List[str] , UpperCamelCase__ : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = '''lower newer''' SCREAMING_SNAKE_CASE : Optional[int] = '''lower newer''' return input_text, output_text def __A ( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = BioGptTokenizer(self.vocab_file , self.merges_file ) SCREAMING_SNAKE_CASE : Dict = '''lower''' SCREAMING_SNAKE_CASE : Optional[Any] = ['''low''', '''er</w>'''] SCREAMING_SNAKE_CASE : Tuple = tokenizer.tokenize(_lowerCAmelCase ) self.assertListEqual(_lowerCAmelCase , _lowerCAmelCase ) SCREAMING_SNAKE_CASE : List[str] = tokens + ['''<unk>'''] SCREAMING_SNAKE_CASE : List[str] = [14, 15, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(_lowerCAmelCase ) , _lowerCAmelCase ) @slow def __A ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = BioGptTokenizer.from_pretrained('''microsoft/biogpt''' ) SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer.encode('''sequence builders''' , add_special_tokens=_lowerCAmelCase ) SCREAMING_SNAKE_CASE : List[Any] = tokenizer.encode('''multi-sequence build''' , add_special_tokens=_lowerCAmelCase ) SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer.build_inputs_with_special_tokens(_lowerCAmelCase ) SCREAMING_SNAKE_CASE : int = tokenizer.build_inputs_with_special_tokens(_lowerCAmelCase , _lowerCAmelCase ) self.assertTrue(encoded_sentence == [2] + text ) self.assertTrue(encoded_pair == [2] + text + [2] + text_a )
708
import math from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import SchedulerMixin, SchedulerOutput class lowercase__ ( UpperCamelCase_ , UpperCamelCase_): UpperCamelCase_ = 1 @register_to_config def __init__( self : List[str] , UpperCamelCase__ : int = 1000 , UpperCamelCase__ : Optional[Union[np.ndarray, List[float]]] = None ): '''simple docstring''' self.set_timesteps(UpperCamelCase__ ) # standard deviation of the initial noise distribution SCREAMING_SNAKE_CASE : str = 1.0 # For now we only support F-PNDM, i.e. the runge-kutta method # For more information on the algorithm please take a look at the paper: https://arxiv.org/pdf/2202.09778.pdf # mainly at formula (9), (12), (13) and the Algorithm 2. SCREAMING_SNAKE_CASE : Tuple = 4 # running values SCREAMING_SNAKE_CASE : int = [] def __A ( self : Dict , UpperCamelCase__ : int , UpperCamelCase__ : Union[str, torch.device] = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = num_inference_steps SCREAMING_SNAKE_CASE : Union[str, Any] = torch.linspace(1 , 0 , num_inference_steps + 1 )[:-1] SCREAMING_SNAKE_CASE : Tuple = torch.cat([steps, torch.tensor([0.0] )] ) if self.config.trained_betas is not None: SCREAMING_SNAKE_CASE : int = torch.tensor(self.config.trained_betas , dtype=torch.floataa ) else: SCREAMING_SNAKE_CASE : Optional[Any] = torch.sin(steps * math.pi / 2 ) ** 2 SCREAMING_SNAKE_CASE : Dict = (1.0 - self.betas**2) ** 0.5 SCREAMING_SNAKE_CASE : Optional[Any] = (torch.atana(self.betas , self.alphas ) / math.pi * 2)[:-1] SCREAMING_SNAKE_CASE : List[str] = timesteps.to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Any = [] def __A ( self : Tuple , UpperCamelCase__ : torch.FloatTensor , UpperCamelCase__ : int , UpperCamelCase__ : torch.FloatTensor , UpperCamelCase__ : bool = True , ): '''simple docstring''' if self.num_inference_steps is None: raise ValueError( '''Number of inference steps is \'None\', you need to run \'set_timesteps\' after creating the scheduler''' ) SCREAMING_SNAKE_CASE : Optional[int] = (self.timesteps == timestep).nonzero().item() SCREAMING_SNAKE_CASE : Union[str, Any] = timestep_index + 1 SCREAMING_SNAKE_CASE : int = sample * self.betas[timestep_index] + model_output * self.alphas[timestep_index] self.ets.append(UpperCamelCase__ ) if len(self.ets ) == 1: SCREAMING_SNAKE_CASE : Dict = self.ets[-1] elif len(self.ets ) == 2: SCREAMING_SNAKE_CASE : Optional[int] = (3 * self.ets[-1] - self.ets[-2]) / 2 elif len(self.ets ) == 3: SCREAMING_SNAKE_CASE : str = (23 * self.ets[-1] - 16 * self.ets[-2] + 5 * self.ets[-3]) / 12 else: SCREAMING_SNAKE_CASE : Optional[Any] = (1 / 24) * (55 * self.ets[-1] - 59 * self.ets[-2] + 37 * self.ets[-3] - 9 * self.ets[-4]) SCREAMING_SNAKE_CASE : Optional[int] = self._get_prev_sample(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=UpperCamelCase__ ) def __A ( self : Optional[Any] , UpperCamelCase__ : torch.FloatTensor , *UpperCamelCase__ : List[str] , **UpperCamelCase__ : Optional[Any] ): '''simple docstring''' return sample def __A ( self : Union[str, Any] , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Any , UpperCamelCase__ : Tuple , UpperCamelCase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = self.alphas[timestep_index] SCREAMING_SNAKE_CASE : List[str] = self.betas[timestep_index] SCREAMING_SNAKE_CASE : Union[str, Any] = self.alphas[prev_timestep_index] SCREAMING_SNAKE_CASE : Tuple = self.betas[prev_timestep_index] SCREAMING_SNAKE_CASE : Dict = (sample - sigma * ets) / max(UpperCamelCase__ , 1E-8 ) SCREAMING_SNAKE_CASE : Optional[Any] = next_alpha * pred + ets * next_sigma return prev_sample def __len__( self : int ): '''simple docstring''' return self.config.num_train_timesteps
34
0
from typing import Optional, Union import torch from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention from ...modeling_utils import PreTrainedModel from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging from .configuration_mobilenet_va import MobileNetVaConfig __UpperCamelCase : List[str] = logging.get_logger(__name__) # General docstring __UpperCamelCase : Dict = 'MobileNetV1Config' # Base docstring __UpperCamelCase : Tuple = 'google/mobilenet_v1_1.0_224' __UpperCamelCase : Dict = [1, 1024, 7, 7] # Image classification docstring __UpperCamelCase : int = 'google/mobilenet_v1_1.0_224' __UpperCamelCase : List[str] = 'tabby, tabby cat' __UpperCamelCase : Tuple = [ 'google/mobilenet_v1_1.0_224', 'google/mobilenet_v1_0.75_192', # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1 ] def A ( _lowercase , _lowercase , _lowercase=None ): SCREAMING_SNAKE_CASE : Optional[int] = {} if isinstance(snake_case_ , snake_case_ ): SCREAMING_SNAKE_CASE : str = model.mobilenet_va else: SCREAMING_SNAKE_CASE : Any = model SCREAMING_SNAKE_CASE : List[str] = """MobilenetV1/Conv2d_0/""" SCREAMING_SNAKE_CASE : Dict = backbone.conv_stem.convolution.weight SCREAMING_SNAKE_CASE : Tuple = backbone.conv_stem.normalization.bias SCREAMING_SNAKE_CASE : int = backbone.conv_stem.normalization.weight SCREAMING_SNAKE_CASE : int = backbone.conv_stem.normalization.running_mean SCREAMING_SNAKE_CASE : Tuple = backbone.conv_stem.normalization.running_var for i in range(13 ): SCREAMING_SNAKE_CASE : Union[str, Any] = i + 1 SCREAMING_SNAKE_CASE : Tuple = i * 2 SCREAMING_SNAKE_CASE : int = backbone.layer[pt_index] SCREAMING_SNAKE_CASE : List[str] = f"""MobilenetV1/Conv2d_{tf_index}_depthwise/""" SCREAMING_SNAKE_CASE : Optional[int] = pointer.convolution.weight SCREAMING_SNAKE_CASE : int = pointer.normalization.bias SCREAMING_SNAKE_CASE : int = pointer.normalization.weight SCREAMING_SNAKE_CASE : Tuple = pointer.normalization.running_mean SCREAMING_SNAKE_CASE : Any = pointer.normalization.running_var SCREAMING_SNAKE_CASE : List[str] = backbone.layer[pt_index + 1] SCREAMING_SNAKE_CASE : Union[str, Any] = f"""MobilenetV1/Conv2d_{tf_index}_pointwise/""" SCREAMING_SNAKE_CASE : Optional[int] = pointer.convolution.weight SCREAMING_SNAKE_CASE : List[str] = pointer.normalization.bias SCREAMING_SNAKE_CASE : Dict = pointer.normalization.weight SCREAMING_SNAKE_CASE : List[str] = pointer.normalization.running_mean SCREAMING_SNAKE_CASE : str = pointer.normalization.running_var if isinstance(snake_case_ , snake_case_ ): SCREAMING_SNAKE_CASE : str = """MobilenetV1/Logits/Conv2d_1c_1x1/""" SCREAMING_SNAKE_CASE : Dict = model.classifier.weight SCREAMING_SNAKE_CASE : Optional[Any] = model.classifier.bias return tf_to_pt_map def A ( _lowercase , _lowercase , _lowercase ): try: import numpy as np import tensorflow as tf except ImportError: logger.error( '''Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see ''' '''https://www.tensorflow.org/install/ for installation instructions.''' ) raise # Load weights from TF model SCREAMING_SNAKE_CASE : Optional[Any] = tf.train.list_variables(snake_case_ ) SCREAMING_SNAKE_CASE : List[str] = {} for name, shape in init_vars: logger.info(f"""Loading TF weight {name} with shape {shape}""" ) SCREAMING_SNAKE_CASE : List[Any] = tf.train.load_variable(snake_case_ , snake_case_ ) SCREAMING_SNAKE_CASE : Tuple = array # Build TF to PyTorch weights loading map SCREAMING_SNAKE_CASE : Any = _build_tf_to_pytorch_map(snake_case_ , snake_case_ , snake_case_ ) for name, pointer in tf_to_pt_map.items(): logger.info(f"""Importing {name}""" ) if name not in tf_weights: logger.info(f"""{name} not in tf pre-trained weights, skipping""" ) continue SCREAMING_SNAKE_CASE : Tuple = tf_weights[name] if "depthwise_weights" in name: logger.info('''Transposing depthwise''' ) SCREAMING_SNAKE_CASE : Optional[int] = np.transpose(snake_case_ , (2, 3, 0, 1) ) elif "weights" in name: logger.info('''Transposing''' ) if len(pointer.shape ) == 2: # copying into linear layer SCREAMING_SNAKE_CASE : Any = array.squeeze().transpose() else: SCREAMING_SNAKE_CASE : Optional[int] = np.transpose(snake_case_ , (3, 2, 0, 1) ) if pointer.shape != array.shape: raise ValueError(f"""Pointer shape {pointer.shape} and array shape {array.shape} mismatched""" ) logger.info(f"""Initialize PyTorch weight {name} {array.shape}""" ) SCREAMING_SNAKE_CASE : Optional[int] = torch.from_numpy(snake_case_ ) tf_weights.pop(snake_case_ , snake_case_ ) tf_weights.pop(name + '''/RMSProp''' , snake_case_ ) tf_weights.pop(name + '''/RMSProp_1''' , snake_case_ ) tf_weights.pop(name + '''/ExponentialMovingAverage''' , snake_case_ ) logger.info(f"""Weights not copied to PyTorch model: {', '.join(tf_weights.keys() )}""" ) return model def A ( _lowercase , _lowercase ): SCREAMING_SNAKE_CASE : Tuple = features.shape[-2:] SCREAMING_SNAKE_CASE : Any = conv_layer.stride SCREAMING_SNAKE_CASE : Dict = conv_layer.kernel_size if in_height % stride_height == 0: SCREAMING_SNAKE_CASE : Tuple = max(kernel_height - stride_height , 0 ) else: SCREAMING_SNAKE_CASE : Dict = max(kernel_height - (in_height % stride_height) , 0 ) if in_width % stride_width == 0: SCREAMING_SNAKE_CASE : Any = max(kernel_width - stride_width , 0 ) else: SCREAMING_SNAKE_CASE : Tuple = max(kernel_width - (in_width % stride_width) , 0 ) SCREAMING_SNAKE_CASE : Dict = pad_along_width // 2 SCREAMING_SNAKE_CASE : Any = pad_along_width - pad_left SCREAMING_SNAKE_CASE : Optional[int] = pad_along_height // 2 SCREAMING_SNAKE_CASE : Tuple = pad_along_height - pad_top SCREAMING_SNAKE_CASE : List[str] = (pad_left, pad_right, pad_top, pad_bottom) return nn.functional.pad(snake_case_ , snake_case_ , '''constant''' , 0.0 ) class lowercase__ ( nn.Module): def __init__( self : Any , UpperCamelCase__ : List[str] , UpperCamelCase__ : str , UpperCamelCase__ : List[Any] , UpperCamelCase__ : int , UpperCamelCase__ : Tuple = 1 , UpperCamelCase__ : List[str] = 1 , UpperCamelCase__ : List[Any] = False , UpperCamelCase__ : str = True , UpperCamelCase__ : Optional[Any] = True , ): '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE : List[Any] = config if in_channels % groups != 0: raise ValueError(f"""Input channels ({in_channels}) are not divisible by {groups} groups.""" ) if out_channels % groups != 0: raise ValueError(f"""Output channels ({out_channels}) are not divisible by {groups} groups.""" ) SCREAMING_SNAKE_CASE : Tuple = 0 if config.tf_padding else int((kernel_size - 1) / 2 ) SCREAMING_SNAKE_CASE : List[str] = nn.Convad( in_channels=_a , out_channels=_a , kernel_size=_a , stride=_a , padding=_a , groups=_a , bias=_a , padding_mode='''zeros''' , ) if use_normalization: SCREAMING_SNAKE_CASE : Union[str, Any] = nn.BatchNormad( num_features=_a , eps=config.layer_norm_eps , momentum=0.9997 , affine=_a , track_running_stats=_a , ) else: SCREAMING_SNAKE_CASE : Optional[int] = None if use_activation: if isinstance(_a , _a ): SCREAMING_SNAKE_CASE : List[str] = ACTaFN[use_activation] elif isinstance(config.hidden_act , _a ): SCREAMING_SNAKE_CASE : List[str] = ACTaFN[config.hidden_act] else: SCREAMING_SNAKE_CASE : Optional[int] = config.hidden_act else: SCREAMING_SNAKE_CASE : Tuple = None def __A ( self : int , UpperCamelCase__ : Dict ): '''simple docstring''' if self.config.tf_padding: SCREAMING_SNAKE_CASE : Tuple = apply_tf_padding(_a , self.convolution ) SCREAMING_SNAKE_CASE : Tuple = self.convolution(_a ) if self.normalization is not None: SCREAMING_SNAKE_CASE : Dict = self.normalization(_a ) if self.activation is not None: SCREAMING_SNAKE_CASE : str = self.activation(_a ) return features class lowercase__ ( UpperCamelCase__): UpperCamelCase_ = MobileNetVaConfig UpperCamelCase_ = load_tf_weights_in_mobilenet_va UpperCamelCase_ = """mobilenet_v1""" UpperCamelCase_ = """pixel_values""" UpperCamelCase_ = False def __A ( self : List[str] , UpperCamelCase__ : List[str] ): '''simple docstring''' if isinstance(_a , (nn.Linear, nn.Convad) ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() elif isinstance(_a , nn.BatchNormad ): module.bias.data.zero_() module.weight.data.fill_(1.0 ) __UpperCamelCase : Optional[int] = R'\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it\n as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n\n Parameters:\n config ([`MobileNetV1Config`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n' __UpperCamelCase : Optional[int] = R'\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`MobileNetV1ImageProcessor.__call__`] for details.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n' @add_start_docstrings( """The bare MobileNetV1 model outputting raw hidden-states without any specific head on top.""" , UpperCamelCase__ , ) class lowercase__ ( UpperCamelCase__): def __init__( self : Dict , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : Optional[int] = True ): '''simple docstring''' super().__init__(_a ) SCREAMING_SNAKE_CASE : Any = config SCREAMING_SNAKE_CASE : Optional[int] = 32 SCREAMING_SNAKE_CASE : str = max(int(depth * config.depth_multiplier ) , config.min_depth ) SCREAMING_SNAKE_CASE : List[Any] = MobileNetVaConvLayer( _a , in_channels=config.num_channels , out_channels=_a , kernel_size=3 , stride=2 , ) SCREAMING_SNAKE_CASE : Dict = [1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1] SCREAMING_SNAKE_CASE : Union[str, Any] = nn.ModuleList() for i in range(13 ): SCREAMING_SNAKE_CASE : int = out_channels if strides[i] == 2 or i == 0: depth *= 2 SCREAMING_SNAKE_CASE : int = max(int(depth * config.depth_multiplier ) , config.min_depth ) self.layer.append( MobileNetVaConvLayer( _a , in_channels=_a , out_channels=_a , kernel_size=3 , stride=strides[i] , groups=_a , ) ) self.layer.append( MobileNetVaConvLayer( _a , in_channels=_a , out_channels=_a , kernel_size=1 , ) ) SCREAMING_SNAKE_CASE : Union[str, Any] = nn.AdaptiveAvgPoolad((1, 1) ) if add_pooling_layer else None # Initialize weights and apply final processing self.post_init() def __A ( self : str , UpperCamelCase__ : Dict ): '''simple docstring''' raise NotImplementedError @add_start_docstrings_to_model_forward(_a ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=_a , config_class=_CONFIG_FOR_DOC , modality='''vision''' , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def __A ( self : Any , UpperCamelCase__ : str = None , UpperCamelCase__ : Union[str, Any] = None , UpperCamelCase__ : str = None , ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) SCREAMING_SNAKE_CASE : Optional[Any] = return_dict if return_dict is not None else self.config.use_return_dict if pixel_values is None: raise ValueError('''You have to specify pixel_values''' ) SCREAMING_SNAKE_CASE : str = self.conv_stem(_a ) SCREAMING_SNAKE_CASE : int = () if output_hidden_states else None for i, layer_module in enumerate(self.layer ): SCREAMING_SNAKE_CASE : str = layer_module(_a ) if output_hidden_states: SCREAMING_SNAKE_CASE : Optional[Any] = all_hidden_states + (hidden_states,) SCREAMING_SNAKE_CASE : Optional[int] = hidden_states if self.pooler is not None: SCREAMING_SNAKE_CASE : int = torch.flatten(self.pooler(_a ) , start_dim=1 ) else: SCREAMING_SNAKE_CASE : Dict = None if not return_dict: return tuple(v for v in [last_hidden_state, pooled_output, all_hidden_states] if v is not None ) return BaseModelOutputWithPoolingAndNoAttention( last_hidden_state=_a , pooler_output=_a , hidden_states=_a , ) @add_start_docstrings( """\n MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n """ , UpperCamelCase__ , ) class lowercase__ ( UpperCamelCase__): def __init__( self : Dict , UpperCamelCase__ : List[Any] ): '''simple docstring''' super().__init__(_a ) SCREAMING_SNAKE_CASE : Optional[Any] = config.num_labels SCREAMING_SNAKE_CASE : Union[str, Any] = MobileNetVaModel(_a ) SCREAMING_SNAKE_CASE : List[str] = self.mobilenet_va.layer[-1].convolution.out_channels # Classifier head SCREAMING_SNAKE_CASE : List[Any] = nn.Dropout(config.classifier_dropout_prob , inplace=_a ) SCREAMING_SNAKE_CASE : Optional[Any] = nn.Linear(_a , config.num_labels ) if config.num_labels > 0 else nn.Identity() # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(_a ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=_a , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def __A ( self : str , UpperCamelCase__ : List[str] = None , UpperCamelCase__ : str = None , UpperCamelCase__ : str = None , UpperCamelCase__ : Dict = None , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = return_dict if return_dict is not None else self.config.use_return_dict SCREAMING_SNAKE_CASE : Tuple = self.mobilenet_va(_a , output_hidden_states=_a , return_dict=_a ) SCREAMING_SNAKE_CASE : List[Any] = outputs.pooler_output if return_dict else outputs[1] SCREAMING_SNAKE_CASE : Any = self.classifier(self.dropout(_a ) ) SCREAMING_SNAKE_CASE : str = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: SCREAMING_SNAKE_CASE : int = """regression""" elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): SCREAMING_SNAKE_CASE : Tuple = """single_label_classification""" else: SCREAMING_SNAKE_CASE : Optional[Any] = """multi_label_classification""" if self.config.problem_type == "regression": SCREAMING_SNAKE_CASE : Any = MSELoss() if self.num_labels == 1: SCREAMING_SNAKE_CASE : List[str] = loss_fct(logits.squeeze() , labels.squeeze() ) else: SCREAMING_SNAKE_CASE : str = loss_fct(_a , _a ) elif self.config.problem_type == "single_label_classification": SCREAMING_SNAKE_CASE : str = CrossEntropyLoss() SCREAMING_SNAKE_CASE : Any = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": SCREAMING_SNAKE_CASE : Tuple = BCEWithLogitsLoss() SCREAMING_SNAKE_CASE : Optional[Any] = loss_fct(_a , _a ) if not return_dict: SCREAMING_SNAKE_CASE : Dict = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention( loss=_a , logits=_a , hidden_states=outputs.hidden_states , )
709
import gc import random import unittest import torch from diffusers import ( IFImgaImgPipeline, IFImgaImgSuperResolutionPipeline, IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline, IFPipeline, IFSuperResolutionPipeline, ) from diffusers.models.attention_processor import AttnAddedKVProcessor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import floats_tensor, load_numpy, require_torch_gpu, skip_mps, slow, torch_device from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference from . import IFPipelineTesterMixin @skip_mps class lowercase__ ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): UpperCamelCase_ = IFPipeline UpperCamelCase_ = TEXT_TO_IMAGE_PARAMS - {"""width""", """height""", """latents"""} UpperCamelCase_ = TEXT_TO_IMAGE_BATCH_PARAMS UpperCamelCase_ = PipelineTesterMixin.required_optional_params - {"""latents"""} def __A ( self : Tuple ): '''simple docstring''' return self._get_dummy_components() def __A ( self : int , UpperCamelCase__ : Dict , UpperCamelCase__ : int=0 ): '''simple docstring''' if str(UpperCamelCase__ ).startswith('''mps''' ): SCREAMING_SNAKE_CASE : Tuple = torch.manual_seed(UpperCamelCase__ ) else: SCREAMING_SNAKE_CASE : Dict = torch.Generator(device=UpperCamelCase__ ).manual_seed(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : int = { '''prompt''': '''A painting of a squirrel eating a burger''', '''generator''': generator, '''num_inference_steps''': 2, '''output_type''': '''numpy''', } return inputs def __A ( self : List[str] ): '''simple docstring''' self._test_save_load_optional_components() @unittest.skipIf(torch_device != '''cuda''' , reason='''float16 requires CUDA''' ) def __A ( self : Any ): '''simple docstring''' super().test_save_load_floataa(expected_max_diff=1E-1 ) def __A ( self : Union[str, Any] ): '''simple docstring''' self._test_attention_slicing_forward_pass(expected_max_diff=1E-2 ) def __A ( self : List[Any] ): '''simple docstring''' self._test_save_load_local() def __A ( self : List[str] ): '''simple docstring''' self._test_inference_batch_single_identical( expected_max_diff=1E-2 , ) @unittest.skipIf( torch_device != '''cuda''' or not is_xformers_available() , reason='''XFormers attention is only available with CUDA and `xformers` installed''' , ) def __A ( self : Tuple ): '''simple docstring''' self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 ) @slow @require_torch_gpu class lowercase__ ( unittest.TestCase): def __A ( self : Optional[Any] ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = IFPipeline.from_pretrained('''DeepFloyd/IF-I-XL-v1.0''' , variant='''fp16''' , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE : str = IFSuperResolutionPipeline.from_pretrained( '''DeepFloyd/IF-II-L-v1.0''' , variant='''fp16''' , torch_dtype=torch.floataa , text_encoder=UpperCamelCase__ , tokenizer=UpperCamelCase__ ) # pre compute text embeddings and remove T5 to save memory pipe_a.text_encoder.to('''cuda''' ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Dict = pipe_a.encode_prompt('''anime turtle''' , device='''cuda''' ) del pipe_a.tokenizer del pipe_a.text_encoder gc.collect() SCREAMING_SNAKE_CASE : Tuple = None SCREAMING_SNAKE_CASE : str = None pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) pipe_a.remove_all_hooks() pipe_a.remove_all_hooks() # img2img SCREAMING_SNAKE_CASE : Optional[int] = IFImgaImgPipeline(**pipe_a.components ) SCREAMING_SNAKE_CASE : Optional[int] = IFImgaImgSuperResolutionPipeline(**pipe_a.components ) pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if_imgaimg(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) pipe_a.remove_all_hooks() pipe_a.remove_all_hooks() # inpainting SCREAMING_SNAKE_CASE : Tuple = IFInpaintingPipeline(**pipe_a.components ) SCREAMING_SNAKE_CASE : Optional[int] = IFInpaintingSuperResolutionPipeline(**pipe_a.components ) pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if_inpainting(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) def __A ( self : Tuple , UpperCamelCase__ : int , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Dict ): '''simple docstring''' _start_torch_memory_measurement() SCREAMING_SNAKE_CASE : List[str] = torch.Generator(device='''cpu''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[Any] = pipe_a( prompt_embeds=UpperCamelCase__ , negative_prompt_embeds=UpperCamelCase__ , num_inference_steps=2 , generator=UpperCamelCase__ , output_type='''np''' , ) SCREAMING_SNAKE_CASE : Optional[int] = output.images[0] assert image.shape == (64, 64, 3) SCREAMING_SNAKE_CASE : Tuple = torch.cuda.max_memory_allocated() assert mem_bytes < 13 * 10**9 SCREAMING_SNAKE_CASE : Optional[Any] = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if.npy''' ) assert_mean_pixel_difference(UpperCamelCase__ , UpperCamelCase__ ) # pipeline 2 _start_torch_memory_measurement() SCREAMING_SNAKE_CASE : Tuple = torch.Generator(device='''cpu''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE : int = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Any = pipe_a( prompt_embeds=UpperCamelCase__ , negative_prompt_embeds=UpperCamelCase__ , image=UpperCamelCase__ , generator=UpperCamelCase__ , num_inference_steps=2 , output_type='''np''' , ) SCREAMING_SNAKE_CASE : Tuple = output.images[0] assert image.shape == (256, 256, 3) SCREAMING_SNAKE_CASE : Union[str, Any] = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 SCREAMING_SNAKE_CASE : int = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_superresolution_stage_II.npy''' ) assert_mean_pixel_difference(UpperCamelCase__ , UpperCamelCase__ ) def __A ( self : Optional[int] , UpperCamelCase__ : str , UpperCamelCase__ : int , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : str ): '''simple docstring''' _start_torch_memory_measurement() SCREAMING_SNAKE_CASE : Tuple = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Any = torch.Generator(device='''cpu''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE : List[Any] = pipe_a( prompt_embeds=UpperCamelCase__ , negative_prompt_embeds=UpperCamelCase__ , image=UpperCamelCase__ , num_inference_steps=2 , generator=UpperCamelCase__ , output_type='''np''' , ) SCREAMING_SNAKE_CASE : int = output.images[0] assert image.shape == (64, 64, 3) SCREAMING_SNAKE_CASE : Optional[int] = torch.cuda.max_memory_allocated() assert mem_bytes < 10 * 10**9 SCREAMING_SNAKE_CASE : Tuple = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img.npy''' ) assert_mean_pixel_difference(UpperCamelCase__ , UpperCamelCase__ ) # pipeline 2 _start_torch_memory_measurement() SCREAMING_SNAKE_CASE : Union[str, Any] = torch.Generator(device='''cpu''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[Any] = floats_tensor((1, 3, 256, 256) , rng=random.Random(0 ) ).to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[Any] = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : str = pipe_a( prompt_embeds=UpperCamelCase__ , negative_prompt_embeds=UpperCamelCase__ , image=UpperCamelCase__ , original_image=UpperCamelCase__ , generator=UpperCamelCase__ , num_inference_steps=2 , output_type='''np''' , ) SCREAMING_SNAKE_CASE : Optional[int] = output.images[0] assert image.shape == (256, 256, 3) SCREAMING_SNAKE_CASE : List[Any] = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 SCREAMING_SNAKE_CASE : Optional[Any] = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img_superresolution_stage_II.npy''' ) assert_mean_pixel_difference(UpperCamelCase__ , UpperCamelCase__ ) def __A ( self : List[str] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Optional[Any] ): '''simple docstring''' _start_torch_memory_measurement() SCREAMING_SNAKE_CASE : str = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Union[str, Any] = floats_tensor((1, 3, 64, 64) , rng=random.Random(1 ) ).to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[int] = torch.Generator(device='''cpu''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE : int = pipe_a( prompt_embeds=UpperCamelCase__ , negative_prompt_embeds=UpperCamelCase__ , image=UpperCamelCase__ , mask_image=UpperCamelCase__ , num_inference_steps=2 , generator=UpperCamelCase__ , output_type='''np''' , ) SCREAMING_SNAKE_CASE : Any = output.images[0] assert image.shape == (64, 64, 3) SCREAMING_SNAKE_CASE : Any = torch.cuda.max_memory_allocated() assert mem_bytes < 10 * 10**9 SCREAMING_SNAKE_CASE : List[Any] = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting.npy''' ) assert_mean_pixel_difference(UpperCamelCase__ , UpperCamelCase__ ) # pipeline 2 _start_torch_memory_measurement() SCREAMING_SNAKE_CASE : str = torch.Generator(device='''cpu''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE : List[str] = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : int = floats_tensor((1, 3, 256, 256) , rng=random.Random(0 ) ).to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[int] = floats_tensor((1, 3, 256, 256) , rng=random.Random(1 ) ).to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Dict = pipe_a( prompt_embeds=UpperCamelCase__ , negative_prompt_embeds=UpperCamelCase__ , image=UpperCamelCase__ , mask_image=UpperCamelCase__ , original_image=UpperCamelCase__ , generator=UpperCamelCase__ , num_inference_steps=2 , output_type='''np''' , ) SCREAMING_SNAKE_CASE : Optional[Any] = output.images[0] assert image.shape == (256, 256, 3) SCREAMING_SNAKE_CASE : Any = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 SCREAMING_SNAKE_CASE : Tuple = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting_superresolution_stage_II.npy''' ) assert_mean_pixel_difference(UpperCamelCase__ , UpperCamelCase__ ) def A ( ): torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats()
34
0
from timeit import timeit def A ( _lowercase ) -> int: if number < 0: raise ValueError('''the value of input must not be negative''' ) SCREAMING_SNAKE_CASE : int = 0 while number: number &= number - 1 result += 1 return result def A ( _lowercase ) -> int: if number < 0: raise ValueError('''the value of input must not be negative''' ) SCREAMING_SNAKE_CASE : Optional[Any] = 0 while number: if number % 2 == 1: result += 1 number >>= 1 return result def A ( ) -> None: def do_benchmark(_lowercase ) -> None: SCREAMING_SNAKE_CASE : List[str] = '''import __main__ as z''' print(f"""Benchmark when {number = }:""" ) print(f"""{get_set_bits_count_using_modulo_operator(__UpperCamelCase ) = }""" ) SCREAMING_SNAKE_CASE : int = timeit('''z.get_set_bits_count_using_modulo_operator(25)''' , setup=__UpperCamelCase ) print(f"""timeit() runs in {timing} seconds""" ) print(f"""{get_set_bits_count_using_brian_kernighans_algorithm(__UpperCamelCase ) = }""" ) SCREAMING_SNAKE_CASE : Any = timeit( '''z.get_set_bits_count_using_brian_kernighans_algorithm(25)''' , setup=__UpperCamelCase , ) print(f"""timeit() runs in {timing} seconds""" ) for number in (25, 37, 58, 0): do_benchmark(__UpperCamelCase ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
710
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 : int = logging.get_logger(__name__) def A ( _lowercase , _lowercase , _lowercase , _lowercase ): def constraint_to_multiple_of(_lowercase , _lowercase , _lowercase=0 , _lowercase=None ): SCREAMING_SNAKE_CASE : int = round(val / multiple ) * multiple if max_val is not None and x > max_val: SCREAMING_SNAKE_CASE : Dict = math.floor(val / multiple ) * multiple if x < min_val: SCREAMING_SNAKE_CASE : Optional[Any] = math.ceil(val / multiple ) * multiple return x SCREAMING_SNAKE_CASE : Optional[Any] = (output_size, output_size) if isinstance(_lowercase , _lowercase ) else output_size SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = get_image_size(_lowercase ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = output_size # determine new height and width SCREAMING_SNAKE_CASE : Dict = output_height / input_height SCREAMING_SNAKE_CASE : Optional[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 SCREAMING_SNAKE_CASE : List[Any] = scale_width else: # fit height SCREAMING_SNAKE_CASE : List[Any] = scale_height SCREAMING_SNAKE_CASE : List[str] = constraint_to_multiple_of(scale_height * input_height , multiple=_lowercase ) SCREAMING_SNAKE_CASE : Optional[int] = constraint_to_multiple_of(scale_width * input_width , multiple=_lowercase ) return (new_height, new_width) class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = ["""pixel_values"""] def __init__( self : int , UpperCamelCase__ : bool = True , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : PILImageResampling = PILImageResampling.BILINEAR , UpperCamelCase__ : bool = False , UpperCamelCase__ : int = 1 , UpperCamelCase__ : bool = True , UpperCamelCase__ : Union[int, float] = 1 / 255 , UpperCamelCase__ : bool = True , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , **UpperCamelCase__ : Optional[int] , ): '''simple docstring''' super().__init__(**UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[str] = size if size is not None else {'''height''': 384, '''width''': 384} SCREAMING_SNAKE_CASE : Any = get_size_dict(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Dict = do_resize SCREAMING_SNAKE_CASE : Any = size SCREAMING_SNAKE_CASE : str = keep_aspect_ratio SCREAMING_SNAKE_CASE : List[str] = ensure_multiple_of SCREAMING_SNAKE_CASE : int = resample SCREAMING_SNAKE_CASE : Any = do_rescale SCREAMING_SNAKE_CASE : List[Any] = rescale_factor SCREAMING_SNAKE_CASE : Optional[int] = do_normalize SCREAMING_SNAKE_CASE : str = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN SCREAMING_SNAKE_CASE : Union[str, Any] = image_std if image_std is not None else IMAGENET_STANDARD_STD def __A ( self : Optional[Any] , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Dict[str, int] , UpperCamelCase__ : bool = False , UpperCamelCase__ : int = 1 , UpperCamelCase__ : PILImageResampling = PILImageResampling.BICUBIC , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : Union[str, Any] , ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = get_size_dict(UpperCamelCase__ ) 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()}""" ) SCREAMING_SNAKE_CASE : Any = get_resize_output_image_size( UpperCamelCase__ , output_size=(size['''height'''], size['''width''']) , keep_aspect_ratio=UpperCamelCase__ , multiple=UpperCamelCase__ , ) return resize(UpperCamelCase__ , size=UpperCamelCase__ , resample=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def __A ( self : Dict , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Union[int, float] , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : str , ): '''simple docstring''' return rescale(UpperCamelCase__ , scale=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def __A ( self : Any , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Union[float, List[float]] , UpperCamelCase__ : Union[float, List[float]] , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : List[str] , ): '''simple docstring''' return normalize(UpperCamelCase__ , mean=UpperCamelCase__ , std=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def __A ( self : Optional[Any] , UpperCamelCase__ : ImageInput , UpperCamelCase__ : bool = None , UpperCamelCase__ : int = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : int = None , UpperCamelCase__ : PILImageResampling = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : float = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : Optional[Union[str, TensorType]] = None , UpperCamelCase__ : ChannelDimension = ChannelDimension.FIRST , **UpperCamelCase__ : Optional[int] , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE : Optional[Any] = size if size is not None else self.size SCREAMING_SNAKE_CASE : Union[str, Any] = get_size_dict(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[Any] = keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio SCREAMING_SNAKE_CASE : List[str] = ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of SCREAMING_SNAKE_CASE : Tuple = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE : Optional[Any] = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE : Union[str, Any] = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE : str = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE : List[Any] = image_mean if image_mean is not None else self.image_mean SCREAMING_SNAKE_CASE : List[Any] = image_std if image_std is not None else self.image_std SCREAMING_SNAKE_CASE : Dict = make_list_of_images(UpperCamelCase__ ) if not valid_images(UpperCamelCase__ ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None or resample is None: raise ValueError('''Size and resample must be specified if do_resize is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('''Image mean and std must be specified if do_normalize is True.''' ) # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE : Tuple = [to_numpy_array(UpperCamelCase__ ) for image in images] if do_resize: SCREAMING_SNAKE_CASE : Dict = [self.resize(image=UpperCamelCase__ , size=UpperCamelCase__ , resample=UpperCamelCase__ ) for image in images] if do_rescale: SCREAMING_SNAKE_CASE : Any = [self.rescale(image=UpperCamelCase__ , scale=UpperCamelCase__ ) for image in images] if do_normalize: SCREAMING_SNAKE_CASE : Any = [self.normalize(image=UpperCamelCase__ , mean=UpperCamelCase__ , std=UpperCamelCase__ ) for image in images] SCREAMING_SNAKE_CASE : Optional[int] = [to_channel_dimension_format(UpperCamelCase__ , UpperCamelCase__ ) for image in images] SCREAMING_SNAKE_CASE : Tuple = {'''pixel_values''': images} return BatchFeature(data=UpperCamelCase__ , tensor_type=UpperCamelCase__ ) def __A ( self : Tuple , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : List[Tuple] = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(UpperCamelCase__ ) != len(UpperCamelCase__ ): raise ValueError( '''Make sure that you pass in as many target sizes as the batch dimension of the logits''' ) if is_torch_tensor(UpperCamelCase__ ): SCREAMING_SNAKE_CASE : List[Any] = target_sizes.numpy() SCREAMING_SNAKE_CASE : Optional[int] = [] for idx in range(len(UpperCamelCase__ ) ): SCREAMING_SNAKE_CASE : List[str] = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode='''bilinear''' , align_corners=UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Dict = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(UpperCamelCase__ ) else: SCREAMING_SNAKE_CASE : List[Any] = logits.argmax(dim=1 ) SCREAMING_SNAKE_CASE : List[Any] = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
34
0
import os import warnings from typing import List, Optional from ...tokenization_utils_base import BatchEncoding from ...utils import logging from .configuration_rag import RagConfig __UpperCamelCase : List[str] = logging.get_logger(__name__) class lowercase__ : def __init__( self : Dict , UpperCamelCase__ : Tuple , UpperCamelCase__ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = question_encoder SCREAMING_SNAKE_CASE : Any = generator SCREAMING_SNAKE_CASE : List[str] = self.question_encoder def __A ( self : str , UpperCamelCase__ : Dict ): '''simple docstring''' if os.path.isfile(_lowerCamelCase ): raise ValueError(f"""Provided path ({save_directory}) should be a directory, not a file""" ) os.makedirs(_lowerCamelCase , exist_ok=_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = os.path.join(_lowerCamelCase , '''question_encoder_tokenizer''' ) SCREAMING_SNAKE_CASE : Any = os.path.join(_lowerCamelCase , '''generator_tokenizer''' ) self.question_encoder.save_pretrained(_lowerCamelCase ) self.generator.save_pretrained(_lowerCamelCase ) @classmethod def __A ( cls : List[str] , UpperCamelCase__ : List[str] , **UpperCamelCase__ : Optional[Any] ): '''simple docstring''' from ..auto.tokenization_auto import AutoTokenizer SCREAMING_SNAKE_CASE : str = kwargs.pop('''config''' , _lowerCamelCase ) if config is None: SCREAMING_SNAKE_CASE : Optional[int] = RagConfig.from_pretrained(_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[str] = AutoTokenizer.from_pretrained( _lowerCamelCase , config=config.question_encoder , subfolder='''question_encoder_tokenizer''' ) SCREAMING_SNAKE_CASE : Dict = AutoTokenizer.from_pretrained( _lowerCamelCase , config=config.generator , subfolder='''generator_tokenizer''' ) return cls(question_encoder=_lowerCamelCase , generator=_lowerCamelCase ) def __call__( self : Optional[int] , *UpperCamelCase__ : Optional[int] , **UpperCamelCase__ : Tuple ): '''simple docstring''' return self.current_tokenizer(*_lowerCamelCase , **_lowerCamelCase ) def __A ( self : Dict , *UpperCamelCase__ : Union[str, Any] , **UpperCamelCase__ : List[Any] ): '''simple docstring''' return self.generator.batch_decode(*_lowerCamelCase , **_lowerCamelCase ) def __A ( self : int , *UpperCamelCase__ : Optional[int] , **UpperCamelCase__ : Optional[int] ): '''simple docstring''' return self.generator.decode(*_lowerCamelCase , **_lowerCamelCase ) def __A ( self : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self.question_encoder def __A ( self : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = self.generator def __A ( self : Tuple , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Dict = None , UpperCamelCase__ : str = None , UpperCamelCase__ : int = None , UpperCamelCase__ : str = "longest" , UpperCamelCase__ : Dict = None , UpperCamelCase__ : Optional[int] = True , **UpperCamelCase__ : Any , ): '''simple docstring''' warnings.warn( '''`prepare_seq2seq_batch` is deprecated and will be removed in version 5 of 🤗 Transformers. Use the ''' '''regular `__call__` method to prepare your inputs and the tokenizer under the `with_target_tokenizer` ''' '''context manager to prepare your targets. See the documentation of your specific tokenizer for more ''' '''details''' , _lowerCamelCase , ) if max_length is None: SCREAMING_SNAKE_CASE : Any = self.current_tokenizer.model_max_length SCREAMING_SNAKE_CASE : Tuple = self( _lowerCamelCase , add_special_tokens=_lowerCamelCase , return_tensors=_lowerCamelCase , max_length=_lowerCamelCase , padding=_lowerCamelCase , truncation=_lowerCamelCase , **_lowerCamelCase , ) if tgt_texts is None: return model_inputs # Process tgt_texts if max_target_length is None: SCREAMING_SNAKE_CASE : Tuple = self.current_tokenizer.model_max_length SCREAMING_SNAKE_CASE : Optional[Any] = self( text_target=_lowerCamelCase , add_special_tokens=_lowerCamelCase , return_tensors=_lowerCamelCase , padding=_lowerCamelCase , max_length=_lowerCamelCase , truncation=_lowerCamelCase , **_lowerCamelCase , ) SCREAMING_SNAKE_CASE : List[Any] = labels['''input_ids'''] return model_inputs
711
import random def A ( _lowercase , _lowercase ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = [], [], [] for element in data: if element < pivot: less.append(_lowercase ) elif element > pivot: greater.append(_lowercase ) else: equal.append(_lowercase ) return less, equal, greater def A ( _lowercase , _lowercase ): # index = len(items) // 2 when trying to find the median # (value of index when items is sorted) # invalid input if index >= len(_lowercase ) or index < 0: return None SCREAMING_SNAKE_CASE : Dict = items[random.randint(0 , len(_lowercase ) - 1 )] SCREAMING_SNAKE_CASE : int = 0 SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = _partition(_lowercase , _lowercase ) SCREAMING_SNAKE_CASE : List[Any] = len(_lowercase ) SCREAMING_SNAKE_CASE : Optional[Any] = len(_lowercase ) # index is the pivot if m <= index < m + count: return pivot # must be in smaller elif m > index: return quick_select(_lowercase , _lowercase ) # must be in larger else: return quick_select(_lowercase , index - (m + count) )
34
0
import argparse import collections import numpy as np import torch from flax import traverse_util from tax import checkpoints from transformers import MTaConfig, UMTaEncoderModel, UMTaForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() def A ( _lowercase , _lowercase , _lowercase ): '''simple docstring''' return params[f"""{prefix}/{prefix}/relpos_bias/rel_embedding"""][:, i, :] def A ( _lowercase , _lowercase , _lowercase , _lowercase="attention" ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = np.ascontiguousarray(params[f"""{prefix}/{prefix}/{layer_name}/key/kernel"""][:, i, :, :] ) SCREAMING_SNAKE_CASE : int = k_tmp.reshape(k_tmp.shape[0] , k_tmp.shape[1] * k_tmp.shape[2] ) SCREAMING_SNAKE_CASE : Dict = np.ascontiguousarray(params[f"""{prefix}/{prefix}/{layer_name}/out/kernel"""][:, i, :, :] ) SCREAMING_SNAKE_CASE : Tuple = o_tmp.reshape(o_tmp.shape[0] * o_tmp.shape[1] , o_tmp.shape[2] ) SCREAMING_SNAKE_CASE : Optional[Any] = np.ascontiguousarray(params[f"""{prefix}/{prefix}/{layer_name}/query/kernel"""][:, i, :, :] ) SCREAMING_SNAKE_CASE : Union[str, Any] = q_tmp.reshape(q_tmp.shape[0] , q_tmp.shape[1] * q_tmp.shape[2] ) SCREAMING_SNAKE_CASE : List[str] = np.ascontiguousarray(params[f"""{prefix}/{prefix}/{layer_name}/value/kernel"""][:, i, :, :] ) SCREAMING_SNAKE_CASE : str = v_tmp.reshape(v_tmp.shape[0] , v_tmp.shape[1] * v_tmp.shape[2] ) return k, o, q, v def A ( _lowercase , _lowercase , _lowercase , _lowercase=False ): '''simple docstring''' if split_mlp_wi: SCREAMING_SNAKE_CASE : str = params[f"""{prefix}/{prefix}/mlp/wi_0/kernel"""][:, i, :] SCREAMING_SNAKE_CASE : str = params[f"""{prefix}/{prefix}/mlp/wi_1/kernel"""][:, i, :] SCREAMING_SNAKE_CASE : int = (wi_a, wi_a) else: SCREAMING_SNAKE_CASE : Optional[int] = params[f"""{prefix}/{prefix}/mlp/wi/kernel"""][:, i, :] SCREAMING_SNAKE_CASE : Optional[int] = params[f"""{prefix}/{prefix}/mlp/wo/kernel"""][:, i, :] return wi, wo def A ( _lowercase , _lowercase , _lowercase , _lowercase ): '''simple docstring''' return params[f"""{prefix}/{prefix}/{layer_name}/scale"""][:, i] def A ( _lowercase , *, _lowercase , _lowercase , _lowercase = False ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = traverse_util.flatten_dict(variables['''target'''] ) SCREAMING_SNAKE_CASE : Dict = {"/".join(__snake_case ): v for k, v in old.items()} # v1.1 models have a gated GeLU with wi_0 and wi_1 instead of wi SCREAMING_SNAKE_CASE : Optional[Any] = "encoder/encoder/mlp/wi_0/kernel" in old print('''Split MLP:''' , __snake_case ) SCREAMING_SNAKE_CASE : Union[str, Any] = collections.OrderedDict() # Shared embeddings. SCREAMING_SNAKE_CASE : List[str] = old["token_embedder/embedding"] # Encoder. for i in range(__snake_case ): # Block i, layer 0 (Self Attention). SCREAMING_SNAKE_CASE : Tuple = tax_layer_norm_lookup(__snake_case , __snake_case , '''encoder''' , '''pre_attention_layer_norm''' ) SCREAMING_SNAKE_CASE : List[str] = tax_attention_lookup(__snake_case , __snake_case , '''encoder''' , '''attention''' ) SCREAMING_SNAKE_CASE : str = layer_norm SCREAMING_SNAKE_CASE : Optional[int] = k.T SCREAMING_SNAKE_CASE : Tuple = o.T SCREAMING_SNAKE_CASE : Optional[int] = q.T SCREAMING_SNAKE_CASE : List[str] = v.T # Block i, layer 1 (MLP). SCREAMING_SNAKE_CASE : Any = tax_layer_norm_lookup(__snake_case , __snake_case , '''encoder''' , '''pre_mlp_layer_norm''' ) SCREAMING_SNAKE_CASE : Union[str, Any] = tax_mlp_lookup(__snake_case , __snake_case , '''encoder''' , __snake_case ) SCREAMING_SNAKE_CASE : List[Any] = layer_norm if split_mlp_wi: SCREAMING_SNAKE_CASE : int = wi[0].T SCREAMING_SNAKE_CASE : Optional[Any] = wi[1].T else: SCREAMING_SNAKE_CASE : List[str] = wi.T SCREAMING_SNAKE_CASE : Dict = wo.T if scalable_attention: # convert the rel_embedding of each layer SCREAMING_SNAKE_CASE : str = tax_relpos_bias_lookup( __snake_case , __snake_case , '''encoder''' ).T SCREAMING_SNAKE_CASE : int = old["encoder/encoder_norm/scale"] if not scalable_attention: SCREAMING_SNAKE_CASE : List[Any] = tax_relpos_bias_lookup( __snake_case , 0 , '''encoder''' ).T SCREAMING_SNAKE_CASE : Union[str, Any] = tax_relpos_bias_lookup( __snake_case , 0 , '''decoder''' ).T if not is_encoder_only: # Decoder. for i in range(__snake_case ): # Block i, layer 0 (Self Attention). SCREAMING_SNAKE_CASE : Dict = tax_layer_norm_lookup(__snake_case , __snake_case , '''decoder''' , '''pre_self_attention_layer_norm''' ) SCREAMING_SNAKE_CASE : List[Any] = tax_attention_lookup(__snake_case , __snake_case , '''decoder''' , '''self_attention''' ) SCREAMING_SNAKE_CASE : List[Any] = layer_norm SCREAMING_SNAKE_CASE : Tuple = k.T SCREAMING_SNAKE_CASE : Optional[int] = o.T SCREAMING_SNAKE_CASE : Tuple = q.T SCREAMING_SNAKE_CASE : List[str] = v.T # Block i, layer 1 (Cross Attention). SCREAMING_SNAKE_CASE : List[Any] = tax_layer_norm_lookup(__snake_case , __snake_case , '''decoder''' , '''pre_cross_attention_layer_norm''' ) SCREAMING_SNAKE_CASE : int = tax_attention_lookup(__snake_case , __snake_case , '''decoder''' , '''encoder_decoder_attention''' ) SCREAMING_SNAKE_CASE : List[Any] = layer_norm SCREAMING_SNAKE_CASE : Optional[Any] = k.T SCREAMING_SNAKE_CASE : List[Any] = o.T SCREAMING_SNAKE_CASE : str = q.T SCREAMING_SNAKE_CASE : Optional[Any] = v.T # Block i, layer 2 (MLP). SCREAMING_SNAKE_CASE : Optional[int] = tax_layer_norm_lookup(__snake_case , __snake_case , '''decoder''' , '''pre_mlp_layer_norm''' ) SCREAMING_SNAKE_CASE : Dict = tax_mlp_lookup(__snake_case , __snake_case , '''decoder''' , __snake_case ) SCREAMING_SNAKE_CASE : int = layer_norm if split_mlp_wi: SCREAMING_SNAKE_CASE : Optional[Any] = wi[0].T SCREAMING_SNAKE_CASE : List[str] = wi[1].T else: SCREAMING_SNAKE_CASE : Optional[int] = wi.T SCREAMING_SNAKE_CASE : Optional[int] = wo.T if scalable_attention: # convert the rel_embedding of each layer SCREAMING_SNAKE_CASE : Optional[Any] = tax_relpos_bias_lookup(__snake_case , __snake_case , '''decoder''' ).T SCREAMING_SNAKE_CASE : Dict = old["decoder/decoder_norm/scale"] # LM Head (only in v1.1 checkpoints, in v1.0 embeddings are used instead) if "decoder/logits_dense/kernel" in old: SCREAMING_SNAKE_CASE : Optional[Any] = old["decoder/logits_dense/kernel"].T return new def A ( _lowercase , _lowercase ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = collections.OrderedDict([(k, torch.from_numpy(v.copy() )) for (k, v) in converted_params.items()] ) # Add what is missing. if "encoder.embed_tokens.weight" not in state_dict: SCREAMING_SNAKE_CASE : Tuple = state_dict["shared.weight"] if not is_encoder_only: if "decoder.embed_tokens.weight" not in state_dict: SCREAMING_SNAKE_CASE : Optional[Any] = state_dict["shared.weight"] if "lm_head.weight" not in state_dict: # For old 1.0 models. print('''Using shared word embeddings as lm_head.''' ) SCREAMING_SNAKE_CASE : Optional[int] = state_dict["shared.weight"] return state_dict def A ( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = checkpoints.load_tax_checkpoint(__snake_case ) SCREAMING_SNAKE_CASE : List[Any] = convert_tax_to_pytorch( __snake_case , num_layers=config.num_layers , is_encoder_only=__snake_case , scalable_attention=__snake_case ) SCREAMING_SNAKE_CASE : Optional[Any] = make_state_dict(__snake_case , __snake_case ) model.load_state_dict(__snake_case , strict=__snake_case ) def A ( _lowercase , _lowercase , _lowercase , _lowercase = False , _lowercase = False , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = MTaConfig.from_json_file(__snake_case ) print(f"""Building PyTorch model from configuration: {config}""" ) # Non-v1.1 checkpoints could also use T5Model, but this works for all. # The v1.0 checkpoints will simply have an LM head that is the word embeddings. if is_encoder_only: SCREAMING_SNAKE_CASE : Any = UMTaEncoderModel(__snake_case ) else: SCREAMING_SNAKE_CASE : List[Any] = UMTaForConditionalGeneration(__snake_case ) # Load weights from tf checkpoint load_tax_weights_in_ta(__snake_case , __snake_case , __snake_case , __snake_case , __snake_case ) # Save pytorch-model print(f"""Save PyTorch model to {pytorch_dump_path}""" ) model.save_pretrained(__snake_case ) # Verify that we can load the checkpoint. model.from_pretrained(__snake_case ) print('''Done''' ) if __name__ == "__main__": __UpperCamelCase : Dict = argparse.ArgumentParser(description='Converts a native T5X checkpoint into a PyTorch checkpoint.') # Required parameters parser.add_argument( '--t5x_checkpoint_path', default=None, type=str, required=True, help='Path to the T5X checkpoint.' ) parser.add_argument( '--config_file', default=None, type=str, required=True, help='The config json file corresponding to the pre-trained T5 model.\nThis specifies the model architecture.', ) parser.add_argument( '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) parser.add_argument( '--is_encoder_only', action='store_true', help='Check if the model is encoder-decoder model', default=False ) parser.add_argument( '--scalable_attention', action='store_true', help='Whether the model uses scaled attention (umt5 model)', default=False, ) __UpperCamelCase : str = parser.parse_args() convert_tax_checkpoint_to_pytorch( args.tax_checkpoint_path, args.config_file, args.pytorch_dump_path, args.is_encoder_only, args.scalable_attention, )
712
from dataclasses import asdict, dataclass from typing import Optional from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCamelCase : Tuple = logging.get_logger(__name__) # TODO Update this __UpperCamelCase : List[str] = { 'facebook/esm-1b': 'https://huggingface.co/facebook/esm-1b/resolve/main/config.json', # See all ESM models at https://huggingface.co/models?filter=esm } class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = """esm""" def __init__( self : Tuple , UpperCamelCase__ : Optional[Any]=None , UpperCamelCase__ : int=None , UpperCamelCase__ : List[str]=None , UpperCamelCase__ : Any=768 , UpperCamelCase__ : Optional[Any]=12 , UpperCamelCase__ : str=12 , UpperCamelCase__ : Optional[int]=3072 , UpperCamelCase__ : Optional[Any]=0.1 , UpperCamelCase__ : Any=0.1 , UpperCamelCase__ : Union[str, Any]=1026 , UpperCamelCase__ : Dict=0.02 , UpperCamelCase__ : Any=1E-12 , UpperCamelCase__ : Dict="absolute" , UpperCamelCase__ : Optional[Any]=True , UpperCamelCase__ : int=None , UpperCamelCase__ : Optional[int]=False , UpperCamelCase__ : Tuple=False , UpperCamelCase__ : List[str]=None , UpperCamelCase__ : Optional[Any]=None , **UpperCamelCase__ : Any , ): '''simple docstring''' super().__init__(pad_token_id=UpperCamelCase__ , mask_token_id=UpperCamelCase__ , **UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[Any] = vocab_size SCREAMING_SNAKE_CASE : Any = hidden_size SCREAMING_SNAKE_CASE : Union[str, Any] = num_hidden_layers SCREAMING_SNAKE_CASE : Dict = num_attention_heads SCREAMING_SNAKE_CASE : Any = intermediate_size SCREAMING_SNAKE_CASE : str = hidden_dropout_prob SCREAMING_SNAKE_CASE : List[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : str = max_position_embeddings SCREAMING_SNAKE_CASE : Tuple = initializer_range SCREAMING_SNAKE_CASE : Optional[int] = layer_norm_eps SCREAMING_SNAKE_CASE : Dict = position_embedding_type SCREAMING_SNAKE_CASE : Any = use_cache SCREAMING_SNAKE_CASE : Dict = emb_layer_norm_before SCREAMING_SNAKE_CASE : List[str] = token_dropout SCREAMING_SNAKE_CASE : List[Any] = is_folding_model if is_folding_model: if esmfold_config is None: logger.info('''No esmfold_config supplied for folding model, using default values.''' ) SCREAMING_SNAKE_CASE : List[Any] = EsmFoldConfig() elif isinstance(UpperCamelCase__ , UpperCamelCase__ ): SCREAMING_SNAKE_CASE : Union[str, Any] = EsmFoldConfig(**UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[Any] = esmfold_config if vocab_list is None: logger.warning('''No vocab_list supplied for folding model, assuming the ESM-2 vocabulary!''' ) SCREAMING_SNAKE_CASE : Optional[int] = get_default_vocab_list() else: SCREAMING_SNAKE_CASE : Optional[Any] = vocab_list else: SCREAMING_SNAKE_CASE : str = None SCREAMING_SNAKE_CASE : int = None if self.esmfold_config is not None and getattr(self.esmfold_config , '''use_esm_attn_map''' , UpperCamelCase__ ): raise ValueError('''The HuggingFace port of ESMFold does not support use_esm_attn_map at this time!''' ) def __A ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = super().to_dict() if isinstance(self.esmfold_config , UpperCamelCase__ ): SCREAMING_SNAKE_CASE : Optional[Any] = self.esmfold_config.to_dict() return output @dataclass class lowercase__ : UpperCamelCase_ = None UpperCamelCase_ = True UpperCamelCase_ = False UpperCamelCase_ = False UpperCamelCase_ = False UpperCamelCase_ = 0 UpperCamelCase_ = True UpperCamelCase_ = False UpperCamelCase_ = 128 UpperCamelCase_ = None def __A ( self : Optional[int] ): '''simple docstring''' if self.trunk is None: SCREAMING_SNAKE_CASE : Optional[Any] = TrunkConfig() elif isinstance(self.trunk , UpperCamelCase__ ): SCREAMING_SNAKE_CASE : Tuple = TrunkConfig(**self.trunk ) def __A ( self : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = asdict(self ) SCREAMING_SNAKE_CASE : Tuple = self.trunk.to_dict() return output @dataclass class lowercase__ : UpperCamelCase_ = 48 UpperCamelCase_ = 1_024 UpperCamelCase_ = 128 UpperCamelCase_ = 32 UpperCamelCase_ = 32 UpperCamelCase_ = 32 UpperCamelCase_ = 0 UpperCamelCase_ = 0 UpperCamelCase_ = False UpperCamelCase_ = 4 UpperCamelCase_ = 128 UpperCamelCase_ = None def __A ( self : Any ): '''simple docstring''' if self.structure_module is None: SCREAMING_SNAKE_CASE : Optional[int] = StructureModuleConfig() elif isinstance(self.structure_module , UpperCamelCase__ ): SCREAMING_SNAKE_CASE : Optional[Any] = StructureModuleConfig(**self.structure_module ) if self.max_recycles <= 0: raise ValueError(f"""`max_recycles` should be positive, got {self.max_recycles}.""" ) if self.sequence_state_dim % self.sequence_state_dim != 0: raise ValueError( '''`sequence_state_dim` should be a round multiple of `sequence_state_dim`, got''' f""" {self.sequence_state_dim} and {self.sequence_state_dim}.""" ) if self.pairwise_state_dim % self.pairwise_state_dim != 0: raise ValueError( '''`pairwise_state_dim` should be a round multiple of `pairwise_state_dim`, got''' f""" {self.pairwise_state_dim} and {self.pairwise_state_dim}.""" ) SCREAMING_SNAKE_CASE : Dict = self.sequence_state_dim // self.sequence_head_width SCREAMING_SNAKE_CASE : Tuple = self.pairwise_state_dim // self.pairwise_head_width if self.sequence_state_dim != sequence_num_heads * self.sequence_head_width: raise ValueError( '''`sequence_state_dim` should be equal to `sequence_num_heads * sequence_head_width, got''' f""" {self.sequence_state_dim} != {sequence_num_heads} * {self.sequence_head_width}.""" ) if self.pairwise_state_dim != pairwise_num_heads * self.pairwise_head_width: raise ValueError( '''`pairwise_state_dim` should be equal to `pairwise_num_heads * pairwise_head_width, got''' f""" {self.pairwise_state_dim} != {pairwise_num_heads} * {self.pairwise_head_width}.""" ) if self.pairwise_state_dim % 2 != 0: raise ValueError(f"""`pairwise_state_dim` should be even, got {self.pairwise_state_dim}.""" ) if self.dropout >= 0.4: raise ValueError(f"""`dropout` should not be greater than 0.4, got {self.dropout}.""" ) def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = asdict(self ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.structure_module.to_dict() return output @dataclass class lowercase__ : UpperCamelCase_ = 384 UpperCamelCase_ = 128 UpperCamelCase_ = 16 UpperCamelCase_ = 128 UpperCamelCase_ = 12 UpperCamelCase_ = 4 UpperCamelCase_ = 8 UpperCamelCase_ = 0.1 UpperCamelCase_ = 8 UpperCamelCase_ = 1 UpperCamelCase_ = 2 UpperCamelCase_ = 7 UpperCamelCase_ = 10 UpperCamelCase_ = 1E-8 UpperCamelCase_ = 1E5 def __A ( self : Dict ): '''simple docstring''' return asdict(self ) def A ( ): return ( "<cls>", "<pad>", "<eos>", "<unk>", "L", "A", "G", "V", "S", "E", "R", "T", "I", "D", "P", "K", "Q", "N", "F", "Y", "M", "H", "W", "C", "X", "B", "U", "Z", "O", ".", "-", "<null_1>", "<mask>", )
34
0
import unittest from knapsack import knapsack as k class lowercase__ ( unittest.TestCase): def __A ( self : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = 0 SCREAMING_SNAKE_CASE : List[str] = [0] SCREAMING_SNAKE_CASE : Optional[Any] = [0] SCREAMING_SNAKE_CASE : Optional[Any] = len(__A ) self.assertEqual(k.knapsack(__A , __A , __A , __A ) , 0 ) SCREAMING_SNAKE_CASE : str = [60] SCREAMING_SNAKE_CASE : int = [10] SCREAMING_SNAKE_CASE : Any = len(__A ) self.assertEqual(k.knapsack(__A , __A , __A , __A ) , 0 ) def __A ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = 3 SCREAMING_SNAKE_CASE : Optional[Any] = [1, 2, 3] SCREAMING_SNAKE_CASE : Optional[int] = [3, 2, 1] SCREAMING_SNAKE_CASE : Optional[int] = len(__A ) self.assertEqual(k.knapsack(__A , __A , __A , __A ) , 5 ) def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = 50 SCREAMING_SNAKE_CASE : List[str] = [60, 100, 120] SCREAMING_SNAKE_CASE : Tuple = [10, 20, 30] SCREAMING_SNAKE_CASE : Dict = len(__A ) self.assertEqual(k.knapsack(__A , __A , __A , __A ) , 220 ) if __name__ == "__main__": unittest.main()
713
import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv("""TEST_SAGEMAKER""" , """False""")) is not True , reason="""Skipping test because should only be run when releasing minor transformers version""" , ) @pytest.mark.usefixtures("""sm_env""") @parameterized_class( [ { """framework""": """pytorch""", """script""": """run_glue.py""", """model_name_or_path""": """distilbert-base-cased""", """instance_type""": """ml.p3.16xlarge""", """results""": {"""train_runtime""": 650, """eval_accuracy""": 0.7, """eval_loss""": 0.6}, }, { """framework""": """pytorch""", """script""": """run_ddp.py""", """model_name_or_path""": """distilbert-base-cased""", """instance_type""": """ml.p3.16xlarge""", """results""": {"""train_runtime""": 600, """eval_accuracy""": 0.7, """eval_loss""": 0.6}, }, { """framework""": """tensorflow""", """script""": """run_tf_dist.py""", """model_name_or_path""": """distilbert-base-cased""", """instance_type""": """ml.p3.16xlarge""", """results""": {"""train_runtime""": 600, """eval_accuracy""": 0.6, """eval_loss""": 0.7}, }, ]) class lowercase__ ( unittest.TestCase): def __A ( self : Any ): '''simple docstring''' if self.framework == "pytorch": subprocess.run( f"""cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py""".split() , encoding='''utf-8''' , check=UpperCamelCase__ , ) assert hasattr(self , '''env''' ) def __A ( self : str , UpperCamelCase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = f"""{self.env.base_job_name}-{instance_count}-{'ddp' if 'ddp' in self.script else 'smd'}""" # distributed data settings SCREAMING_SNAKE_CASE : Any = {'''smdistributed''': {'''dataparallel''': {'''enabled''': True}}} if self.script != '''run_ddp.py''' else None # creates estimator return HuggingFace( entry_point=self.script , source_dir=self.env.test_path , role=self.env.role , image_uri=self.env.image_uri , base_job_name=UpperCamelCase__ , instance_count=UpperCamelCase__ , instance_type=self.instance_type , debugger_hook_config=UpperCamelCase__ , hyperparameters={**self.env.distributed_hyperparameters, '''model_name_or_path''': self.model_name_or_path} , metric_definitions=self.env.metric_definitions , distribution=UpperCamelCase__ , py_version='''py36''' , ) def __A ( self : Optional[Any] , UpperCamelCase__ : List[str] ): '''simple docstring''' TrainingJobAnalytics(UpperCamelCase__ ).export_csv(f"""{self.env.test_path}/{job_name}_metrics.csv""" ) @parameterized.expand([(2,)] ) def __A ( self : Tuple , UpperCamelCase__ : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = self.create_estimator(UpperCamelCase__ ) # run training estimator.fit() # result dataframe SCREAMING_SNAKE_CASE : Optional[Any] = TrainingJobAnalytics(estimator.latest_training_job.name ).dataframe() # extract kpis SCREAMING_SNAKE_CASE : List[str] = list(result_metrics_df[result_metrics_df.metric_name == '''eval_accuracy''']['''value'''] ) SCREAMING_SNAKE_CASE : Dict = list(result_metrics_df[result_metrics_df.metric_name == '''eval_loss''']['''value'''] ) # get train time from SageMaker job, this includes starting, preprocessing, stopping SCREAMING_SNAKE_CASE : List[Any] = ( Session().describe_training_job(estimator.latest_training_job.name ).get('''TrainingTimeInSeconds''' , 99_9999 ) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results['''eval_accuracy'''] for t in eval_accuracy ) assert all(t <= self.results['''eval_loss'''] for t in eval_loss ) # dump tests result into json file to share in PR with open(f"""{estimator.latest_training_job.name}.json""" , '''w''' ) as outfile: json.dump({'''train_time''': train_runtime, '''eval_accuracy''': eval_accuracy, '''eval_loss''': eval_loss} , UpperCamelCase__ )
34
0
from math import ceil, sqrt def A ( _lowercase = 1_000_000 ): SCREAMING_SNAKE_CASE : Optional[int] = 0 for outer_width in range(3 , (limit // 4) + 2 ): if outer_width**2 > limit: SCREAMING_SNAKE_CASE : Any = max(ceil(sqrt(outer_width**2 - limit ) ) , 1 ) else: SCREAMING_SNAKE_CASE : int = 1 if (outer_width - hole_width_lower_bound) % 2: hole_width_lower_bound += 1 answer += (outer_width - hole_width_lower_bound - 2) // 2 + 1 return answer if __name__ == "__main__": print(f"""{solution() = }""")
714
import os try: from .build_directory_md import good_file_paths except ImportError: from build_directory_md import good_file_paths # type: ignore __UpperCamelCase : Dict = list(good_file_paths()) assert filepaths, "good_file_paths() failed!" __UpperCamelCase : Tuple = [file for file in filepaths if file != file.lower()] if upper_files: print(f"""{len(upper_files)} files contain uppercase characters:""") print('\n'.join(upper_files) + '\n') __UpperCamelCase : List[Any] = [file for file in filepaths if ' ' in file] if space_files: print(f"""{len(space_files)} files contain space characters:""") print('\n'.join(space_files) + '\n') __UpperCamelCase : List[Any] = [file for file in filepaths if '-' in file] if hyphen_files: print(f"""{len(hyphen_files)} files contain hyphen characters:""") print('\n'.join(hyphen_files) + '\n') __UpperCamelCase : List[Any] = [file for file in filepaths if os.sep not in file] if nodir_files: print(f"""{len(nodir_files)} files are not in a directory:""") print('\n'.join(nodir_files) + '\n') __UpperCamelCase : Optional[Any] = len(upper_files + space_files + hyphen_files + nodir_files) if bad_files: import sys sys.exit(bad_files)
34
0
import glob import os import random from string import ascii_lowercase, digits import cva import numpy as np # Parrameters __UpperCamelCase : Any = (720, 1280) # Height, Width __UpperCamelCase : Optional[int] = (0.4, 0.6) # if height or width lower than this scale, drop it. __UpperCamelCase : int = 1 / 100 __UpperCamelCase : int = '''''' __UpperCamelCase : str = '''''' __UpperCamelCase : int = '''''' __UpperCamelCase : List[str] = 250 def A ( ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : str = get_dataset(_UpperCAmelCase , _UpperCAmelCase ) for index in range(_UpperCAmelCase ): SCREAMING_SNAKE_CASE : Optional[Any] = random.sample(range(len(_UpperCAmelCase ) ) , 4 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = update_image_and_anno( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , filter_scale=_UpperCAmelCase , ) # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' SCREAMING_SNAKE_CASE : Tuple = random_chars(32 ) SCREAMING_SNAKE_CASE : Union[str, Any] = path.split(os.sep )[-1].rsplit('''.''' , 1 )[0] SCREAMING_SNAKE_CASE : List[str] = f"""{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}""" cva.imwrite(f"""{file_root}.jpg""" , _UpperCAmelCase , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(f"""Succeeded {index+1}/{NUMBER_IMAGES} with {file_name}""" ) SCREAMING_SNAKE_CASE : Tuple = [] for anno in new_annos: SCREAMING_SNAKE_CASE : List[Any] = anno[3] - anno[1] SCREAMING_SNAKE_CASE : Tuple = anno[4] - anno[2] SCREAMING_SNAKE_CASE : Optional[int] = anno[1] + width / 2 SCREAMING_SNAKE_CASE : Tuple = anno[2] + height / 2 SCREAMING_SNAKE_CASE : Optional[int] = f"""{anno[0]} {x_center} {y_center} {width} {height}""" annos_list.append(_UpperCAmelCase ) with open(f"""{file_root}.txt""" , '''w''' ) as outfile: outfile.write('''\n'''.join(line for line in annos_list ) ) def A ( _lowercase , _lowercase ): SCREAMING_SNAKE_CASE : Dict = [] SCREAMING_SNAKE_CASE : Union[str, Any] = [] for label_file in glob.glob(os.path.join(_UpperCAmelCase , '''*.txt''' ) ): SCREAMING_SNAKE_CASE : Optional[int] = label_file.split(os.sep )[-1].rsplit('''.''' , 1 )[0] with open(_UpperCAmelCase ) as in_file: SCREAMING_SNAKE_CASE : Tuple = in_file.readlines() SCREAMING_SNAKE_CASE : Dict = os.path.join(_UpperCAmelCase , f"""{label_name}.jpg""" ) SCREAMING_SNAKE_CASE : int = [] for obj_list in obj_lists: SCREAMING_SNAKE_CASE : List[str] = obj_list.rstrip('''\n''' ).split(''' ''' ) SCREAMING_SNAKE_CASE : Dict = float(obj[1] ) - float(obj[3] ) / 2 SCREAMING_SNAKE_CASE : Optional[Any] = float(obj[2] ) - float(obj[4] ) / 2 SCREAMING_SNAKE_CASE : Dict = float(obj[1] ) + float(obj[3] ) / 2 SCREAMING_SNAKE_CASE : Dict = float(obj[2] ) + float(obj[4] ) / 2 boxes.append([int(obj[0] ), xmin, ymin, xmax, ymax] ) if not boxes: continue img_paths.append(_UpperCAmelCase ) labels.append(_UpperCAmelCase ) return img_paths, labels def A ( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase = 0.0 , ): SCREAMING_SNAKE_CASE : Optional[int] = np.zeros([output_size[0], output_size[1], 3] , dtype=np.uinta ) SCREAMING_SNAKE_CASE : Optional[int] = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) SCREAMING_SNAKE_CASE : Optional[int] = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) SCREAMING_SNAKE_CASE : List[Any] = int(scale_x * output_size[1] ) SCREAMING_SNAKE_CASE : str = int(scale_y * output_size[0] ) SCREAMING_SNAKE_CASE : List[Any] = [] SCREAMING_SNAKE_CASE : Optional[int] = [] for i, index in enumerate(_UpperCAmelCase ): SCREAMING_SNAKE_CASE : str = all_img_list[index] path_list.append(_UpperCAmelCase ) SCREAMING_SNAKE_CASE : Dict = all_annos[index] SCREAMING_SNAKE_CASE : int = cva.imread(_UpperCAmelCase ) if i == 0: # top-left SCREAMING_SNAKE_CASE : List[Any] = cva.resize(_UpperCAmelCase , (divid_point_x, divid_point_y) ) SCREAMING_SNAKE_CASE : str = img for bbox in img_annos: SCREAMING_SNAKE_CASE : str = bbox[1] * scale_x SCREAMING_SNAKE_CASE : Any = bbox[2] * scale_y SCREAMING_SNAKE_CASE : str = bbox[3] * scale_x SCREAMING_SNAKE_CASE : Optional[int] = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 1: # top-right SCREAMING_SNAKE_CASE : Union[str, Any] = cva.resize(_UpperCAmelCase , (output_size[1] - divid_point_x, divid_point_y) ) SCREAMING_SNAKE_CASE : str = img for bbox in img_annos: SCREAMING_SNAKE_CASE : List[Any] = scale_x + bbox[1] * (1 - scale_x) SCREAMING_SNAKE_CASE : List[str] = bbox[2] * scale_y SCREAMING_SNAKE_CASE : int = scale_x + bbox[3] * (1 - scale_x) SCREAMING_SNAKE_CASE : Union[str, Any] = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 2: # bottom-left SCREAMING_SNAKE_CASE : Any = cva.resize(_UpperCAmelCase , (divid_point_x, output_size[0] - divid_point_y) ) SCREAMING_SNAKE_CASE : str = img for bbox in img_annos: SCREAMING_SNAKE_CASE : List[str] = bbox[1] * scale_x SCREAMING_SNAKE_CASE : Union[str, Any] = scale_y + bbox[2] * (1 - scale_y) SCREAMING_SNAKE_CASE : Optional[Any] = bbox[3] * scale_x SCREAMING_SNAKE_CASE : Union[str, Any] = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) else: # bottom-right SCREAMING_SNAKE_CASE : List[str] = cva.resize( _UpperCAmelCase , (output_size[1] - divid_point_x, output_size[0] - divid_point_y) ) SCREAMING_SNAKE_CASE : Any = img for bbox in img_annos: SCREAMING_SNAKE_CASE : Any = scale_x + bbox[1] * (1 - scale_x) SCREAMING_SNAKE_CASE : Tuple = scale_y + bbox[2] * (1 - scale_y) SCREAMING_SNAKE_CASE : str = scale_x + bbox[3] * (1 - scale_x) SCREAMING_SNAKE_CASE : Dict = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) # Remove bounding box small than scale of filter if filter_scale > 0: SCREAMING_SNAKE_CASE : str = [ anno for anno in new_anno if filter_scale < (anno[3] - anno[1]) and filter_scale < (anno[4] - anno[2]) ] return output_img, new_anno, path_list[0] def A ( _lowercase ): assert number_char > 1, "The number of character should greater than 1" SCREAMING_SNAKE_CASE : str = ascii_lowercase + digits return "".join(random.choice(_UpperCAmelCase ) for _ in range(_UpperCAmelCase ) ) if __name__ == "__main__": main() print('DONE ✅')
715
import os import re import warnings from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_ta import TaTokenizer else: __UpperCamelCase : Dict = None __UpperCamelCase : Tuple = logging.get_logger(__name__) __UpperCamelCase : Optional[int] = {'vocab_file': 'spiece.model', 'tokenizer_file': 'tokenizer.json'} __UpperCamelCase : Optional[int] = { 'vocab_file': { 't5-small': 'https://huggingface.co/t5-small/resolve/main/spiece.model', 't5-base': 'https://huggingface.co/t5-base/resolve/main/spiece.model', 't5-large': 'https://huggingface.co/t5-large/resolve/main/spiece.model', 't5-3b': 'https://huggingface.co/t5-3b/resolve/main/spiece.model', 't5-11b': 'https://huggingface.co/t5-11b/resolve/main/spiece.model', }, 'tokenizer_file': { 't5-small': 'https://huggingface.co/t5-small/resolve/main/tokenizer.json', 't5-base': 'https://huggingface.co/t5-base/resolve/main/tokenizer.json', 't5-large': 'https://huggingface.co/t5-large/resolve/main/tokenizer.json', 't5-3b': 'https://huggingface.co/t5-3b/resolve/main/tokenizer.json', 't5-11b': 'https://huggingface.co/t5-11b/resolve/main/tokenizer.json', }, } # TODO(PVP) - this should be removed in Transformers v5 __UpperCamelCase : Union[str, Any] = { 't5-small': 512, 't5-base': 512, 't5-large': 512, 't5-3b': 512, 't5-11b': 512, } class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = VOCAB_FILES_NAMES UpperCamelCase_ = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase_ = ["""input_ids""", """attention_mask"""] UpperCamelCase_ = TaTokenizer UpperCamelCase_ = [] def __init__( self : str , UpperCamelCase__ : Optional[int]=None , UpperCamelCase__ : Dict=None , UpperCamelCase__ : str="</s>" , UpperCamelCase__ : str="<unk>" , UpperCamelCase__ : Optional[int]="<pad>" , UpperCamelCase__ : Optional[Any]=100 , UpperCamelCase__ : List[Any]=None , **UpperCamelCase__ : str , ): '''simple docstring''' if extra_ids > 0 and additional_special_tokens is None: SCREAMING_SNAKE_CASE : List[str] = [f"""<extra_id_{i}>""" for i in range(UpperCamelCase__ )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra special tokens SCREAMING_SNAKE_CASE : int = len(set(filter(lambda UpperCamelCase__ : bool('''extra_id_''' in str(UpperCamelCase__ ) ) , UpperCamelCase__ ) ) ) if extra_tokens != extra_ids: raise ValueError( f"""Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are""" ''' provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids''' ''' tokens''' ) super().__init__( UpperCamelCase__ , tokenizer_file=UpperCamelCase__ , eos_token=UpperCamelCase__ , unk_token=UpperCamelCase__ , pad_token=UpperCamelCase__ , extra_ids=UpperCamelCase__ , additional_special_tokens=UpperCamelCase__ , **UpperCamelCase__ , ) SCREAMING_SNAKE_CASE : str = vocab_file SCREAMING_SNAKE_CASE : int = False if not self.vocab_file else True SCREAMING_SNAKE_CASE : str = extra_ids @staticmethod def __A ( UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Optional[Any] ): '''simple docstring''' if pretrained_model_name_or_path in TaTokenizerFast.max_model_input_sizes: SCREAMING_SNAKE_CASE : List[str] = TaTokenizerFast.max_model_input_sizes[pretrained_model_name_or_path] if init_max_model_length is not None and init_max_model_length != max_model_length: return init_max_model_length elif init_max_model_length is None: warnings.warn( '''This tokenizer was incorrectly instantiated with a model max length of''' f""" {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this""" ''' behavior is kept to avoid breaking backwards compatibility when padding/encoding with''' ''' `truncation is True`.\n- Be aware that you SHOULD NOT rely on''' f""" {pretrained_model_name_or_path} automatically truncating your input to""" f""" {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences""" f""" longer than {deprecated_max_model_length} you can either instantiate this tokenizer with""" ''' `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please''' ''' instantiate this tokenizer with `model_max_length` set to your preferred value.''' , UpperCamelCase__ , ) return max_model_length def __A ( self : Tuple , UpperCamelCase__ : str , UpperCamelCase__ : Optional[str] = None ): '''simple docstring''' if not self.can_save_slow_tokenizer: raise ValueError( '''Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ''' '''tokenizer.''' ) if not os.path.isdir(UpperCamelCase__ ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return SCREAMING_SNAKE_CASE : Any = os.path.join( UpperCamelCase__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCamelCase__ ): copyfile(self.vocab_file , UpperCamelCase__ ) logger.info(f"""Copy vocab file to {out_vocab_file}""" ) return (out_vocab_file,) def __A ( self : Optional[Any] , UpperCamelCase__ : List[int] , UpperCamelCase__ : Optional[List[int]] = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = token_ids_a + [self.eos_token_id] if token_ids_a is None: return self.prefix_tokens + token_ids_a else: SCREAMING_SNAKE_CASE : Tuple = token_ids_a + [self.eos_token_id] return self.prefix_tokens + token_ids_a + token_ids_a def __A ( self : Any , UpperCamelCase__ : List[int] , UpperCamelCase__ : Optional[List[int]] = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def __A ( self : Dict ): '''simple docstring''' return list( set(filter(lambda UpperCamelCase__ : bool(re.search(r'''<extra_id_\d+>''' , UpperCamelCase__ ) ) is not None , self.additional_special_tokens ) ) ) def __A ( self : List[Any] ): '''simple docstring''' return [self.convert_tokens_to_ids(UpperCamelCase__ ) for token in self.get_sentinel_tokens()]
34
0
import warnings from transformers import AutoTokenizer from transformers.utils import is_torch_available from transformers.utils.generic import ExplicitEnum from ...processing_utils import ProcessorMixin if is_torch_available(): import torch class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = """char""" UpperCamelCase_ = """bpe""" UpperCamelCase_ = """wp""" __UpperCamelCase : List[str] = (DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE) class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = ["""image_processor""", """char_tokenizer"""] UpperCamelCase_ = """ViTImageProcessor""" UpperCamelCase_ = """MgpstrTokenizer""" def __init__( self : Tuple , UpperCamelCase__ : Union[str, Any]=None , UpperCamelCase__ : str=None , **UpperCamelCase__ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , __a , ) SCREAMING_SNAKE_CASE : List[Any] = kwargs.pop('''feature_extractor''' ) SCREAMING_SNAKE_CASE : str = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('''You need to specify an `image_processor`.''' ) if tokenizer is None: raise ValueError('''You need to specify a `tokenizer`.''' ) SCREAMING_SNAKE_CASE : Tuple = tokenizer SCREAMING_SNAKE_CASE : Any = AutoTokenizer.from_pretrained('''gpt2''' ) SCREAMING_SNAKE_CASE : List[str] = AutoTokenizer.from_pretrained('''bert-base-uncased''' ) super().__init__(__a , __a ) def __call__( self : List[Any] , UpperCamelCase__ : Any=None , UpperCamelCase__ : List[str]=None , UpperCamelCase__ : int=None , **UpperCamelCase__ : Union[str, Any] ): '''simple docstring''' if images is None and text is None: raise ValueError('''You need to specify either an `images` or `text` input to process.''' ) if images is not None: SCREAMING_SNAKE_CASE : Union[str, Any] = self.image_processor(__a , return_tensors=__a , **__a ) if text is not None: SCREAMING_SNAKE_CASE : Dict = self.char_tokenizer(__a , return_tensors=__a , **__a ) if text is None: return inputs elif images is None: return encodings else: SCREAMING_SNAKE_CASE : Union[str, Any] = encodings['input_ids'] return inputs def __A ( self : Dict , UpperCamelCase__ : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = sequences SCREAMING_SNAKE_CASE : int = char_preds.size(0 ) SCREAMING_SNAKE_CASE : str = self._decode_helper(__a , '''char''' ) SCREAMING_SNAKE_CASE : List[str] = self._decode_helper(__a , '''bpe''' ) SCREAMING_SNAKE_CASE : List[str] = self._decode_helper(__a , '''wp''' ) SCREAMING_SNAKE_CASE : Any = [] SCREAMING_SNAKE_CASE : List[str] = [] for i in range(__a ): SCREAMING_SNAKE_CASE : Union[str, Any] = [char_scores[i], bpe_scores[i], wp_scores[i]] SCREAMING_SNAKE_CASE : Any = [char_strs[i], bpe_strs[i], wp_strs[i]] SCREAMING_SNAKE_CASE : List[str] = scores.index(max(__a ) ) final_strs.append(strs[max_score_index] ) final_scores.append(scores[max_score_index] ) SCREAMING_SNAKE_CASE : str = {} SCREAMING_SNAKE_CASE : Optional[Any] = final_strs SCREAMING_SNAKE_CASE : str = final_scores SCREAMING_SNAKE_CASE : Tuple = char_strs SCREAMING_SNAKE_CASE : str = bpe_strs SCREAMING_SNAKE_CASE : Any = wp_strs return out def __A ( self : Tuple , UpperCamelCase__ : Dict , UpperCamelCase__ : int ): '''simple docstring''' if format == DecodeType.CHARACTER: SCREAMING_SNAKE_CASE : str = self.char_decode SCREAMING_SNAKE_CASE : Union[str, Any] = 1 SCREAMING_SNAKE_CASE : Union[str, Any] = '[s]' elif format == DecodeType.BPE: SCREAMING_SNAKE_CASE : Tuple = self.bpe_decode SCREAMING_SNAKE_CASE : str = 2 SCREAMING_SNAKE_CASE : Any = '#' elif format == DecodeType.WORDPIECE: SCREAMING_SNAKE_CASE : Any = self.wp_decode SCREAMING_SNAKE_CASE : Tuple = 102 SCREAMING_SNAKE_CASE : Dict = '[SEP]' else: raise ValueError(f"""Format {format} is not supported.""" ) SCREAMING_SNAKE_CASE : Tuple = [], [] SCREAMING_SNAKE_CASE : List[str] = pred_logits.size(0 ) SCREAMING_SNAKE_CASE : Optional[Any] = pred_logits.size(1 ) SCREAMING_SNAKE_CASE : str = pred_logits.topk(1 , dim=-1 , largest=__a , sorted=__a ) SCREAMING_SNAKE_CASE : Optional[Any] = preds_index.view(-1 , __a )[:, 1:] SCREAMING_SNAKE_CASE : Optional[Any] = decoder(__a ) SCREAMING_SNAKE_CASE : str = torch.nn.functional.softmax(__a , dim=2 ).max(dim=2 ) SCREAMING_SNAKE_CASE : Union[str, Any] = preds_max_prob[:, 1:] for index in range(__a ): SCREAMING_SNAKE_CASE : List[Any] = preds_str[index].find(__a ) SCREAMING_SNAKE_CASE : List[Any] = preds_str[index][:pred_eos] SCREAMING_SNAKE_CASE : Union[str, Any] = preds_index[index].cpu().tolist() SCREAMING_SNAKE_CASE : str = pred_index.index(__a ) if eos_token in pred_index else -1 SCREAMING_SNAKE_CASE : Any = preds_max_prob[index][: pred_eos_index + 1] SCREAMING_SNAKE_CASE : Dict = pred_max_prob.cumprod(dim=0 )[-1] if pred_max_prob.nelement() != 0 else 0.0 dec_strs.append(__a ) conf_scores.append(__a ) return dec_strs, conf_scores def __A ( self : Tuple , UpperCamelCase__ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = [seq.replace(''' ''' , '''''' ) for seq in self.char_tokenizer.batch_decode(__a )] return decode_strs def __A ( self : int , UpperCamelCase__ : Tuple ): '''simple docstring''' return self.bpe_tokenizer.batch_decode(__a ) def __A ( self : Any , UpperCamelCase__ : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = [seq.replace(''' ''' , '''''' ) for seq in self.wp_tokenizer.batch_decode(__a )] return decode_strs
716
import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionPipeline from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device __UpperCamelCase : str = False class lowercase__ ( unittest.TestCase): pass @nightly @require_torch_gpu class lowercase__ ( unittest.TestCase): def __A ( self : Union[str, Any] ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = VersatileDiffusionPipeline.from_pretrained('''shi-labs/versatile-diffusion''' , torch_dtype=torch.floataa ) pipe.to(UpperCamelCase__ ) pipe.set_progress_bar_config(disable=UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[Any] = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg''' ) SCREAMING_SNAKE_CASE : Optional[Any] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Dict = pipe.dual_guided( prompt='''first prompt''' , image=UpperCamelCase__ , text_to_image_strength=0.75 , generator=UpperCamelCase__ , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' , ).images with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[Any] = VersatileDiffusionPipeline.from_pretrained(UpperCamelCase__ , torch_dtype=torch.floataa ) pipe.to(UpperCamelCase__ ) pipe.set_progress_bar_config(disable=UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[Any] = generator.manual_seed(0 ) SCREAMING_SNAKE_CASE : int = pipe.dual_guided( prompt='''first prompt''' , image=UpperCamelCase__ , text_to_image_strength=0.75 , generator=UpperCamelCase__ , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' , ).images assert np.abs(image - new_image ).sum() < 1E-5, "Models don't have the same forward pass" def __A ( self : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = VersatileDiffusionPipeline.from_pretrained('''shi-labs/versatile-diffusion''' , torch_dtype=torch.floataa ) pipe.to(UpperCamelCase__ ) pipe.set_progress_bar_config(disable=UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[int] = '''cyberpunk 2077''' SCREAMING_SNAKE_CASE : Tuple = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg''' ) SCREAMING_SNAKE_CASE : List[Any] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Tuple = pipe.dual_guided( prompt=UpperCamelCase__ , image=UpperCamelCase__ , text_to_image_strength=0.75 , generator=UpperCamelCase__ , guidance_scale=7.5 , num_inference_steps=50 , output_type='''numpy''' , ).images SCREAMING_SNAKE_CASE : Tuple = image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE : int = np.array([0.1448, 0.1619, 0.1741, 0.1086, 0.1147, 0.1128, 0.1199, 0.1165, 0.1001] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 SCREAMING_SNAKE_CASE : Optional[Any] = '''A painting of a squirrel eating a burger ''' SCREAMING_SNAKE_CASE : Optional[Any] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Any = pipe.text_to_image( prompt=UpperCamelCase__ , generator=UpperCamelCase__ , guidance_scale=7.5 , num_inference_steps=50 , output_type='''numpy''' ).images SCREAMING_SNAKE_CASE : List[str] = image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE : Any = np.array([0.3367, 0.3169, 0.2656, 0.3870, 0.4790, 0.3796, 0.4009, 0.4878, 0.4778] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 SCREAMING_SNAKE_CASE : Optional[Any] = pipe.image_variation(UpperCamelCase__ , generator=UpperCamelCase__ , output_type='''numpy''' ).images SCREAMING_SNAKE_CASE : Optional[int] = image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE : Union[str, Any] = np.array([0.3076, 0.3123, 0.3284, 0.3782, 0.3770, 0.3894, 0.4297, 0.4331, 0.4456] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1
34
0
'''simple docstring''' from typing import Any class lowercase__ : def __init__( self : str , UpperCamelCase__ : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = data SCREAMING_SNAKE_CASE : str = None def __repr__( self : int ): '''simple docstring''' return f"""Node({self.data})""" class lowercase__ : def __init__( self : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = None def __iter__( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = self.head while node: yield node.data SCREAMING_SNAKE_CASE : List[Any] = node.next def __len__( self : int ): '''simple docstring''' return sum(1 for _ in self ) def __repr__( self : Optional[int] ): '''simple docstring''' return "->".join([str(__A ) for item in self] ) def __getitem__( self : int , UpperCamelCase__ : int ): '''simple docstring''' if not 0 <= index < len(self ): raise ValueError('''list index out of range.''' ) for i, node in enumerate(self ): if i == index: return node return None def __setitem__( self : Tuple , UpperCamelCase__ : int , UpperCamelCase__ : Any ): '''simple docstring''' if not 0 <= index < len(self ): raise ValueError('''list index out of range.''' ) SCREAMING_SNAKE_CASE : List[str] = self.head for _ in range(__A ): SCREAMING_SNAKE_CASE : str = current.next SCREAMING_SNAKE_CASE : List[str] = data def __A ( self : int , UpperCamelCase__ : Any ): '''simple docstring''' self.insert_nth(len(self ) , __A ) def __A ( self : List[str] , UpperCamelCase__ : Any ): '''simple docstring''' self.insert_nth(0 , __A ) def __A ( self : str , UpperCamelCase__ : int , UpperCamelCase__ : Any ): '''simple docstring''' if not 0 <= index <= len(self ): raise IndexError('''list index out of range''' ) SCREAMING_SNAKE_CASE : List[Any] = Node(__A ) if self.head is None: SCREAMING_SNAKE_CASE : Tuple = new_node elif index == 0: SCREAMING_SNAKE_CASE : List[Any] = self.head # link new_node to head SCREAMING_SNAKE_CASE : Optional[int] = new_node else: SCREAMING_SNAKE_CASE : Optional[Any] = self.head for _ in range(index - 1 ): SCREAMING_SNAKE_CASE : Dict = temp.next SCREAMING_SNAKE_CASE : Optional[Any] = temp.next SCREAMING_SNAKE_CASE : Union[str, Any] = new_node def __A ( self : Union[str, Any] ): # print every node data '''simple docstring''' print(self ) def __A ( self : Dict ): '''simple docstring''' return self.delete_nth(0 ) def __A ( self : Tuple ): # delete from tail '''simple docstring''' return self.delete_nth(len(self ) - 1 ) def __A ( self : Optional[Any] , UpperCamelCase__ : int = 0 ): '''simple docstring''' if not 0 <= index <= len(self ) - 1: # test if index is valid raise IndexError('''List index out of range.''' ) SCREAMING_SNAKE_CASE : List[Any] = self.head # default first node if index == 0: SCREAMING_SNAKE_CASE : Any = self.head.next else: SCREAMING_SNAKE_CASE : Union[str, Any] = self.head for _ in range(index - 1 ): SCREAMING_SNAKE_CASE : int = temp.next SCREAMING_SNAKE_CASE : Tuple = temp.next SCREAMING_SNAKE_CASE : Optional[Any] = temp.next.next return delete_node.data def __A ( self : Any ): '''simple docstring''' return self.head is None def __A ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = None SCREAMING_SNAKE_CASE : Dict = self.head while current: # Store the current node's next node. SCREAMING_SNAKE_CASE : int = current.next # Make the current node's next point backwards SCREAMING_SNAKE_CASE : List[str] = prev # Make the previous node be the current node SCREAMING_SNAKE_CASE : Optional[int] = current # Make the current node the next node (to progress iteration) SCREAMING_SNAKE_CASE : Optional[int] = next_node # Return prev in order to put the head at the end SCREAMING_SNAKE_CASE : int = prev def A ( ): SCREAMING_SNAKE_CASE : Any = LinkedList() assert linked_list.is_empty() is True assert str(_lowercase ) == "" try: linked_list.delete_head() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. try: linked_list.delete_tail() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. for i in range(10 ): assert len(_lowercase ) == i linked_list.insert_nth(_lowercase , i + 1 ) assert str(_lowercase ) == "->".join(str(_lowercase ) for i in range(1 , 11 ) ) linked_list.insert_head(0 ) linked_list.insert_tail(11 ) assert str(_lowercase ) == "->".join(str(_lowercase ) for i in range(0 , 12 ) ) assert linked_list.delete_head() == 0 assert linked_list.delete_nth(9 ) == 10 assert linked_list.delete_tail() == 11 assert len(_lowercase ) == 9 assert str(_lowercase ) == "->".join(str(_lowercase ) for i in range(1 , 10 ) ) assert all(linked_list[i] == i + 1 for i in range(0 , 9 ) ) is True for i in range(0 , 9 ): SCREAMING_SNAKE_CASE : Optional[int] = -i assert all(linked_list[i] == -i for i in range(0 , 9 ) ) is True linked_list.reverse() assert str(_lowercase ) == "->".join(str(_lowercase ) for i in range(-8 , 1 ) ) def A ( ): SCREAMING_SNAKE_CASE : Optional[int] = [ -9, 100, Node(77_345_112 ), '''dlrow olleH''', 7, 5_555, 0, -192.55_555, '''Hello, world!''', 77.9, Node(10 ), None, None, 12.20, ] SCREAMING_SNAKE_CASE : Tuple = LinkedList() for i in test_input: linked_list.insert_tail(_lowercase ) # Check if it's empty or not assert linked_list.is_empty() is False assert ( str(_lowercase ) == "-9->100->Node(77345112)->dlrow olleH->7->5555->0->" "-192.55555->Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the head SCREAMING_SNAKE_CASE : Any = linked_list.delete_head() assert result == -9 assert ( str(_lowercase ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the tail SCREAMING_SNAKE_CASE : Optional[Any] = linked_list.delete_tail() assert result == 12.2 assert ( str(_lowercase ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None" ) # Delete a node in specific location in linked list SCREAMING_SNAKE_CASE : Union[str, Any] = linked_list.delete_nth(10 ) assert result is None assert ( str(_lowercase ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None" ) # Add a Node instance to its head linked_list.insert_head(Node('''Hello again, world!''' ) ) assert ( str(_lowercase ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None" ) # Add None to its tail linked_list.insert_tail(_lowercase ) assert ( str(_lowercase ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None->None" ) # Reverse the linked list linked_list.reverse() assert ( str(_lowercase ) == "None->None->Node(10)->77.9->Hello, world!->-192.55555->0->5555->" "7->dlrow olleH->Node(77345112)->100->Node(Hello again, world!)" ) def A ( ): from doctest import testmod testmod() SCREAMING_SNAKE_CASE : Tuple = LinkedList() linked_list.insert_head(input('''Inserting 1st at head ''' ).strip() ) linked_list.insert_head(input('''Inserting 2nd at head ''' ).strip() ) print('''\nPrint list:''' ) linked_list.print_list() linked_list.insert_tail(input('''\nInserting 1st at tail ''' ).strip() ) linked_list.insert_tail(input('''Inserting 2nd at tail ''' ).strip() ) print('''\nPrint list:''' ) linked_list.print_list() print('''\nDelete head''' ) linked_list.delete_head() print('''Delete tail''' ) linked_list.delete_tail() print('''\nPrint list:''' ) linked_list.print_list() print('''\nReverse linked list''' ) linked_list.reverse() print('''\nPrint list:''' ) linked_list.print_list() print('''\nString representation of linked list:''' ) print(_lowercase ) print('''\nReading/changing Node data using indexing:''' ) print(f"""Element at Position 1: {linked_list[1]}""" ) SCREAMING_SNAKE_CASE : Tuple = input('''Enter New Value: ''' ).strip() print('''New list:''' ) print(_lowercase ) print(f"""length of linked_list is : {len(_lowercase )}""" ) if __name__ == "__main__": main()
717
from __future__ import annotations import math from collections import Counter from string import ascii_lowercase def A ( _lowercase ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = analyze_text(_lowercase ) SCREAMING_SNAKE_CASE : Any = list(''' ''' + ascii_lowercase ) # what is our total sum of probabilities. SCREAMING_SNAKE_CASE : Tuple = sum(single_char_strings.values() ) # one length string SCREAMING_SNAKE_CASE : Tuple = 0 # for each alpha we go in our dict and if it is in it we calculate entropy for ch in my_alphas: if ch in single_char_strings: SCREAMING_SNAKE_CASE : Tuple = single_char_strings[ch] SCREAMING_SNAKE_CASE : List[str] = my_str / all_sum my_fir_sum += prob * math.loga(_lowercase ) # entropy formula. # print entropy print(f"""{round(-1 * my_fir_sum ):.1f}""" ) # two len string SCREAMING_SNAKE_CASE : Optional[Any] = sum(two_char_strings.values() ) SCREAMING_SNAKE_CASE : List[str] = 0 # for each alpha (two in size) calculate entropy. for cha in my_alphas: for cha in my_alphas: SCREAMING_SNAKE_CASE : Union[str, Any] = cha + cha if sequence in two_char_strings: SCREAMING_SNAKE_CASE : Any = two_char_strings[sequence] SCREAMING_SNAKE_CASE : Dict = int(_lowercase ) / all_sum my_sec_sum += prob * math.loga(_lowercase ) # print second entropy print(f"""{round(-1 * my_sec_sum ):.1f}""" ) # print the difference between them print(f"""{round((-1 * my_sec_sum) - (-1 * my_fir_sum) ):.1f}""" ) def A ( _lowercase ): SCREAMING_SNAKE_CASE : Tuple = Counter() # type: ignore SCREAMING_SNAKE_CASE : Any = Counter() # type: ignore single_char_strings[text[-1]] += 1 # first case when we have space at start. two_char_strings[" " + text[0]] += 1 for i in range(0 , len(_lowercase ) - 1 ): single_char_strings[text[i]] += 1 two_char_strings[text[i : i + 2]] += 1 return single_char_strings, two_char_strings def A ( ): import doctest doctest.testmod() # text = ( # "Had repulsive dashwoods suspicion sincerity but advantage now him. Remark " # "easily garret nor nay. Civil those mrs enjoy shy fat merry. You greatest " # "jointure saw horrible. He private he on be imagine suppose. Fertile " # "beloved evident through no service elderly is. Blind there if every no so " # "at. Own neglected you preferred way sincerity delivered his attempted. To " # "of message cottage windows do besides against uncivil. Delightful " # "unreserved impossible few estimating men favourable see entreaties. She " # "propriety immediate was improving. He or entrance humoured likewise " # "moderate. Much nor game son say feel. Fat make met can must form into " # "gate. Me we offending prevailed discovery. " # ) # calculate_prob(text) if __name__ == "__main__": main()
34
0
'''simple docstring''' def A ( _lowercase , _lowercase ): print('''\nThe shortest path matrix using Floyd Warshall algorithm\n''' ) for i in range(_lowerCamelCase ): for j in range(_lowerCamelCase ): if dist[i][j] != float('''inf''' ): print(int(dist[i][j] ) , end='''\t''' ) else: print('''INF''' , end='''\t''' ) print() def A ( _lowercase , _lowercase ): SCREAMING_SNAKE_CASE : Optional[int] = [[float('''inf''' ) for _ in range(_lowerCamelCase )] for _ in range(_lowerCamelCase )] for i in range(_lowerCamelCase ): for j in range(_lowerCamelCase ): SCREAMING_SNAKE_CASE : Dict = graph[i][j] # check vertex k against all other vertices (i, j) for k in range(_lowerCamelCase ): # looping through rows of graph array for i in range(_lowerCamelCase ): # looping through columns of graph array for j in range(_lowerCamelCase ): if ( dist[i][k] != float('''inf''' ) and dist[k][j] != float('''inf''' ) and dist[i][k] + dist[k][j] < dist[i][j] ): SCREAMING_SNAKE_CASE : Any = dist[i][k] + dist[k][j] _print_dist(_lowerCamelCase , _lowerCamelCase ) return dist, v if __name__ == "__main__": __UpperCamelCase : Tuple = int(input('Enter number of vertices: ')) __UpperCamelCase : Optional[int] = int(input('Enter number of edges: ')) __UpperCamelCase : Any = [[float('inf') for i in range(v)] for j in range(v)] for i in range(v): __UpperCamelCase : List[str] = 0.0 # src and dst are indices that must be within the array size graph[e][v] # failure to follow this will result in an error for i in range(e): print('\nEdge ', i + 1) __UpperCamelCase : str = int(input('Enter source:')) __UpperCamelCase : Dict = int(input('Enter destination:')) __UpperCamelCase : List[str] = float(input('Enter weight:')) __UpperCamelCase : str = weight floyd_warshall(graph, v) # Example Input # Enter number of vertices: 3 # Enter number of edges: 2 # # generated graph from vertex and edge inputs # [[inf, inf, inf], [inf, inf, inf], [inf, inf, inf]] # [[0.0, inf, inf], [inf, 0.0, inf], [inf, inf, 0.0]] # specify source, destination and weight for edge #1 # Edge 1 # Enter source:1 # Enter destination:2 # Enter weight:2 # specify source, destination and weight for edge #2 # Edge 2 # Enter source:2 # Enter destination:1 # Enter weight:1 # # Expected Output from the vertice, edge and src, dst, weight inputs!! # 0 INF INF # INF 0 2 # INF 1 0
718
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __UpperCamelCase : Tuple = { 'configuration_ctrl': ['CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP', 'CTRLConfig'], 'tokenization_ctrl': ['CTRLTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Dict = [ 'CTRL_PRETRAINED_MODEL_ARCHIVE_LIST', 'CTRLForSequenceClassification', 'CTRLLMHeadModel', 'CTRLModel', 'CTRLPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Any = [ 'TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFCTRLForSequenceClassification', 'TFCTRLLMHeadModel', 'TFCTRLModel', 'TFCTRLPreTrainedModel', ] if TYPE_CHECKING: from .configuration_ctrl import CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRLConfig from .tokenization_ctrl import CTRLTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ctrl import ( CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, CTRLForSequenceClassification, CTRLLMHeadModel, CTRLModel, CTRLPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_ctrl import ( TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, TFCTRLForSequenceClassification, TFCTRLLMHeadModel, TFCTRLModel, TFCTRLPreTrainedModel, ) else: import sys __UpperCamelCase : Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
34
0
import os def A ( ): SCREAMING_SNAKE_CASE : Dict = os.path.dirname(os.path.realpath(lowercase_ ) ) SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.join(lowercase_ , '''triangle.txt''' ) with open(lowercase_ ) as f: SCREAMING_SNAKE_CASE : List[Any] = f.readlines() SCREAMING_SNAKE_CASE : Optional[Any] = [] for line in triangle: SCREAMING_SNAKE_CASE : Optional[Any] = [] for number in line.strip().split(''' ''' ): numbers_from_line.append(int(lowercase_ ) ) a.append(lowercase_ ) for i in range(1 , len(lowercase_ ) ): for j in range(len(a[i] ) ): SCREAMING_SNAKE_CASE : int = a[i - 1][j] if j != len(a[i - 1] ) else 0 SCREAMING_SNAKE_CASE : Optional[int] = a[i - 1][j - 1] if j > 0 else 0 a[i][j] += max(lowercase_ , lowercase_ ) return max(a[-1] ) if __name__ == "__main__": print(solution())
719
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __UpperCamelCase : Tuple = { 'configuration_maskformer': ['MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MaskFormerConfig'], 'configuration_maskformer_swin': ['MaskFormerSwinConfig'], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Optional[Any] = ['MaskFormerFeatureExtractor'] __UpperCamelCase : List[Any] = ['MaskFormerImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Optional[int] = [ 'MASKFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'MaskFormerForInstanceSegmentation', 'MaskFormerModel', 'MaskFormerPreTrainedModel', ] __UpperCamelCase : Union[str, Any] = [ 'MaskFormerSwinBackbone', 'MaskFormerSwinModel', 'MaskFormerSwinPreTrainedModel', ] if TYPE_CHECKING: from .configuration_maskformer import MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskFormerConfig from .configuration_maskformer_swin import MaskFormerSwinConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_maskformer import MaskFormerFeatureExtractor from .image_processing_maskformer import MaskFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskformer import ( MASKFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskFormerForInstanceSegmentation, MaskFormerModel, MaskFormerPreTrainedModel, ) from .modeling_maskformer_swin import ( MaskFormerSwinBackbone, MaskFormerSwinModel, MaskFormerSwinPreTrainedModel, ) else: import sys __UpperCamelCase : List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure)
34
0
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 A ( _lowercase , _lowercase , _lowercase , _lowercase ): if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): SCREAMING_SNAKE_CASE : Tuple = np.full((len(lowerCAmelCase__ ), sequence_length, 2) , lowerCAmelCase__ ) else: SCREAMING_SNAKE_CASE : Union[str, Any] = np.full((len(lowerCAmelCase__ ), sequence_length) , lowerCAmelCase__ ) for i, tensor in enumerate(lowerCAmelCase__ ): if padding_side == "right": if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): SCREAMING_SNAKE_CASE : List[str] = tensor[:sequence_length] else: SCREAMING_SNAKE_CASE : Optional[int] = tensor[:sequence_length] else: if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): SCREAMING_SNAKE_CASE : Union[str, Any] = tensor[:sequence_length] else: SCREAMING_SNAKE_CASE : str = tensor[:sequence_length] return out_tensor.tolist() def A ( _lowercase ): SCREAMING_SNAKE_CASE : Optional[Any] = ord(lowerCAmelCase__ ) if (cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or (cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126): return True SCREAMING_SNAKE_CASE : Any = unicodedata.category(lowerCAmelCase__ ) if cat.startswith('''P''' ): return True return False @dataclass class lowercase__ ( __SCREAMING_SNAKE_CASE): UpperCamelCase_ = 42 UpperCamelCase_ = True UpperCamelCase_ = None UpperCamelCase_ = None UpperCamelCase_ = -100 UpperCamelCase_ = "pt" def __A ( self : Tuple , UpperCamelCase__ : List[str] ): '''simple docstring''' import torch SCREAMING_SNAKE_CASE : List[str] = '''label''' if '''label''' in features[0].keys() else '''labels''' SCREAMING_SNAKE_CASE : List[Any] = [feature[label_name] for feature in features] if label_name in features[0].keys() else None SCREAMING_SNAKE_CASE : 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 SCREAMING_SNAKE_CASE : Tuple = torch.tensor(batch['''entity_ids'''] ).shape[1] SCREAMING_SNAKE_CASE : Tuple = self.tokenizer.padding_side if padding_side == "right": SCREAMING_SNAKE_CASE : int = [ list(_a ) + [self.label_pad_token_id] * (sequence_length - len(_a )) for label in labels ] else: SCREAMING_SNAKE_CASE : List[Any] = [ [self.label_pad_token_id] * (sequence_length - len(_a )) + list(_a ) for label in labels ] SCREAMING_SNAKE_CASE : int = [feature['''ner_tags'''] for feature in features] SCREAMING_SNAKE_CASE : List[Any] = padding_tensor(_a , -1 , _a , _a ) SCREAMING_SNAKE_CASE : Any = [feature['''original_entity_spans'''] for feature in features] SCREAMING_SNAKE_CASE : Optional[Any] = padding_tensor(_a , (-1, -1) , _a , _a ) SCREAMING_SNAKE_CASE : List[str] = {k: torch.tensor(_a , dtype=torch.intaa ) for k, v in batch.items()} return batch
720
# 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 from ...utils.dataclasses import ( ComputeEnvironment, DistributedType, DynamoBackend, PrecisionType, SageMakerDistributedType, ) from ..menu import BulletMenu __UpperCamelCase : Dict = [ 'EAGER', 'AOT_EAGER', 'INDUCTOR', 'NVFUSER', 'AOT_NVFUSER', 'AOT_CUDAGRAPHS', 'OFI', 'FX2TRT', 'ONNXRT', 'IPEX', ] def A ( _lowercase , _lowercase=None , _lowercase=None , _lowercase=None ): SCREAMING_SNAKE_CASE : Union[str, Any] = True while ask_again: SCREAMING_SNAKE_CASE : Optional[Any] = input(_lowercase ) try: if default is not None and len(_lowercase ) == 0: return default return convert_value(_lowercase ) if convert_value is not None else result except Exception: if error_message is not None: print(_lowercase ) def A ( _lowercase , _lowercase=[] , _lowercase=None , _lowercase=0 ): SCREAMING_SNAKE_CASE : Dict = BulletMenu(_lowercase , _lowercase ) SCREAMING_SNAKE_CASE : str = menu.run(default_choice=_lowercase ) return convert_value(_lowercase ) if convert_value is not None else result def A ( _lowercase ): SCREAMING_SNAKE_CASE : Dict = int(_lowercase ) return ComputeEnvironment(['''LOCAL_MACHINE''', '''AMAZON_SAGEMAKER'''][value] ) def A ( _lowercase ): SCREAMING_SNAKE_CASE : Any = int(_lowercase ) return DistributedType(['''NO''', '''MULTI_CPU''', '''MULTI_XPU''', '''MULTI_GPU''', '''MULTI_NPU''', '''TPU'''][value] ) def A ( _lowercase ): SCREAMING_SNAKE_CASE : Union[str, Any] = int(_lowercase ) return DynamoBackend(DYNAMO_BACKENDS[value] ).value def A ( _lowercase ): SCREAMING_SNAKE_CASE : Union[str, Any] = int(_lowercase ) return PrecisionType(['''no''', '''fp16''', '''bf16''', '''fp8'''][value] ) def A ( _lowercase ): SCREAMING_SNAKE_CASE : Dict = int(_lowercase ) return SageMakerDistributedType(['''NO''', '''DATA_PARALLEL''', '''MODEL_PARALLEL'''][value] ) def A ( _lowercase ): return {"yes": True, "no": False}[value.lower()] class lowercase__ ( argparse.RawDescriptionHelpFormatter): def __A ( self : List[str] , UpperCamelCase__ : List[str] , UpperCamelCase__ : Dict , UpperCamelCase__ : Dict , UpperCamelCase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = super()._format_usage(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[Any] = usage.replace('''<command> [<args>] ''' , '''''' ) return usage
34
0
from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable __UpperCamelCase : Dict = {"""configuration_gpt_neox""": ["""GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GPTNeoXConfig"""]} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Any = ["""GPTNeoXTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : str = [ """GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST""", """GPTNeoXForCausalLM""", """GPTNeoXForQuestionAnswering""", """GPTNeoXForSequenceClassification""", """GPTNeoXForTokenClassification""", """GPTNeoXLayer""", """GPTNeoXModel""", """GPTNeoXPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_gpt_neox import GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXConfig try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_neox_fast import GPTNeoXTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox import ( GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, GPTNeoXLayer, GPTNeoXModel, GPTNeoXPreTrainedModel, ) else: import sys __UpperCamelCase : str = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
721
from __future__ import annotations from typing import Any class lowercase__ ( UpperCamelCase_): pass class lowercase__ : def __init__( self : Union[str, Any] , UpperCamelCase__ : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = data SCREAMING_SNAKE_CASE : Node | None = None def __iter__( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = self SCREAMING_SNAKE_CASE : Tuple = [] while node: if node in visited: raise ContainsLoopError visited.append(UpperCamelCase__ ) yield node.data SCREAMING_SNAKE_CASE : Dict = node.next_node @property def __A ( self : Optional[int] ): '''simple docstring''' try: list(self ) return False except ContainsLoopError: return True if __name__ == "__main__": __UpperCamelCase : List[Any] = Node(1) __UpperCamelCase : str = Node(2) __UpperCamelCase : Dict = Node(3) __UpperCamelCase : List[Any] = Node(4) print(root_node.has_loop) # False __UpperCamelCase : int = root_node.next_node print(root_node.has_loop) # True __UpperCamelCase : Union[str, Any] = Node(5) __UpperCamelCase : Union[str, Any] = Node(6) __UpperCamelCase : List[Any] = Node(5) __UpperCamelCase : List[str] = Node(6) print(root_node.has_loop) # False __UpperCamelCase : List[Any] = Node(1) print(root_node.has_loop) # False
34
0
import json import os import shutil import tempfile import unittest from transformers import BatchEncoding, CanineTokenizer from transformers.testing_utils import require_tokenizers, require_torch from transformers.tokenization_utils import AddedToken from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin class lowercase__ ( snake_case_ , unittest.TestCase): UpperCamelCase_ = CanineTokenizer UpperCamelCase_ = False def __A ( self : Optional[Any] ): '''simple docstring''' super().setUp() SCREAMING_SNAKE_CASE : Optional[int] = CanineTokenizer() tokenizer.save_pretrained(self.tmpdirname ) @cached_property def __A ( self : str ): '''simple docstring''' return CanineTokenizer.from_pretrained('''google/canine-s''' ) def __A ( self : List[Any] , **UpperCamelCase__ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = self.tokenizer_class.from_pretrained(self.tmpdirname , **UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[int] = 1024 return tokenizer @require_torch def __A ( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = self.canine_tokenizer SCREAMING_SNAKE_CASE : Union[str, Any] = ['''Life is like a box of chocolates.''', '''You never know what you\'re gonna get.'''] # fmt: off SCREAMING_SNAKE_CASE : Optional[Any] = [5_7344, 76, 105, 102, 101, 32, 105, 115, 32, 108, 105, 107, 101, 32, 97, 32, 98, 111, 120, 32, 111, 102, 32, 99, 104, 111, 99, 111, 108, 97, 116, 101, 115, 46, 5_7345, 0, 0, 0, 0] # fmt: on SCREAMING_SNAKE_CASE : int = tokenizer(UpperCamelCase__ , padding=UpperCamelCase__ , return_tensors='''pt''' ) self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE : int = list(batch.input_ids.numpy()[0] ) self.assertListEqual(UpperCamelCase__ , UpperCamelCase__ ) self.assertEqual((2, 39) , batch.input_ids.shape ) self.assertEqual((2, 39) , batch.attention_mask.shape ) @require_torch def __A ( self : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self.canine_tokenizer SCREAMING_SNAKE_CASE : List[Any] = ['''Once there was a man.''', '''He wrote a test in HuggingFace Tranformers.'''] SCREAMING_SNAKE_CASE : str = tokenizer(UpperCamelCase__ , padding=UpperCamelCase__ , return_tensors='''pt''' ) # check if input_ids, attention_mask and token_type_ids are returned self.assertIn('''input_ids''' , UpperCamelCase__ ) self.assertIn('''attention_mask''' , UpperCamelCase__ ) self.assertIn('''token_type_ids''' , UpperCamelCase__ ) @require_torch def __A ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = self.canine_tokenizer SCREAMING_SNAKE_CASE : Dict = [ '''What\'s the weater?''', '''It\'s about 25 degrees.''', ] SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer( text_target=UpperCamelCase__ , max_length=32 , padding='''max_length''' , truncation=UpperCamelCase__ , return_tensors='''pt''' ) self.assertEqual(32 , targets['''input_ids'''].shape[1] ) def __A ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f"""{tokenizer.__class__.__name__}""" ): self.assertNotEqual(tokenizer.model_max_length , 42 ) # Now let's start the test SCREAMING_SNAKE_CASE : List[Any] = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f"""{tokenizer.__class__.__name__}""" ): # Isolate this from the other tests because we save additional tokens/etc SCREAMING_SNAKE_CASE : Tuple = tempfile.mkdtemp() SCREAMING_SNAKE_CASE : Optional[Any] = ''' He is very happy, UNwant\u00E9d,running''' SCREAMING_SNAKE_CASE : str = tokenizer.encode(UpperCamelCase__ , add_special_tokens=UpperCamelCase__ ) tokenizer.save_pretrained(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer.__class__.from_pretrained(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Union[str, Any] = after_tokenizer.encode(UpperCamelCase__ , add_special_tokens=UpperCamelCase__ ) self.assertListEqual(UpperCamelCase__ , UpperCamelCase__ ) shutil.rmtree(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Tuple = self.get_tokenizers(model_max_length=42 ) for tokenizer in tokenizers: with self.subTest(f"""{tokenizer.__class__.__name__}""" ): # Isolate this from the other tests because we save additional tokens/etc SCREAMING_SNAKE_CASE : List[str] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE : str = ''' He is very happy, UNwant\u00E9d,running''' SCREAMING_SNAKE_CASE : int = tokenizer.additional_special_tokens # We can add a new special token for Canine as follows: SCREAMING_SNAKE_CASE : Dict = chr(0Xe0_07 ) additional_special_tokens.append(UpperCamelCase__ ) tokenizer.add_special_tokens({'''additional_special_tokens''': additional_special_tokens} ) SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer.encode(UpperCamelCase__ , add_special_tokens=UpperCamelCase__ ) tokenizer.save_pretrained(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Any = tokenizer.__class__.from_pretrained(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Union[str, Any] = after_tokenizer.encode(UpperCamelCase__ , add_special_tokens=UpperCamelCase__ ) self.assertListEqual(UpperCamelCase__ , UpperCamelCase__ ) self.assertIn(UpperCamelCase__ , after_tokenizer.additional_special_tokens ) self.assertEqual(after_tokenizer.model_max_length , 42 ) SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer.__class__.from_pretrained(UpperCamelCase__ , model_max_length=43 ) self.assertEqual(tokenizer.model_max_length , 43 ) shutil.rmtree(UpperCamelCase__ ) def __A ( self : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self.get_tokenizers(do_lower_case=UpperCamelCase__ ) for tokenizer in tokenizers: with self.subTest(f"""{tokenizer.__class__.__name__}""" ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[Any] = self.get_clean_sequence(UpperCamelCase__ ) # a special token for Canine can be defined as follows: SCREAMING_SNAKE_CASE : Dict = 0Xe0_05 SCREAMING_SNAKE_CASE : List[Any] = chr(UpperCamelCase__ ) tokenizer.add_special_tokens({'''cls_token''': special_token} ) SCREAMING_SNAKE_CASE : List[Any] = tokenizer.encode(UpperCamelCase__ , add_special_tokens=UpperCamelCase__ ) self.assertEqual(len(UpperCamelCase__ ) , 1 ) SCREAMING_SNAKE_CASE : List[Any] = tokenizer.decode(ids + encoded_special_token , clean_up_tokenization_spaces=UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[Any] = tokenizer.encode(UpperCamelCase__ , add_special_tokens=UpperCamelCase__ ) SCREAMING_SNAKE_CASE : int = tokenizer.encode(UpperCamelCase__ , add_special_tokens=UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[int] = tokenizer.encode(UpperCamelCase__ , add_special_tokens=UpperCamelCase__ ) self.assertEqual(UpperCamelCase__ , input_encoded + special_token_id ) SCREAMING_SNAKE_CASE : List[Any] = tokenizer.decode(UpperCamelCase__ , skip_special_tokens=UpperCamelCase__ ) self.assertTrue(special_token not in decoded ) def __A ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self.get_tokenizers(do_lower_case=UpperCamelCase__ ) for tokenizer in tokenizers: with self.subTest(f"""{tokenizer.__class__.__name__}""" ): SCREAMING_SNAKE_CASE : List[str] = chr(0Xe0_05 ) SCREAMING_SNAKE_CASE : List[str] = chr(0Xe0_06 ) # `add_tokens` method stores special tokens only in `tokenizer.unique_no_split_tokens`. (in tokenization_utils.py) tokenizer.add_tokens([SPECIAL_TOKEN_1] , special_tokens=UpperCamelCase__ ) # `add_special_tokens` method stores special tokens in `tokenizer.additional_special_tokens`, # which also occur in `tokenizer.all_special_tokens`. (in tokenization_utils_base.py) tokenizer.add_special_tokens({'''additional_special_tokens''': [SPECIAL_TOKEN_2]} ) SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer.tokenize(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : int = tokenizer.tokenize(UpperCamelCase__ ) self.assertEqual(len(UpperCamelCase__ ) , 1 ) self.assertEqual(len(UpperCamelCase__ ) , 1 ) self.assertEqual(token_a[0] , UpperCamelCase__ ) self.assertEqual(token_a[0] , UpperCamelCase__ ) @require_tokenizers def __A ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = self.get_tokenizers(do_lower_case=UpperCamelCase__ ) for tokenizer in tokenizers: with self.subTest(f"""{tokenizer.__class__.__name__}""" ): # a special token for Canine can be defined as follows: SCREAMING_SNAKE_CASE : str = 0Xe0_06 SCREAMING_SNAKE_CASE : Tuple = chr(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[str] = AddedToken(UpperCamelCase__ , lstrip=UpperCamelCase__ ) tokenizer.add_special_tokens({'''additional_special_tokens''': [new_token]} ) with tempfile.TemporaryDirectory() as tmp_dir_name: tokenizer.save_pretrained(UpperCamelCase__ ) tokenizer.from_pretrained(UpperCamelCase__ ) def __A ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(UpperCamelCase__ ) with open(os.path.join(UpperCamelCase__ , '''special_tokens_map.json''' ) , encoding='''utf-8''' ) as json_file: SCREAMING_SNAKE_CASE : Dict = json.load(UpperCamelCase__ ) with open(os.path.join(UpperCamelCase__ , '''tokenizer_config.json''' ) , encoding='''utf-8''' ) as json_file: SCREAMING_SNAKE_CASE : List[Any] = json.load(UpperCamelCase__ ) # a special token for Canine can be defined as follows: SCREAMING_SNAKE_CASE : str = 0Xe0_06 SCREAMING_SNAKE_CASE : List[str] = chr(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : int = [new_token_a] SCREAMING_SNAKE_CASE : int = [new_token_a] with open(os.path.join(UpperCamelCase__ , '''special_tokens_map.json''' ) , '''w''' , encoding='''utf-8''' ) as outfile: json.dump(UpperCamelCase__ , UpperCamelCase__ ) with open(os.path.join(UpperCamelCase__ , '''tokenizer_config.json''' ) , '''w''' , encoding='''utf-8''' ) as outfile: json.dump(UpperCamelCase__ , UpperCamelCase__ ) # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and # "special_tokens_map.json" files SCREAMING_SNAKE_CASE : Dict = tokenizer_class.from_pretrained(UpperCamelCase__ , extra_ids=0 ) self.assertIn(UpperCamelCase__ , tokenizer_without_change_in_init.additional_special_tokens ) # self.assertIn("an_additional_special_token",tokenizer_without_change_in_init.get_vocab()) # ByT5Tokenization no vocab self.assertEqual( [new_token_a] , tokenizer_without_change_in_init.convert_ids_to_tokens( tokenizer_without_change_in_init.convert_tokens_to_ids([new_token_a] ) ) , ) SCREAMING_SNAKE_CASE : Union[str, Any] = 0Xe0_07 SCREAMING_SNAKE_CASE : Union[str, Any] = chr(UpperCamelCase__ ) # Now we test that we can change the value of additional_special_tokens in the from_pretrained SCREAMING_SNAKE_CASE : int = [AddedToken(UpperCamelCase__ , lstrip=UpperCamelCase__ )] SCREAMING_SNAKE_CASE : Optional[int] = tokenizer_class.from_pretrained( UpperCamelCase__ , additional_special_tokens=UpperCamelCase__ , extra_ids=0 ) self.assertIn(UpperCamelCase__ , tokenizer.additional_special_tokens ) # self.assertIn(new_token_2,tokenizer.get_vocab()) # ByT5Tokenization no vocab self.assertEqual( [new_token_a] , tokenizer.convert_ids_to_tokens(tokenizer.convert_tokens_to_ids([new_token_a] ) ) ) @require_tokenizers def __A ( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self.get_tokenizers(do_lower_case=UpperCamelCase__ ) for tokenizer in tokenizers: with self.subTest(f"""{tokenizer.__class__.__name__}""" ): SCREAMING_SNAKE_CASE : Union[str, Any] = '''hello world''' if self.space_between_special_tokens: SCREAMING_SNAKE_CASE : List[Any] = '''[CLS] hello world [SEP]''' else: SCREAMING_SNAKE_CASE : Dict = input SCREAMING_SNAKE_CASE : Optional[int] = tokenizer.encode(UpperCamelCase__ , add_special_tokens=UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Dict = tokenizer.decode(UpperCamelCase__ , spaces_between_special_tokens=self.space_between_special_tokens ) self.assertIn(UpperCamelCase__ , [output, output.lower()] ) def __A ( self : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f"""{tokenizer.__class__.__name__}""" ): SCREAMING_SNAKE_CASE : Union[str, Any] = [ '''bos_token''', '''eos_token''', '''unk_token''', '''sep_token''', '''pad_token''', '''cls_token''', '''mask_token''', ] SCREAMING_SNAKE_CASE : Tuple = '''a''' SCREAMING_SNAKE_CASE : Optional[Any] = ord(UpperCamelCase__ ) for attr in attributes_list: setattr(UpperCamelCase__ , attr + '''_id''' , UpperCamelCase__ ) self.assertEqual(getattr(UpperCamelCase__ , UpperCamelCase__ ) , UpperCamelCase__ ) self.assertEqual(getattr(UpperCamelCase__ , attr + '''_id''' ) , UpperCamelCase__ ) setattr(UpperCamelCase__ , attr + '''_id''' , UpperCamelCase__ ) self.assertEqual(getattr(UpperCamelCase__ , UpperCamelCase__ ) , UpperCamelCase__ ) self.assertEqual(getattr(UpperCamelCase__ , attr + '''_id''' ) , UpperCamelCase__ ) setattr(UpperCamelCase__ , '''additional_special_tokens_ids''' , [] ) self.assertListEqual(getattr(UpperCamelCase__ , '''additional_special_tokens''' ) , [] ) self.assertListEqual(getattr(UpperCamelCase__ , '''additional_special_tokens_ids''' ) , [] ) SCREAMING_SNAKE_CASE : Optional[int] = 0Xe0_06 SCREAMING_SNAKE_CASE : Dict = chr(UpperCamelCase__ ) setattr(UpperCamelCase__ , '''additional_special_tokens_ids''' , [additional_special_token_id] ) self.assertListEqual(getattr(UpperCamelCase__ , '''additional_special_tokens''' ) , [additional_special_token] ) self.assertListEqual(getattr(UpperCamelCase__ , '''additional_special_tokens_ids''' ) , [additional_special_token_id] ) def __A ( self : List[Any] ): '''simple docstring''' pass def __A ( self : str ): '''simple docstring''' pass def __A ( self : List[Any] ): '''simple docstring''' pass def __A ( self : int ): '''simple docstring''' pass def __A ( self : Tuple ): '''simple docstring''' pass def __A ( self : Union[str, Any] ): '''simple docstring''' pass def __A ( self : int ): '''simple docstring''' pass def __A ( self : Any ): '''simple docstring''' pass
700
import copy from typing import Any, Dict, List, Optional, Union import numpy as np import torch from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import TensorType, logging __UpperCamelCase : Union[str, Any] = logging.get_logger(__name__) class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = ["""input_features""", """is_longer"""] def __init__( self : Optional[Any] , UpperCamelCase__ : Dict=64 , UpperCamelCase__ : Optional[Any]=4_8000 , UpperCamelCase__ : Tuple=480 , UpperCamelCase__ : Union[str, Any]=10 , UpperCamelCase__ : List[Any]=1024 , UpperCamelCase__ : Tuple=0.0 , UpperCamelCase__ : int=False , UpperCamelCase__ : float = 0 , UpperCamelCase__ : float = 1_4000 , UpperCamelCase__ : int = None , UpperCamelCase__ : str = "fusion" , UpperCamelCase__ : str = "repeatpad" , **UpperCamelCase__ : Union[str, Any] , ): '''simple docstring''' super().__init__( feature_size=UpperCamelCase__ , sampling_rate=UpperCamelCase__ , padding_value=UpperCamelCase__ , return_attention_mask=UpperCamelCase__ , **UpperCamelCase__ , ) SCREAMING_SNAKE_CASE : Union[str, Any] = top_db SCREAMING_SNAKE_CASE : Union[str, Any] = truncation SCREAMING_SNAKE_CASE : str = padding SCREAMING_SNAKE_CASE : List[Any] = fft_window_size SCREAMING_SNAKE_CASE : Tuple = (fft_window_size >> 1) + 1 SCREAMING_SNAKE_CASE : List[str] = hop_length SCREAMING_SNAKE_CASE : List[Any] = max_length_s SCREAMING_SNAKE_CASE : Tuple = max_length_s * sampling_rate SCREAMING_SNAKE_CASE : List[Any] = sampling_rate SCREAMING_SNAKE_CASE : List[str] = frequency_min SCREAMING_SNAKE_CASE : Any = frequency_max SCREAMING_SNAKE_CASE : List[Any] = mel_filter_bank( num_frequency_bins=self.nb_frequency_bins , num_mel_filters=UpperCamelCase__ , min_frequency=UpperCamelCase__ , max_frequency=UpperCamelCase__ , sampling_rate=UpperCamelCase__ , norm=UpperCamelCase__ , mel_scale='''htk''' , ) SCREAMING_SNAKE_CASE : Optional[Any] = mel_filter_bank( num_frequency_bins=self.nb_frequency_bins , num_mel_filters=UpperCamelCase__ , min_frequency=UpperCamelCase__ , max_frequency=UpperCamelCase__ , sampling_rate=UpperCamelCase__ , norm='''slaney''' , mel_scale='''slaney''' , ) def __A ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE : Optional[Any] = self.__class__.__name__ if "mel_filters" in output: del output["mel_filters"] if "mel_filters_slaney" in output: del output["mel_filters_slaney"] return output def __A ( self : Optional[int] , UpperCamelCase__ : np.array , UpperCamelCase__ : Optional[np.array] = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = spectrogram( UpperCamelCase__ , window_function(self.fft_window_size , '''hann''' ) , frame_length=self.fft_window_size , hop_length=self.hop_length , power=2.0 , mel_filters=UpperCamelCase__ , log_mel='''dB''' , ) return log_mel_spectrogram.T def __A ( self : Union[str, Any] , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Dict , UpperCamelCase__ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = np.array_split(list(range(0 , total_frames - chunk_frames + 1 ) ) , 3 ) if len(ranges[1] ) == 0: # if the audio is too short, we just use the first chunk SCREAMING_SNAKE_CASE : int = [0] if len(ranges[2] ) == 0: # if the audio is too short, we just use the first chunk SCREAMING_SNAKE_CASE : Any = [0] # randomly choose index for each part SCREAMING_SNAKE_CASE : Union[str, Any] = np.random.choice(ranges[0] ) SCREAMING_SNAKE_CASE : List[Any] = np.random.choice(ranges[1] ) SCREAMING_SNAKE_CASE : int = np.random.choice(ranges[2] ) SCREAMING_SNAKE_CASE : Optional[int] = mel[idx_front : idx_front + chunk_frames, :] SCREAMING_SNAKE_CASE : Optional[Any] = mel[idx_middle : idx_middle + chunk_frames, :] SCREAMING_SNAKE_CASE : Tuple = mel[idx_back : idx_back + chunk_frames, :] SCREAMING_SNAKE_CASE : str = torch.tensor(mel[None, None, :] ) SCREAMING_SNAKE_CASE : Optional[int] = torch.nn.functional.interpolate( UpperCamelCase__ , size=[chunk_frames, 64] , mode='''bilinear''' , align_corners=UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[Any] = mel_shrink[0][0].numpy() SCREAMING_SNAKE_CASE : Union[str, Any] = np.stack([mel_shrink, mel_chunk_front, mel_chunk_middle, mel_chunk_back] , axis=0 ) return mel_fusion def __A ( self : Dict , UpperCamelCase__ : np.array , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Dict , UpperCamelCase__ : List[str] ): '''simple docstring''' if waveform.shape[0] > max_length: if truncation == "rand_trunc": SCREAMING_SNAKE_CASE : Optional[Any] = True # random crop to max_length (for compatibility) -> this should be handled by self.pad SCREAMING_SNAKE_CASE : List[Any] = len(UpperCamelCase__ ) - max_length SCREAMING_SNAKE_CASE : Dict = np.random.randint(0 , overflow + 1 ) SCREAMING_SNAKE_CASE : Optional[Any] = waveform[idx : idx + max_length] SCREAMING_SNAKE_CASE : Any = self._np_extract_fbank_features(UpperCamelCase__ , self.mel_filters_slaney )[None, :] elif truncation == "fusion": SCREAMING_SNAKE_CASE : Any = self._np_extract_fbank_features(UpperCamelCase__ , self.mel_filters ) SCREAMING_SNAKE_CASE : List[str] = max_length // self.hop_length + 1 # the +1 related to how the spectrogram is computed SCREAMING_SNAKE_CASE : List[Any] = mel.shape[0] if chunk_frames == total_frames: # there is a corner case where the audio length is larger than max_length but smaller than max_length+hop_length. # In this case, we just use the whole audio. SCREAMING_SNAKE_CASE : Optional[Any] = np.stack([mel, mel, mel, mel] , axis=0 ) SCREAMING_SNAKE_CASE : Tuple = False else: SCREAMING_SNAKE_CASE : str = self._random_mel_fusion(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[int] = True else: raise NotImplementedError(f"""data_truncating {truncation} not implemented""" ) else: SCREAMING_SNAKE_CASE : List[str] = False # only use repeat as a new possible value for padding. you repeat the audio before applying the usual max_length padding if waveform.shape[0] < max_length: if padding == "repeat": SCREAMING_SNAKE_CASE : Tuple = int(max_length / len(UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE : Any = np.stack(np.tile(UpperCamelCase__ , n_repeat + 1 ) )[:max_length] if padding == "repeatpad": SCREAMING_SNAKE_CASE : List[Any] = int(max_length / len(UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE : Dict = np.stack(np.tile(UpperCamelCase__ , UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE : Dict = np.pad(UpperCamelCase__ , (0, max_length - waveform.shape[0]) , mode='''constant''' , constant_values=0 ) if truncation == "fusion": SCREAMING_SNAKE_CASE : List[Any] = self._np_extract_fbank_features(UpperCamelCase__ , self.mel_filters ) SCREAMING_SNAKE_CASE : Union[str, Any] = np.stack([input_mel, input_mel, input_mel, input_mel] , axis=0 ) else: SCREAMING_SNAKE_CASE : List[str] = self._np_extract_fbank_features(UpperCamelCase__ , self.mel_filters_slaney )[None, :] return input_mel, longer def __call__( self : Union[str, Any] , UpperCamelCase__ : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , UpperCamelCase__ : str = None , UpperCamelCase__ : Optional[str] = None , UpperCamelCase__ : Optional[int] = None , UpperCamelCase__ : Optional[int] = None , UpperCamelCase__ : Optional[Union[str, TensorType]] = None , **UpperCamelCase__ : Any , ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = truncation if truncation is not None else self.truncation SCREAMING_SNAKE_CASE : List[str] = padding if padding else self.padding if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f"""The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a""" f""" sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input""" f""" was sampled with {self.sampling_rate} and not {sampling_rate}.""" ) else: logger.warning( '''It is strongly recommended to pass the `sampling_rate` argument to this function. ''' '''Failing to do so can result in silent errors that might be hard to debug.''' ) SCREAMING_SNAKE_CASE : List[str] = isinstance(UpperCamelCase__ , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f"""Only mono-channel audio is supported for input to {self}""" ) SCREAMING_SNAKE_CASE : int = is_batched_numpy or ( isinstance(UpperCamelCase__ , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: SCREAMING_SNAKE_CASE : Any = [np.asarray(UpperCamelCase__ , dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(UpperCamelCase__ , np.ndarray ): SCREAMING_SNAKE_CASE : List[Any] = np.asarray(UpperCamelCase__ , dtype=np.floataa ) elif isinstance(UpperCamelCase__ , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): SCREAMING_SNAKE_CASE : Union[str, Any] = raw_speech.astype(np.floataa ) # always return batch if not is_batched: SCREAMING_SNAKE_CASE : List[str] = [np.asarray(UpperCamelCase__ )] # convert to mel spectrogram, truncate and pad if needed. SCREAMING_SNAKE_CASE : int = [ self._get_input_mel(UpperCamelCase__ , max_length if max_length else self.nb_max_samples , UpperCamelCase__ , UpperCamelCase__ ) for waveform in raw_speech ] SCREAMING_SNAKE_CASE : str = [] SCREAMING_SNAKE_CASE : List[str] = [] for mel, longer in padded_inputs: input_mel.append(UpperCamelCase__ ) is_longer.append(UpperCamelCase__ ) if truncation == "fusion" and sum(UpperCamelCase__ ) == 0: # if no audio is longer than 10s, then randomly select one audio to be longer SCREAMING_SNAKE_CASE : Union[str, Any] = np.random.randint(0 , len(UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE : Optional[Any] = True if isinstance(input_mel[0] , UpperCamelCase__ ): SCREAMING_SNAKE_CASE : Union[str, Any] = [np.asarray(UpperCamelCase__ , dtype=np.floataa ) for feature in input_mel] # is_longer is a list of bool SCREAMING_SNAKE_CASE : Optional[Any] = [[longer] for longer in is_longer] SCREAMING_SNAKE_CASE : Union[str, Any] = {'''input_features''': input_mel, '''is_longer''': is_longer} SCREAMING_SNAKE_CASE : int = BatchFeature(UpperCamelCase__ ) if return_tensors is not None: SCREAMING_SNAKE_CASE : int = input_features.convert_to_tensors(UpperCamelCase__ ) return input_features
34
0
import math def A ( _lowercase ): assert isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) and ( number >= 0 ), "'number' must been an int and positive" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or not number % 2: # Negatives, 0, 1 and all even numbers are not primes return False SCREAMING_SNAKE_CASE : Optional[Any] = range(3 , int(math.sqrt(SCREAMING_SNAKE_CASE_ ) + 1 ) , 2 ) return not any(not number % i for i in odd_numbers ) def A ( _lowercase , _lowercase=1 , **_lowercase ): SCREAMING_SNAKE_CASE : Tuple = factor * value SCREAMING_SNAKE_CASE : List[str] = value while not is_prime(SCREAMING_SNAKE_CASE_ ): value += 1 if not ("desc" in kwargs and kwargs["desc"] is True) else -1 if value == first_value_val: return next_prime(value + 1 , **SCREAMING_SNAKE_CASE_ ) return value
701
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...utils import logging if TYPE_CHECKING: from ...processing_utils import ProcessorMixin from ...utils import TensorType __UpperCamelCase : str = logging.get_logger(__name__) __UpperCamelCase : str = { 'microsoft/layoutlmv3-base': 'https://huggingface.co/microsoft/layoutlmv3-base/resolve/main/config.json', } class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = """layoutlmv3""" def __init__( self : Optional[int] , UpperCamelCase__ : Union[str, Any]=5_0265 , UpperCamelCase__ : List[Any]=768 , UpperCamelCase__ : Union[str, Any]=12 , UpperCamelCase__ : Union[str, Any]=12 , UpperCamelCase__ : Tuple=3072 , UpperCamelCase__ : List[Any]="gelu" , UpperCamelCase__ : List[Any]=0.1 , UpperCamelCase__ : List[str]=0.1 , UpperCamelCase__ : Any=512 , UpperCamelCase__ : List[Any]=2 , UpperCamelCase__ : List[Any]=0.02 , UpperCamelCase__ : Optional[Any]=1E-5 , UpperCamelCase__ : List[str]=1 , UpperCamelCase__ : int=0 , UpperCamelCase__ : str=2 , UpperCamelCase__ : List[str]=1024 , UpperCamelCase__ : str=128 , UpperCamelCase__ : str=128 , UpperCamelCase__ : Tuple=True , UpperCamelCase__ : Optional[int]=32 , UpperCamelCase__ : Any=128 , UpperCamelCase__ : Optional[Any]=64 , UpperCamelCase__ : Dict=256 , UpperCamelCase__ : List[Any]=True , UpperCamelCase__ : str=True , UpperCamelCase__ : Dict=True , UpperCamelCase__ : Dict=224 , UpperCamelCase__ : Optional[Any]=3 , UpperCamelCase__ : Any=16 , UpperCamelCase__ : Any=None , **UpperCamelCase__ : Optional[Any] , ): '''simple docstring''' super().__init__( vocab_size=UpperCamelCase__ , hidden_size=UpperCamelCase__ , num_hidden_layers=UpperCamelCase__ , num_attention_heads=UpperCamelCase__ , intermediate_size=UpperCamelCase__ , hidden_act=UpperCamelCase__ , hidden_dropout_prob=UpperCamelCase__ , attention_probs_dropout_prob=UpperCamelCase__ , max_position_embeddings=UpperCamelCase__ , type_vocab_size=UpperCamelCase__ , initializer_range=UpperCamelCase__ , layer_norm_eps=UpperCamelCase__ , pad_token_id=UpperCamelCase__ , bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ , **UpperCamelCase__ , ) SCREAMING_SNAKE_CASE : Union[str, Any] = max_ad_position_embeddings SCREAMING_SNAKE_CASE : List[Any] = coordinate_size SCREAMING_SNAKE_CASE : List[str] = shape_size SCREAMING_SNAKE_CASE : Optional[int] = has_relative_attention_bias SCREAMING_SNAKE_CASE : List[Any] = rel_pos_bins SCREAMING_SNAKE_CASE : str = max_rel_pos SCREAMING_SNAKE_CASE : Any = has_spatial_attention_bias SCREAMING_SNAKE_CASE : Union[str, Any] = rel_ad_pos_bins SCREAMING_SNAKE_CASE : Union[str, Any] = max_rel_ad_pos SCREAMING_SNAKE_CASE : Union[str, Any] = text_embed SCREAMING_SNAKE_CASE : List[str] = visual_embed SCREAMING_SNAKE_CASE : Optional[Any] = input_size SCREAMING_SNAKE_CASE : Optional[Any] = num_channels SCREAMING_SNAKE_CASE : List[Any] = patch_size SCREAMING_SNAKE_CASE : List[Any] = classifier_dropout class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = version.parse("""1.12""") @property def __A ( self : str ): '''simple docstring''' if self.task in ["question-answering", "sequence-classification"]: return OrderedDict( [ ('''input_ids''', {0: '''batch''', 1: '''sequence'''}), ('''attention_mask''', {0: '''batch''', 1: '''sequence'''}), ('''bbox''', {0: '''batch''', 1: '''sequence'''}), ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) else: return OrderedDict( [ ('''input_ids''', {0: '''batch''', 1: '''sequence'''}), ('''bbox''', {0: '''batch''', 1: '''sequence'''}), ('''attention_mask''', {0: '''batch''', 1: '''sequence'''}), ('''pixel_values''', {0: '''batch''', 1: '''num_channels'''}), ] ) @property def __A ( self : int ): '''simple docstring''' return 1E-5 @property def __A ( self : Union[str, Any] ): '''simple docstring''' return 12 def __A ( self : Optional[Any] , UpperCamelCase__ : "ProcessorMixin" , UpperCamelCase__ : int = -1 , UpperCamelCase__ : int = -1 , UpperCamelCase__ : bool = False , UpperCamelCase__ : Optional["TensorType"] = None , UpperCamelCase__ : int = 3 , UpperCamelCase__ : int = 40 , UpperCamelCase__ : int = 40 , ): '''simple docstring''' setattr(processor.image_processor , '''apply_ocr''' , UpperCamelCase__ ) # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX SCREAMING_SNAKE_CASE : Any = compute_effective_axis_dimension( UpperCamelCase__ , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX SCREAMING_SNAKE_CASE : List[Any] = processor.tokenizer.num_special_tokens_to_add(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Tuple = compute_effective_axis_dimension( UpperCamelCase__ , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=UpperCamelCase__ ) # Generate dummy inputs according to compute batch and sequence SCREAMING_SNAKE_CASE : Union[str, Any] = [[''' '''.join([processor.tokenizer.unk_token] ) * seq_length]] * batch_size # Generate dummy bounding boxes SCREAMING_SNAKE_CASE : Any = [[[48, 84, 73, 128]]] * batch_size # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX # batch_size = compute_effective_axis_dimension(batch_size, fixed_dimension=OnnxConfig.default_fixed_batch) SCREAMING_SNAKE_CASE : List[Any] = self._generate_dummy_images(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[int] = dict( processor( UpperCamelCase__ , text=UpperCamelCase__ , boxes=UpperCamelCase__ , return_tensors=UpperCamelCase__ , ) ) return inputs
34
0
import argparse import logging from collections import namedtuple import torch from model_bertabs import BertAbsSummarizer from models.model_builder import AbsSummarizer # The authors' implementation from transformers import BertTokenizer logging.basicConfig(level=logging.INFO) __UpperCamelCase : List[str] = logging.getLogger(__name__) __UpperCamelCase : List[Any] = 'Hello world! cécé herlolip' __UpperCamelCase : Any = namedtuple( 'BertAbsConfig', [ 'temp_dir', 'large', 'use_bert_emb', 'finetune_bert', 'encoder', 'share_emb', 'max_pos', 'enc_layers', 'enc_hidden_size', 'enc_heads', 'enc_ff_size', 'enc_dropout', 'dec_layers', 'dec_hidden_size', 'dec_heads', 'dec_ff_size', 'dec_dropout', ], ) def A ( _lowercase , _lowercase ): SCREAMING_SNAKE_CASE : Dict = BertAbsConfig( temp_dir='''.''' , finetune_bert=SCREAMING_SNAKE_CASE_ , large=SCREAMING_SNAKE_CASE_ , share_emb=SCREAMING_SNAKE_CASE_ , use_bert_emb=SCREAMING_SNAKE_CASE_ , encoder='''bert''' , max_pos=512 , enc_layers=6 , enc_hidden_size=512 , enc_heads=8 , enc_ff_size=512 , enc_dropout=0.2 , dec_layers=6 , dec_hidden_size=768 , dec_heads=8 , dec_ff_size=2_048 , dec_dropout=0.2 , ) SCREAMING_SNAKE_CASE : Optional[int] = torch.load(SCREAMING_SNAKE_CASE_ , lambda _lowercase , _lowercase : storage ) SCREAMING_SNAKE_CASE : int = AbsSummarizer(SCREAMING_SNAKE_CASE_ , torch.device('''cpu''' ) , SCREAMING_SNAKE_CASE_ ) original.eval() SCREAMING_SNAKE_CASE : str = BertAbsSummarizer(SCREAMING_SNAKE_CASE_ , torch.device('''cpu''' ) ) new_model.eval() # ------------------- # Convert the weights # ------------------- logging.info('''convert the model''' ) new_model.bert.load_state_dict(original.bert.state_dict() ) new_model.decoder.load_state_dict(original.decoder.state_dict() ) new_model.generator.load_state_dict(original.generator.state_dict() ) # ---------------------------------- # Make sure the outpus are identical # ---------------------------------- logging.info('''Make sure that the models\' outputs are identical''' ) SCREAMING_SNAKE_CASE : Dict = BertTokenizer.from_pretrained('''bert-base-uncased''' ) # prepare the model inputs SCREAMING_SNAKE_CASE : int = tokenizer.encode('''This is sample éàalj\'-.''' ) encoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(SCREAMING_SNAKE_CASE_ )) ) SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor(SCREAMING_SNAKE_CASE_ ).unsqueeze(0 ) SCREAMING_SNAKE_CASE : Dict = tokenizer.encode('''This is sample 3 éàalj\'-.''' ) decoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(SCREAMING_SNAKE_CASE_ )) ) SCREAMING_SNAKE_CASE : Tuple = torch.tensor(SCREAMING_SNAKE_CASE_ ).unsqueeze(0 ) # failsafe to make sure the weights reset does not affect the # loaded weights. assert torch.max(torch.abs(original.generator[0].weight - new_model.generator[0].weight ) ) == 0 # forward pass SCREAMING_SNAKE_CASE : List[str] = encoder_input_ids SCREAMING_SNAKE_CASE : Optional[Any] = decoder_input_ids SCREAMING_SNAKE_CASE : Any = None SCREAMING_SNAKE_CASE : Optional[int] = None SCREAMING_SNAKE_CASE : Optional[Any] = None SCREAMING_SNAKE_CASE : Union[str, Any] = None SCREAMING_SNAKE_CASE : int = None # The original model does not apply the geneator layer immediatly but rather in # the beam search (where it combines softmax + linear layer). Since we already # apply the softmax in our generation process we only apply the linear layer here. # We make sure that the outputs of the full stack are identical SCREAMING_SNAKE_CASE : List[Any] = original(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )[0] SCREAMING_SNAKE_CASE : Optional[Any] = original.generator(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE : Dict = new_model( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )[0] SCREAMING_SNAKE_CASE : str = new_model.generator(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE : Any = torch.max(torch.abs(output_converted_model - output_original_model ) ).item() print('''Maximum absolute difference beween weights: {:.2f}'''.format(SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE : List[Any] = torch.max(torch.abs(output_converted_generator - output_original_generator ) ).item() print('''Maximum absolute difference beween weights: {:.2f}'''.format(SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE : Any = torch.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1e-3 ) if are_identical: logging.info('''all weights are equal up to 1e-3''' ) else: raise ValueError('''the weights are different. The new model is likely different from the original one.''' ) # The model has been saved with torch.save(model) and this is bound to the exact # directory structure. We save the state_dict instead. logging.info('''saving the model\'s state dictionary''' ) torch.save( new_model.state_dict() , '''./bertabs-finetuned-cnndm-extractive-abstractive-summarization/pytorch_model.bin''' ) if __name__ == "__main__": __UpperCamelCase : int = argparse.ArgumentParser() parser.add_argument( '--bertabs_checkpoint_path', default=None, type=str, required=True, help='Path the official PyTorch dump.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.', ) __UpperCamelCase : Dict = parser.parse_args() convert_bertabs_checkpoints( args.bertabs_checkpoint_path, args.pytorch_dump_folder_path, )
702
import os import unittest from transformers import FunnelTokenizer, FunnelTokenizerFast from transformers.models.funnel.tokenization_funnel import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowercase__ ( UpperCamelCase_ , unittest.TestCase): UpperCamelCase_ = FunnelTokenizer UpperCamelCase_ = FunnelTokenizerFast UpperCamelCase_ = True UpperCamelCase_ = True def __A ( self : Union[str, Any] ): '''simple docstring''' super().setUp() SCREAMING_SNAKE_CASE : Optional[Any] = [ '''<unk>''', '''<cls>''', '''<sep>''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] SCREAMING_SNAKE_CASE : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) def __A ( self : int , **UpperCamelCase__ : List[Any] ): '''simple docstring''' return FunnelTokenizer.from_pretrained(self.tmpdirname , **UpperCamelCase__ ) def __A ( self : int , **UpperCamelCase__ : List[Any] ): '''simple docstring''' return FunnelTokenizerFast.from_pretrained(self.tmpdirname , **UpperCamelCase__ ) def __A ( self : Any , UpperCamelCase__ : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = '''UNwant\u00E9d,running''' SCREAMING_SNAKE_CASE : int = '''unwanted, running''' return input_text, output_text def __A ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = self.tokenizer_class(self.vocab_file ) SCREAMING_SNAKE_CASE : int = tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(UpperCamelCase__ , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCamelCase__ ) , [7, 4, 5, 10, 8, 9] ) def __A ( self : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self.get_tokenizers(do_lower_case=UpperCamelCase__ ) for tokenizer in tokenizers: SCREAMING_SNAKE_CASE : int = tokenizer('''UNwant\u00E9d,running''' ) SCREAMING_SNAKE_CASE : Optional[Any] = len(inputs['''input_ids'''] ) - 1 self.assertListEqual(inputs['''token_type_ids'''] , [2] + [0] * sentence_len ) SCREAMING_SNAKE_CASE : List[Any] = tokenizer('''UNwant\u00E9d,running''' , '''UNwant\u00E9d,running''' ) self.assertListEqual(inputs['''token_type_ids'''] , [2] + [0] * sentence_len + [1] * sentence_len )
34
0
import unittest from transformers.testing_utils import CaptureStdout from transformers.tools.python_interpreter import evaluate def A ( _lowercase ): return x + 2 class lowercase__ ( unittest.TestCase): def __A ( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = 'x = 3' SCREAMING_SNAKE_CASE : Union[str, Any] = {} SCREAMING_SNAKE_CASE : List[str] = evaluate(UpperCamelCase__ , {} , state=UpperCamelCase__ ) assert result == 3 self.assertDictEqual(UpperCamelCase__ , {'''x''': 3} ) SCREAMING_SNAKE_CASE : List[str] = 'x = y' SCREAMING_SNAKE_CASE : Dict = {'y': 5} SCREAMING_SNAKE_CASE : List[Any] = evaluate(UpperCamelCase__ , {} , state=UpperCamelCase__ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(UpperCamelCase__ , {'''x''': 5, '''y''': 5} ) def __A ( self : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = 'y = add_two(x)' SCREAMING_SNAKE_CASE : Optional[int] = {'x': 3} SCREAMING_SNAKE_CASE : Dict = evaluate(UpperCamelCase__ , {'''add_two''': add_two} , state=UpperCamelCase__ ) assert result == 5 self.assertDictEqual(UpperCamelCase__ , {'''x''': 3, '''y''': 5} ) # Won't work without the tool with CaptureStdout() as out: SCREAMING_SNAKE_CASE : Any = evaluate(UpperCamelCase__ , {} , state=UpperCamelCase__ ) assert result is None assert "tried to execute add_two" in out.out def __A ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = 'x = 3' SCREAMING_SNAKE_CASE : Tuple = {} SCREAMING_SNAKE_CASE : List[Any] = evaluate(UpperCamelCase__ , {} , state=UpperCamelCase__ ) assert result == 3 self.assertDictEqual(UpperCamelCase__ , {'''x''': 3} ) def __A ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = 'test_dict = {\'x\': x, \'y\': add_two(x)}' SCREAMING_SNAKE_CASE : Dict = {'x': 3} SCREAMING_SNAKE_CASE : Dict = evaluate(UpperCamelCase__ , {'''add_two''': add_two} , state=UpperCamelCase__ ) self.assertDictEqual(UpperCamelCase__ , {'''x''': 3, '''y''': 5} ) self.assertDictEqual(UpperCamelCase__ , {'''x''': 3, '''test_dict''': {'''x''': 3, '''y''': 5}} ) def __A ( self : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = 'x = 3\ny = 5' SCREAMING_SNAKE_CASE : Optional[Any] = {} SCREAMING_SNAKE_CASE : List[str] = evaluate(UpperCamelCase__ , {} , state=UpperCamelCase__ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(UpperCamelCase__ , {'''x''': 3, '''y''': 5} ) def __A ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = 'text = f\'This is x: {x}.\'' SCREAMING_SNAKE_CASE : Optional[Any] = {'x': 3} SCREAMING_SNAKE_CASE : List[str] = evaluate(UpperCamelCase__ , {} , state=UpperCamelCase__ ) # evaluate returns the value of the last assignment. assert result == "This is x: 3." self.assertDictEqual(UpperCamelCase__ , {'''x''': 3, '''text''': '''This is x: 3.'''} ) def __A ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = 'if x <= 3:\n y = 2\nelse:\n y = 5' SCREAMING_SNAKE_CASE : str = {'x': 3} SCREAMING_SNAKE_CASE : Tuple = evaluate(UpperCamelCase__ , {} , state=UpperCamelCase__ ) # evaluate returns the value of the last assignment. assert result == 2 self.assertDictEqual(UpperCamelCase__ , {'''x''': 3, '''y''': 2} ) SCREAMING_SNAKE_CASE : Dict = {'x': 8} SCREAMING_SNAKE_CASE : Optional[Any] = evaluate(UpperCamelCase__ , {} , state=UpperCamelCase__ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(UpperCamelCase__ , {'''x''': 8, '''y''': 5} ) def __A ( self : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = 'test_list = [x, add_two(x)]' SCREAMING_SNAKE_CASE : str = {'x': 3} SCREAMING_SNAKE_CASE : Optional[int] = evaluate(UpperCamelCase__ , {'''add_two''': add_two} , state=UpperCamelCase__ ) self.assertListEqual(UpperCamelCase__ , [3, 5] ) self.assertDictEqual(UpperCamelCase__ , {'''x''': 3, '''test_list''': [3, 5]} ) def __A ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = 'y = x' SCREAMING_SNAKE_CASE : str = {'x': 3} SCREAMING_SNAKE_CASE : int = evaluate(UpperCamelCase__ , {} , state=UpperCamelCase__ ) assert result == 3 self.assertDictEqual(UpperCamelCase__ , {'''x''': 3, '''y''': 3} ) def __A ( self : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = 'test_list = [x, add_two(x)]\ntest_list[1]' SCREAMING_SNAKE_CASE : List[str] = {'x': 3} SCREAMING_SNAKE_CASE : Optional[Any] = evaluate(UpperCamelCase__ , {'''add_two''': add_two} , state=UpperCamelCase__ ) assert result == 5 self.assertDictEqual(UpperCamelCase__ , {'''x''': 3, '''test_list''': [3, 5]} ) SCREAMING_SNAKE_CASE : str = 'test_dict = {\'x\': x, \'y\': add_two(x)}\ntest_dict[\'y\']' SCREAMING_SNAKE_CASE : List[Any] = {'x': 3} SCREAMING_SNAKE_CASE : List[str] = evaluate(UpperCamelCase__ , {'''add_two''': add_two} , state=UpperCamelCase__ ) assert result == 5 self.assertDictEqual(UpperCamelCase__ , {'''x''': 3, '''test_dict''': {'''x''': 3, '''y''': 5}} ) def __A ( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = 'x = 0\nfor i in range(3):\n x = i' SCREAMING_SNAKE_CASE : Any = {} SCREAMING_SNAKE_CASE : Any = evaluate(UpperCamelCase__ , {'''range''': range} , state=UpperCamelCase__ ) assert result == 2 self.assertDictEqual(UpperCamelCase__ , {'''x''': 2, '''i''': 2} )
703
import numpy as np import torch from torch.utils.data import Dataset, IterableDataset from ..utils.generic import ModelOutput class lowercase__ ( UpperCamelCase_): def __init__( self : str , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = dataset SCREAMING_SNAKE_CASE : Optional[Any] = process SCREAMING_SNAKE_CASE : Union[str, Any] = params def __len__( self : Tuple ): '''simple docstring''' return len(self.dataset ) def __getitem__( self : List[str] , UpperCamelCase__ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = self.dataset[i] SCREAMING_SNAKE_CASE : Optional[int] = self.process(UpperCamelCase__ , **self.params ) return processed class lowercase__ ( UpperCamelCase_): def __init__( self : Dict , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Dict , UpperCamelCase__ : List[Any]=None ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = loader SCREAMING_SNAKE_CASE : List[Any] = infer SCREAMING_SNAKE_CASE : int = params if loader_batch_size == 1: # Let's spare some time by deactivating altogether SCREAMING_SNAKE_CASE : Optional[int] = None SCREAMING_SNAKE_CASE : List[str] = loader_batch_size # Internal bookkeeping SCREAMING_SNAKE_CASE : Optional[int] = None SCREAMING_SNAKE_CASE : int = None def __len__( self : int ): '''simple docstring''' return len(self.loader ) def __iter__( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = iter(self.loader ) return self def __A ( self : List[str] ): '''simple docstring''' if isinstance(self._loader_batch_data , torch.Tensor ): # Batch data is simple tensor, just fetch the slice SCREAMING_SNAKE_CASE : Optional[Any] = self._loader_batch_data[self._loader_batch_index] else: # Batch data is assumed to be BaseModelOutput (or dict) SCREAMING_SNAKE_CASE : Union[str, Any] = {} for k, element in self._loader_batch_data.items(): if isinstance(UpperCamelCase__ , UpperCamelCase__ ): # Convert ModelOutput to tuple first SCREAMING_SNAKE_CASE : Dict = element.to_tuple() if isinstance(element[0] , torch.Tensor ): SCREAMING_SNAKE_CASE : Dict = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element ) elif isinstance(element[0] , np.ndarray ): SCREAMING_SNAKE_CASE : Union[str, Any] = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element ) continue if k in {"hidden_states", "past_key_values", "attentions"} and isinstance(UpperCamelCase__ , UpperCamelCase__ ): # Those are stored as lists of tensors so need specific unbatching. if isinstance(element[0] , torch.Tensor ): SCREAMING_SNAKE_CASE : Union[str, Any] = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element ) elif isinstance(element[0] , np.ndarray ): SCREAMING_SNAKE_CASE : List[str] = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element ) continue if element is None: # This can happen for optional data that get passed around SCREAMING_SNAKE_CASE : int = None elif isinstance(element[self._loader_batch_index] , torch.Tensor ): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers SCREAMING_SNAKE_CASE : Union[str, Any] = element[self._loader_batch_index].unsqueeze(0 ) elif isinstance(element[self._loader_batch_index] , np.ndarray ): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers SCREAMING_SNAKE_CASE : Tuple = np.expand_dims(element[self._loader_batch_index] , 0 ) else: # This is typically a list, so no need to `unsqueeze`. SCREAMING_SNAKE_CASE : Tuple = element[self._loader_batch_index] # Recreate the element by reusing the original class to make it look # batch_size=1 SCREAMING_SNAKE_CASE : Any = self._loader_batch_data.__class__(UpperCamelCase__ ) self._loader_batch_index += 1 return result def __A ( self : Union[str, Any] ): '''simple docstring''' if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: # We are currently unrolling a batch so we just need to return # the current item within a batch return self.loader_batch_item() # We're out of items within a batch SCREAMING_SNAKE_CASE : Tuple = next(self.iterator ) SCREAMING_SNAKE_CASE : List[Any] = self.infer(UpperCamelCase__ , **self.params ) # We now have a batch of "inferred things". if self.loader_batch_size is not None: # Try to infer the size of the batch if isinstance(UpperCamelCase__ , torch.Tensor ): SCREAMING_SNAKE_CASE : Optional[int] = processed else: SCREAMING_SNAKE_CASE : int = list(processed.keys() )[0] SCREAMING_SNAKE_CASE : int = processed[key] if isinstance(UpperCamelCase__ , UpperCamelCase__ ): SCREAMING_SNAKE_CASE : List[Any] = len(UpperCamelCase__ ) else: SCREAMING_SNAKE_CASE : Dict = first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. SCREAMING_SNAKE_CASE : List[Any] = observed_batch_size # Setting internal index to unwrap the batch SCREAMING_SNAKE_CASE : List[Any] = processed SCREAMING_SNAKE_CASE : int = 0 return self.loader_batch_item() else: # We're not unrolling batches return processed class lowercase__ ( UpperCamelCase_): def __init__( self : str , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Union[str, Any]=None ): '''simple docstring''' super().__init__(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) def __iter__( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = iter(self.loader ) SCREAMING_SNAKE_CASE : List[Any] = None return self def __A ( self : List[str] ): '''simple docstring''' if self.subiterator is None: SCREAMING_SNAKE_CASE : Dict = self.infer(next(self.iterator ) , **self.params ) try: # Try to return next item SCREAMING_SNAKE_CASE : Any = next(self.subiterator ) except StopIteration: # When a preprocess iterator ends, we can start lookig at the next item # ChunkIterator will keep feeding until ALL elements of iterator # all have created their subiterator and have been iterating against. # # Another way to look at it, is we're basically flattening lists of lists # into a single list, but with generators SCREAMING_SNAKE_CASE : Optional[Any] = self.infer(next(self.iterator ) , **self.params ) SCREAMING_SNAKE_CASE : Union[str, Any] = next(self.subiterator ) return processed class lowercase__ ( UpperCamelCase_): def __iter__( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = iter(self.loader ) return self def __A ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = False SCREAMING_SNAKE_CASE : Optional[int] = [] if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: while self._loader_batch_index < self.loader_batch_size: SCREAMING_SNAKE_CASE : Tuple = self.loader_batch_item() SCREAMING_SNAKE_CASE : Any = item.pop('''is_last''' ) accumulator.append(UpperCamelCase__ ) if is_last: return accumulator while not is_last: SCREAMING_SNAKE_CASE : Any = self.infer(next(self.iterator ) , **self.params ) if self.loader_batch_size is not None: if isinstance(UpperCamelCase__ , torch.Tensor ): SCREAMING_SNAKE_CASE : Tuple = processed else: SCREAMING_SNAKE_CASE : Union[str, Any] = list(processed.keys() )[0] SCREAMING_SNAKE_CASE : List[str] = processed[key] if isinstance(UpperCamelCase__ , UpperCamelCase__ ): SCREAMING_SNAKE_CASE : List[Any] = len(UpperCamelCase__ ) else: SCREAMING_SNAKE_CASE : int = first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. SCREAMING_SNAKE_CASE : List[str] = observed_batch_size SCREAMING_SNAKE_CASE : List[Any] = processed SCREAMING_SNAKE_CASE : str = 0 while self._loader_batch_index < self.loader_batch_size: SCREAMING_SNAKE_CASE : Any = self.loader_batch_item() SCREAMING_SNAKE_CASE : List[Any] = item.pop('''is_last''' ) accumulator.append(UpperCamelCase__ ) if is_last: return accumulator else: SCREAMING_SNAKE_CASE : int = processed SCREAMING_SNAKE_CASE : List[str] = item.pop('''is_last''' ) accumulator.append(UpperCamelCase__ ) return accumulator class lowercase__ ( UpperCamelCase_): def __init__( self : Optional[Any] , UpperCamelCase__ : Dataset , UpperCamelCase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = dataset SCREAMING_SNAKE_CASE : Dict = key def __len__( self : Optional[int] ): '''simple docstring''' return len(self.dataset ) def __getitem__( self : Dict , UpperCamelCase__ : Tuple ): '''simple docstring''' return self.dataset[i][self.key] class lowercase__ ( UpperCamelCase_): def __init__( self : List[Any] , UpperCamelCase__ : Dataset , UpperCamelCase__ : str , UpperCamelCase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = dataset SCREAMING_SNAKE_CASE : List[str] = keya SCREAMING_SNAKE_CASE : Tuple = keya def __len__( self : List[str] ): '''simple docstring''' return len(self.dataset ) def __getitem__( self : Union[str, Any] , UpperCamelCase__ : Any ): '''simple docstring''' return {"text": self.dataset[i][self.keya], "text_pair": self.dataset[i][self.keya]}
34
0
import pytest import datasets # Import fixture modules as plugins __UpperCamelCase : List[Any] = ['tests.fixtures.files', 'tests.fixtures.hub', 'tests.fixtures.fsspec'] def A ( _lowercase , _lowercase ): # Mark tests as "unit" by default if not marked as "integration" (or already marked as "unit") for item in items: if any(marker in item.keywords for marker in ['''integration''', '''unit'''] ): continue item.add_marker(pytest.mark.unit ) def A ( _lowercase ): config.addinivalue_line('''markers''' , '''torchaudio_latest: mark test to run with torchaudio>=0.12''' ) @pytest.fixture(autouse=__snake_case ) def A ( _lowercase , _lowercase ): # test_hf_cache_home = tmp_path_factory.mktemp("cache") # TODO: why a cache dir per test function does not work? SCREAMING_SNAKE_CASE : Union[str, Any] = tmp_path_factory.getbasetemp() / '''cache''' SCREAMING_SNAKE_CASE : Union[str, Any] = test_hf_cache_home / '''datasets''' SCREAMING_SNAKE_CASE : List[Any] = test_hf_cache_home / '''metrics''' SCREAMING_SNAKE_CASE : List[Any] = test_hf_cache_home / '''modules''' monkeypatch.setattr('''datasets.config.HF_DATASETS_CACHE''' , str(__snake_case ) ) monkeypatch.setattr('''datasets.config.HF_METRICS_CACHE''' , str(__snake_case ) ) monkeypatch.setattr('''datasets.config.HF_MODULES_CACHE''' , str(__snake_case ) ) SCREAMING_SNAKE_CASE : int = test_hf_datasets_cache / '''downloads''' monkeypatch.setattr('''datasets.config.DOWNLOADED_DATASETS_PATH''' , str(__snake_case ) ) SCREAMING_SNAKE_CASE : Tuple = test_hf_datasets_cache / '''downloads''' / '''extracted''' monkeypatch.setattr('''datasets.config.EXTRACTED_DATASETS_PATH''' , str(__snake_case ) ) @pytest.fixture(autouse=__snake_case , scope='''session''' ) def A ( ): datasets.disable_progress_bar() @pytest.fixture(autouse=__snake_case ) def A ( _lowercase ): # don't take tests into account when counting downloads monkeypatch.setattr('''datasets.config.HF_UPDATE_DOWNLOAD_COUNTS''' , __snake_case ) @pytest.fixture def A ( _lowercase ): # Required to suppress RemovedIn20Warning when feature(s) are not compatible with SQLAlchemy 2.0 # To be removed once SQLAlchemy 2.0 supported monkeypatch.setattr('''sqlalchemy.util.deprecations.SILENCE_UBER_WARNING''' , __snake_case )
704
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging if TYPE_CHECKING: from ... import FeatureExtractionMixin, PreTrainedTokenizerBase, TensorType __UpperCamelCase : Optional[Any] = logging.get_logger(__name__) __UpperCamelCase : Optional[Any] = { 'microsoft/deberta-v2-xlarge': 'https://huggingface.co/microsoft/deberta-v2-xlarge/resolve/main/config.json', 'microsoft/deberta-v2-xxlarge': 'https://huggingface.co/microsoft/deberta-v2-xxlarge/resolve/main/config.json', 'microsoft/deberta-v2-xlarge-mnli': ( 'https://huggingface.co/microsoft/deberta-v2-xlarge-mnli/resolve/main/config.json' ), 'microsoft/deberta-v2-xxlarge-mnli': ( 'https://huggingface.co/microsoft/deberta-v2-xxlarge-mnli/resolve/main/config.json' ), } class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = """deberta-v2""" def __init__( self : Optional[Any] , UpperCamelCase__ : Any=12_8100 , UpperCamelCase__ : Optional[int]=1536 , UpperCamelCase__ : Dict=24 , UpperCamelCase__ : List[str]=24 , UpperCamelCase__ : Tuple=6144 , UpperCamelCase__ : List[Any]="gelu" , UpperCamelCase__ : Optional[int]=0.1 , UpperCamelCase__ : List[str]=0.1 , UpperCamelCase__ : Optional[int]=512 , UpperCamelCase__ : Optional[Any]=0 , UpperCamelCase__ : Union[str, Any]=0.02 , UpperCamelCase__ : List[Any]=1E-7 , UpperCamelCase__ : List[str]=False , UpperCamelCase__ : str=-1 , UpperCamelCase__ : List[Any]=0 , UpperCamelCase__ : List[Any]=True , UpperCamelCase__ : Optional[Any]=None , UpperCamelCase__ : Tuple=0 , UpperCamelCase__ : str="gelu" , **UpperCamelCase__ : Optional[int] , ): '''simple docstring''' super().__init__(**UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[Any] = hidden_size SCREAMING_SNAKE_CASE : int = num_hidden_layers SCREAMING_SNAKE_CASE : Union[str, Any] = num_attention_heads SCREAMING_SNAKE_CASE : List[Any] = intermediate_size SCREAMING_SNAKE_CASE : Any = hidden_act SCREAMING_SNAKE_CASE : Dict = hidden_dropout_prob SCREAMING_SNAKE_CASE : Optional[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : str = max_position_embeddings SCREAMING_SNAKE_CASE : Dict = type_vocab_size SCREAMING_SNAKE_CASE : str = initializer_range SCREAMING_SNAKE_CASE : Optional[Any] = relative_attention SCREAMING_SNAKE_CASE : Optional[Any] = max_relative_positions SCREAMING_SNAKE_CASE : Optional[int] = pad_token_id SCREAMING_SNAKE_CASE : Optional[Any] = position_biased_input # Backwards compatibility if type(UpperCamelCase__ ) == str: SCREAMING_SNAKE_CASE : Optional[int] = [x.strip() for x in pos_att_type.lower().split('''|''' )] SCREAMING_SNAKE_CASE : Any = pos_att_type SCREAMING_SNAKE_CASE : int = vocab_size SCREAMING_SNAKE_CASE : Dict = layer_norm_eps SCREAMING_SNAKE_CASE : Tuple = kwargs.get('''pooler_hidden_size''' , UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Any = pooler_dropout SCREAMING_SNAKE_CASE : Union[str, Any] = pooler_hidden_act class lowercase__ ( UpperCamelCase_): @property def __A ( self : Union[str, Any] ): '''simple docstring''' if self.task == "multiple-choice": SCREAMING_SNAKE_CASE : Optional[int] = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: SCREAMING_SNAKE_CASE : Optional[Any] = {0: '''batch''', 1: '''sequence'''} if self._config.type_vocab_size > 0: return OrderedDict( [('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ('''token_type_ids''', dynamic_axis)] ) else: return OrderedDict([('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis)] ) @property def __A ( self : Union[str, Any] ): '''simple docstring''' return 12 def __A ( self : Dict , UpperCamelCase__ : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , UpperCamelCase__ : int = -1 , UpperCamelCase__ : int = -1 , UpperCamelCase__ : int = -1 , UpperCamelCase__ : bool = False , UpperCamelCase__ : Optional["TensorType"] = None , UpperCamelCase__ : int = 3 , UpperCamelCase__ : int = 40 , UpperCamelCase__ : int = 40 , UpperCamelCase__ : "PreTrainedTokenizerBase" = None , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = super().generate_dummy_inputs(preprocessor=UpperCamelCase__ , framework=UpperCamelCase__ ) if self._config.type_vocab_size == 0 and "token_type_ids" in dummy_inputs: del dummy_inputs["token_type_ids"] return dummy_inputs
34
0
import argparse import logging import pickle import random import time import numpy as np from transformers import BertTokenizer, GPTaTokenizer, RobertaTokenizer logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO ) __UpperCamelCase : Optional[Any] = logging.getLogger(__name__) def A ( ): SCREAMING_SNAKE_CASE : Optional[int] = argparse.ArgumentParser( description='''Preprocess the data to avoid re-doing it several times by (tokenization + token_to_ids).''' ) parser.add_argument('''--file_path''' , type=lowerCAmelCase__ , default='''data/dump.txt''' , help='''The path to the data.''' ) parser.add_argument('''--tokenizer_type''' , type=lowerCAmelCase__ , default='''bert''' , choices=['''bert''', '''roberta''', '''gpt2'''] ) parser.add_argument('''--tokenizer_name''' , type=lowerCAmelCase__ , default='''bert-base-uncased''' , help='''The tokenizer to use.''' ) parser.add_argument('''--dump_file''' , type=lowerCAmelCase__ , default='''data/dump''' , help='''The dump file prefix.''' ) SCREAMING_SNAKE_CASE : List[str] = parser.parse_args() logger.info(f"""Loading Tokenizer ({args.tokenizer_name})""" ) if args.tokenizer_type == "bert": SCREAMING_SNAKE_CASE : Any = BertTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE : int = tokenizer.special_tokens_map['''cls_token'''] # `[CLS]` SCREAMING_SNAKE_CASE : Any = tokenizer.special_tokens_map['''sep_token'''] # `[SEP]` elif args.tokenizer_type == "roberta": SCREAMING_SNAKE_CASE : Optional[Any] = RobertaTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE : Any = tokenizer.special_tokens_map['''cls_token'''] # `<s>` SCREAMING_SNAKE_CASE : List[Any] = tokenizer.special_tokens_map['''sep_token'''] # `</s>` elif args.tokenizer_type == "gpt2": SCREAMING_SNAKE_CASE : List[str] = GPTaTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE : List[str] = tokenizer.special_tokens_map['''bos_token'''] # `<|endoftext|>` SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer.special_tokens_map['''eos_token'''] # `<|endoftext|>` logger.info(f"""Loading text from {args.file_path}""" ) with open(args.file_path , '''r''' , encoding='''utf8''' ) as fp: SCREAMING_SNAKE_CASE : Optional[Any] = fp.readlines() logger.info('''Start encoding''' ) logger.info(f"""{len(lowerCAmelCase__ )} examples to process.""" ) SCREAMING_SNAKE_CASE : Optional[Any] = [] SCREAMING_SNAKE_CASE : List[str] = 0 SCREAMING_SNAKE_CASE : List[str] = 10_000 SCREAMING_SNAKE_CASE : int = time.time() for text in data: SCREAMING_SNAKE_CASE : Union[str, Any] = f"""{bos} {text.strip()} {sep}""" SCREAMING_SNAKE_CASE : Any = tokenizer.encode(lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ ) rslt.append(lowerCAmelCase__ ) iter += 1 if iter % interval == 0: SCREAMING_SNAKE_CASE : int = time.time() logger.info(f"""{iter} examples processed. - {(end-start):.2f}s/{interval}expl""" ) SCREAMING_SNAKE_CASE : Union[str, Any] = time.time() logger.info('''Finished binarization''' ) logger.info(f"""{len(lowerCAmelCase__ )} examples processed.""" ) SCREAMING_SNAKE_CASE : int = f"""{args.dump_file}.{args.tokenizer_name}.pickle""" SCREAMING_SNAKE_CASE : str = tokenizer.vocab_size if vocab_size < (1 << 16): SCREAMING_SNAKE_CASE : Optional[Any] = [np.uintaa(lowerCAmelCase__ ) for d in rslt] else: SCREAMING_SNAKE_CASE : int = [np.intaa(lowerCAmelCase__ ) for d in rslt] random.shuffle(rslt_ ) logger.info(f"""Dump to {dp_file}""" ) with open(lowerCAmelCase__ , '''wb''' ) as handle: pickle.dump(rslt_ , lowerCAmelCase__ , protocol=pickle.HIGHEST_PROTOCOL ) if __name__ == "__main__": main()
705
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from timm import create_model from timm.data import resolve_data_config from timm.data.transforms_factory import create_transform from transformers import BitConfig, BitForImageClassification, BitImageProcessor from transformers.image_utils import PILImageResampling from transformers.utils import logging logging.set_verbosity_info() __UpperCamelCase : str = logging.get_logger(__name__) def A ( _lowercase ): SCREAMING_SNAKE_CASE : Any = '''huggingface/label-files''' SCREAMING_SNAKE_CASE : Any = '''imagenet-1k-id2label.json''' SCREAMING_SNAKE_CASE : Any = json.load(open(hf_hub_download(_lowercase , _lowercase , repo_type='''dataset''' ) , '''r''' ) ) SCREAMING_SNAKE_CASE : Union[str, Any] = {int(_lowercase ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE : Dict = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE : str = '''std_conv''' if '''bit''' in model_name else False # note that when using BiT as backbone for ViT-hybrid checkpoints, # one needs to additionally set config.layer_type = "bottleneck", config.stem_type = "same", # config.conv_layer = "std_conv_same" SCREAMING_SNAKE_CASE : Optional[int] = BitConfig( conv_layer=_lowercase , num_labels=1_000 , idalabel=_lowercase , labelaid=_lowercase , ) return config def A ( _lowercase ): if "stem.conv" in name: SCREAMING_SNAKE_CASE : Optional[int] = name.replace('''stem.conv''' , '''bit.embedder.convolution''' ) if "blocks" in name: SCREAMING_SNAKE_CASE : Tuple = name.replace('''blocks''' , '''layers''' ) if "head.fc" in name: SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace('''head.fc''' , '''classifier.1''' ) if name.startswith('''norm''' ): SCREAMING_SNAKE_CASE : str = '''bit.''' + name if "bit" not in name and "classifier" not in name: SCREAMING_SNAKE_CASE : Union[str, Any] = '''bit.encoder.''' + name return name def A ( ): SCREAMING_SNAKE_CASE : Any = '''http://images.cocodataset.org/val2017/000000039769.jpg''' SCREAMING_SNAKE_CASE : List[str] = Image.open(requests.get(_lowercase , stream=_lowercase ).raw ) return im @torch.no_grad() def A ( _lowercase , _lowercase , _lowercase=False ): SCREAMING_SNAKE_CASE : List[Any] = get_config(_lowercase ) # load original model from timm SCREAMING_SNAKE_CASE : Optional[Any] = create_model(_lowercase , pretrained=_lowercase ) timm_model.eval() # load state_dict of original model SCREAMING_SNAKE_CASE : Optional[int] = timm_model.state_dict() for key in state_dict.copy().keys(): SCREAMING_SNAKE_CASE : Dict = state_dict.pop(_lowercase ) SCREAMING_SNAKE_CASE : Optional[int] = val.squeeze() if '''head''' in key else val # load HuggingFace model SCREAMING_SNAKE_CASE : str = BitForImageClassification(_lowercase ) model.eval() model.load_state_dict(_lowercase ) # create image processor SCREAMING_SNAKE_CASE : Optional[Any] = create_transform(**resolve_data_config({} , model=_lowercase ) ) SCREAMING_SNAKE_CASE : List[str] = transform.transforms SCREAMING_SNAKE_CASE : Union[str, Any] = { '''bilinear''': PILImageResampling.BILINEAR, '''bicubic''': PILImageResampling.BICUBIC, '''nearest''': PILImageResampling.NEAREST, } SCREAMING_SNAKE_CASE : Tuple = BitImageProcessor( do_resize=_lowercase , size={'''shortest_edge''': timm_transforms[0].size} , resample=pillow_resamplings[timm_transforms[0].interpolation.value] , do_center_crop=_lowercase , crop_size={'''height''': timm_transforms[1].size[0], '''width''': timm_transforms[1].size[1]} , do_normalize=_lowercase , image_mean=timm_transforms[-1].mean.tolist() , image_std=timm_transforms[-1].std.tolist() , ) SCREAMING_SNAKE_CASE : Any = prepare_img() SCREAMING_SNAKE_CASE : Union[str, Any] = transform(_lowercase ).unsqueeze(0 ) SCREAMING_SNAKE_CASE : Optional[int] = processor(_lowercase , return_tensors='''pt''' ).pixel_values # verify pixel values assert torch.allclose(_lowercase , _lowercase ) # verify logits with torch.no_grad(): SCREAMING_SNAKE_CASE : Dict = model(_lowercase ) SCREAMING_SNAKE_CASE : Optional[Any] = outputs.logits print('''Logits:''' , logits[0, :3] ) print('''Predicted class:''' , model.config.idalabel[logits.argmax(-1 ).item()] ) SCREAMING_SNAKE_CASE : List[Any] = timm_model(_lowercase ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(_lowercase , outputs.logits , atol=1e-3 ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: Path(_lowercase ).mkdir(exist_ok=_lowercase ) print(f"""Saving model {model_name} and processor to {pytorch_dump_folder_path}""" ) model.save_pretrained(_lowercase ) processor.save_pretrained(_lowercase ) if push_to_hub: print(f"""Pushing model {model_name} and processor to the hub""" ) model.push_to_hub(f"""ybelkada/{model_name}""" ) processor.push_to_hub(f"""ybelkada/{model_name}""" ) if __name__ == "__main__": __UpperCamelCase : Any = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='resnetv2_50x1_bitm', type=str, help='Name of the BiT 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.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether to push the model to the hub.', ) __UpperCamelCase : Optional[int] = parser.parse_args() convert_bit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
34
0
import os import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from huggingface_hub.file_download import http_get from requests.exceptions import HTTPError from transformers import ( AlbertTokenizer, AutoTokenizer, BertTokenizer, BertTokenizerFast, GPTaTokenizerFast, is_tokenizers_available, ) from transformers.testing_utils import TOKEN, USER, is_staging_test, require_tokenizers from transformers.tokenization_utils import Trie sys.path.append(str(Path(__file__).parent.parent / 'utils')) from test_module.custom_tokenization import CustomTokenizer # noqa E402 if is_tokenizers_available(): from test_module.custom_tokenization_fast import CustomTokenizerFast class lowercase__ ( unittest.TestCase): def __A ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = mock.Mock() SCREAMING_SNAKE_CASE : Union[str, Any] = 500 SCREAMING_SNAKE_CASE : str = {} SCREAMING_SNAKE_CASE : List[str] = HTTPError SCREAMING_SNAKE_CASE : Optional[Any] = {} # Download this model to make sure it's in the cache. SCREAMING_SNAKE_CASE : List[str] = BertTokenizer.from_pretrained('''hf-internal-testing/tiny-random-bert''' ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('''requests.Session.request''' , return_value=a_ ) as mock_head: SCREAMING_SNAKE_CASE : Optional[Any] = BertTokenizer.from_pretrained('''hf-internal-testing/tiny-random-bert''' ) # This check we did call the fake head request mock_head.assert_called() @require_tokenizers def __A ( self : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = mock.Mock() SCREAMING_SNAKE_CASE : Any = 500 SCREAMING_SNAKE_CASE : int = {} SCREAMING_SNAKE_CASE : int = HTTPError SCREAMING_SNAKE_CASE : Any = {} # Download this model to make sure it's in the cache. SCREAMING_SNAKE_CASE : List[str] = GPTaTokenizerFast.from_pretrained('''gpt2''' ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('''requests.Session.request''' , return_value=a_ ) as mock_head: SCREAMING_SNAKE_CASE : Optional[int] = GPTaTokenizerFast.from_pretrained('''gpt2''' ) # This check we did call the fake head request mock_head.assert_called() def __A ( self : Any ): '''simple docstring''' try: SCREAMING_SNAKE_CASE : Union[str, Any] = tempfile.mktemp() with open(a_ , '''wb''' ) as f: http_get('''https://huggingface.co/albert-base-v1/resolve/main/spiece.model''' , a_ ) SCREAMING_SNAKE_CASE : Dict = AlbertTokenizer.from_pretrained(a_ ) finally: os.remove(a_ ) # Supporting this legacy load introduced a weird bug where the tokenizer would load local files if they are in # the current folder and have the right name. if os.path.isfile('''tokenizer.json''' ): # We skip the test if the user has a `tokenizer.json` in this folder to avoid deleting it. return try: with open('''tokenizer.json''' , '''wb''' ) as f: http_get('''https://huggingface.co/hf-internal-testing/tiny-random-bert/blob/main/tokenizer.json''' , a_ ) SCREAMING_SNAKE_CASE : Tuple = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-gpt2''' ) # The tiny random BERT has a vocab size of 1024, tiny gpt2 as a vocab size of 1000 self.assertEqual(tokenizer.vocab_size , 1000 ) # Tokenizer should depend on the remote checkpoint, not the local tokenizer.json file. finally: os.remove('''tokenizer.json''' ) def __A ( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = AlbertTokenizer.from_pretrained('''https://huggingface.co/albert-base-v1/resolve/main/spiece.model''' ) @is_staging_test class lowercase__ ( unittest.TestCase): UpperCamelCase_ = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''bla''', '''blou'''] @classmethod def __A ( cls : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = TOKEN HfFolder.save_token(a_ ) @classmethod def __A ( cls : Any ): '''simple docstring''' try: delete_repo(token=cls._token , repo_id='''test-tokenizer''' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''valid_org/test-tokenizer-org''' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''test-dynamic-tokenizer''' ) except HTTPError: pass def __A ( self : int ): '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE : int = os.path.join(a_ , '''vocab.txt''' ) with open(a_ , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE : str = BertTokenizer(a_ ) tokenizer.push_to_hub('''test-tokenizer''' , use_auth_token=self._token ) SCREAMING_SNAKE_CASE : List[Any] = BertTokenizer.from_pretrained(f"""{USER}/test-tokenizer""" ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) # Reset repo delete_repo(token=self._token , repo_id='''test-tokenizer''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(a_ , repo_id='''test-tokenizer''' , push_to_hub=a_ , use_auth_token=self._token ) SCREAMING_SNAKE_CASE : str = BertTokenizer.from_pretrained(f"""{USER}/test-tokenizer""" ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) def __A ( self : str ): '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE : List[Any] = os.path.join(a_ , '''vocab.txt''' ) with open(a_ , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE : Any = BertTokenizer(a_ ) tokenizer.push_to_hub('''valid_org/test-tokenizer-org''' , use_auth_token=self._token ) SCREAMING_SNAKE_CASE : Dict = BertTokenizer.from_pretrained('''valid_org/test-tokenizer-org''' ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) # Reset repo delete_repo(token=self._token , repo_id='''valid_org/test-tokenizer-org''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained( a_ , repo_id='''valid_org/test-tokenizer-org''' , push_to_hub=a_ , use_auth_token=self._token ) SCREAMING_SNAKE_CASE : int = BertTokenizer.from_pretrained('''valid_org/test-tokenizer-org''' ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) @require_tokenizers def __A ( self : Any ): '''simple docstring''' CustomTokenizer.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE : Optional[int] = os.path.join(a_ , '''vocab.txt''' ) with open(a_ , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE : Tuple = CustomTokenizer(a_ ) # No fast custom tokenizer tokenizer.push_to_hub('''test-dynamic-tokenizer''' , use_auth_token=self._token ) SCREAMING_SNAKE_CASE : int = AutoTokenizer.from_pretrained(f"""{USER}/test-dynamic-tokenizer""" , trust_remote_code=a_ ) # Can't make an isinstance check because the new_model.config is from the CustomTokenizer class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ , '''CustomTokenizer''' ) # Fast and slow custom tokenizer CustomTokenizerFast.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE : Optional[Any] = os.path.join(a_ , '''vocab.txt''' ) with open(a_ , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE : List[Any] = BertTokenizerFast.from_pretrained(a_ ) bert_tokenizer.save_pretrained(a_ ) SCREAMING_SNAKE_CASE : List[str] = CustomTokenizerFast.from_pretrained(a_ ) tokenizer.push_to_hub('''test-dynamic-tokenizer''' , use_auth_token=self._token ) SCREAMING_SNAKE_CASE : Dict = AutoTokenizer.from_pretrained(f"""{USER}/test-dynamic-tokenizer""" , trust_remote_code=a_ ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ , '''CustomTokenizerFast''' ) SCREAMING_SNAKE_CASE : Dict = AutoTokenizer.from_pretrained( f"""{USER}/test-dynamic-tokenizer""" , use_fast=a_ , trust_remote_code=a_ ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ , '''CustomTokenizer''' ) class lowercase__ ( unittest.TestCase): def __A ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = Trie() trie.add('''Hello 友達''' ) self.assertEqual(trie.data , {'''H''': {'''e''': {'''l''': {'''l''': {'''o''': {''' ''': {'''友''': {'''達''': {'''''': 1}}}}}}}}} ) trie.add('''Hello''' ) trie.data self.assertEqual(trie.data , {'''H''': {'''e''': {'''l''': {'''l''': {'''o''': {'''''': 1, ''' ''': {'''友''': {'''達''': {'''''': 1}}}}}}}}} ) def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = Trie() self.assertEqual(trie.split('''[CLS] This is a extra_id_100''' ) , ['''[CLS] This is a extra_id_100'''] ) trie.add('''[CLS]''' ) trie.add('''extra_id_1''' ) trie.add('''extra_id_100''' ) self.assertEqual(trie.split('''[CLS] This is a extra_id_100''' ) , ['''[CLS]''', ''' This is a ''', '''extra_id_100'''] ) def __A ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = Trie() trie.add('''A''' ) self.assertEqual(trie.split('''ABC''' ) , ['''A''', '''BC'''] ) self.assertEqual(trie.split('''BCA''' ) , ['''BC''', '''A'''] ) def __A ( self : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = Trie() trie.add('''TOKEN]''' ) trie.add('''[SPECIAL_TOKEN]''' ) self.assertEqual(trie.split('''This is something [SPECIAL_TOKEN]''' ) , ['''This is something ''', '''[SPECIAL_TOKEN]'''] ) def __A ( self : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = Trie() trie.add('''A''' ) trie.add('''P''' ) trie.add('''[SPECIAL_TOKEN]''' ) self.assertEqual(trie.split('''This is something [SPECIAL_TOKEN]''' ) , ['''This is something ''', '''[SPECIAL_TOKEN]'''] ) def __A ( self : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = Trie() trie.add('''AB''' ) trie.add('''B''' ) trie.add('''C''' ) self.assertEqual(trie.split('''ABC''' ) , ['''AB''', '''C'''] ) def __A ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = Trie() trie.add('''ABC''' ) trie.add('''B''' ) trie.add('''CD''' ) self.assertEqual(trie.split('''ABCD''' ) , ['''ABC''', '''D'''] ) def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = Trie() SCREAMING_SNAKE_CASE : str = trie.cut_text('''ABC''' , [0, 0, 2, 1, 2, 3] ) self.assertEqual(a_ , ['''AB''', '''C'''] )
706
import argparse import json import logging import os import sys from unittest.mock import patch from transformers.testing_utils import TestCasePlus, get_gpu_count, slow __UpperCamelCase : str = [ os.path.join(os.path.dirname(__file__), dirname) for dirname in [ 'text-classification', 'language-modeling', 'summarization', 'token-classification', 'question-answering', ] ] sys.path.extend(SRC_DIRS) if SRC_DIRS is not None: import run_clm_flax import run_flax_glue import run_flax_ner import run_mlm_flax import run_qa import run_summarization_flax import run_ta_mlm_flax logging.basicConfig(level=logging.DEBUG) __UpperCamelCase : int = logging.getLogger() def A ( ): SCREAMING_SNAKE_CASE : str = argparse.ArgumentParser() parser.add_argument('''-f''' ) SCREAMING_SNAKE_CASE : List[str] = parser.parse_args() return args.f def A ( _lowercase , _lowercase="eval" ): SCREAMING_SNAKE_CASE : Dict = os.path.join(_lowercase , f"""{split}_results.json""" ) if os.path.exists(_lowercase ): with open(_lowercase , '''r''' ) as f: return json.load(_lowercase ) raise ValueError(f"""can't find {path}""" ) __UpperCamelCase : Optional[Any] = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class lowercase__ ( UpperCamelCase_): def __A ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE : Tuple = f""" run_glue.py --model_name_or_path distilbert-base-uncased --output_dir {tmp_dir} --train_file ./tests/fixtures/tests_samples/MRPC/train.csv --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --learning_rate=1e-4 --eval_steps=2 --warmup_steps=2 --seed=42 --max_seq_length=128 """.split() with patch.object(UpperCamelCase__ , '''argv''' , UpperCamelCase__ ): run_flax_glue.main() SCREAMING_SNAKE_CASE : Union[str, Any] = get_results(UpperCamelCase__ ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 ) @slow def __A ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE : str = f""" run_clm_flax.py --model_name_or_path distilgpt2 --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --do_train --do_eval --block_size 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --num_train_epochs 2 --logging_steps 2 --eval_steps 2 --output_dir {tmp_dir} --overwrite_output_dir """.split() with patch.object(UpperCamelCase__ , '''argv''' , UpperCamelCase__ ): run_clm_flax.main() SCREAMING_SNAKE_CASE : Dict = get_results(UpperCamelCase__ ) self.assertLess(result['''eval_perplexity'''] , 100 ) @slow def __A ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE : Union[str, Any] = f""" run_summarization.py --model_name_or_path t5-small --train_file tests/fixtures/tests_samples/xsum/sample.json --validation_file tests/fixtures/tests_samples/xsum/sample.json --test_file tests/fixtures/tests_samples/xsum/sample.json --output_dir {tmp_dir} --overwrite_output_dir --num_train_epochs=3 --warmup_steps=8 --do_train --do_eval --do_predict --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --predict_with_generate """.split() with patch.object(UpperCamelCase__ , '''argv''' , UpperCamelCase__ ): run_summarization_flax.main() SCREAMING_SNAKE_CASE : Union[str, Any] = get_results(UpperCamelCase__ , split='''test''' ) self.assertGreaterEqual(result['''test_rouge1'''] , 10 ) self.assertGreaterEqual(result['''test_rouge2'''] , 2 ) self.assertGreaterEqual(result['''test_rougeL'''] , 7 ) self.assertGreaterEqual(result['''test_rougeLsum'''] , 7 ) @slow def __A ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE : Dict = f""" run_mlm.py --model_name_or_path distilroberta-base --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --output_dir {tmp_dir} --overwrite_output_dir --max_seq_length 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --logging_steps 2 --eval_steps 2 --do_train --do_eval --num_train_epochs=1 """.split() with patch.object(UpperCamelCase__ , '''argv''' , UpperCamelCase__ ): run_mlm_flax.main() SCREAMING_SNAKE_CASE : List[Any] = get_results(UpperCamelCase__ ) self.assertLess(result['''eval_perplexity'''] , 42 ) @slow def __A ( self : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE : Union[str, Any] = f""" run_t5_mlm_flax.py --model_name_or_path t5-small --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --do_train --do_eval --max_seq_length 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --num_train_epochs 2 --logging_steps 2 --eval_steps 2 --output_dir {tmp_dir} --overwrite_output_dir """.split() with patch.object(UpperCamelCase__ , '''argv''' , UpperCamelCase__ ): run_ta_mlm_flax.main() SCREAMING_SNAKE_CASE : Optional[int] = get_results(UpperCamelCase__ ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.42 ) @slow def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = 7 if get_gpu_count() > 1 else 2 SCREAMING_SNAKE_CASE : Dict = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE : Any = f""" run_flax_ner.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/conll/sample.json --validation_file tests/fixtures/tests_samples/conll/sample.json --output_dir {tmp_dir} --overwrite_output_dir --do_train --do_eval --warmup_steps=2 --learning_rate=2e-4 --logging_steps 2 --eval_steps 2 --per_device_train_batch_size=2 --per_device_eval_batch_size=2 --num_train_epochs={epochs} --seed 7 """.split() with patch.object(UpperCamelCase__ , '''argv''' , UpperCamelCase__ ): run_flax_ner.main() SCREAMING_SNAKE_CASE : List[str] = get_results(UpperCamelCase__ ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 ) self.assertGreaterEqual(result['''eval_f1'''] , 0.3 ) @slow def __A ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE : Union[str, Any] = f""" run_qa.py --model_name_or_path bert-base-uncased --version_2_with_negative --train_file tests/fixtures/tests_samples/SQUAD/sample.json --validation_file tests/fixtures/tests_samples/SQUAD/sample.json --output_dir {tmp_dir} --overwrite_output_dir --num_train_epochs=3 --warmup_steps=2 --do_train --do_eval --logging_steps 2 --eval_steps 2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 """.split() with patch.object(UpperCamelCase__ , '''argv''' , UpperCamelCase__ ): run_qa.main() SCREAMING_SNAKE_CASE : str = get_results(UpperCamelCase__ ) self.assertGreaterEqual(result['''eval_f1'''] , 30 ) self.assertGreaterEqual(result['''eval_exact'''] , 30 )
34
0
import os from typing import Optional import fsspec from fsspec.archive import AbstractArchiveFileSystem from fsspec.utils import DEFAULT_BLOCK_SIZE class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = """""" UpperCamelCase_ = ( None # protocol passed in prefix to the url. ex: "gzip", for gzip://file.txt::http://foo.bar/file.txt.gz ) UpperCamelCase_ = None # compression type in fsspec. ex: "gzip" UpperCamelCase_ = None # extension of the filename to strip. ex: "".gz" to get file.txt from file.txt.gz def __init__( self : Optional[int] , UpperCamelCase__ : List[Any] = "" , UpperCamelCase__ : List[Any] = None , UpperCamelCase__ : Tuple = None , **UpperCamelCase__ : Tuple ): '''simple docstring''' super().__init__(self , **UpperCamelCase__ ) # always open as "rb" since fsspec can then use the TextIOWrapper to make it work for "r" mode SCREAMING_SNAKE_CASE : Tuple = fsspec.open( UpperCamelCase__ , mode='''rb''' , protocol=UpperCamelCase__ , compression=self.compression , client_kwargs={ '''requote_redirect_url''': False, # see https://github.com/huggingface/datasets/pull/5459 '''trust_env''': True, # Enable reading proxy env variables. **(target_options or {}).pop('''client_kwargs''' , {} ), # To avoid issues if it was already passed. } , **(target_options or {}) , ) SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.basename(self.file.path.split('''::''' )[0] ) SCREAMING_SNAKE_CASE : Any = ( self.compressed_name[: self.compressed_name.rindex('''.''' )] if '''.''' in self.compressed_name else self.compressed_name ) SCREAMING_SNAKE_CASE : List[Any] = None @classmethod def __A ( cls : int , UpperCamelCase__ : Any ): '''simple docstring''' return super()._strip_protocol(UpperCamelCase__ ).lstrip('''/''' ) def __A ( self : List[Any] ): '''simple docstring''' if self.dir_cache is None: SCREAMING_SNAKE_CASE : Optional[Any] = {**self.file.fs.info(self.file.path ), '''name''': self.uncompressed_name} SCREAMING_SNAKE_CASE : List[str] = {f['''name''']: f} def __A ( self : List[Any] , UpperCamelCase__ : List[str] ): '''simple docstring''' return self.file.open().read() def __A ( self : Union[str, Any] , UpperCamelCase__ : List[str] , UpperCamelCase__ : Tuple = "rb" , UpperCamelCase__ : Dict=None , UpperCamelCase__ : Optional[Any]=True , UpperCamelCase__ : str=None , **UpperCamelCase__ : str , ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = self._strip_protocol(UpperCamelCase__ ) if mode != "rb": raise ValueError(f"""Tried to read with mode {mode} on file {self.file.path} opened with mode \'rb\'""" ) return self.file.open() class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = """bz2""" UpperCamelCase_ = """bz2""" UpperCamelCase_ = """.bz2""" class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = """gzip""" UpperCamelCase_ = """gzip""" UpperCamelCase_ = """.gz""" class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = """lz4""" UpperCamelCase_ = """lz4""" UpperCamelCase_ = """.lz4""" class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = """xz""" UpperCamelCase_ = """xz""" UpperCamelCase_ = """.xz""" class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = """zstd""" UpperCamelCase_ = """zstd""" UpperCamelCase_ = """.zst""" def __init__( self : int , UpperCamelCase__ : List[str] , UpperCamelCase__ : Union[str, Any] = "rb" , UpperCamelCase__ : int = None , UpperCamelCase__ : int = None , UpperCamelCase__ : List[Any] = DEFAULT_BLOCK_SIZE , **UpperCamelCase__ : int , ): '''simple docstring''' super().__init__( fo=UpperCamelCase__ , mode=UpperCamelCase__ , target_protocol=UpperCamelCase__ , target_options=UpperCamelCase__ , block_size=UpperCamelCase__ , **UpperCamelCase__ , ) # We need to wrap the zstd decompressor to avoid this error in fsspec==2021.7.0 and zstandard==0.15.2: # # File "/Users/user/.virtualenvs/hf-datasets/lib/python3.7/site-packages/fsspec/core.py", line 145, in open # out.close = close # AttributeError: 'zstd.ZstdDecompressionReader' object attribute 'close' is read-only # # see https://github.com/intake/filesystem_spec/issues/725 SCREAMING_SNAKE_CASE : Any = self.file.__enter__ class lowercase__ : def __init__( self : Optional[Any] , UpperCamelCase__ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = file_ def __enter__( self : List[Any] ): '''simple docstring''' self._file.__enter__() return self def __exit__( self : Dict , *UpperCamelCase__ : List[Any] , **UpperCamelCase__ : Dict ): '''simple docstring''' self._file.__exit__(*UpperCamelCase__ , **UpperCamelCase__ ) def __iter__( self : Union[str, Any] ): '''simple docstring''' return iter(self._file ) def __A ( self : Union[str, Any] ): '''simple docstring''' return next(self._file ) def __getattr__( self : Any , UpperCamelCase__ : Tuple ): '''simple docstring''' return getattr(self._file , UpperCamelCase__ ) def fixed_enter(*UpperCamelCase__ : str , **UpperCamelCase__ : Optional[int] ): return WrappedFile(_enter(*UpperCamelCase__ , **UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE : Union[str, Any] = fixed_enter
707
import itertools import os import random import tempfile import unittest import numpy as np from transformers import TvltFeatureExtractor, is_datasets_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_torch_available(): import torch if is_datasets_available(): from datasets import load_dataset __UpperCamelCase : Dict = random.Random() def A ( _lowercase , _lowercase=1.0 , _lowercase=None , _lowercase=None ): if rng is None: SCREAMING_SNAKE_CASE : Any = global_rng SCREAMING_SNAKE_CASE : int = [] 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 : List[Any] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : str=7 , UpperCamelCase__ : Any=400 , UpperCamelCase__ : List[str]=2000 , UpperCamelCase__ : List[Any]=2048 , UpperCamelCase__ : Any=128 , UpperCamelCase__ : Union[str, Any]=1 , UpperCamelCase__ : List[Any]=512 , UpperCamelCase__ : str=30 , UpperCamelCase__ : Tuple=4_4100 , ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = parent SCREAMING_SNAKE_CASE : str = batch_size SCREAMING_SNAKE_CASE : str = min_seq_length SCREAMING_SNAKE_CASE : Dict = max_seq_length SCREAMING_SNAKE_CASE : Optional[int] = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) SCREAMING_SNAKE_CASE : Optional[Any] = spectrogram_length SCREAMING_SNAKE_CASE : Optional[int] = feature_size SCREAMING_SNAKE_CASE : Tuple = num_audio_channels SCREAMING_SNAKE_CASE : Union[str, Any] = hop_length SCREAMING_SNAKE_CASE : List[Any] = chunk_length SCREAMING_SNAKE_CASE : str = sampling_rate def __A ( self : Optional[Any] ): '''simple docstring''' return { "spectrogram_length": self.spectrogram_length, "feature_size": self.feature_size, "num_audio_channels": self.num_audio_channels, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "sampling_rate": self.sampling_rate, } def __A ( self : Tuple , UpperCamelCase__ : List[str]=False , UpperCamelCase__ : Optional[int]=False ): '''simple docstring''' def _flatten(UpperCamelCase__ : str ): return list(itertools.chain(*UpperCamelCase__ ) ) if equal_length: SCREAMING_SNAKE_CASE : List[str] = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE : int = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE : Optional[Any] = [np.asarray(UpperCamelCase__ ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class lowercase__ ( UpperCamelCase_ , unittest.TestCase): UpperCamelCase_ = TvltFeatureExtractor def __A ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = TvltFeatureExtractionTester(self ) def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = self.feature_extraction_class(**self.feat_extract_dict ) self.assertTrue(hasattr(UpperCamelCase__ , '''spectrogram_length''' ) ) self.assertTrue(hasattr(UpperCamelCase__ , '''feature_size''' ) ) self.assertTrue(hasattr(UpperCamelCase__ , '''num_audio_channels''' ) ) self.assertTrue(hasattr(UpperCamelCase__ , '''hop_length''' ) ) self.assertTrue(hasattr(UpperCamelCase__ , '''chunk_length''' ) ) self.assertTrue(hasattr(UpperCamelCase__ , '''sampling_rate''' ) ) def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE : Optional[Any] = feat_extract_first.save_pretrained(UpperCamelCase__ )[0] check_json_file_has_correct_format(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[Any] = self.feature_extraction_class.from_pretrained(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[Any] = feat_extract_first.to_dict() SCREAMING_SNAKE_CASE : str = feat_extract_second.to_dict() SCREAMING_SNAKE_CASE : Optional[int] = dict_first.pop('''mel_filters''' ) SCREAMING_SNAKE_CASE : Optional[int] = dict_second.pop('''mel_filters''' ) self.assertTrue(np.allclose(UpperCamelCase__ , UpperCamelCase__ ) ) self.assertEqual(UpperCamelCase__ , UpperCamelCase__ ) def __A ( self : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE : Tuple = os.path.join(UpperCamelCase__ , '''feat_extract.json''' ) feat_extract_first.to_json_file(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[str] = self.feature_extraction_class.from_json_file(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Any = feat_extract_first.to_dict() SCREAMING_SNAKE_CASE : str = feat_extract_second.to_dict() SCREAMING_SNAKE_CASE : int = dict_first.pop('''mel_filters''' ) SCREAMING_SNAKE_CASE : Any = dict_second.pop('''mel_filters''' ) self.assertTrue(np.allclose(UpperCamelCase__ , UpperCamelCase__ ) ) self.assertEqual(UpperCamelCase__ , UpperCamelCase__ ) def __A ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = self.feature_extraction_class(**self.feat_extract_dict ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE : List[Any] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE : Optional[int] = [np.asarray(UpperCamelCase__ ) for speech_input in speech_inputs] # Test not batched input SCREAMING_SNAKE_CASE : List[Any] = feature_extractor(np_speech_inputs[0] , return_tensors='''np''' , sampling_rate=4_4100 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test batched SCREAMING_SNAKE_CASE : Optional[Any] = feature_extractor(UpperCamelCase__ , return_tensors='''np''' , sampling_rate=4_4100 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test audio masking SCREAMING_SNAKE_CASE : List[str] = feature_extractor( UpperCamelCase__ , return_tensors='''np''' , sampling_rate=4_4100 , mask_audio=UpperCamelCase__ ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test 2-D numpy arrays are batched. SCREAMING_SNAKE_CASE : Optional[Any] = [floats_list((1, x) )[0] for x in (800, 800, 800)] SCREAMING_SNAKE_CASE : Dict = np.asarray(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : str = feature_extractor(UpperCamelCase__ , return_tensors='''np''' , sampling_rate=4_4100 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) def __A ( self : Optional[int] , UpperCamelCase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = load_dataset('''hf-internal-testing/librispeech_asr_dummy''' , '''clean''' , split='''validation''' ) # automatic decoding with librispeech SCREAMING_SNAKE_CASE : Dict = ds.sort('''id''' ).select(range(UpperCamelCase__ ) )[:num_samples]['''audio'''] return [x["array"] for x in speech_samples] def __A ( self : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE : int = TvltFeatureExtractor() SCREAMING_SNAKE_CASE : List[Any] = feature_extractor(UpperCamelCase__ , return_tensors='''pt''' ).audio_values self.assertEquals(audio_values.shape , (1, 1, 192, 128) ) SCREAMING_SNAKE_CASE : str = torch.tensor([[-0.3032, -0.2708], [-0.4434, -0.4007]] ) self.assertTrue(torch.allclose(audio_values[0, 0, :2, :2] , UpperCamelCase__ , atol=1E-4 ) )
34
0
from math import factorial def A ( _lowercase , _lowercase , _lowercase ): if successes > trials: raise ValueError('''successes must be lower or equal to trials''' ) if trials < 0 or successes < 0: raise ValueError('''the function is defined for non-negative integers''' ) if not isinstance(_A , _A ) or not isinstance(_A , _A ): raise ValueError('''the function is defined for non-negative integers''' ) if not 0 < prob < 1: raise ValueError('''prob has to be in range of 1 - 0''' ) SCREAMING_SNAKE_CASE : List[str] = (prob**successes) * ((1 - prob) ** (trials - successes)) # Calculate the binomial coefficient: n! / k!(n-k)! SCREAMING_SNAKE_CASE : Tuple = float(factorial(_A ) ) coefficient /= factorial(_A ) * factorial(trials - successes ) return probability * coefficient if __name__ == "__main__": from doctest import testmod testmod() print('Probability of 2 successes out of 4 trails') print('with probability of 0.75 is:', end=' ') print(binomial_distribution(2, 4, 0.75))
708
import math from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import SchedulerMixin, SchedulerOutput class lowercase__ ( UpperCamelCase_ , UpperCamelCase_): UpperCamelCase_ = 1 @register_to_config def __init__( self : List[str] , UpperCamelCase__ : int = 1000 , UpperCamelCase__ : Optional[Union[np.ndarray, List[float]]] = None ): '''simple docstring''' self.set_timesteps(UpperCamelCase__ ) # standard deviation of the initial noise distribution SCREAMING_SNAKE_CASE : str = 1.0 # For now we only support F-PNDM, i.e. the runge-kutta method # For more information on the algorithm please take a look at the paper: https://arxiv.org/pdf/2202.09778.pdf # mainly at formula (9), (12), (13) and the Algorithm 2. SCREAMING_SNAKE_CASE : Tuple = 4 # running values SCREAMING_SNAKE_CASE : int = [] def __A ( self : Dict , UpperCamelCase__ : int , UpperCamelCase__ : Union[str, torch.device] = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = num_inference_steps SCREAMING_SNAKE_CASE : Union[str, Any] = torch.linspace(1 , 0 , num_inference_steps + 1 )[:-1] SCREAMING_SNAKE_CASE : Tuple = torch.cat([steps, torch.tensor([0.0] )] ) if self.config.trained_betas is not None: SCREAMING_SNAKE_CASE : int = torch.tensor(self.config.trained_betas , dtype=torch.floataa ) else: SCREAMING_SNAKE_CASE : Optional[Any] = torch.sin(steps * math.pi / 2 ) ** 2 SCREAMING_SNAKE_CASE : Dict = (1.0 - self.betas**2) ** 0.5 SCREAMING_SNAKE_CASE : Optional[Any] = (torch.atana(self.betas , self.alphas ) / math.pi * 2)[:-1] SCREAMING_SNAKE_CASE : List[str] = timesteps.to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Any = [] def __A ( self : Tuple , UpperCamelCase__ : torch.FloatTensor , UpperCamelCase__ : int , UpperCamelCase__ : torch.FloatTensor , UpperCamelCase__ : bool = True , ): '''simple docstring''' if self.num_inference_steps is None: raise ValueError( '''Number of inference steps is \'None\', you need to run \'set_timesteps\' after creating the scheduler''' ) SCREAMING_SNAKE_CASE : Optional[int] = (self.timesteps == timestep).nonzero().item() SCREAMING_SNAKE_CASE : Union[str, Any] = timestep_index + 1 SCREAMING_SNAKE_CASE : int = sample * self.betas[timestep_index] + model_output * self.alphas[timestep_index] self.ets.append(UpperCamelCase__ ) if len(self.ets ) == 1: SCREAMING_SNAKE_CASE : Dict = self.ets[-1] elif len(self.ets ) == 2: SCREAMING_SNAKE_CASE : Optional[int] = (3 * self.ets[-1] - self.ets[-2]) / 2 elif len(self.ets ) == 3: SCREAMING_SNAKE_CASE : str = (23 * self.ets[-1] - 16 * self.ets[-2] + 5 * self.ets[-3]) / 12 else: SCREAMING_SNAKE_CASE : Optional[Any] = (1 / 24) * (55 * self.ets[-1] - 59 * self.ets[-2] + 37 * self.ets[-3] - 9 * self.ets[-4]) SCREAMING_SNAKE_CASE : Optional[int] = self._get_prev_sample(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=UpperCamelCase__ ) def __A ( self : Optional[Any] , UpperCamelCase__ : torch.FloatTensor , *UpperCamelCase__ : List[str] , **UpperCamelCase__ : Optional[Any] ): '''simple docstring''' return sample def __A ( self : Union[str, Any] , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Any , UpperCamelCase__ : Tuple , UpperCamelCase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = self.alphas[timestep_index] SCREAMING_SNAKE_CASE : List[str] = self.betas[timestep_index] SCREAMING_SNAKE_CASE : Union[str, Any] = self.alphas[prev_timestep_index] SCREAMING_SNAKE_CASE : Tuple = self.betas[prev_timestep_index] SCREAMING_SNAKE_CASE : Dict = (sample - sigma * ets) / max(UpperCamelCase__ , 1E-8 ) SCREAMING_SNAKE_CASE : Optional[Any] = next_alpha * pred + ets * next_sigma return prev_sample def __len__( self : int ): '''simple docstring''' return self.config.num_train_timesteps
34
0
import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler from tensorflow.keras.layers import LSTM, Dense from tensorflow.keras.models import Sequential if __name__ == "__main__": __UpperCamelCase : int = pd.read_csv('sample_data.csv', header=None) __UpperCamelCase : str = df.shape[:1][0] # If you're using some other dataset input the target column __UpperCamelCase : Tuple = df.iloc[:, 1:2] __UpperCamelCase : List[Any] = actual_data.values.reshape(len_data, 1) __UpperCamelCase : Union[str, Any] = MinMaxScaler().fit_transform(actual_data) __UpperCamelCase : int = 10 __UpperCamelCase : Dict = 5 __UpperCamelCase : Tuple = 20 __UpperCamelCase : int = len_data - periods * look_back __UpperCamelCase : str = actual_data[:division] __UpperCamelCase : int = actual_data[division - look_back :] __UpperCamelCase : Optional[int] = [], [] __UpperCamelCase : Dict = [], [] for i in range(0, len(train_data) - forward_days - look_back + 1): train_x.append(train_data[i : i + look_back]) train_y.append(train_data[i + look_back : i + look_back + forward_days]) for i in range(0, len(test_data) - forward_days - look_back + 1): test_x.append(test_data[i : i + look_back]) test_y.append(test_data[i + look_back : i + look_back + forward_days]) __UpperCamelCase : Any = np.array(train_x) __UpperCamelCase : int = np.array(test_x) __UpperCamelCase : Optional[int] = np.array([list(i.ravel()) for i in train_y]) __UpperCamelCase : Dict = np.array([list(i.ravel()) for i in test_y]) __UpperCamelCase : Optional[int] = Sequential() model.add(LSTM(128, input_shape=(look_back, 1), return_sequences=True)) model.add(LSTM(64, input_shape=(128, 1))) model.add(Dense(forward_days)) model.compile(loss='mean_squared_error', optimizer='adam') __UpperCamelCase : str = model.fit( x_train, y_train, epochs=150, verbose=1, shuffle=True, batch_size=4 ) __UpperCamelCase : Optional[int] = model.predict(x_test)
709
import gc import random import unittest import torch from diffusers import ( IFImgaImgPipeline, IFImgaImgSuperResolutionPipeline, IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline, IFPipeline, IFSuperResolutionPipeline, ) from diffusers.models.attention_processor import AttnAddedKVProcessor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import floats_tensor, load_numpy, require_torch_gpu, skip_mps, slow, torch_device from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference from . import IFPipelineTesterMixin @skip_mps class lowercase__ ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): UpperCamelCase_ = IFPipeline UpperCamelCase_ = TEXT_TO_IMAGE_PARAMS - {"""width""", """height""", """latents"""} UpperCamelCase_ = TEXT_TO_IMAGE_BATCH_PARAMS UpperCamelCase_ = PipelineTesterMixin.required_optional_params - {"""latents"""} def __A ( self : Tuple ): '''simple docstring''' return self._get_dummy_components() def __A ( self : int , UpperCamelCase__ : Dict , UpperCamelCase__ : int=0 ): '''simple docstring''' if str(UpperCamelCase__ ).startswith('''mps''' ): SCREAMING_SNAKE_CASE : Tuple = torch.manual_seed(UpperCamelCase__ ) else: SCREAMING_SNAKE_CASE : Dict = torch.Generator(device=UpperCamelCase__ ).manual_seed(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : int = { '''prompt''': '''A painting of a squirrel eating a burger''', '''generator''': generator, '''num_inference_steps''': 2, '''output_type''': '''numpy''', } return inputs def __A ( self : List[str] ): '''simple docstring''' self._test_save_load_optional_components() @unittest.skipIf(torch_device != '''cuda''' , reason='''float16 requires CUDA''' ) def __A ( self : Any ): '''simple docstring''' super().test_save_load_floataa(expected_max_diff=1E-1 ) def __A ( self : Union[str, Any] ): '''simple docstring''' self._test_attention_slicing_forward_pass(expected_max_diff=1E-2 ) def __A ( self : List[Any] ): '''simple docstring''' self._test_save_load_local() def __A ( self : List[str] ): '''simple docstring''' self._test_inference_batch_single_identical( expected_max_diff=1E-2 , ) @unittest.skipIf( torch_device != '''cuda''' or not is_xformers_available() , reason='''XFormers attention is only available with CUDA and `xformers` installed''' , ) def __A ( self : Tuple ): '''simple docstring''' self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 ) @slow @require_torch_gpu class lowercase__ ( unittest.TestCase): def __A ( self : Optional[Any] ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = IFPipeline.from_pretrained('''DeepFloyd/IF-I-XL-v1.0''' , variant='''fp16''' , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE : str = IFSuperResolutionPipeline.from_pretrained( '''DeepFloyd/IF-II-L-v1.0''' , variant='''fp16''' , torch_dtype=torch.floataa , text_encoder=UpperCamelCase__ , tokenizer=UpperCamelCase__ ) # pre compute text embeddings and remove T5 to save memory pipe_a.text_encoder.to('''cuda''' ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Dict = pipe_a.encode_prompt('''anime turtle''' , device='''cuda''' ) del pipe_a.tokenizer del pipe_a.text_encoder gc.collect() SCREAMING_SNAKE_CASE : Tuple = None SCREAMING_SNAKE_CASE : str = None pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) pipe_a.remove_all_hooks() pipe_a.remove_all_hooks() # img2img SCREAMING_SNAKE_CASE : Optional[int] = IFImgaImgPipeline(**pipe_a.components ) SCREAMING_SNAKE_CASE : Optional[int] = IFImgaImgSuperResolutionPipeline(**pipe_a.components ) pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if_imgaimg(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) pipe_a.remove_all_hooks() pipe_a.remove_all_hooks() # inpainting SCREAMING_SNAKE_CASE : Tuple = IFInpaintingPipeline(**pipe_a.components ) SCREAMING_SNAKE_CASE : Optional[int] = IFInpaintingSuperResolutionPipeline(**pipe_a.components ) pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if_inpainting(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) def __A ( self : Tuple , UpperCamelCase__ : int , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Dict ): '''simple docstring''' _start_torch_memory_measurement() SCREAMING_SNAKE_CASE : List[str] = torch.Generator(device='''cpu''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[Any] = pipe_a( prompt_embeds=UpperCamelCase__ , negative_prompt_embeds=UpperCamelCase__ , num_inference_steps=2 , generator=UpperCamelCase__ , output_type='''np''' , ) SCREAMING_SNAKE_CASE : Optional[int] = output.images[0] assert image.shape == (64, 64, 3) SCREAMING_SNAKE_CASE : Tuple = torch.cuda.max_memory_allocated() assert mem_bytes < 13 * 10**9 SCREAMING_SNAKE_CASE : Optional[Any] = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if.npy''' ) assert_mean_pixel_difference(UpperCamelCase__ , UpperCamelCase__ ) # pipeline 2 _start_torch_memory_measurement() SCREAMING_SNAKE_CASE : Tuple = torch.Generator(device='''cpu''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE : int = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Any = pipe_a( prompt_embeds=UpperCamelCase__ , negative_prompt_embeds=UpperCamelCase__ , image=UpperCamelCase__ , generator=UpperCamelCase__ , num_inference_steps=2 , output_type='''np''' , ) SCREAMING_SNAKE_CASE : Tuple = output.images[0] assert image.shape == (256, 256, 3) SCREAMING_SNAKE_CASE : Union[str, Any] = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 SCREAMING_SNAKE_CASE : int = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_superresolution_stage_II.npy''' ) assert_mean_pixel_difference(UpperCamelCase__ , UpperCamelCase__ ) def __A ( self : Optional[int] , UpperCamelCase__ : str , UpperCamelCase__ : int , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : str ): '''simple docstring''' _start_torch_memory_measurement() SCREAMING_SNAKE_CASE : Tuple = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Any = torch.Generator(device='''cpu''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE : List[Any] = pipe_a( prompt_embeds=UpperCamelCase__ , negative_prompt_embeds=UpperCamelCase__ , image=UpperCamelCase__ , num_inference_steps=2 , generator=UpperCamelCase__ , output_type='''np''' , ) SCREAMING_SNAKE_CASE : int = output.images[0] assert image.shape == (64, 64, 3) SCREAMING_SNAKE_CASE : Optional[int] = torch.cuda.max_memory_allocated() assert mem_bytes < 10 * 10**9 SCREAMING_SNAKE_CASE : Tuple = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img.npy''' ) assert_mean_pixel_difference(UpperCamelCase__ , UpperCamelCase__ ) # pipeline 2 _start_torch_memory_measurement() SCREAMING_SNAKE_CASE : Union[str, Any] = torch.Generator(device='''cpu''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[Any] = floats_tensor((1, 3, 256, 256) , rng=random.Random(0 ) ).to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[Any] = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : str = pipe_a( prompt_embeds=UpperCamelCase__ , negative_prompt_embeds=UpperCamelCase__ , image=UpperCamelCase__ , original_image=UpperCamelCase__ , generator=UpperCamelCase__ , num_inference_steps=2 , output_type='''np''' , ) SCREAMING_SNAKE_CASE : Optional[int] = output.images[0] assert image.shape == (256, 256, 3) SCREAMING_SNAKE_CASE : List[Any] = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 SCREAMING_SNAKE_CASE : Optional[Any] = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img_superresolution_stage_II.npy''' ) assert_mean_pixel_difference(UpperCamelCase__ , UpperCamelCase__ ) def __A ( self : List[str] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Optional[Any] ): '''simple docstring''' _start_torch_memory_measurement() SCREAMING_SNAKE_CASE : str = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Union[str, Any] = floats_tensor((1, 3, 64, 64) , rng=random.Random(1 ) ).to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[int] = torch.Generator(device='''cpu''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE : int = pipe_a( prompt_embeds=UpperCamelCase__ , negative_prompt_embeds=UpperCamelCase__ , image=UpperCamelCase__ , mask_image=UpperCamelCase__ , num_inference_steps=2 , generator=UpperCamelCase__ , output_type='''np''' , ) SCREAMING_SNAKE_CASE : Any = output.images[0] assert image.shape == (64, 64, 3) SCREAMING_SNAKE_CASE : Any = torch.cuda.max_memory_allocated() assert mem_bytes < 10 * 10**9 SCREAMING_SNAKE_CASE : List[Any] = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting.npy''' ) assert_mean_pixel_difference(UpperCamelCase__ , UpperCamelCase__ ) # pipeline 2 _start_torch_memory_measurement() SCREAMING_SNAKE_CASE : str = torch.Generator(device='''cpu''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE : List[str] = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : int = floats_tensor((1, 3, 256, 256) , rng=random.Random(0 ) ).to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[int] = floats_tensor((1, 3, 256, 256) , rng=random.Random(1 ) ).to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Dict = pipe_a( prompt_embeds=UpperCamelCase__ , negative_prompt_embeds=UpperCamelCase__ , image=UpperCamelCase__ , mask_image=UpperCamelCase__ , original_image=UpperCamelCase__ , generator=UpperCamelCase__ , num_inference_steps=2 , output_type='''np''' , ) SCREAMING_SNAKE_CASE : Optional[Any] = output.images[0] assert image.shape == (256, 256, 3) SCREAMING_SNAKE_CASE : Any = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 SCREAMING_SNAKE_CASE : Tuple = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting_superresolution_stage_II.npy''' ) assert_mean_pixel_difference(UpperCamelCase__ , UpperCamelCase__ ) def A ( ): torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats()
34
0
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import OwlViTImageProcessor, OwlViTProcessor @require_vision class lowercase__ ( unittest.TestCase): def __A ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = tempfile.mkdtemp() # fmt: off SCREAMING_SNAKE_CASE : Union[str, 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 SCREAMING_SNAKE_CASE : Dict = dict(zip(_A , range(len(_A ) ) ) ) SCREAMING_SNAKE_CASE : int = ['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>', ''] SCREAMING_SNAKE_CASE : Optional[Any] = {'unk_token': '<unk>'} SCREAMING_SNAKE_CASE : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) SCREAMING_SNAKE_CASE : Optional[Any] = 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(_A ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(_A ) ) SCREAMING_SNAKE_CASE : Union[str, Any] = { 'do_resize': True, 'size': 20, 'do_center_crop': True, 'crop_size': 18, 'do_normalize': True, 'image_mean': [0.4814_5466, 0.457_8275, 0.4082_1073], 'image_std': [0.2686_2954, 0.2613_0258, 0.2757_7711], } SCREAMING_SNAKE_CASE : List[str] = os.path.join(self.tmpdirname , _A ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(_A , _A ) def __A ( self : List[Any] , **UpperCamelCase__ : Dict ): '''simple docstring''' return CLIPTokenizer.from_pretrained(self.tmpdirname , pad_token='''!''' , **_A ) def __A ( self : Union[str, Any] , **UpperCamelCase__ : Optional[Any] ): '''simple docstring''' return CLIPTokenizerFast.from_pretrained(self.tmpdirname , pad_token='''!''' , **_A ) def __A ( self : Dict , **UpperCamelCase__ : Union[str, Any] ): '''simple docstring''' return OwlViTImageProcessor.from_pretrained(self.tmpdirname , **_A ) def __A ( self : int ): '''simple docstring''' shutil.rmtree(self.tmpdirname ) def __A ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE : Optional[int] = [Image.fromarray(np.moveaxis(_A , 0 , -1 ) ) for x in image_inputs] return image_inputs def __A ( self : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizer() SCREAMING_SNAKE_CASE : Dict = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE : Optional[Any] = self.get_image_processor() SCREAMING_SNAKE_CASE : Dict = OwlViTProcessor(tokenizer=_A , image_processor=_A ) processor_slow.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE : Optional[int] = OwlViTProcessor.from_pretrained(self.tmpdirname , use_fast=_A ) SCREAMING_SNAKE_CASE : Any = OwlViTProcessor(tokenizer=_A , image_processor=_A ) processor_fast.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE : Optional[int] = OwlViTProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , _A ) self.assertIsInstance(processor_fast.tokenizer , _A ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , _A ) self.assertIsInstance(processor_fast.image_processor , _A ) def __A ( self : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = OwlViTProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE : str = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) SCREAMING_SNAKE_CASE : int = self.get_image_processor(do_normalize=_A ) SCREAMING_SNAKE_CASE : int = OwlViTProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=_A ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , _A ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _A ) def __A ( self : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = self.get_image_processor() SCREAMING_SNAKE_CASE : Optional[Any] = self.get_tokenizer() SCREAMING_SNAKE_CASE : Union[str, Any] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) SCREAMING_SNAKE_CASE : List[Any] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE : Any = image_processor(_A , return_tensors='''np''' ) SCREAMING_SNAKE_CASE : 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 __A ( self : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = self.get_image_processor() SCREAMING_SNAKE_CASE : int = self.get_tokenizer() SCREAMING_SNAKE_CASE : Optional[int] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) SCREAMING_SNAKE_CASE : Union[str, Any] = 'lower newer' SCREAMING_SNAKE_CASE : Any = processor(text=_A , return_tensors='''np''' ) SCREAMING_SNAKE_CASE : Dict = tokenizer(_A , return_tensors='''np''' ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key][0].tolist() , encoded_processor[key][0].tolist() ) def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = self.get_image_processor() SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizer() SCREAMING_SNAKE_CASE : Tuple = OwlViTProcessor(tokenizer=_A , image_processor=_A ) SCREAMING_SNAKE_CASE : Tuple = 'lower newer' SCREAMING_SNAKE_CASE : Union[str, Any] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE : List[Any] = processor(text=_A , images=_A ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = 'google/owlvit-base-patch32' SCREAMING_SNAKE_CASE : str = OwlViTProcessor.from_pretrained(_A ) SCREAMING_SNAKE_CASE : Any = ['cat', 'nasa badge'] SCREAMING_SNAKE_CASE : List[Any] = processor(text=_A ) SCREAMING_SNAKE_CASE : Dict = 16 self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''attention_mask'''] ) self.assertEqual(inputs['''input_ids'''].shape , (2, seq_length) ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def __A ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = 'google/owlvit-base-patch32' SCREAMING_SNAKE_CASE : Any = OwlViTProcessor.from_pretrained(_A ) SCREAMING_SNAKE_CASE : int = [['cat', 'nasa badge'], ['person']] SCREAMING_SNAKE_CASE : str = processor(text=_A ) SCREAMING_SNAKE_CASE : int = 16 SCREAMING_SNAKE_CASE : Optional[int] = len(_A ) SCREAMING_SNAKE_CASE : int = max([len(_A ) for texts in input_texts] ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''attention_mask'''] ) self.assertEqual(inputs['''input_ids'''].shape , (batch_size * num_max_text_queries, seq_length) ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def __A ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = 'google/owlvit-base-patch32' SCREAMING_SNAKE_CASE : List[str] = OwlViTProcessor.from_pretrained(_A ) SCREAMING_SNAKE_CASE : Tuple = ['cat', 'nasa badge'] SCREAMING_SNAKE_CASE : Dict = processor(text=_A ) SCREAMING_SNAKE_CASE : Tuple = 16 SCREAMING_SNAKE_CASE : str = inputs['input_ids'] SCREAMING_SNAKE_CASE : str = [ [4_9406, 2368, 4_9407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [4_9406, 6841, 1_1301, 4_9407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''attention_mask'''] ) self.assertEqual(inputs['''input_ids'''].shape , (2, seq_length) ) self.assertListEqual(list(input_ids[0] ) , predicted_ids[0] ) self.assertListEqual(list(input_ids[1] ) , predicted_ids[1] ) def __A ( self : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self.get_image_processor() SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer() SCREAMING_SNAKE_CASE : Dict = OwlViTProcessor(tokenizer=_A , image_processor=_A ) SCREAMING_SNAKE_CASE : Any = self.prepare_image_inputs() SCREAMING_SNAKE_CASE : Tuple = self.prepare_image_inputs() SCREAMING_SNAKE_CASE : Any = processor(images=_A , query_images=_A ) self.assertListEqual(list(inputs.keys() ) , ['''query_pixel_values''', '''pixel_values'''] ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = self.get_image_processor() SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_tokenizer() SCREAMING_SNAKE_CASE : Optional[int] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) SCREAMING_SNAKE_CASE : int = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] SCREAMING_SNAKE_CASE : Any = processor.batch_decode(_A ) SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer.batch_decode(_A ) self.assertListEqual(_A , _A )
710
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 : int = logging.get_logger(__name__) def A ( _lowercase , _lowercase , _lowercase , _lowercase ): def constraint_to_multiple_of(_lowercase , _lowercase , _lowercase=0 , _lowercase=None ): SCREAMING_SNAKE_CASE : int = round(val / multiple ) * multiple if max_val is not None and x > max_val: SCREAMING_SNAKE_CASE : Dict = math.floor(val / multiple ) * multiple if x < min_val: SCREAMING_SNAKE_CASE : Optional[Any] = math.ceil(val / multiple ) * multiple return x SCREAMING_SNAKE_CASE : Optional[Any] = (output_size, output_size) if isinstance(_lowercase , _lowercase ) else output_size SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = get_image_size(_lowercase ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = output_size # determine new height and width SCREAMING_SNAKE_CASE : Dict = output_height / input_height SCREAMING_SNAKE_CASE : Optional[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 SCREAMING_SNAKE_CASE : List[Any] = scale_width else: # fit height SCREAMING_SNAKE_CASE : List[Any] = scale_height SCREAMING_SNAKE_CASE : List[str] = constraint_to_multiple_of(scale_height * input_height , multiple=_lowercase ) SCREAMING_SNAKE_CASE : Optional[int] = constraint_to_multiple_of(scale_width * input_width , multiple=_lowercase ) return (new_height, new_width) class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = ["""pixel_values"""] def __init__( self : int , UpperCamelCase__ : bool = True , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : PILImageResampling = PILImageResampling.BILINEAR , UpperCamelCase__ : bool = False , UpperCamelCase__ : int = 1 , UpperCamelCase__ : bool = True , UpperCamelCase__ : Union[int, float] = 1 / 255 , UpperCamelCase__ : bool = True , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , **UpperCamelCase__ : Optional[int] , ): '''simple docstring''' super().__init__(**UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[str] = size if size is not None else {'''height''': 384, '''width''': 384} SCREAMING_SNAKE_CASE : Any = get_size_dict(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Dict = do_resize SCREAMING_SNAKE_CASE : Any = size SCREAMING_SNAKE_CASE : str = keep_aspect_ratio SCREAMING_SNAKE_CASE : List[str] = ensure_multiple_of SCREAMING_SNAKE_CASE : int = resample SCREAMING_SNAKE_CASE : Any = do_rescale SCREAMING_SNAKE_CASE : List[Any] = rescale_factor SCREAMING_SNAKE_CASE : Optional[int] = do_normalize SCREAMING_SNAKE_CASE : str = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN SCREAMING_SNAKE_CASE : Union[str, Any] = image_std if image_std is not None else IMAGENET_STANDARD_STD def __A ( self : Optional[Any] , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Dict[str, int] , UpperCamelCase__ : bool = False , UpperCamelCase__ : int = 1 , UpperCamelCase__ : PILImageResampling = PILImageResampling.BICUBIC , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : Union[str, Any] , ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = get_size_dict(UpperCamelCase__ ) 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()}""" ) SCREAMING_SNAKE_CASE : Any = get_resize_output_image_size( UpperCamelCase__ , output_size=(size['''height'''], size['''width''']) , keep_aspect_ratio=UpperCamelCase__ , multiple=UpperCamelCase__ , ) return resize(UpperCamelCase__ , size=UpperCamelCase__ , resample=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def __A ( self : Dict , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Union[int, float] , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : str , ): '''simple docstring''' return rescale(UpperCamelCase__ , scale=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def __A ( self : Any , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Union[float, List[float]] , UpperCamelCase__ : Union[float, List[float]] , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : List[str] , ): '''simple docstring''' return normalize(UpperCamelCase__ , mean=UpperCamelCase__ , std=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def __A ( self : Optional[Any] , UpperCamelCase__ : ImageInput , UpperCamelCase__ : bool = None , UpperCamelCase__ : int = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : int = None , UpperCamelCase__ : PILImageResampling = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : float = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : Optional[Union[str, TensorType]] = None , UpperCamelCase__ : ChannelDimension = ChannelDimension.FIRST , **UpperCamelCase__ : Optional[int] , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE : Optional[Any] = size if size is not None else self.size SCREAMING_SNAKE_CASE : Union[str, Any] = get_size_dict(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[Any] = keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio SCREAMING_SNAKE_CASE : List[str] = ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of SCREAMING_SNAKE_CASE : Tuple = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE : Optional[Any] = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE : Union[str, Any] = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE : str = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE : List[Any] = image_mean if image_mean is not None else self.image_mean SCREAMING_SNAKE_CASE : List[Any] = image_std if image_std is not None else self.image_std SCREAMING_SNAKE_CASE : Dict = make_list_of_images(UpperCamelCase__ ) if not valid_images(UpperCamelCase__ ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None or resample is None: raise ValueError('''Size and resample must be specified if do_resize is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('''Image mean and std must be specified if do_normalize is True.''' ) # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE : Tuple = [to_numpy_array(UpperCamelCase__ ) for image in images] if do_resize: SCREAMING_SNAKE_CASE : Dict = [self.resize(image=UpperCamelCase__ , size=UpperCamelCase__ , resample=UpperCamelCase__ ) for image in images] if do_rescale: SCREAMING_SNAKE_CASE : Any = [self.rescale(image=UpperCamelCase__ , scale=UpperCamelCase__ ) for image in images] if do_normalize: SCREAMING_SNAKE_CASE : Any = [self.normalize(image=UpperCamelCase__ , mean=UpperCamelCase__ , std=UpperCamelCase__ ) for image in images] SCREAMING_SNAKE_CASE : Optional[int] = [to_channel_dimension_format(UpperCamelCase__ , UpperCamelCase__ ) for image in images] SCREAMING_SNAKE_CASE : Tuple = {'''pixel_values''': images} return BatchFeature(data=UpperCamelCase__ , tensor_type=UpperCamelCase__ ) def __A ( self : Tuple , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : List[Tuple] = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(UpperCamelCase__ ) != len(UpperCamelCase__ ): raise ValueError( '''Make sure that you pass in as many target sizes as the batch dimension of the logits''' ) if is_torch_tensor(UpperCamelCase__ ): SCREAMING_SNAKE_CASE : List[Any] = target_sizes.numpy() SCREAMING_SNAKE_CASE : Optional[int] = [] for idx in range(len(UpperCamelCase__ ) ): SCREAMING_SNAKE_CASE : List[str] = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode='''bilinear''' , align_corners=UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Dict = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(UpperCamelCase__ ) else: SCREAMING_SNAKE_CASE : List[Any] = logits.argmax(dim=1 ) SCREAMING_SNAKE_CASE : List[Any] = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
34
0
from math import pi, sqrt, tan def A ( _lowercase ): if side_length < 0: raise ValueError('''surface_area_cube() only accepts non-negative values''' ) return 6 * side_length**2 def A ( _lowercase , _lowercase , _lowercase ): if length < 0 or breadth < 0 or height < 0: raise ValueError('''surface_area_cuboid() only accepts non-negative values''' ) return 2 * ((length * breadth) + (breadth * height) + (length * height)) def A ( _lowercase ): if radius < 0: raise ValueError('''surface_area_sphere() only accepts non-negative values''' ) return 4 * pi * radius**2 def A ( _lowercase ): if radius < 0: raise ValueError('''surface_area_hemisphere() only accepts non-negative values''' ) return 3 * pi * radius**2 def A ( _lowercase , _lowercase ): if radius < 0 or height < 0: raise ValueError('''surface_area_cone() only accepts non-negative values''' ) return pi * radius * (radius + (height**2 + radius**2) ** 0.5) def A ( _lowercase , _lowercase , _lowercase ): if radius_a < 0 or radius_a < 0 or height < 0: raise ValueError( '''surface_area_conical_frustum() only accepts non-negative values''' ) SCREAMING_SNAKE_CASE : Optional[int] = (height**2 + (radius_a - radius_a) ** 2) ** 0.5 return pi * ((slant_height * (radius_a + radius_a)) + radius_a**2 + radius_a**2) def A ( _lowercase , _lowercase ): if radius < 0 or height < 0: raise ValueError('''surface_area_cylinder() only accepts non-negative values''' ) return 2 * pi * radius * (height + radius) def A ( _lowercase , _lowercase ): if torus_radius < 0 or tube_radius < 0: raise ValueError('''surface_area_torus() only accepts non-negative values''' ) if torus_radius < tube_radius: raise ValueError( '''surface_area_torus() does not support spindle or self intersecting tori''' ) return 4 * pow(__snake_case , 2 ) * torus_radius * tube_radius def A ( _lowercase , _lowercase ): if length < 0 or width < 0: raise ValueError('''area_rectangle() only accepts non-negative values''' ) return length * width def A ( _lowercase ): if side_length < 0: raise ValueError('''area_square() only accepts non-negative values''' ) return side_length**2 def A ( _lowercase , _lowercase ): if base < 0 or height < 0: raise ValueError('''area_triangle() only accepts non-negative values''' ) return (base * height) / 2 def A ( _lowercase , _lowercase , _lowercase ): if sidea < 0 or sidea < 0 or sidea < 0: raise ValueError('''area_triangle_three_sides() only accepts non-negative values''' ) elif sidea + sidea < sidea or sidea + sidea < sidea or sidea + sidea < sidea: raise ValueError('''Given three sides do not form a triangle''' ) SCREAMING_SNAKE_CASE : Optional[int] = (sidea + sidea + sidea) / 2 SCREAMING_SNAKE_CASE : Dict = sqrt( semi_perimeter * (semi_perimeter - sidea) * (semi_perimeter - sidea) * (semi_perimeter - sidea) ) return area def A ( _lowercase , _lowercase ): if base < 0 or height < 0: raise ValueError('''area_parallelogram() only accepts non-negative values''' ) return base * height def A ( _lowercase , _lowercase , _lowercase ): if basea < 0 or basea < 0 or height < 0: raise ValueError('''area_trapezium() only accepts non-negative values''' ) return 1 / 2 * (basea + basea) * height def A ( _lowercase ): if radius < 0: raise ValueError('''area_circle() only accepts non-negative values''' ) return pi * radius**2 def A ( _lowercase , _lowercase ): if radius_x < 0 or radius_y < 0: raise ValueError('''area_ellipse() only accepts non-negative values''' ) return pi * radius_x * radius_y def A ( _lowercase , _lowercase ): if diagonal_a < 0 or diagonal_a < 0: raise ValueError('''area_rhombus() only accepts non-negative values''' ) return 1 / 2 * diagonal_a * diagonal_a def A ( _lowercase , _lowercase ): if not isinstance(__snake_case , __snake_case ) or sides < 3: raise ValueError( '''area_reg_polygon() only accepts integers greater than or \ equal to three as number of sides''' ) elif length < 0: raise ValueError( '''area_reg_polygon() only accepts non-negative values as \ length of a side''' ) return (sides * length**2) / (4 * tan(pi / sides )) return (sides * length**2) / (4 * tan(pi / sides )) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) # verbose so we can see methods missing tests print('[DEMO] Areas of various geometric shapes: \n') print(f"""Rectangle: {area_rectangle(10, 20) = }""") print(f"""Square: {area_square(10) = }""") print(f"""Triangle: {area_triangle(10, 10) = }""") print(f"""Triangle: {area_triangle_three_sides(5, 12, 13) = }""") print(f"""Parallelogram: {area_parallelogram(10, 20) = }""") print(f"""Rhombus: {area_rhombus(10, 20) = }""") print(f"""Trapezium: {area_trapezium(10, 20, 30) = }""") print(f"""Circle: {area_circle(20) = }""") print(f"""Ellipse: {area_ellipse(10, 20) = }""") print('\nSurface Areas of various geometric shapes: \n') print(f"""Cube: {surface_area_cube(20) = }""") print(f"""Cuboid: {surface_area_cuboid(10, 20, 30) = }""") print(f"""Sphere: {surface_area_sphere(20) = }""") print(f"""Hemisphere: {surface_area_hemisphere(20) = }""") print(f"""Cone: {surface_area_cone(10, 20) = }""") print(f"""Conical Frustum: {surface_area_conical_frustum(10, 20, 30) = }""") print(f"""Cylinder: {surface_area_cylinder(10, 20) = }""") print(f"""Torus: {surface_area_torus(20, 10) = }""") print(f"""Equilateral Triangle: {area_reg_polygon(3, 10) = }""") print(f"""Square: {area_reg_polygon(4, 10) = }""") print(f"""Reqular Pentagon: {area_reg_polygon(5, 10) = }""")
711
import random def A ( _lowercase , _lowercase ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = [], [], [] for element in data: if element < pivot: less.append(_lowercase ) elif element > pivot: greater.append(_lowercase ) else: equal.append(_lowercase ) return less, equal, greater def A ( _lowercase , _lowercase ): # index = len(items) // 2 when trying to find the median # (value of index when items is sorted) # invalid input if index >= len(_lowercase ) or index < 0: return None SCREAMING_SNAKE_CASE : Dict = items[random.randint(0 , len(_lowercase ) - 1 )] SCREAMING_SNAKE_CASE : int = 0 SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = _partition(_lowercase , _lowercase ) SCREAMING_SNAKE_CASE : List[Any] = len(_lowercase ) SCREAMING_SNAKE_CASE : Optional[Any] = len(_lowercase ) # index is the pivot if m <= index < m + count: return pivot # must be in smaller elif m > index: return quick_select(_lowercase , _lowercase ) # must be in larger else: return quick_select(_lowercase , index - (m + count) )
34
0
from __future__ import annotations import pandas as pd def A ( _lowercase , _lowercase , _lowercase ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = [0] * no_of_processes SCREAMING_SNAKE_CASE : Union[str, Any] = [0] * no_of_processes # Copy the burst time into remaining_time[] for i in range(lowerCamelCase_ ): SCREAMING_SNAKE_CASE : int = burst_time[i] SCREAMING_SNAKE_CASE : Union[str, Any] = 0 SCREAMING_SNAKE_CASE : List[Any] = 0 SCREAMING_SNAKE_CASE : Any = 999_999_999 SCREAMING_SNAKE_CASE : str = 0 SCREAMING_SNAKE_CASE : List[Any] = False # Process until all processes are completed while complete != no_of_processes: for j in range(lowerCamelCase_ ): if arrival_time[j] <= increment_time and remaining_time[j] > 0: if remaining_time[j] < minm: SCREAMING_SNAKE_CASE : Tuple = remaining_time[j] SCREAMING_SNAKE_CASE : Tuple = j SCREAMING_SNAKE_CASE : Optional[Any] = True if not check: increment_time += 1 continue remaining_time[short] -= 1 SCREAMING_SNAKE_CASE : Any = remaining_time[short] if minm == 0: SCREAMING_SNAKE_CASE : Union[str, Any] = 999_999_999 if remaining_time[short] == 0: complete += 1 SCREAMING_SNAKE_CASE : Optional[Any] = False # Find finish time of current process SCREAMING_SNAKE_CASE : Tuple = increment_time + 1 # Calculate waiting time SCREAMING_SNAKE_CASE : Optional[int] = finish_time - arrival_time[short] SCREAMING_SNAKE_CASE : Any = finar - burst_time[short] if waiting_time[short] < 0: SCREAMING_SNAKE_CASE : Tuple = 0 # Increment time increment_time += 1 return waiting_time def A ( _lowercase , _lowercase , _lowercase ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = [0] * no_of_processes for i in range(lowerCamelCase_ ): SCREAMING_SNAKE_CASE : Any = burst_time[i] + waiting_time[i] return turn_around_time def A ( _lowercase , _lowercase , _lowercase ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = 0 SCREAMING_SNAKE_CASE : Union[str, Any] = 0 for i in range(lowerCamelCase_ ): SCREAMING_SNAKE_CASE : Dict = total_waiting_time + waiting_time[i] SCREAMING_SNAKE_CASE : Union[str, Any] = total_turn_around_time + turn_around_time[i] print(f"""Average waiting time = {total_waiting_time / no_of_processes:.5f}""" ) print('''Average turn around time =''' , total_turn_around_time / no_of_processes ) if __name__ == "__main__": print('Enter how many process you want to analyze') __UpperCamelCase : Optional[int] = int(input()) __UpperCamelCase : int = [0] * no_of_processes __UpperCamelCase : Dict = [0] * no_of_processes __UpperCamelCase : List[Any] = list(range(1, no_of_processes + 1)) for i in range(no_of_processes): print('Enter the arrival time and burst time for process:--' + str(i + 1)) __UpperCamelCase , __UpperCamelCase : Any = map(int, input().split()) __UpperCamelCase : str = calculate_waitingtime(arrival_time, burst_time, no_of_processes) __UpperCamelCase : Any = burst_time __UpperCamelCase : List[str] = no_of_processes __UpperCamelCase : List[str] = waiting_time __UpperCamelCase : Optional[int] = calculate_turnaroundtime(bt, n, wt) calculate_average_times(waiting_time, turn_around_time, no_of_processes) __UpperCamelCase : Union[str, Any] = pd.DataFrame( list(zip(processes, burst_time, arrival_time, waiting_time, turn_around_time)), columns=[ 'Process', 'BurstTime', 'ArrivalTime', 'WaitingTime', 'TurnAroundTime', ], ) # Printing the dataFrame pd.set_option('display.max_rows', fcfs.shape[0] + 1) print(fcfs)
712
from dataclasses import asdict, dataclass from typing import Optional from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCamelCase : Tuple = logging.get_logger(__name__) # TODO Update this __UpperCamelCase : List[str] = { 'facebook/esm-1b': 'https://huggingface.co/facebook/esm-1b/resolve/main/config.json', # See all ESM models at https://huggingface.co/models?filter=esm } class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = """esm""" def __init__( self : Tuple , UpperCamelCase__ : Optional[Any]=None , UpperCamelCase__ : int=None , UpperCamelCase__ : List[str]=None , UpperCamelCase__ : Any=768 , UpperCamelCase__ : Optional[Any]=12 , UpperCamelCase__ : str=12 , UpperCamelCase__ : Optional[int]=3072 , UpperCamelCase__ : Optional[Any]=0.1 , UpperCamelCase__ : Any=0.1 , UpperCamelCase__ : Union[str, Any]=1026 , UpperCamelCase__ : Dict=0.02 , UpperCamelCase__ : Any=1E-12 , UpperCamelCase__ : Dict="absolute" , UpperCamelCase__ : Optional[Any]=True , UpperCamelCase__ : int=None , UpperCamelCase__ : Optional[int]=False , UpperCamelCase__ : Tuple=False , UpperCamelCase__ : List[str]=None , UpperCamelCase__ : Optional[Any]=None , **UpperCamelCase__ : Any , ): '''simple docstring''' super().__init__(pad_token_id=UpperCamelCase__ , mask_token_id=UpperCamelCase__ , **UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[Any] = vocab_size SCREAMING_SNAKE_CASE : Any = hidden_size SCREAMING_SNAKE_CASE : Union[str, Any] = num_hidden_layers SCREAMING_SNAKE_CASE : Dict = num_attention_heads SCREAMING_SNAKE_CASE : Any = intermediate_size SCREAMING_SNAKE_CASE : str = hidden_dropout_prob SCREAMING_SNAKE_CASE : List[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : str = max_position_embeddings SCREAMING_SNAKE_CASE : Tuple = initializer_range SCREAMING_SNAKE_CASE : Optional[int] = layer_norm_eps SCREAMING_SNAKE_CASE : Dict = position_embedding_type SCREAMING_SNAKE_CASE : Any = use_cache SCREAMING_SNAKE_CASE : Dict = emb_layer_norm_before SCREAMING_SNAKE_CASE : List[str] = token_dropout SCREAMING_SNAKE_CASE : List[Any] = is_folding_model if is_folding_model: if esmfold_config is None: logger.info('''No esmfold_config supplied for folding model, using default values.''' ) SCREAMING_SNAKE_CASE : List[Any] = EsmFoldConfig() elif isinstance(UpperCamelCase__ , UpperCamelCase__ ): SCREAMING_SNAKE_CASE : Union[str, Any] = EsmFoldConfig(**UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[Any] = esmfold_config if vocab_list is None: logger.warning('''No vocab_list supplied for folding model, assuming the ESM-2 vocabulary!''' ) SCREAMING_SNAKE_CASE : Optional[int] = get_default_vocab_list() else: SCREAMING_SNAKE_CASE : Optional[Any] = vocab_list else: SCREAMING_SNAKE_CASE : str = None SCREAMING_SNAKE_CASE : int = None if self.esmfold_config is not None and getattr(self.esmfold_config , '''use_esm_attn_map''' , UpperCamelCase__ ): raise ValueError('''The HuggingFace port of ESMFold does not support use_esm_attn_map at this time!''' ) def __A ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = super().to_dict() if isinstance(self.esmfold_config , UpperCamelCase__ ): SCREAMING_SNAKE_CASE : Optional[Any] = self.esmfold_config.to_dict() return output @dataclass class lowercase__ : UpperCamelCase_ = None UpperCamelCase_ = True UpperCamelCase_ = False UpperCamelCase_ = False UpperCamelCase_ = False UpperCamelCase_ = 0 UpperCamelCase_ = True UpperCamelCase_ = False UpperCamelCase_ = 128 UpperCamelCase_ = None def __A ( self : Optional[int] ): '''simple docstring''' if self.trunk is None: SCREAMING_SNAKE_CASE : Optional[Any] = TrunkConfig() elif isinstance(self.trunk , UpperCamelCase__ ): SCREAMING_SNAKE_CASE : Tuple = TrunkConfig(**self.trunk ) def __A ( self : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = asdict(self ) SCREAMING_SNAKE_CASE : Tuple = self.trunk.to_dict() return output @dataclass class lowercase__ : UpperCamelCase_ = 48 UpperCamelCase_ = 1_024 UpperCamelCase_ = 128 UpperCamelCase_ = 32 UpperCamelCase_ = 32 UpperCamelCase_ = 32 UpperCamelCase_ = 0 UpperCamelCase_ = 0 UpperCamelCase_ = False UpperCamelCase_ = 4 UpperCamelCase_ = 128 UpperCamelCase_ = None def __A ( self : Any ): '''simple docstring''' if self.structure_module is None: SCREAMING_SNAKE_CASE : Optional[int] = StructureModuleConfig() elif isinstance(self.structure_module , UpperCamelCase__ ): SCREAMING_SNAKE_CASE : Optional[Any] = StructureModuleConfig(**self.structure_module ) if self.max_recycles <= 0: raise ValueError(f"""`max_recycles` should be positive, got {self.max_recycles}.""" ) if self.sequence_state_dim % self.sequence_state_dim != 0: raise ValueError( '''`sequence_state_dim` should be a round multiple of `sequence_state_dim`, got''' f""" {self.sequence_state_dim} and {self.sequence_state_dim}.""" ) if self.pairwise_state_dim % self.pairwise_state_dim != 0: raise ValueError( '''`pairwise_state_dim` should be a round multiple of `pairwise_state_dim`, got''' f""" {self.pairwise_state_dim} and {self.pairwise_state_dim}.""" ) SCREAMING_SNAKE_CASE : Dict = self.sequence_state_dim // self.sequence_head_width SCREAMING_SNAKE_CASE : Tuple = self.pairwise_state_dim // self.pairwise_head_width if self.sequence_state_dim != sequence_num_heads * self.sequence_head_width: raise ValueError( '''`sequence_state_dim` should be equal to `sequence_num_heads * sequence_head_width, got''' f""" {self.sequence_state_dim} != {sequence_num_heads} * {self.sequence_head_width}.""" ) if self.pairwise_state_dim != pairwise_num_heads * self.pairwise_head_width: raise ValueError( '''`pairwise_state_dim` should be equal to `pairwise_num_heads * pairwise_head_width, got''' f""" {self.pairwise_state_dim} != {pairwise_num_heads} * {self.pairwise_head_width}.""" ) if self.pairwise_state_dim % 2 != 0: raise ValueError(f"""`pairwise_state_dim` should be even, got {self.pairwise_state_dim}.""" ) if self.dropout >= 0.4: raise ValueError(f"""`dropout` should not be greater than 0.4, got {self.dropout}.""" ) def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = asdict(self ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.structure_module.to_dict() return output @dataclass class lowercase__ : UpperCamelCase_ = 384 UpperCamelCase_ = 128 UpperCamelCase_ = 16 UpperCamelCase_ = 128 UpperCamelCase_ = 12 UpperCamelCase_ = 4 UpperCamelCase_ = 8 UpperCamelCase_ = 0.1 UpperCamelCase_ = 8 UpperCamelCase_ = 1 UpperCamelCase_ = 2 UpperCamelCase_ = 7 UpperCamelCase_ = 10 UpperCamelCase_ = 1E-8 UpperCamelCase_ = 1E5 def __A ( self : Dict ): '''simple docstring''' return asdict(self ) def A ( ): return ( "<cls>", "<pad>", "<eos>", "<unk>", "L", "A", "G", "V", "S", "E", "R", "T", "I", "D", "P", "K", "Q", "N", "F", "Y", "M", "H", "W", "C", "X", "B", "U", "Z", "O", ".", "-", "<null_1>", "<mask>", )
34
0
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ShapEPipeline else: from .camera import create_pan_cameras from .pipeline_shap_e import ShapEPipeline from .pipeline_shap_e_img2img import ShapEImgaImgPipeline from .renderer import ( BoundingBoxVolume, ImportanceRaySampler, MLPNeRFModelOutput, MLPNeRSTFModel, ShapEParamsProjModel, ShapERenderer, StratifiedRaySampler, VoidNeRFModel, )
713
import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv("""TEST_SAGEMAKER""" , """False""")) is not True , reason="""Skipping test because should only be run when releasing minor transformers version""" , ) @pytest.mark.usefixtures("""sm_env""") @parameterized_class( [ { """framework""": """pytorch""", """script""": """run_glue.py""", """model_name_or_path""": """distilbert-base-cased""", """instance_type""": """ml.p3.16xlarge""", """results""": {"""train_runtime""": 650, """eval_accuracy""": 0.7, """eval_loss""": 0.6}, }, { """framework""": """pytorch""", """script""": """run_ddp.py""", """model_name_or_path""": """distilbert-base-cased""", """instance_type""": """ml.p3.16xlarge""", """results""": {"""train_runtime""": 600, """eval_accuracy""": 0.7, """eval_loss""": 0.6}, }, { """framework""": """tensorflow""", """script""": """run_tf_dist.py""", """model_name_or_path""": """distilbert-base-cased""", """instance_type""": """ml.p3.16xlarge""", """results""": {"""train_runtime""": 600, """eval_accuracy""": 0.6, """eval_loss""": 0.7}, }, ]) class lowercase__ ( unittest.TestCase): def __A ( self : Any ): '''simple docstring''' if self.framework == "pytorch": subprocess.run( f"""cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py""".split() , encoding='''utf-8''' , check=UpperCamelCase__ , ) assert hasattr(self , '''env''' ) def __A ( self : str , UpperCamelCase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = f"""{self.env.base_job_name}-{instance_count}-{'ddp' if 'ddp' in self.script else 'smd'}""" # distributed data settings SCREAMING_SNAKE_CASE : Any = {'''smdistributed''': {'''dataparallel''': {'''enabled''': True}}} if self.script != '''run_ddp.py''' else None # creates estimator return HuggingFace( entry_point=self.script , source_dir=self.env.test_path , role=self.env.role , image_uri=self.env.image_uri , base_job_name=UpperCamelCase__ , instance_count=UpperCamelCase__ , instance_type=self.instance_type , debugger_hook_config=UpperCamelCase__ , hyperparameters={**self.env.distributed_hyperparameters, '''model_name_or_path''': self.model_name_or_path} , metric_definitions=self.env.metric_definitions , distribution=UpperCamelCase__ , py_version='''py36''' , ) def __A ( self : Optional[Any] , UpperCamelCase__ : List[str] ): '''simple docstring''' TrainingJobAnalytics(UpperCamelCase__ ).export_csv(f"""{self.env.test_path}/{job_name}_metrics.csv""" ) @parameterized.expand([(2,)] ) def __A ( self : Tuple , UpperCamelCase__ : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = self.create_estimator(UpperCamelCase__ ) # run training estimator.fit() # result dataframe SCREAMING_SNAKE_CASE : Optional[Any] = TrainingJobAnalytics(estimator.latest_training_job.name ).dataframe() # extract kpis SCREAMING_SNAKE_CASE : List[str] = list(result_metrics_df[result_metrics_df.metric_name == '''eval_accuracy''']['''value'''] ) SCREAMING_SNAKE_CASE : Dict = list(result_metrics_df[result_metrics_df.metric_name == '''eval_loss''']['''value'''] ) # get train time from SageMaker job, this includes starting, preprocessing, stopping SCREAMING_SNAKE_CASE : List[Any] = ( Session().describe_training_job(estimator.latest_training_job.name ).get('''TrainingTimeInSeconds''' , 99_9999 ) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results['''eval_accuracy'''] for t in eval_accuracy ) assert all(t <= self.results['''eval_loss'''] for t in eval_loss ) # dump tests result into json file to share in PR with open(f"""{estimator.latest_training_job.name}.json""" , '''w''' ) as outfile: json.dump({'''train_time''': train_runtime, '''eval_accuracy''': eval_accuracy, '''eval_loss''': eval_loss} , UpperCamelCase__ )
34
0
import warnings from transformers import AutoTokenizer from transformers.utils import is_torch_available from transformers.utils.generic import ExplicitEnum from ...processing_utils import ProcessorMixin if is_torch_available(): import torch class lowercase__ ( _UpperCamelCase): UpperCamelCase_ = """char""" UpperCamelCase_ = """bpe""" UpperCamelCase_ = """wp""" __UpperCamelCase : int = (DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE) class lowercase__ ( _UpperCamelCase): UpperCamelCase_ = ["""image_processor""", """char_tokenizer"""] UpperCamelCase_ = """ViTImageProcessor""" UpperCamelCase_ = """MgpstrTokenizer""" def __init__( self : Optional[int] , UpperCamelCase__ : List[Any]=None , UpperCamelCase__ : int=None , **UpperCamelCase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , UpperCamelCase__ , ) SCREAMING_SNAKE_CASE : List[str] = kwargs.pop('''feature_extractor''' ) SCREAMING_SNAKE_CASE : Optional[Any] = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('''You need to specify an `image_processor`.''' ) if tokenizer is None: raise ValueError('''You need to specify a `tokenizer`.''' ) SCREAMING_SNAKE_CASE : Tuple = tokenizer SCREAMING_SNAKE_CASE : Union[str, Any] = AutoTokenizer.from_pretrained('''gpt2''' ) SCREAMING_SNAKE_CASE : List[Any] = AutoTokenizer.from_pretrained('''bert-base-uncased''' ) super().__init__(UpperCamelCase__ , UpperCamelCase__ ) def __call__( self : Any , UpperCamelCase__ : Dict=None , UpperCamelCase__ : List[Any]=None , UpperCamelCase__ : str=None , **UpperCamelCase__ : int ): '''simple docstring''' if images is None and text is None: raise ValueError('''You need to specify either an `images` or `text` input to process.''' ) if images is not None: SCREAMING_SNAKE_CASE : Any = self.image_processor(UpperCamelCase__ , return_tensors=UpperCamelCase__ , **UpperCamelCase__ ) if text is not None: SCREAMING_SNAKE_CASE : List[str] = self.char_tokenizer(UpperCamelCase__ , return_tensors=UpperCamelCase__ , **UpperCamelCase__ ) if text is None: return inputs elif images is None: return encodings else: SCREAMING_SNAKE_CASE : Any = encodings["input_ids"] return inputs def __A ( self : Union[str, Any] , UpperCamelCase__ : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = sequences SCREAMING_SNAKE_CASE : Optional[int] = char_preds.size(0 ) SCREAMING_SNAKE_CASE : List[Any] = self._decode_helper(UpperCamelCase__ , '''char''' ) SCREAMING_SNAKE_CASE : Optional[int] = self._decode_helper(UpperCamelCase__ , '''bpe''' ) SCREAMING_SNAKE_CASE : Any = self._decode_helper(UpperCamelCase__ , '''wp''' ) SCREAMING_SNAKE_CASE : Tuple = [] SCREAMING_SNAKE_CASE : Dict = [] for i in range(UpperCamelCase__ ): SCREAMING_SNAKE_CASE : str = [char_scores[i], bpe_scores[i], wp_scores[i]] SCREAMING_SNAKE_CASE : Union[str, Any] = [char_strs[i], bpe_strs[i], wp_strs[i]] SCREAMING_SNAKE_CASE : Any = scores.index(max(UpperCamelCase__ ) ) final_strs.append(strs[max_score_index] ) final_scores.append(scores[max_score_index] ) SCREAMING_SNAKE_CASE : str = {} SCREAMING_SNAKE_CASE : int = final_strs SCREAMING_SNAKE_CASE : List[str] = final_scores SCREAMING_SNAKE_CASE : int = char_strs SCREAMING_SNAKE_CASE : Any = bpe_strs SCREAMING_SNAKE_CASE : Union[str, Any] = wp_strs return out def __A ( self : List[Any] , UpperCamelCase__ : Tuple , UpperCamelCase__ : Optional[Any] ): '''simple docstring''' if format == DecodeType.CHARACTER: SCREAMING_SNAKE_CASE : Tuple = self.char_decode SCREAMING_SNAKE_CASE : Optional[Any] = 1 SCREAMING_SNAKE_CASE : List[Any] = "[s]" elif format == DecodeType.BPE: SCREAMING_SNAKE_CASE : int = self.bpe_decode SCREAMING_SNAKE_CASE : Dict = 2 SCREAMING_SNAKE_CASE : str = "#" elif format == DecodeType.WORDPIECE: SCREAMING_SNAKE_CASE : str = self.wp_decode SCREAMING_SNAKE_CASE : List[str] = 102 SCREAMING_SNAKE_CASE : Dict = "[SEP]" else: raise ValueError(f"""Format {format} is not supported.""" ) SCREAMING_SNAKE_CASE : Dict = [], [] SCREAMING_SNAKE_CASE : Dict = pred_logits.size(0 ) SCREAMING_SNAKE_CASE : str = pred_logits.size(1 ) SCREAMING_SNAKE_CASE : int = pred_logits.topk(1 , dim=-1 , largest=UpperCamelCase__ , sorted=UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Dict = preds_index.view(-1 , UpperCamelCase__ )[:, 1:] SCREAMING_SNAKE_CASE : Optional[int] = decoder(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Dict = torch.nn.functional.softmax(UpperCamelCase__ , dim=2 ).max(dim=2 ) SCREAMING_SNAKE_CASE : List[Any] = preds_max_prob[:, 1:] for index in range(UpperCamelCase__ ): SCREAMING_SNAKE_CASE : List[str] = preds_str[index].find(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[Any] = preds_str[index][:pred_eos] SCREAMING_SNAKE_CASE : int = preds_index[index].cpu().tolist() SCREAMING_SNAKE_CASE : Tuple = pred_index.index(UpperCamelCase__ ) if eos_token in pred_index else -1 SCREAMING_SNAKE_CASE : Dict = preds_max_prob[index][: pred_eos_index + 1] SCREAMING_SNAKE_CASE : int = pred_max_prob.cumprod(dim=0 )[-1] if pred_max_prob.nelement() != 0 else 0.0 dec_strs.append(UpperCamelCase__ ) conf_scores.append(UpperCamelCase__ ) return dec_strs, conf_scores def __A ( self : str , UpperCamelCase__ : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = [seq.replace(''' ''' , '''''' ) for seq in self.char_tokenizer.batch_decode(UpperCamelCase__ )] return decode_strs def __A ( self : Union[str, Any] , UpperCamelCase__ : Any ): '''simple docstring''' return self.bpe_tokenizer.batch_decode(UpperCamelCase__ ) def __A ( self : Any , UpperCamelCase__ : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = [seq.replace(''' ''' , '''''' ) for seq in self.wp_tokenizer.batch_decode(UpperCamelCase__ )] return decode_strs
714
import os try: from .build_directory_md import good_file_paths except ImportError: from build_directory_md import good_file_paths # type: ignore __UpperCamelCase : Dict = list(good_file_paths()) assert filepaths, "good_file_paths() failed!" __UpperCamelCase : Tuple = [file for file in filepaths if file != file.lower()] if upper_files: print(f"""{len(upper_files)} files contain uppercase characters:""") print('\n'.join(upper_files) + '\n') __UpperCamelCase : List[Any] = [file for file in filepaths if ' ' in file] if space_files: print(f"""{len(space_files)} files contain space characters:""") print('\n'.join(space_files) + '\n') __UpperCamelCase : List[Any] = [file for file in filepaths if '-' in file] if hyphen_files: print(f"""{len(hyphen_files)} files contain hyphen characters:""") print('\n'.join(hyphen_files) + '\n') __UpperCamelCase : List[Any] = [file for file in filepaths if os.sep not in file] if nodir_files: print(f"""{len(nodir_files)} files are not in a directory:""") print('\n'.join(nodir_files) + '\n') __UpperCamelCase : Optional[Any] = len(upper_files + space_files + hyphen_files + nodir_files) if bad_files: import sys sys.exit(bad_files)
34
0
import unittest import numpy as np import timeout_decorator # noqa from transformers import BlenderbotSmallConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): import os # The slow tests are often failing with OOM error on GPU # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html __UpperCamelCase : Tuple = 'platform' import jax import jax.numpy as jnp from transformers.models.blenderbot_small.modeling_flax_blenderbot_small import ( FlaxBlenderbotSmallForConditionalGeneration, FlaxBlenderbotSmallModel, shift_tokens_right, ) def A ( _lowercase , _lowercase , _lowercase=None , _lowercase=None , _lowercase=None , _lowercase=None , _lowercase=None , _lowercase=None , ): if attention_mask is None: SCREAMING_SNAKE_CASE : Optional[Any] = np.where(input_ids != config.pad_token_id , 1 , 0 ) if decoder_attention_mask is None: SCREAMING_SNAKE_CASE : List[str] = np.where(decoder_input_ids != config.pad_token_id , 1 , 0 ) if head_mask is None: SCREAMING_SNAKE_CASE : Any = np.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: SCREAMING_SNAKE_CASE : List[Any] = np.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: SCREAMING_SNAKE_CASE : List[str] = np.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": attention_mask, } class lowercase__ : def __init__( self : List[str] , UpperCamelCase__ : int , UpperCamelCase__ : List[str]=13 , UpperCamelCase__ : Optional[int]=7 , UpperCamelCase__ : List[str]=True , UpperCamelCase__ : int=False , UpperCamelCase__ : List[str]=99 , UpperCamelCase__ : Any=16 , UpperCamelCase__ : Any=2 , UpperCamelCase__ : Union[str, Any]=4 , UpperCamelCase__ : List[Any]=4 , UpperCamelCase__ : Any="gelu" , UpperCamelCase__ : str=0.1 , UpperCamelCase__ : Optional[int]=0.1 , UpperCamelCase__ : List[str]=32 , UpperCamelCase__ : Optional[int]=2 , UpperCamelCase__ : List[str]=1 , UpperCamelCase__ : str=0 , UpperCamelCase__ : Optional[int]=0.02 , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = parent SCREAMING_SNAKE_CASE : List[str] = batch_size SCREAMING_SNAKE_CASE : Any = seq_length SCREAMING_SNAKE_CASE : Union[str, Any] = is_training SCREAMING_SNAKE_CASE : Any = use_labels SCREAMING_SNAKE_CASE : str = vocab_size SCREAMING_SNAKE_CASE : Optional[int] = hidden_size SCREAMING_SNAKE_CASE : Optional[int] = num_hidden_layers SCREAMING_SNAKE_CASE : str = num_attention_heads SCREAMING_SNAKE_CASE : Union[str, Any] = intermediate_size SCREAMING_SNAKE_CASE : Any = hidden_act SCREAMING_SNAKE_CASE : Optional[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE : Tuple = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : str = max_position_embeddings SCREAMING_SNAKE_CASE : List[str] = eos_token_id SCREAMING_SNAKE_CASE : List[str] = pad_token_id SCREAMING_SNAKE_CASE : Optional[int] = bos_token_id SCREAMING_SNAKE_CASE : str = initializer_range def __A ( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = np.clip(ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) , 3 , self.vocab_size ) SCREAMING_SNAKE_CASE : Optional[Any] = np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1) , dtype=np.intaa )) , -1 ) SCREAMING_SNAKE_CASE : Any = shift_tokens_right(lowercase_ , 1 , 2 ) SCREAMING_SNAKE_CASE : List[Any] = BlenderbotSmallConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , initializer_range=self.initializer_range , use_cache=lowercase_ , ) SCREAMING_SNAKE_CASE : List[Any] = prepare_blenderbot_inputs_dict(lowercase_ , lowercase_ , lowercase_ ) return config, inputs_dict def __A ( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Dict = self.prepare_config_and_inputs() return config, inputs_dict def __A ( self : Tuple , UpperCamelCase__ : Dict , UpperCamelCase__ : List[str] , UpperCamelCase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = 20 SCREAMING_SNAKE_CASE : Any = model_class_name(lowercase_ ) SCREAMING_SNAKE_CASE : int = model.encode(inputs_dict['''input_ids'''] ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = ( inputs_dict['''decoder_input_ids'''], inputs_dict['''decoder_attention_mask'''], ) SCREAMING_SNAKE_CASE : str = model.init_cache(decoder_input_ids.shape[0] , lowercase_ , lowercase_ ) SCREAMING_SNAKE_CASE : int = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype='''i4''' ) SCREAMING_SNAKE_CASE : List[Any] = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) SCREAMING_SNAKE_CASE : List[Any] = model.decode( decoder_input_ids[:, :-1] , lowercase_ , decoder_attention_mask=lowercase_ , past_key_values=lowercase_ , decoder_position_ids=lowercase_ , ) SCREAMING_SNAKE_CASE : List[str] = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype='''i4''' ) SCREAMING_SNAKE_CASE : Optional[int] = model.decode( decoder_input_ids[:, -1:] , lowercase_ , decoder_attention_mask=lowercase_ , past_key_values=outputs_cache.past_key_values , decoder_position_ids=lowercase_ , ) SCREAMING_SNAKE_CASE : List[Any] = model.decode(lowercase_ , lowercase_ ) SCREAMING_SNAKE_CASE : str = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=f"""Max diff is {diff}""" ) def __A ( self : Optional[int] , UpperCamelCase__ : Any , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = 20 SCREAMING_SNAKE_CASE : Any = model_class_name(lowercase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = model.encode(inputs_dict['''input_ids'''] ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = ( inputs_dict['''decoder_input_ids'''], inputs_dict['''decoder_attention_mask'''], ) SCREAMING_SNAKE_CASE : Dict = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) SCREAMING_SNAKE_CASE : Optional[int] = model.init_cache(decoder_input_ids.shape[0] , lowercase_ , lowercase_ ) SCREAMING_SNAKE_CASE : List[Any] = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) SCREAMING_SNAKE_CASE : str = model.decode( decoder_input_ids[:, :-1] , lowercase_ , decoder_attention_mask=lowercase_ , past_key_values=lowercase_ , decoder_position_ids=lowercase_ , ) SCREAMING_SNAKE_CASE : List[Any] = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype='''i4''' ) SCREAMING_SNAKE_CASE : Union[str, Any] = model.decode( decoder_input_ids[:, -1:] , lowercase_ , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=lowercase_ , decoder_position_ids=lowercase_ , ) SCREAMING_SNAKE_CASE : Union[str, Any] = model.decode(lowercase_ , lowercase_ , decoder_attention_mask=lowercase_ ) SCREAMING_SNAKE_CASE : str = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=f"""Max diff is {diff}""" ) @require_flax class lowercase__ ( unittest.TestCase): UpperCamelCase_ = 99 def __A ( self : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = np.array( [ [71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 82, 2], [5, 97, 17, 39, 94, 40, 2], [76, 83, 94, 25, 70, 78, 2], [87, 59, 41, 35, 48, 66, 2], [55, 13, 16, 58, 5, 2, 1], # note padding [64, 27, 31, 51, 12, 75, 2], [52, 64, 86, 17, 83, 39, 2], [48, 61, 9, 24, 71, 82, 2], [26, 1, 60, 48, 22, 13, 2], [21, 5, 62, 28, 14, 76, 2], [45, 98, 37, 86, 59, 48, 2], [70, 70, 50, 9, 28, 0, 2], ] , dtype=np.intaa , ) SCREAMING_SNAKE_CASE : List[str] = input_ids.shape[0] SCREAMING_SNAKE_CASE : str = BlenderbotSmallConfig( vocab_size=self.vocab_size , d_model=24 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=32 , decoder_ffn_dim=32 , max_position_embeddings=48 , eos_token_id=2 , pad_token_id=1 , bos_token_id=0 , ) return config, input_ids, batch_size def __A ( self : int ): '''simple docstring''' SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[Any] = self._get_config_and_data() SCREAMING_SNAKE_CASE : Any = FlaxBlenderbotSmallForConditionalGeneration(lowercase_ ) SCREAMING_SNAKE_CASE : Optional[int] = lm_model(input_ids=lowercase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = (batch_size, input_ids.shape[1], config.vocab_size) self.assertEqual(outputs['''logits'''].shape , lowercase_ ) def __A ( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = BlenderbotSmallConfig( vocab_size=self.vocab_size , d_model=14 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=8 , decoder_ffn_dim=8 , max_position_embeddings=48 , ) SCREAMING_SNAKE_CASE : Union[str, Any] = FlaxBlenderbotSmallForConditionalGeneration(lowercase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = np.array([[71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 2, 1]] , dtype=np.intaa ) SCREAMING_SNAKE_CASE : str = np.array([[82, 71, 82, 18, 2], [58, 68, 2, 1, 1]] , dtype=np.intaa ) SCREAMING_SNAKE_CASE : Optional[Any] = lm_model(input_ids=lowercase_ , decoder_input_ids=lowercase_ ) SCREAMING_SNAKE_CASE : List[str] = (*summary.shape, config.vocab_size) self.assertEqual(outputs['''logits'''].shape , lowercase_ ) def __A ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = np.array([[71, 82, 18, 33, 2, 1, 1], [68, 34, 26, 58, 30, 82, 2]] , dtype=np.intaa ) SCREAMING_SNAKE_CASE : Dict = shift_tokens_right(lowercase_ , 1 , 2 ) SCREAMING_SNAKE_CASE : Optional[Any] = np.equal(lowercase_ , 1 ).astype(np.floataa ).sum() SCREAMING_SNAKE_CASE : List[str] = np.equal(lowercase_ , 1 ).astype(np.floataa ).sum() self.assertEqual(shifted.shape , input_ids.shape ) self.assertEqual(lowercase_ , n_pad_before - 1 ) self.assertTrue(np.equal(shifted[:, 0] , 2 ).all() ) @require_flax class lowercase__ ( UpperCamelCase_ , unittest.TestCase , UpperCamelCase_): UpperCamelCase_ = True UpperCamelCase_ = ( ( FlaxBlenderbotSmallModel, FlaxBlenderbotSmallForConditionalGeneration, ) if is_flax_available() else () ) UpperCamelCase_ = (FlaxBlenderbotSmallForConditionalGeneration,) if is_flax_available() else () def __A ( self : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = FlaxBlenderbotSmallModelTester(self ) def __A ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(lowercase_ , lowercase_ , lowercase_ ) def __A ( self : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(lowercase_ , lowercase_ , lowercase_ ) def __A ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): SCREAMING_SNAKE_CASE : Optional[Any] = self._prepare_for_class(lowercase_ , lowercase_ ) SCREAMING_SNAKE_CASE : Dict = model_class(lowercase_ ) @jax.jit def encode_jitted(UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Tuple=None , **UpperCamelCase__ : Any ): return model.encode(input_ids=lowercase_ , attention_mask=lowercase_ ) with self.subTest('''JIT Enabled''' ): SCREAMING_SNAKE_CASE : str = encode_jitted(**lowercase_ ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): SCREAMING_SNAKE_CASE : Dict = encode_jitted(**lowercase_ ).to_tuple() self.assertEqual(len(lowercase_ ) , len(lowercase_ ) ) for jitted_output, output in zip(lowercase_ , lowercase_ ): self.assertEqual(jitted_output.shape , output.shape ) def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): SCREAMING_SNAKE_CASE : Dict = model_class(lowercase_ ) SCREAMING_SNAKE_CASE : List[Any] = model.encode(inputs_dict['''input_ids'''] , inputs_dict['''attention_mask'''] ) SCREAMING_SNAKE_CASE : Dict = { '''decoder_input_ids''': inputs_dict['''decoder_input_ids'''], '''decoder_attention_mask''': inputs_dict['''decoder_attention_mask'''], '''encoder_outputs''': encoder_outputs, } @jax.jit def decode_jitted(UpperCamelCase__ : Any , UpperCamelCase__ : int , UpperCamelCase__ : List[str] ): return model.decode( decoder_input_ids=lowercase_ , decoder_attention_mask=lowercase_ , encoder_outputs=lowercase_ , ) with self.subTest('''JIT Enabled''' ): SCREAMING_SNAKE_CASE : List[Any] = decode_jitted(**lowercase_ ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): SCREAMING_SNAKE_CASE : Optional[Any] = decode_jitted(**lowercase_ ).to_tuple() self.assertEqual(len(lowercase_ ) , len(lowercase_ ) ) for jitted_output, output in zip(lowercase_ , lowercase_ ): self.assertEqual(jitted_output.shape , output.shape ) @slow def __A ( self : Optional[int] ): '''simple docstring''' for model_class_name in self.all_model_classes: SCREAMING_SNAKE_CASE : List[str] = model_class_name.from_pretrained('''facebook/blenderbot_small-90M''' ) # FlaxBlenderbotForSequenceClassification expects eos token in input_ids SCREAMING_SNAKE_CASE : str = np.ones((1, 1) ) * model.config.eos_token_id SCREAMING_SNAKE_CASE : Optional[Any] = model(lowercase_ ) self.assertIsNotNone(lowercase_ )
715
import os import re import warnings from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_ta import TaTokenizer else: __UpperCamelCase : Dict = None __UpperCamelCase : Tuple = logging.get_logger(__name__) __UpperCamelCase : Optional[int] = {'vocab_file': 'spiece.model', 'tokenizer_file': 'tokenizer.json'} __UpperCamelCase : Optional[int] = { 'vocab_file': { 't5-small': 'https://huggingface.co/t5-small/resolve/main/spiece.model', 't5-base': 'https://huggingface.co/t5-base/resolve/main/spiece.model', 't5-large': 'https://huggingface.co/t5-large/resolve/main/spiece.model', 't5-3b': 'https://huggingface.co/t5-3b/resolve/main/spiece.model', 't5-11b': 'https://huggingface.co/t5-11b/resolve/main/spiece.model', }, 'tokenizer_file': { 't5-small': 'https://huggingface.co/t5-small/resolve/main/tokenizer.json', 't5-base': 'https://huggingface.co/t5-base/resolve/main/tokenizer.json', 't5-large': 'https://huggingface.co/t5-large/resolve/main/tokenizer.json', 't5-3b': 'https://huggingface.co/t5-3b/resolve/main/tokenizer.json', 't5-11b': 'https://huggingface.co/t5-11b/resolve/main/tokenizer.json', }, } # TODO(PVP) - this should be removed in Transformers v5 __UpperCamelCase : Union[str, Any] = { 't5-small': 512, 't5-base': 512, 't5-large': 512, 't5-3b': 512, 't5-11b': 512, } class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = VOCAB_FILES_NAMES UpperCamelCase_ = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase_ = ["""input_ids""", """attention_mask"""] UpperCamelCase_ = TaTokenizer UpperCamelCase_ = [] def __init__( self : str , UpperCamelCase__ : Optional[int]=None , UpperCamelCase__ : Dict=None , UpperCamelCase__ : str="</s>" , UpperCamelCase__ : str="<unk>" , UpperCamelCase__ : Optional[int]="<pad>" , UpperCamelCase__ : Optional[Any]=100 , UpperCamelCase__ : List[Any]=None , **UpperCamelCase__ : str , ): '''simple docstring''' if extra_ids > 0 and additional_special_tokens is None: SCREAMING_SNAKE_CASE : List[str] = [f"""<extra_id_{i}>""" for i in range(UpperCamelCase__ )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra special tokens SCREAMING_SNAKE_CASE : int = len(set(filter(lambda UpperCamelCase__ : bool('''extra_id_''' in str(UpperCamelCase__ ) ) , UpperCamelCase__ ) ) ) if extra_tokens != extra_ids: raise ValueError( f"""Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are""" ''' provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids''' ''' tokens''' ) super().__init__( UpperCamelCase__ , tokenizer_file=UpperCamelCase__ , eos_token=UpperCamelCase__ , unk_token=UpperCamelCase__ , pad_token=UpperCamelCase__ , extra_ids=UpperCamelCase__ , additional_special_tokens=UpperCamelCase__ , **UpperCamelCase__ , ) SCREAMING_SNAKE_CASE : str = vocab_file SCREAMING_SNAKE_CASE : int = False if not self.vocab_file else True SCREAMING_SNAKE_CASE : str = extra_ids @staticmethod def __A ( UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Optional[Any] ): '''simple docstring''' if pretrained_model_name_or_path in TaTokenizerFast.max_model_input_sizes: SCREAMING_SNAKE_CASE : List[str] = TaTokenizerFast.max_model_input_sizes[pretrained_model_name_or_path] if init_max_model_length is not None and init_max_model_length != max_model_length: return init_max_model_length elif init_max_model_length is None: warnings.warn( '''This tokenizer was incorrectly instantiated with a model max length of''' f""" {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this""" ''' behavior is kept to avoid breaking backwards compatibility when padding/encoding with''' ''' `truncation is True`.\n- Be aware that you SHOULD NOT rely on''' f""" {pretrained_model_name_or_path} automatically truncating your input to""" f""" {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences""" f""" longer than {deprecated_max_model_length} you can either instantiate this tokenizer with""" ''' `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please''' ''' instantiate this tokenizer with `model_max_length` set to your preferred value.''' , UpperCamelCase__ , ) return max_model_length def __A ( self : Tuple , UpperCamelCase__ : str , UpperCamelCase__ : Optional[str] = None ): '''simple docstring''' if not self.can_save_slow_tokenizer: raise ValueError( '''Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ''' '''tokenizer.''' ) if not os.path.isdir(UpperCamelCase__ ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return SCREAMING_SNAKE_CASE : Any = os.path.join( UpperCamelCase__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCamelCase__ ): copyfile(self.vocab_file , UpperCamelCase__ ) logger.info(f"""Copy vocab file to {out_vocab_file}""" ) return (out_vocab_file,) def __A ( self : Optional[Any] , UpperCamelCase__ : List[int] , UpperCamelCase__ : Optional[List[int]] = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = token_ids_a + [self.eos_token_id] if token_ids_a is None: return self.prefix_tokens + token_ids_a else: SCREAMING_SNAKE_CASE : Tuple = token_ids_a + [self.eos_token_id] return self.prefix_tokens + token_ids_a + token_ids_a def __A ( self : Any , UpperCamelCase__ : List[int] , UpperCamelCase__ : Optional[List[int]] = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def __A ( self : Dict ): '''simple docstring''' return list( set(filter(lambda UpperCamelCase__ : bool(re.search(r'''<extra_id_\d+>''' , UpperCamelCase__ ) ) is not None , self.additional_special_tokens ) ) ) def __A ( self : List[Any] ): '''simple docstring''' return [self.convert_tokens_to_ids(UpperCamelCase__ ) for token in self.get_sentinel_tokens()]
34
0
import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionTextToImagePipeline from diffusers.utils.testing_utils import nightly, require_torch_gpu, torch_device __UpperCamelCase : List[Any] = False class lowercase__ ( unittest.TestCase): pass @nightly @require_torch_gpu class lowercase__ ( unittest.TestCase): def __A ( self : str ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def __A ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = VersatileDiffusionTextToImagePipeline.from_pretrained('''shi-labs/versatile-diffusion''' ) # remove text_unet pipe.remove_unused_weights() pipe.to(lowerCAmelCase_ ) pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = '''A painting of a squirrel eating a burger ''' SCREAMING_SNAKE_CASE : Optional[Any] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Tuple = pipe( prompt=lowerCAmelCase_ , generator=lowerCAmelCase_ , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' ).images with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = VersatileDiffusionTextToImagePipeline.from_pretrained(lowerCAmelCase_ ) pipe.to(lowerCAmelCase_ ) pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = generator.manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[Any] = pipe( prompt=lowerCAmelCase_ , generator=lowerCAmelCase_ , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' ).images assert np.abs(image - new_image ).sum() < 1E-5, "Models don't have the same forward pass" def __A ( self : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = VersatileDiffusionTextToImagePipeline.from_pretrained( '''shi-labs/versatile-diffusion''' , torch_dtype=torch.floataa ) pipe.to(lowerCAmelCase_ ) pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE : int = '''A painting of a squirrel eating a burger ''' SCREAMING_SNAKE_CASE : List[Any] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[Any] = pipe( prompt=lowerCAmelCase_ , generator=lowerCAmelCase_ , guidance_scale=7.5 , num_inference_steps=50 , output_type='''numpy''' ).images SCREAMING_SNAKE_CASE : List[Any] = image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE : Dict = np.array([0.3367, 0.3169, 0.2656, 0.3870, 0.4790, 0.3796, 0.4009, 0.4878, 0.4778] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
716
import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionPipeline from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device __UpperCamelCase : str = False class lowercase__ ( unittest.TestCase): pass @nightly @require_torch_gpu class lowercase__ ( unittest.TestCase): def __A ( self : Union[str, Any] ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = VersatileDiffusionPipeline.from_pretrained('''shi-labs/versatile-diffusion''' , torch_dtype=torch.floataa ) pipe.to(UpperCamelCase__ ) pipe.set_progress_bar_config(disable=UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[Any] = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg''' ) SCREAMING_SNAKE_CASE : Optional[Any] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Dict = pipe.dual_guided( prompt='''first prompt''' , image=UpperCamelCase__ , text_to_image_strength=0.75 , generator=UpperCamelCase__ , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' , ).images with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[Any] = VersatileDiffusionPipeline.from_pretrained(UpperCamelCase__ , torch_dtype=torch.floataa ) pipe.to(UpperCamelCase__ ) pipe.set_progress_bar_config(disable=UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[Any] = generator.manual_seed(0 ) SCREAMING_SNAKE_CASE : int = pipe.dual_guided( prompt='''first prompt''' , image=UpperCamelCase__ , text_to_image_strength=0.75 , generator=UpperCamelCase__ , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' , ).images assert np.abs(image - new_image ).sum() < 1E-5, "Models don't have the same forward pass" def __A ( self : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = VersatileDiffusionPipeline.from_pretrained('''shi-labs/versatile-diffusion''' , torch_dtype=torch.floataa ) pipe.to(UpperCamelCase__ ) pipe.set_progress_bar_config(disable=UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[int] = '''cyberpunk 2077''' SCREAMING_SNAKE_CASE : Tuple = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg''' ) SCREAMING_SNAKE_CASE : List[Any] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Tuple = pipe.dual_guided( prompt=UpperCamelCase__ , image=UpperCamelCase__ , text_to_image_strength=0.75 , generator=UpperCamelCase__ , guidance_scale=7.5 , num_inference_steps=50 , output_type='''numpy''' , ).images SCREAMING_SNAKE_CASE : Tuple = image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE : int = np.array([0.1448, 0.1619, 0.1741, 0.1086, 0.1147, 0.1128, 0.1199, 0.1165, 0.1001] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 SCREAMING_SNAKE_CASE : Optional[Any] = '''A painting of a squirrel eating a burger ''' SCREAMING_SNAKE_CASE : Optional[Any] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Any = pipe.text_to_image( prompt=UpperCamelCase__ , generator=UpperCamelCase__ , guidance_scale=7.5 , num_inference_steps=50 , output_type='''numpy''' ).images SCREAMING_SNAKE_CASE : List[str] = image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE : Any = np.array([0.3367, 0.3169, 0.2656, 0.3870, 0.4790, 0.3796, 0.4009, 0.4878, 0.4778] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 SCREAMING_SNAKE_CASE : Optional[Any] = pipe.image_variation(UpperCamelCase__ , generator=UpperCamelCase__ , output_type='''numpy''' ).images SCREAMING_SNAKE_CASE : Optional[int] = image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE : Union[str, Any] = np.array([0.3076, 0.3123, 0.3284, 0.3782, 0.3770, 0.3894, 0.4297, 0.4331, 0.4456] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1
34
0
'''simple docstring''' def A ( _lowercase ): SCREAMING_SNAKE_CASE : Any = n ** (1 / 3) return (val * val * val) == n if __name__ == "__main__": print(perfect_cube(27)) print(perfect_cube(4))
717
from __future__ import annotations import math from collections import Counter from string import ascii_lowercase def A ( _lowercase ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = analyze_text(_lowercase ) SCREAMING_SNAKE_CASE : Any = list(''' ''' + ascii_lowercase ) # what is our total sum of probabilities. SCREAMING_SNAKE_CASE : Tuple = sum(single_char_strings.values() ) # one length string SCREAMING_SNAKE_CASE : Tuple = 0 # for each alpha we go in our dict and if it is in it we calculate entropy for ch in my_alphas: if ch in single_char_strings: SCREAMING_SNAKE_CASE : Tuple = single_char_strings[ch] SCREAMING_SNAKE_CASE : List[str] = my_str / all_sum my_fir_sum += prob * math.loga(_lowercase ) # entropy formula. # print entropy print(f"""{round(-1 * my_fir_sum ):.1f}""" ) # two len string SCREAMING_SNAKE_CASE : Optional[Any] = sum(two_char_strings.values() ) SCREAMING_SNAKE_CASE : List[str] = 0 # for each alpha (two in size) calculate entropy. for cha in my_alphas: for cha in my_alphas: SCREAMING_SNAKE_CASE : Union[str, Any] = cha + cha if sequence in two_char_strings: SCREAMING_SNAKE_CASE : Any = two_char_strings[sequence] SCREAMING_SNAKE_CASE : Dict = int(_lowercase ) / all_sum my_sec_sum += prob * math.loga(_lowercase ) # print second entropy print(f"""{round(-1 * my_sec_sum ):.1f}""" ) # print the difference between them print(f"""{round((-1 * my_sec_sum) - (-1 * my_fir_sum) ):.1f}""" ) def A ( _lowercase ): SCREAMING_SNAKE_CASE : Tuple = Counter() # type: ignore SCREAMING_SNAKE_CASE : Any = Counter() # type: ignore single_char_strings[text[-1]] += 1 # first case when we have space at start. two_char_strings[" " + text[0]] += 1 for i in range(0 , len(_lowercase ) - 1 ): single_char_strings[text[i]] += 1 two_char_strings[text[i : i + 2]] += 1 return single_char_strings, two_char_strings def A ( ): import doctest doctest.testmod() # text = ( # "Had repulsive dashwoods suspicion sincerity but advantage now him. Remark " # "easily garret nor nay. Civil those mrs enjoy shy fat merry. You greatest " # "jointure saw horrible. He private he on be imagine suppose. Fertile " # "beloved evident through no service elderly is. Blind there if every no so " # "at. Own neglected you preferred way sincerity delivered his attempted. To " # "of message cottage windows do besides against uncivil. Delightful " # "unreserved impossible few estimating men favourable see entreaties. She " # "propriety immediate was improving. He or entrance humoured likewise " # "moderate. Much nor game son say feel. Fat make met can must form into " # "gate. Me we offending prevailed discovery. " # ) # calculate_prob(text) if __name__ == "__main__": main()
34
0
'''simple docstring''' from __future__ import annotations import unittest import numpy as np from transformers import OPTConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import GPTaTokenizer, TFOPTForCausalLM, TFOPTModel def A ( _lowercase , _lowercase , _lowercase=None , _lowercase=None ): if attention_mask is None: SCREAMING_SNAKE_CASE : Optional[int] = tf.cast(tf.math.not_equal(_lowercase , config.pad_token_id ) , tf.inta ) return {"input_ids": input_ids, "attention_mask": attention_mask} @require_tf class lowercase__ : UpperCamelCase_ = OPTConfig UpperCamelCase_ = {} UpperCamelCase_ = """gelu""" def __init__( self : Optional[Any] , UpperCamelCase__ : str , UpperCamelCase__ : Dict=13 , UpperCamelCase__ : Tuple=7 , UpperCamelCase__ : Tuple=True , UpperCamelCase__ : List[Any]=False , UpperCamelCase__ : Optional[Any]=99 , UpperCamelCase__ : Dict=16 , UpperCamelCase__ : Union[str, Any]=2 , UpperCamelCase__ : str=4 , UpperCamelCase__ : Dict=4 , UpperCamelCase__ : int="gelu" , UpperCamelCase__ : Dict=0.1 , UpperCamelCase__ : List[str]=0.1 , UpperCamelCase__ : List[str]=20 , UpperCamelCase__ : Optional[int]=2 , UpperCamelCase__ : str=1 , UpperCamelCase__ : Optional[Any]=0 , UpperCamelCase__ : Union[str, Any]=16 , UpperCamelCase__ : Union[str, Any]=16 , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = parent SCREAMING_SNAKE_CASE : int = batch_size SCREAMING_SNAKE_CASE : int = seq_length SCREAMING_SNAKE_CASE : str = is_training SCREAMING_SNAKE_CASE : int = use_labels SCREAMING_SNAKE_CASE : List[str] = vocab_size SCREAMING_SNAKE_CASE : Dict = hidden_size SCREAMING_SNAKE_CASE : int = num_hidden_layers SCREAMING_SNAKE_CASE : str = num_attention_heads SCREAMING_SNAKE_CASE : Optional[Any] = intermediate_size SCREAMING_SNAKE_CASE : List[str] = hidden_act SCREAMING_SNAKE_CASE : Dict = hidden_dropout_prob SCREAMING_SNAKE_CASE : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : Optional[Any] = max_position_embeddings SCREAMING_SNAKE_CASE : Optional[Any] = eos_token_id SCREAMING_SNAKE_CASE : Any = pad_token_id SCREAMING_SNAKE_CASE : List[str] = bos_token_id SCREAMING_SNAKE_CASE : str = embed_dim SCREAMING_SNAKE_CASE : Union[str, Any] = word_embed_proj_dim SCREAMING_SNAKE_CASE : int = False def __A ( self : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) SCREAMING_SNAKE_CASE : Union[str, Any] = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) SCREAMING_SNAKE_CASE : List[str] = tf.concat([input_ids, eos_tensor] , axis=1 ) SCREAMING_SNAKE_CASE : str = self.config_cls( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , embed_dim=self.embed_dim , word_embed_proj_dim=self.word_embed_proj_dim , is_encoder_decoder=snake_case__ , **self.config_updates , ) SCREAMING_SNAKE_CASE : Optional[Any] = prepare_opt_inputs_dict(snake_case__ , snake_case__ ) return config, inputs_dict def __A ( self : Optional[Any] , UpperCamelCase__ : Dict , UpperCamelCase__ : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = TFOPTModel(config=snake_case__ ) SCREAMING_SNAKE_CASE : Any = inputs_dict["input_ids"] SCREAMING_SNAKE_CASE : Optional[int] = input_ids[:1, :] SCREAMING_SNAKE_CASE : Dict = inputs_dict["attention_mask"][:1, :] SCREAMING_SNAKE_CASE : int = 1 # first forward pass SCREAMING_SNAKE_CASE : int = model(snake_case__ , attention_mask=snake_case__ , use_cache=snake_case__ ) SCREAMING_SNAKE_CASE : str = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids SCREAMING_SNAKE_CASE : int = ids_tensor((self.batch_size, 3) , config.vocab_size ) SCREAMING_SNAKE_CASE : Optional[int] = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and SCREAMING_SNAKE_CASE : List[Any] = tf.concat([input_ids, next_tokens] , axis=-1 ) SCREAMING_SNAKE_CASE : List[Any] = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) SCREAMING_SNAKE_CASE : List[str] = model(snake_case__ , attention_mask=snake_case__ )[0] SCREAMING_SNAKE_CASE : Union[str, Any] = model(snake_case__ , attention_mask=snake_case__ , past_key_values=snake_case__ )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice SCREAMING_SNAKE_CASE : List[Any] = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) SCREAMING_SNAKE_CASE : Any = output_from_no_past[:, -3:, random_slice_idx] SCREAMING_SNAKE_CASE : Any = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(snake_case__ , snake_case__ , rtol=1E-3 ) @require_tf class lowercase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , unittest.TestCase): UpperCamelCase_ = (TFOPTModel, TFOPTForCausalLM) if is_tf_available() else () UpperCamelCase_ = (TFOPTForCausalLM,) if is_tf_available() else () UpperCamelCase_ = ( {"""feature-extraction""": TFOPTModel, """text-generation""": TFOPTForCausalLM} if is_tf_available() else {} ) UpperCamelCase_ = False UpperCamelCase_ = False UpperCamelCase_ = False UpperCamelCase_ = 10 def __A ( self : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = TFOPTModelTester(self ) SCREAMING_SNAKE_CASE : Optional[Any] = ConfigTester(self , config_class=snake_case__ ) def __A ( self : Dict ): '''simple docstring''' self.config_tester.run_common_tests() def __A ( self : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*snake_case__ ) def __A ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = self.model_tester.prepare_config_and_inputs_for_common() def _get_word_embedding_weight(UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : List[str] ): if hasattr(snake_case__ , '''weight''' ): return embedding_layer.weight else: # Here we build the word embeddings weights if not exists. # And then we retry to get the attribute once built. model.build() if hasattr(snake_case__ , '''weight''' ): return embedding_layer.weight else: return None for model_class in self.all_model_classes: for size in [config.vocab_size - 10, config.vocab_size + 10]: # build the embeddings SCREAMING_SNAKE_CASE : List[Any] = model_class(config=snake_case__ ) SCREAMING_SNAKE_CASE : Optional[int] = _get_word_embedding_weight(snake_case__ , model.get_input_embeddings() ) SCREAMING_SNAKE_CASE : Union[str, Any] = _get_word_embedding_weight(snake_case__ , model.get_output_embeddings() ) # reshape the embeddings model.resize_token_embeddings(snake_case__ ) SCREAMING_SNAKE_CASE : List[str] = _get_word_embedding_weight(snake_case__ , model.get_input_embeddings() ) SCREAMING_SNAKE_CASE : List[Any] = _get_word_embedding_weight(snake_case__ , model.get_output_embeddings() ) # check that the resized embeddings size matches the desired size. SCREAMING_SNAKE_CASE : str = size if size is not None else config.vocab_size self.assertEqual(new_input_embeddings.shape[0] , snake_case__ ) # check that weights remain the same after resizing SCREAMING_SNAKE_CASE : Any = True for pa, pa in zip(old_input_embeddings.value() , new_input_embeddings.value() ): if tf.math.reduce_sum(tf.math.abs(pa - pa ) ) > 0: SCREAMING_SNAKE_CASE : Dict = False self.assertTrue(snake_case__ ) if old_output_embeddings is not None and new_output_embeddings is not None: self.assertEqual(new_output_embeddings.shape[0] , snake_case__ ) SCREAMING_SNAKE_CASE : List[str] = True for pa, pa in zip(old_output_embeddings.value() , new_output_embeddings.value() ): if tf.math.reduce_sum(tf.math.abs(pa - pa ) ) > 0: SCREAMING_SNAKE_CASE : str = False self.assertTrue(snake_case__ ) def A ( _lowercase ): return tf.constant(_lowercase , dtype=tf.intaa ) @require_tf class lowercase__ ( unittest.TestCase): UpperCamelCase_ = 99 def __A ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = tf.ones((4, 1) , dtype=tf.intaa ) * 2 SCREAMING_SNAKE_CASE : Dict = tf.concat([ids_tensor((4, 6) , self.vocab_size - 3 ) + 3, eos_column_vector] , axis=1 ) SCREAMING_SNAKE_CASE : str = input_ids.shape[0] SCREAMING_SNAKE_CASE : Optional[int] = OPTConfig( vocab_size=self.vocab_size , hidden_size=24 , num_hidden_layers=2 , num_attention_heads=2 , ffn_dim=32 , max_position_embeddings=48 , eos_token_id=2 , pad_token_id=1 , bos_token_id=0 , ) return config, input_ids, batch_size @require_sentencepiece @require_tf class lowercase__ ( unittest.TestCase): @slow def __A ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = TFOPTModel.from_pretrained('''facebook/opt-350m''' ) SCREAMING_SNAKE_CASE : str = _long_tensor([[0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2]] ) SCREAMING_SNAKE_CASE : Tuple = tf.not_equal(snake_case__ , model.config.pad_token_id ) with tf.GradientTape(): SCREAMING_SNAKE_CASE : Tuple = model(input_ids=snake_case__ , attention_mask=snake_case__ ).last_hidden_state SCREAMING_SNAKE_CASE : List[str] = (1, 11, 512) self.assertEqual(output.shape , snake_case__ ) SCREAMING_SNAKE_CASE : Dict = tf.constant( [[-0.2873, -1.9218, -0.3033], [-1.2710, -0.1338, -0.1902], [0.4095, 0.1214, -1.3121]] ) self.assertTrue(np.allclose(output[:, :3, :3] , snake_case__ , atol=4E-3 ) ) SCREAMING_SNAKE_CASE : int = tf.function(snake_case__ , jit_compile=snake_case__ ) SCREAMING_SNAKE_CASE : List[str] = xla_generate(snake_case__ , snake_case__ )[0] self.assertTrue(np.allclose(output[:, :3, :3] , snake_case__ , atol=4E-2 ) ) @require_tf @slow class lowercase__ ( unittest.TestCase): def __A ( self : Dict ): '''simple docstring''' super().setUp() SCREAMING_SNAKE_CASE : List[str] = "facebook/opt-350m" def __A ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = TFOPTForCausalLM.from_pretrained(self.path_model ) SCREAMING_SNAKE_CASE : str = GPTaTokenizer.from_pretrained(self.path_model ) SCREAMING_SNAKE_CASE : Tuple = [ "Today is a beautiful day and I want to", "In the city of", "Paris is the capital of France and", "Computers and mobile phones have taken", ] # verify that prompt without BOS token is identical to Metaseq -> add_special_tokens=False SCREAMING_SNAKE_CASE : int = tokenizer(snake_case__ , return_tensors='''tf''' , padding=snake_case__ , add_special_tokens=snake_case__ ) SCREAMING_SNAKE_CASE : int = tf.math.reduce_mean(model(inputs.input_ids , attention_mask=inputs.attention_mask )[0] , axis=-1 ) SCREAMING_SNAKE_CASE : int = tf.constant( [ [1.3851, -13.8923, -10.5229, -10.7533, -0.2309, -10.2384, -0.5365, -9.0947, -5.1670], [-4.7073, -10.6276, -3.9415, -21.5242, -0.2822, -0.2822, -0.2822, -0.2822, -0.2822], [0.6247, -3.4229, -8.9179, -1.4297, -14.1650, 1.4146, -9.0218, -0.2703, -0.2703], [6.4783, -1.9913, -10.7926, -2.3336, 1.5092, -0.9974, -6.8213, 1.3477, 1.3477], ] ) self.assertTrue(np.allclose(snake_case__ , snake_case__ , atol=1E-4 ) ) SCREAMING_SNAKE_CASE : int = tf.function(snake_case__ , jit_compile=snake_case__ ) SCREAMING_SNAKE_CASE : Optional[Any] = tf.math.reduce_mean(xla_generate(inputs.input_ids , attention_mask=inputs.attention_mask )[0] , axis=-1 ) self.assertTrue(np.allclose(snake_case__ , snake_case__ , atol=1E-4 ) ) @require_tf @slow class lowercase__ ( unittest.TestCase): @property def __A ( self : int ): '''simple docstring''' return [ "Today is a beautiful day and I want", "In the city of", "Paris is the capital of France and", "Computers and mobile phones have taken", ] def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = "facebook/opt-125m" SCREAMING_SNAKE_CASE : List[str] = [ "Today is a beautiful day and I want to", "In the city of New York, the city", "Paris is the capital of France and the capital", "Computers and mobile phones have taken over the", ] SCREAMING_SNAKE_CASE : Union[str, Any] = [] SCREAMING_SNAKE_CASE : Optional[Any] = GPTaTokenizer.from_pretrained(snake_case__ ) SCREAMING_SNAKE_CASE : Any = TFOPTForCausalLM.from_pretrained(snake_case__ ) for prompt in self.prompts: SCREAMING_SNAKE_CASE : Optional[int] = tokenizer(snake_case__ , return_tensors='''tf''' ).input_ids SCREAMING_SNAKE_CASE : List[str] = model.generate(snake_case__ , max_length=10 ) SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer.batch_decode(snake_case__ , skip_special_tokens=snake_case__ ) predicted_outputs += generated_string self.assertListEqual(snake_case__ , snake_case__ ) def __A ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = "facebook/opt-350m" SCREAMING_SNAKE_CASE : Optional[Any] = GPTaTokenizer.from_pretrained(snake_case__ ) SCREAMING_SNAKE_CASE : Optional[int] = TFOPTForCausalLM.from_pretrained(snake_case__ ) SCREAMING_SNAKE_CASE : List[str] = "left" # use different length sentences to test batching SCREAMING_SNAKE_CASE : Dict = [ "Hello, my dog is a little", "Today, I", ] SCREAMING_SNAKE_CASE : Optional[int] = tokenizer(snake_case__ , return_tensors='''tf''' , padding=snake_case__ ) SCREAMING_SNAKE_CASE : int = inputs["input_ids"] SCREAMING_SNAKE_CASE : int = model.generate(input_ids=snake_case__ , attention_mask=inputs['''attention_mask'''] ) SCREAMING_SNAKE_CASE : Dict = tokenizer(sentences[0] , return_tensors='''tf''' ).input_ids SCREAMING_SNAKE_CASE : Optional[Any] = model.generate(input_ids=snake_case__ ) SCREAMING_SNAKE_CASE : Tuple = inputs_non_padded.shape[-1] - tf.math.reduce_sum( tf.cast(inputs['''attention_mask'''][-1] , tf.intaa ) ) SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer(sentences[1] , return_tensors='''tf''' ).input_ids SCREAMING_SNAKE_CASE : Union[str, Any] = model.generate(input_ids=snake_case__ , max_length=model.config.max_length - num_paddings ) SCREAMING_SNAKE_CASE : Tuple = tokenizer.batch_decode(snake_case__ , skip_special_tokens=snake_case__ ) SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer.decode(output_non_padded[0] , skip_special_tokens=snake_case__ ) SCREAMING_SNAKE_CASE : int = tokenizer.decode(output_padded[0] , skip_special_tokens=snake_case__ ) SCREAMING_SNAKE_CASE : List[Any] = [ "Hello, my dog is a little bit of a dork.\nI'm a little bit", "Today, I was in the middle of a conversation with a friend about the", ] self.assertListEqual(snake_case__ , snake_case__ ) self.assertListEqual(snake_case__ , [non_padded_sentence, padded_sentence] ) def __A ( self : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = "facebook/opt-350m" SCREAMING_SNAKE_CASE : Optional[int] = [ "Today is a beautiful day and I want to", "In the city of San Francisco, the city", "Paris is the capital of France and the capital", "Computers and mobile phones have taken over the", ] SCREAMING_SNAKE_CASE : Dict = [] SCREAMING_SNAKE_CASE : Optional[int] = GPTaTokenizer.from_pretrained(snake_case__ ) SCREAMING_SNAKE_CASE : int = TFOPTForCausalLM.from_pretrained(snake_case__ ) for prompt in self.prompts: SCREAMING_SNAKE_CASE : Dict = tokenizer(snake_case__ , return_tensors='''tf''' ).input_ids SCREAMING_SNAKE_CASE : Any = model.generate(snake_case__ , max_length=10 ) SCREAMING_SNAKE_CASE : Tuple = tokenizer.batch_decode(snake_case__ , skip_special_tokens=snake_case__ ) predicted_outputs += generated_string self.assertListEqual(snake_case__ , snake_case__ )
718
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __UpperCamelCase : Tuple = { 'configuration_ctrl': ['CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP', 'CTRLConfig'], 'tokenization_ctrl': ['CTRLTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Dict = [ 'CTRL_PRETRAINED_MODEL_ARCHIVE_LIST', 'CTRLForSequenceClassification', 'CTRLLMHeadModel', 'CTRLModel', 'CTRLPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Any = [ 'TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFCTRLForSequenceClassification', 'TFCTRLLMHeadModel', 'TFCTRLModel', 'TFCTRLPreTrainedModel', ] if TYPE_CHECKING: from .configuration_ctrl import CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRLConfig from .tokenization_ctrl import CTRLTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ctrl import ( CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, CTRLForSequenceClassification, CTRLLMHeadModel, CTRLModel, CTRLPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_ctrl import ( TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, TFCTRLForSequenceClassification, TFCTRLLMHeadModel, TFCTRLModel, TFCTRLPreTrainedModel, ) else: import sys __UpperCamelCase : Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
34
0
from unittest import TestCase from datasets import Dataset from minhash_deduplication import deduplicate_dataset, make_duplicate_clusters def A ( ): SCREAMING_SNAKE_CASE : List[str] = { '''repo_name''': ['''test_repo1''', '''test_repo2''', '''test_repo3'''], '''path''': ['''test_1.py''', '''test_2.py''', '''unit_test.py'''], '''content''': ['''a ''' * 20, '''a ''' * 30, '''b ''' * 7], } SCREAMING_SNAKE_CASE : Union[str, Any] = Dataset.from_dict(__a ) return dataset class lowercase__ ( __lowerCamelCase): def __A ( self : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = get_dataset() SCREAMING_SNAKE_CASE : Union[str, Any] = make_duplicate_clusters(SCREAMING_SNAKE_CASE_ , 0.85 ) self.assertEqual(len(duplicate_clusters[0] ) , 2 ) def __A ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = get_dataset() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = deduplicate_dataset(SCREAMING_SNAKE_CASE_ ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 2 ) print(SCREAMING_SNAKE_CASE_ ) self.assertEqual(duplicate_clusters[0][0]['''copies'''] , 2 ) self.assertEqual(duplicate_clusters[0][0]['''is_extreme'''] , SCREAMING_SNAKE_CASE_ )
719
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __UpperCamelCase : Tuple = { 'configuration_maskformer': ['MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MaskFormerConfig'], 'configuration_maskformer_swin': ['MaskFormerSwinConfig'], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Optional[Any] = ['MaskFormerFeatureExtractor'] __UpperCamelCase : List[Any] = ['MaskFormerImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Optional[int] = [ 'MASKFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'MaskFormerForInstanceSegmentation', 'MaskFormerModel', 'MaskFormerPreTrainedModel', ] __UpperCamelCase : Union[str, Any] = [ 'MaskFormerSwinBackbone', 'MaskFormerSwinModel', 'MaskFormerSwinPreTrainedModel', ] if TYPE_CHECKING: from .configuration_maskformer import MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskFormerConfig from .configuration_maskformer_swin import MaskFormerSwinConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_maskformer import MaskFormerFeatureExtractor from .image_processing_maskformer import MaskFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskformer import ( MASKFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskFormerForInstanceSegmentation, MaskFormerModel, MaskFormerPreTrainedModel, ) from .modeling_maskformer_swin import ( MaskFormerSwinBackbone, MaskFormerSwinModel, MaskFormerSwinPreTrainedModel, ) else: import sys __UpperCamelCase : List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure)
34
0
import tempfile import torch from diffusers import PNDMScheduler from .test_schedulers import SchedulerCommonTest class lowercase__ ( _snake_case): UpperCamelCase_ = (PNDMScheduler,) UpperCamelCase_ = (("""num_inference_steps""", 50),) def __A ( self : Optional[int] , **UpperCamelCase__ : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = { "num_train_timesteps": 1000, "beta_start": 0.0001, "beta_end": 0.02, "beta_schedule": "linear", } config.update(**snake_case_ ) return config def __A ( self : Tuple , UpperCamelCase__ : Tuple=0 , **UpperCamelCase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = dict(self.forward_default_kwargs ) SCREAMING_SNAKE_CASE : Dict = kwargs.pop('''num_inference_steps''' , snake_case_ ) SCREAMING_SNAKE_CASE : Optional[Any] = self.dummy_sample SCREAMING_SNAKE_CASE : Optional[Any] = 0.1 * sample SCREAMING_SNAKE_CASE : Optional[int] = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE : Optional[int] = self.get_scheduler_config(**snake_case_ ) SCREAMING_SNAKE_CASE : Tuple = scheduler_class(**snake_case_ ) scheduler.set_timesteps(snake_case_ ) # copy over dummy past residuals SCREAMING_SNAKE_CASE : int = dummy_past_residuals[:] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(snake_case_ ) SCREAMING_SNAKE_CASE : Any = scheduler_class.from_pretrained(snake_case_ ) new_scheduler.set_timesteps(snake_case_ ) # copy over dummy past residuals SCREAMING_SNAKE_CASE : Optional[Any] = dummy_past_residuals[:] SCREAMING_SNAKE_CASE : int = scheduler.step_prk(snake_case_ , snake_case_ , snake_case_ , **snake_case_ ).prev_sample SCREAMING_SNAKE_CASE : Union[str, Any] = new_scheduler.step_prk(snake_case_ , snake_case_ , snake_case_ , **snake_case_ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" SCREAMING_SNAKE_CASE : Tuple = scheduler.step_plms(snake_case_ , snake_case_ , snake_case_ , **snake_case_ ).prev_sample SCREAMING_SNAKE_CASE : str = new_scheduler.step_plms(snake_case_ , snake_case_ , snake_case_ , **snake_case_ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def __A ( self : str ): '''simple docstring''' pass def __A ( self : Optional[Any] , UpperCamelCase__ : int=0 , **UpperCamelCase__ : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = dict(self.forward_default_kwargs ) SCREAMING_SNAKE_CASE : str = kwargs.pop('''num_inference_steps''' , snake_case_ ) SCREAMING_SNAKE_CASE : str = self.dummy_sample SCREAMING_SNAKE_CASE : List[Any] = 0.1 * sample SCREAMING_SNAKE_CASE : Tuple = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE : Tuple = self.get_scheduler_config() SCREAMING_SNAKE_CASE : int = scheduler_class(**snake_case_ ) scheduler.set_timesteps(snake_case_ ) # copy over dummy past residuals (must be after setting timesteps) SCREAMING_SNAKE_CASE : Optional[Any] = dummy_past_residuals[:] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(snake_case_ ) SCREAMING_SNAKE_CASE : Tuple = scheduler_class.from_pretrained(snake_case_ ) # copy over dummy past residuals new_scheduler.set_timesteps(snake_case_ ) # copy over dummy past residual (must be after setting timesteps) SCREAMING_SNAKE_CASE : Dict = dummy_past_residuals[:] SCREAMING_SNAKE_CASE : Union[str, Any] = scheduler.step_prk(snake_case_ , snake_case_ , snake_case_ , **snake_case_ ).prev_sample SCREAMING_SNAKE_CASE : str = new_scheduler.step_prk(snake_case_ , snake_case_ , snake_case_ , **snake_case_ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" SCREAMING_SNAKE_CASE : List[str] = scheduler.step_plms(snake_case_ , snake_case_ , snake_case_ , **snake_case_ ).prev_sample SCREAMING_SNAKE_CASE : List[Any] = new_scheduler.step_plms(snake_case_ , snake_case_ , snake_case_ , **snake_case_ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def __A ( self : str , **UpperCamelCase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self.scheduler_classes[0] SCREAMING_SNAKE_CASE : Optional[int] = self.get_scheduler_config(**snake_case_ ) SCREAMING_SNAKE_CASE : int = scheduler_class(**snake_case_ ) SCREAMING_SNAKE_CASE : Optional[Any] = 10 SCREAMING_SNAKE_CASE : int = self.dummy_model() SCREAMING_SNAKE_CASE : Tuple = self.dummy_sample_deter scheduler.set_timesteps(snake_case_ ) for i, t in enumerate(scheduler.prk_timesteps ): SCREAMING_SNAKE_CASE : List[Any] = model(snake_case_ , snake_case_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = scheduler.step_prk(snake_case_ , snake_case_ , snake_case_ ).prev_sample for i, t in enumerate(scheduler.plms_timesteps ): SCREAMING_SNAKE_CASE : str = model(snake_case_ , snake_case_ ) SCREAMING_SNAKE_CASE : Tuple = scheduler.step_plms(snake_case_ , snake_case_ , snake_case_ ).prev_sample return sample def __A ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = dict(self.forward_default_kwargs ) SCREAMING_SNAKE_CASE : List[Any] = kwargs.pop('''num_inference_steps''' , snake_case_ ) for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE : List[str] = self.get_scheduler_config() SCREAMING_SNAKE_CASE : Union[str, Any] = scheduler_class(**snake_case_ ) SCREAMING_SNAKE_CASE : Tuple = self.dummy_sample SCREAMING_SNAKE_CASE : Tuple = 0.1 * sample if num_inference_steps is not None and hasattr(snake_case_ , '''set_timesteps''' ): scheduler.set_timesteps(snake_case_ ) elif num_inference_steps is not None and not hasattr(snake_case_ , '''set_timesteps''' ): SCREAMING_SNAKE_CASE : Union[str, Any] = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) SCREAMING_SNAKE_CASE : Optional[Any] = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] SCREAMING_SNAKE_CASE : Dict = dummy_past_residuals[:] SCREAMING_SNAKE_CASE : Dict = scheduler.step_prk(snake_case_ , 0 , snake_case_ , **snake_case_ ).prev_sample SCREAMING_SNAKE_CASE : Any = scheduler.step_prk(snake_case_ , 1 , snake_case_ , **snake_case_ ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) SCREAMING_SNAKE_CASE : List[Any] = scheduler.step_plms(snake_case_ , 0 , snake_case_ , **snake_case_ ).prev_sample SCREAMING_SNAKE_CASE : List[Any] = scheduler.step_plms(snake_case_ , 1 , snake_case_ , **snake_case_ ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def __A ( self : List[Any] ): '''simple docstring''' for timesteps in [100, 1000]: self.check_over_configs(num_train_timesteps=snake_case_ ) def __A ( self : Any ): '''simple docstring''' for steps_offset in [0, 1]: self.check_over_configs(steps_offset=snake_case_ ) SCREAMING_SNAKE_CASE : str = self.scheduler_classes[0] SCREAMING_SNAKE_CASE : int = self.get_scheduler_config(steps_offset=1 ) SCREAMING_SNAKE_CASE : str = scheduler_class(**snake_case_ ) scheduler.set_timesteps(10 ) assert torch.equal( scheduler.timesteps , torch.LongTensor( [901, 851, 851, 801, 801, 751, 751, 701, 701, 651, 651, 601, 601, 501, 401, 301, 201, 101, 1] ) , ) def __A ( self : Optional[int] ): '''simple docstring''' for beta_start, beta_end in zip([0.0001, 0.001] , [0.002, 0.02] ): self.check_over_configs(beta_start=snake_case_ , beta_end=snake_case_ ) def __A ( self : Union[str, Any] ): '''simple docstring''' for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=snake_case_ ) def __A ( self : Dict ): '''simple docstring''' for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=snake_case_ ) def __A ( self : Optional[int] ): '''simple docstring''' for t in [1, 5, 10]: self.check_over_forward(time_step=snake_case_ ) def __A ( self : Any ): '''simple docstring''' for t, num_inference_steps in zip([1, 5, 10] , [10, 50, 100] ): self.check_over_forward(num_inference_steps=snake_case_ ) def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = 27 for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE : List[str] = self.dummy_sample SCREAMING_SNAKE_CASE : Union[str, Any] = 0.1 * sample SCREAMING_SNAKE_CASE : int = self.get_scheduler_config() SCREAMING_SNAKE_CASE : Optional[int] = scheduler_class(**snake_case_ ) scheduler.set_timesteps(snake_case_ ) # before power of 3 fix, would error on first step, so we only need to do two for i, t in enumerate(scheduler.prk_timesteps[:2] ): SCREAMING_SNAKE_CASE : List[str] = scheduler.step_prk(snake_case_ , snake_case_ , snake_case_ ).prev_sample def __A ( self : Optional[int] ): '''simple docstring''' with self.assertRaises(snake_case_ ): SCREAMING_SNAKE_CASE : Union[str, Any] = self.scheduler_classes[0] SCREAMING_SNAKE_CASE : Optional[int] = self.get_scheduler_config() SCREAMING_SNAKE_CASE : Any = scheduler_class(**snake_case_ ) scheduler.step_plms(self.dummy_sample , 1 , self.dummy_sample ).prev_sample def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = self.full_loop() SCREAMING_SNAKE_CASE : Tuple = torch.sum(torch.abs(snake_case_ ) ) SCREAMING_SNAKE_CASE : List[Any] = torch.mean(torch.abs(snake_case_ ) ) assert abs(result_sum.item() - 198.1318 ) < 1E-2 assert abs(result_mean.item() - 0.2580 ) < 1E-3 def __A ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = self.full_loop(prediction_type='''v_prediction''' ) SCREAMING_SNAKE_CASE : Optional[Any] = torch.sum(torch.abs(snake_case_ ) ) SCREAMING_SNAKE_CASE : Optional[Any] = torch.mean(torch.abs(snake_case_ ) ) assert abs(result_sum.item() - 67.3986 ) < 1E-2 assert abs(result_mean.item() - 0.0878 ) < 1E-3 def __A ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = self.full_loop(set_alpha_to_one=snake_case_ , beta_start=0.01 ) SCREAMING_SNAKE_CASE : Optional[Any] = torch.sum(torch.abs(snake_case_ ) ) SCREAMING_SNAKE_CASE : Dict = torch.mean(torch.abs(snake_case_ ) ) assert abs(result_sum.item() - 230.0399 ) < 1E-2 assert abs(result_mean.item() - 0.2995 ) < 1E-3 def __A ( self : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = self.full_loop(set_alpha_to_one=snake_case_ , beta_start=0.01 ) SCREAMING_SNAKE_CASE : Tuple = torch.sum(torch.abs(snake_case_ ) ) SCREAMING_SNAKE_CASE : Optional[Any] = torch.mean(torch.abs(snake_case_ ) ) assert abs(result_sum.item() - 186.9482 ) < 1E-2 assert abs(result_mean.item() - 0.2434 ) < 1E-3
720
# 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 from ...utils.dataclasses import ( ComputeEnvironment, DistributedType, DynamoBackend, PrecisionType, SageMakerDistributedType, ) from ..menu import BulletMenu __UpperCamelCase : Dict = [ 'EAGER', 'AOT_EAGER', 'INDUCTOR', 'NVFUSER', 'AOT_NVFUSER', 'AOT_CUDAGRAPHS', 'OFI', 'FX2TRT', 'ONNXRT', 'IPEX', ] def A ( _lowercase , _lowercase=None , _lowercase=None , _lowercase=None ): SCREAMING_SNAKE_CASE : Union[str, Any] = True while ask_again: SCREAMING_SNAKE_CASE : Optional[Any] = input(_lowercase ) try: if default is not None and len(_lowercase ) == 0: return default return convert_value(_lowercase ) if convert_value is not None else result except Exception: if error_message is not None: print(_lowercase ) def A ( _lowercase , _lowercase=[] , _lowercase=None , _lowercase=0 ): SCREAMING_SNAKE_CASE : Dict = BulletMenu(_lowercase , _lowercase ) SCREAMING_SNAKE_CASE : str = menu.run(default_choice=_lowercase ) return convert_value(_lowercase ) if convert_value is not None else result def A ( _lowercase ): SCREAMING_SNAKE_CASE : Dict = int(_lowercase ) return ComputeEnvironment(['''LOCAL_MACHINE''', '''AMAZON_SAGEMAKER'''][value] ) def A ( _lowercase ): SCREAMING_SNAKE_CASE : Any = int(_lowercase ) return DistributedType(['''NO''', '''MULTI_CPU''', '''MULTI_XPU''', '''MULTI_GPU''', '''MULTI_NPU''', '''TPU'''][value] ) def A ( _lowercase ): SCREAMING_SNAKE_CASE : Union[str, Any] = int(_lowercase ) return DynamoBackend(DYNAMO_BACKENDS[value] ).value def A ( _lowercase ): SCREAMING_SNAKE_CASE : Union[str, Any] = int(_lowercase ) return PrecisionType(['''no''', '''fp16''', '''bf16''', '''fp8'''][value] ) def A ( _lowercase ): SCREAMING_SNAKE_CASE : Dict = int(_lowercase ) return SageMakerDistributedType(['''NO''', '''DATA_PARALLEL''', '''MODEL_PARALLEL'''][value] ) def A ( _lowercase ): return {"yes": True, "no": False}[value.lower()] class lowercase__ ( argparse.RawDescriptionHelpFormatter): def __A ( self : List[str] , UpperCamelCase__ : List[str] , UpperCamelCase__ : Dict , UpperCamelCase__ : Dict , UpperCamelCase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = super()._format_usage(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[Any] = usage.replace('''<command> [<args>] ''' , '''''' ) return usage
34
0
def A ( _lowercase , _lowercase ): SCREAMING_SNAKE_CASE : List[str] = '''''' for word_or_phrase in separated: if not isinstance(_lowercase , _lowercase ): raise Exception('''join() accepts only strings to be joined''' ) joined += word_or_phrase + separator return joined.strip(_lowercase ) if __name__ == "__main__": from doctest import testmod testmod()
721
from __future__ import annotations from typing import Any class lowercase__ ( UpperCamelCase_): pass class lowercase__ : def __init__( self : Union[str, Any] , UpperCamelCase__ : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = data SCREAMING_SNAKE_CASE : Node | None = None def __iter__( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = self SCREAMING_SNAKE_CASE : Tuple = [] while node: if node in visited: raise ContainsLoopError visited.append(UpperCamelCase__ ) yield node.data SCREAMING_SNAKE_CASE : Dict = node.next_node @property def __A ( self : Optional[int] ): '''simple docstring''' try: list(self ) return False except ContainsLoopError: return True if __name__ == "__main__": __UpperCamelCase : List[Any] = Node(1) __UpperCamelCase : str = Node(2) __UpperCamelCase : Dict = Node(3) __UpperCamelCase : List[Any] = Node(4) print(root_node.has_loop) # False __UpperCamelCase : int = root_node.next_node print(root_node.has_loop) # True __UpperCamelCase : Union[str, Any] = Node(5) __UpperCamelCase : Union[str, Any] = Node(6) __UpperCamelCase : List[Any] = Node(5) __UpperCamelCase : List[str] = Node(6) print(root_node.has_loop) # False __UpperCamelCase : List[Any] = Node(1) print(root_node.has_loop) # False
34
0
import torch from diffusers import DiffusionPipeline class lowercase__ ( __UpperCAmelCase): def __init__( self : Union[str, Any] , UpperCamelCase__ : int , UpperCamelCase__ : Any ): '''simple docstring''' super().__init__() self.register_modules(unet=_lowerCamelCase , scheduler=_lowerCamelCase ) def __call__( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = torch.randn( (1, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , ) SCREAMING_SNAKE_CASE : Dict = 1 SCREAMING_SNAKE_CASE : Union[str, Any] = self.unet(_lowerCamelCase , _lowerCamelCase ).sample SCREAMING_SNAKE_CASE : Union[str, Any] = self.scheduler.step(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ).prev_sample SCREAMING_SNAKE_CASE : str = scheduler_output - scheduler_output + torch.ones_like(_lowerCamelCase ) return result
700
import copy from typing import Any, Dict, List, Optional, Union import numpy as np import torch from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import TensorType, logging __UpperCamelCase : Union[str, Any] = logging.get_logger(__name__) class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = ["""input_features""", """is_longer"""] def __init__( self : Optional[Any] , UpperCamelCase__ : Dict=64 , UpperCamelCase__ : Optional[Any]=4_8000 , UpperCamelCase__ : Tuple=480 , UpperCamelCase__ : Union[str, Any]=10 , UpperCamelCase__ : List[Any]=1024 , UpperCamelCase__ : Tuple=0.0 , UpperCamelCase__ : int=False , UpperCamelCase__ : float = 0 , UpperCamelCase__ : float = 1_4000 , UpperCamelCase__ : int = None , UpperCamelCase__ : str = "fusion" , UpperCamelCase__ : str = "repeatpad" , **UpperCamelCase__ : Union[str, Any] , ): '''simple docstring''' super().__init__( feature_size=UpperCamelCase__ , sampling_rate=UpperCamelCase__ , padding_value=UpperCamelCase__ , return_attention_mask=UpperCamelCase__ , **UpperCamelCase__ , ) SCREAMING_SNAKE_CASE : Union[str, Any] = top_db SCREAMING_SNAKE_CASE : Union[str, Any] = truncation SCREAMING_SNAKE_CASE : str = padding SCREAMING_SNAKE_CASE : List[Any] = fft_window_size SCREAMING_SNAKE_CASE : Tuple = (fft_window_size >> 1) + 1 SCREAMING_SNAKE_CASE : List[str] = hop_length SCREAMING_SNAKE_CASE : List[Any] = max_length_s SCREAMING_SNAKE_CASE : Tuple = max_length_s * sampling_rate SCREAMING_SNAKE_CASE : List[Any] = sampling_rate SCREAMING_SNAKE_CASE : List[str] = frequency_min SCREAMING_SNAKE_CASE : Any = frequency_max SCREAMING_SNAKE_CASE : List[Any] = mel_filter_bank( num_frequency_bins=self.nb_frequency_bins , num_mel_filters=UpperCamelCase__ , min_frequency=UpperCamelCase__ , max_frequency=UpperCamelCase__ , sampling_rate=UpperCamelCase__ , norm=UpperCamelCase__ , mel_scale='''htk''' , ) SCREAMING_SNAKE_CASE : Optional[Any] = mel_filter_bank( num_frequency_bins=self.nb_frequency_bins , num_mel_filters=UpperCamelCase__ , min_frequency=UpperCamelCase__ , max_frequency=UpperCamelCase__ , sampling_rate=UpperCamelCase__ , norm='''slaney''' , mel_scale='''slaney''' , ) def __A ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE : Optional[Any] = self.__class__.__name__ if "mel_filters" in output: del output["mel_filters"] if "mel_filters_slaney" in output: del output["mel_filters_slaney"] return output def __A ( self : Optional[int] , UpperCamelCase__ : np.array , UpperCamelCase__ : Optional[np.array] = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = spectrogram( UpperCamelCase__ , window_function(self.fft_window_size , '''hann''' ) , frame_length=self.fft_window_size , hop_length=self.hop_length , power=2.0 , mel_filters=UpperCamelCase__ , log_mel='''dB''' , ) return log_mel_spectrogram.T def __A ( self : Union[str, Any] , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Dict , UpperCamelCase__ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = np.array_split(list(range(0 , total_frames - chunk_frames + 1 ) ) , 3 ) if len(ranges[1] ) == 0: # if the audio is too short, we just use the first chunk SCREAMING_SNAKE_CASE : int = [0] if len(ranges[2] ) == 0: # if the audio is too short, we just use the first chunk SCREAMING_SNAKE_CASE : Any = [0] # randomly choose index for each part SCREAMING_SNAKE_CASE : Union[str, Any] = np.random.choice(ranges[0] ) SCREAMING_SNAKE_CASE : List[Any] = np.random.choice(ranges[1] ) SCREAMING_SNAKE_CASE : int = np.random.choice(ranges[2] ) SCREAMING_SNAKE_CASE : Optional[int] = mel[idx_front : idx_front + chunk_frames, :] SCREAMING_SNAKE_CASE : Optional[Any] = mel[idx_middle : idx_middle + chunk_frames, :] SCREAMING_SNAKE_CASE : Tuple = mel[idx_back : idx_back + chunk_frames, :] SCREAMING_SNAKE_CASE : str = torch.tensor(mel[None, None, :] ) SCREAMING_SNAKE_CASE : Optional[int] = torch.nn.functional.interpolate( UpperCamelCase__ , size=[chunk_frames, 64] , mode='''bilinear''' , align_corners=UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[Any] = mel_shrink[0][0].numpy() SCREAMING_SNAKE_CASE : Union[str, Any] = np.stack([mel_shrink, mel_chunk_front, mel_chunk_middle, mel_chunk_back] , axis=0 ) return mel_fusion def __A ( self : Dict , UpperCamelCase__ : np.array , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Dict , UpperCamelCase__ : List[str] ): '''simple docstring''' if waveform.shape[0] > max_length: if truncation == "rand_trunc": SCREAMING_SNAKE_CASE : Optional[Any] = True # random crop to max_length (for compatibility) -> this should be handled by self.pad SCREAMING_SNAKE_CASE : List[Any] = len(UpperCamelCase__ ) - max_length SCREAMING_SNAKE_CASE : Dict = np.random.randint(0 , overflow + 1 ) SCREAMING_SNAKE_CASE : Optional[Any] = waveform[idx : idx + max_length] SCREAMING_SNAKE_CASE : Any = self._np_extract_fbank_features(UpperCamelCase__ , self.mel_filters_slaney )[None, :] elif truncation == "fusion": SCREAMING_SNAKE_CASE : Any = self._np_extract_fbank_features(UpperCamelCase__ , self.mel_filters ) SCREAMING_SNAKE_CASE : List[str] = max_length // self.hop_length + 1 # the +1 related to how the spectrogram is computed SCREAMING_SNAKE_CASE : List[Any] = mel.shape[0] if chunk_frames == total_frames: # there is a corner case where the audio length is larger than max_length but smaller than max_length+hop_length. # In this case, we just use the whole audio. SCREAMING_SNAKE_CASE : Optional[Any] = np.stack([mel, mel, mel, mel] , axis=0 ) SCREAMING_SNAKE_CASE : Tuple = False else: SCREAMING_SNAKE_CASE : str = self._random_mel_fusion(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[int] = True else: raise NotImplementedError(f"""data_truncating {truncation} not implemented""" ) else: SCREAMING_SNAKE_CASE : List[str] = False # only use repeat as a new possible value for padding. you repeat the audio before applying the usual max_length padding if waveform.shape[0] < max_length: if padding == "repeat": SCREAMING_SNAKE_CASE : Tuple = int(max_length / len(UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE : Any = np.stack(np.tile(UpperCamelCase__ , n_repeat + 1 ) )[:max_length] if padding == "repeatpad": SCREAMING_SNAKE_CASE : List[Any] = int(max_length / len(UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE : Dict = np.stack(np.tile(UpperCamelCase__ , UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE : Dict = np.pad(UpperCamelCase__ , (0, max_length - waveform.shape[0]) , mode='''constant''' , constant_values=0 ) if truncation == "fusion": SCREAMING_SNAKE_CASE : List[Any] = self._np_extract_fbank_features(UpperCamelCase__ , self.mel_filters ) SCREAMING_SNAKE_CASE : Union[str, Any] = np.stack([input_mel, input_mel, input_mel, input_mel] , axis=0 ) else: SCREAMING_SNAKE_CASE : List[str] = self._np_extract_fbank_features(UpperCamelCase__ , self.mel_filters_slaney )[None, :] return input_mel, longer def __call__( self : Union[str, Any] , UpperCamelCase__ : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , UpperCamelCase__ : str = None , UpperCamelCase__ : Optional[str] = None , UpperCamelCase__ : Optional[int] = None , UpperCamelCase__ : Optional[int] = None , UpperCamelCase__ : Optional[Union[str, TensorType]] = None , **UpperCamelCase__ : Any , ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = truncation if truncation is not None else self.truncation SCREAMING_SNAKE_CASE : List[str] = padding if padding else self.padding if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f"""The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a""" f""" sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input""" f""" was sampled with {self.sampling_rate} and not {sampling_rate}.""" ) else: logger.warning( '''It is strongly recommended to pass the `sampling_rate` argument to this function. ''' '''Failing to do so can result in silent errors that might be hard to debug.''' ) SCREAMING_SNAKE_CASE : List[str] = isinstance(UpperCamelCase__ , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f"""Only mono-channel audio is supported for input to {self}""" ) SCREAMING_SNAKE_CASE : int = is_batched_numpy or ( isinstance(UpperCamelCase__ , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: SCREAMING_SNAKE_CASE : Any = [np.asarray(UpperCamelCase__ , dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(UpperCamelCase__ , np.ndarray ): SCREAMING_SNAKE_CASE : List[Any] = np.asarray(UpperCamelCase__ , dtype=np.floataa ) elif isinstance(UpperCamelCase__ , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): SCREAMING_SNAKE_CASE : Union[str, Any] = raw_speech.astype(np.floataa ) # always return batch if not is_batched: SCREAMING_SNAKE_CASE : List[str] = [np.asarray(UpperCamelCase__ )] # convert to mel spectrogram, truncate and pad if needed. SCREAMING_SNAKE_CASE : int = [ self._get_input_mel(UpperCamelCase__ , max_length if max_length else self.nb_max_samples , UpperCamelCase__ , UpperCamelCase__ ) for waveform in raw_speech ] SCREAMING_SNAKE_CASE : str = [] SCREAMING_SNAKE_CASE : List[str] = [] for mel, longer in padded_inputs: input_mel.append(UpperCamelCase__ ) is_longer.append(UpperCamelCase__ ) if truncation == "fusion" and sum(UpperCamelCase__ ) == 0: # if no audio is longer than 10s, then randomly select one audio to be longer SCREAMING_SNAKE_CASE : Union[str, Any] = np.random.randint(0 , len(UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE : Optional[Any] = True if isinstance(input_mel[0] , UpperCamelCase__ ): SCREAMING_SNAKE_CASE : Union[str, Any] = [np.asarray(UpperCamelCase__ , dtype=np.floataa ) for feature in input_mel] # is_longer is a list of bool SCREAMING_SNAKE_CASE : Optional[Any] = [[longer] for longer in is_longer] SCREAMING_SNAKE_CASE : Union[str, Any] = {'''input_features''': input_mel, '''is_longer''': is_longer} SCREAMING_SNAKE_CASE : int = BatchFeature(UpperCamelCase__ ) if return_tensors is not None: SCREAMING_SNAKE_CASE : int = input_features.convert_to_tensors(UpperCamelCase__ ) return input_features
34
0
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class lowercase__ ( unittest.TestCase): def __init__( self : Union[str, Any] , UpperCamelCase__ : Dict , UpperCamelCase__ : List[str]=13 , UpperCamelCase__ : Tuple=3 , UpperCamelCase__ : Optional[int]=224 , UpperCamelCase__ : List[Any]=30 , UpperCamelCase__ : Union[str, Any]=400 , UpperCamelCase__ : List[str]=True , UpperCamelCase__ : List[str]=None , UpperCamelCase__ : Any=True , UpperCamelCase__ : Any=[0.5, 0.5, 0.5] , UpperCamelCase__ : Tuple=[0.5, 0.5, 0.5] , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = size if size is not None else {'''height''': 18, '''width''': 18} SCREAMING_SNAKE_CASE : Any = parent SCREAMING_SNAKE_CASE : int = batch_size SCREAMING_SNAKE_CASE : Union[str, Any] = num_channels SCREAMING_SNAKE_CASE : Any = image_size SCREAMING_SNAKE_CASE : int = min_resolution SCREAMING_SNAKE_CASE : int = max_resolution SCREAMING_SNAKE_CASE : Optional[Any] = do_resize SCREAMING_SNAKE_CASE : List[str] = size SCREAMING_SNAKE_CASE : int = do_normalize SCREAMING_SNAKE_CASE : Dict = image_mean SCREAMING_SNAKE_CASE : int = image_std def __A ( self : Any ): '''simple docstring''' 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__ ( lowerCamelCase__ , unittest.TestCase): UpperCamelCase_ = ViTImageProcessor if is_vision_available() else None def __A ( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = EfficientFormerImageProcessorTester(self ) @property def __A ( self : str ): '''simple docstring''' return self.image_proc_tester.prepare_image_processor_dict() def __A ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__lowerCamelCase , '''image_mean''' ) ) self.assertTrue(hasattr(__lowerCamelCase , '''image_std''' ) ) self.assertTrue(hasattr(__lowerCamelCase , '''do_normalize''' ) ) self.assertTrue(hasattr(__lowerCamelCase , '''do_resize''' ) ) self.assertTrue(hasattr(__lowerCamelCase , '''size''' ) ) def __A ( self : List[str] ): '''simple docstring''' pass def __A ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE : List[str] = prepare_image_inputs(self.image_proc_tester , equal_resolution=__lowerCamelCase ) for image in image_inputs: self.assertIsInstance(__lowerCamelCase , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE : Tuple = image_processor(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) # Test batched SCREAMING_SNAKE_CASE : List[Any] = image_processor(__lowerCamelCase , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) def __A ( self : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE : Union[str, Any] = prepare_image_inputs(self.image_proc_tester , equal_resolution=__lowerCamelCase , numpify=__lowerCamelCase ) for image in image_inputs: self.assertIsInstance(__lowerCamelCase , np.ndarray ) # Test not batched input SCREAMING_SNAKE_CASE : int = image_processor(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) # Test batched SCREAMING_SNAKE_CASE : int = image_processor(__lowerCamelCase , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) def __A ( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE : List[str] = prepare_image_inputs(self.image_proc_tester , equal_resolution=__lowerCamelCase , torchify=__lowerCamelCase ) for image in image_inputs: self.assertIsInstance(__lowerCamelCase , torch.Tensor ) # Test not batched input SCREAMING_SNAKE_CASE : Tuple = image_processor(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) # Test batched SCREAMING_SNAKE_CASE : Union[str, Any] = image_processor(__lowerCamelCase , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , )
701
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...utils import logging if TYPE_CHECKING: from ...processing_utils import ProcessorMixin from ...utils import TensorType __UpperCamelCase : str = logging.get_logger(__name__) __UpperCamelCase : str = { 'microsoft/layoutlmv3-base': 'https://huggingface.co/microsoft/layoutlmv3-base/resolve/main/config.json', } class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = """layoutlmv3""" def __init__( self : Optional[int] , UpperCamelCase__ : Union[str, Any]=5_0265 , UpperCamelCase__ : List[Any]=768 , UpperCamelCase__ : Union[str, Any]=12 , UpperCamelCase__ : Union[str, Any]=12 , UpperCamelCase__ : Tuple=3072 , UpperCamelCase__ : List[Any]="gelu" , UpperCamelCase__ : List[Any]=0.1 , UpperCamelCase__ : List[str]=0.1 , UpperCamelCase__ : Any=512 , UpperCamelCase__ : List[Any]=2 , UpperCamelCase__ : List[Any]=0.02 , UpperCamelCase__ : Optional[Any]=1E-5 , UpperCamelCase__ : List[str]=1 , UpperCamelCase__ : int=0 , UpperCamelCase__ : str=2 , UpperCamelCase__ : List[str]=1024 , UpperCamelCase__ : str=128 , UpperCamelCase__ : str=128 , UpperCamelCase__ : Tuple=True , UpperCamelCase__ : Optional[int]=32 , UpperCamelCase__ : Any=128 , UpperCamelCase__ : Optional[Any]=64 , UpperCamelCase__ : Dict=256 , UpperCamelCase__ : List[Any]=True , UpperCamelCase__ : str=True , UpperCamelCase__ : Dict=True , UpperCamelCase__ : Dict=224 , UpperCamelCase__ : Optional[Any]=3 , UpperCamelCase__ : Any=16 , UpperCamelCase__ : Any=None , **UpperCamelCase__ : Optional[Any] , ): '''simple docstring''' super().__init__( vocab_size=UpperCamelCase__ , hidden_size=UpperCamelCase__ , num_hidden_layers=UpperCamelCase__ , num_attention_heads=UpperCamelCase__ , intermediate_size=UpperCamelCase__ , hidden_act=UpperCamelCase__ , hidden_dropout_prob=UpperCamelCase__ , attention_probs_dropout_prob=UpperCamelCase__ , max_position_embeddings=UpperCamelCase__ , type_vocab_size=UpperCamelCase__ , initializer_range=UpperCamelCase__ , layer_norm_eps=UpperCamelCase__ , pad_token_id=UpperCamelCase__ , bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ , **UpperCamelCase__ , ) SCREAMING_SNAKE_CASE : Union[str, Any] = max_ad_position_embeddings SCREAMING_SNAKE_CASE : List[Any] = coordinate_size SCREAMING_SNAKE_CASE : List[str] = shape_size SCREAMING_SNAKE_CASE : Optional[int] = has_relative_attention_bias SCREAMING_SNAKE_CASE : List[Any] = rel_pos_bins SCREAMING_SNAKE_CASE : str = max_rel_pos SCREAMING_SNAKE_CASE : Any = has_spatial_attention_bias SCREAMING_SNAKE_CASE : Union[str, Any] = rel_ad_pos_bins SCREAMING_SNAKE_CASE : Union[str, Any] = max_rel_ad_pos SCREAMING_SNAKE_CASE : Union[str, Any] = text_embed SCREAMING_SNAKE_CASE : List[str] = visual_embed SCREAMING_SNAKE_CASE : Optional[Any] = input_size SCREAMING_SNAKE_CASE : Optional[Any] = num_channels SCREAMING_SNAKE_CASE : List[Any] = patch_size SCREAMING_SNAKE_CASE : List[Any] = classifier_dropout class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = version.parse("""1.12""") @property def __A ( self : str ): '''simple docstring''' if self.task in ["question-answering", "sequence-classification"]: return OrderedDict( [ ('''input_ids''', {0: '''batch''', 1: '''sequence'''}), ('''attention_mask''', {0: '''batch''', 1: '''sequence'''}), ('''bbox''', {0: '''batch''', 1: '''sequence'''}), ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) else: return OrderedDict( [ ('''input_ids''', {0: '''batch''', 1: '''sequence'''}), ('''bbox''', {0: '''batch''', 1: '''sequence'''}), ('''attention_mask''', {0: '''batch''', 1: '''sequence'''}), ('''pixel_values''', {0: '''batch''', 1: '''num_channels'''}), ] ) @property def __A ( self : int ): '''simple docstring''' return 1E-5 @property def __A ( self : Union[str, Any] ): '''simple docstring''' return 12 def __A ( self : Optional[Any] , UpperCamelCase__ : "ProcessorMixin" , UpperCamelCase__ : int = -1 , UpperCamelCase__ : int = -1 , UpperCamelCase__ : bool = False , UpperCamelCase__ : Optional["TensorType"] = None , UpperCamelCase__ : int = 3 , UpperCamelCase__ : int = 40 , UpperCamelCase__ : int = 40 , ): '''simple docstring''' setattr(processor.image_processor , '''apply_ocr''' , UpperCamelCase__ ) # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX SCREAMING_SNAKE_CASE : Any = compute_effective_axis_dimension( UpperCamelCase__ , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX SCREAMING_SNAKE_CASE : List[Any] = processor.tokenizer.num_special_tokens_to_add(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Tuple = compute_effective_axis_dimension( UpperCamelCase__ , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=UpperCamelCase__ ) # Generate dummy inputs according to compute batch and sequence SCREAMING_SNAKE_CASE : Union[str, Any] = [[''' '''.join([processor.tokenizer.unk_token] ) * seq_length]] * batch_size # Generate dummy bounding boxes SCREAMING_SNAKE_CASE : Any = [[[48, 84, 73, 128]]] * batch_size # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX # batch_size = compute_effective_axis_dimension(batch_size, fixed_dimension=OnnxConfig.default_fixed_batch) SCREAMING_SNAKE_CASE : List[Any] = self._generate_dummy_images(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[int] = dict( processor( UpperCamelCase__ , text=UpperCamelCase__ , boxes=UpperCamelCase__ , return_tensors=UpperCamelCase__ , ) ) return inputs
34
0
from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCamelCase : Tuple = logging.get_logger(__name__) __UpperCamelCase : Union[str, Any] = { "SCUT-DLVCLab/lilt-roberta-en-base": ( "https://huggingface.co/SCUT-DLVCLab/lilt-roberta-en-base/resolve/main/config.json" ), } class lowercase__ ( UpperCAmelCase_): UpperCamelCase_ = """lilt""" def __init__( self : Optional[Any] , UpperCamelCase__ : Dict=3_0522 , UpperCamelCase__ : Any=768 , UpperCamelCase__ : Union[str, Any]=12 , UpperCamelCase__ : List[str]=12 , UpperCamelCase__ : str=3072 , UpperCamelCase__ : int="gelu" , UpperCamelCase__ : Union[str, Any]=0.1 , UpperCamelCase__ : Dict=0.1 , UpperCamelCase__ : Optional[Any]=512 , UpperCamelCase__ : Optional[Any]=2 , UpperCamelCase__ : Tuple=0.02 , UpperCamelCase__ : int=1E-12 , UpperCamelCase__ : Any=0 , UpperCamelCase__ : List[str]="absolute" , UpperCamelCase__ : Dict=None , UpperCamelCase__ : Optional[int]=4 , UpperCamelCase__ : Optional[int]=1024 , **UpperCamelCase__ : Union[str, Any] , ): '''simple docstring''' super().__init__(pad_token_id=_lowercase , **_lowercase ) SCREAMING_SNAKE_CASE : int = vocab_size SCREAMING_SNAKE_CASE : Tuple = hidden_size SCREAMING_SNAKE_CASE : List[Any] = num_hidden_layers SCREAMING_SNAKE_CASE : str = num_attention_heads SCREAMING_SNAKE_CASE : Optional[int] = hidden_act SCREAMING_SNAKE_CASE : Dict = intermediate_size SCREAMING_SNAKE_CASE : Union[str, Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE : Dict = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE : str = type_vocab_size SCREAMING_SNAKE_CASE : List[Any] = initializer_range SCREAMING_SNAKE_CASE : Any = layer_norm_eps SCREAMING_SNAKE_CASE : Optional[Any] = position_embedding_type SCREAMING_SNAKE_CASE : str = classifier_dropout SCREAMING_SNAKE_CASE : int = channel_shrink_ratio SCREAMING_SNAKE_CASE : Union[str, Any] = max_ad_position_embeddings
702
import os import unittest from transformers import FunnelTokenizer, FunnelTokenizerFast from transformers.models.funnel.tokenization_funnel import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowercase__ ( UpperCamelCase_ , unittest.TestCase): UpperCamelCase_ = FunnelTokenizer UpperCamelCase_ = FunnelTokenizerFast UpperCamelCase_ = True UpperCamelCase_ = True def __A ( self : Union[str, Any] ): '''simple docstring''' super().setUp() SCREAMING_SNAKE_CASE : Optional[Any] = [ '''<unk>''', '''<cls>''', '''<sep>''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] SCREAMING_SNAKE_CASE : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) def __A ( self : int , **UpperCamelCase__ : List[Any] ): '''simple docstring''' return FunnelTokenizer.from_pretrained(self.tmpdirname , **UpperCamelCase__ ) def __A ( self : int , **UpperCamelCase__ : List[Any] ): '''simple docstring''' return FunnelTokenizerFast.from_pretrained(self.tmpdirname , **UpperCamelCase__ ) def __A ( self : Any , UpperCamelCase__ : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = '''UNwant\u00E9d,running''' SCREAMING_SNAKE_CASE : int = '''unwanted, running''' return input_text, output_text def __A ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = self.tokenizer_class(self.vocab_file ) SCREAMING_SNAKE_CASE : int = tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(UpperCamelCase__ , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCamelCase__ ) , [7, 4, 5, 10, 8, 9] ) def __A ( self : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self.get_tokenizers(do_lower_case=UpperCamelCase__ ) for tokenizer in tokenizers: SCREAMING_SNAKE_CASE : int = tokenizer('''UNwant\u00E9d,running''' ) SCREAMING_SNAKE_CASE : Optional[Any] = len(inputs['''input_ids'''] ) - 1 self.assertListEqual(inputs['''token_type_ids'''] , [2] + [0] * sentence_len ) SCREAMING_SNAKE_CASE : List[Any] = tokenizer('''UNwant\u00E9d,running''' , '''UNwant\u00E9d,running''' ) self.assertListEqual(inputs['''token_type_ids'''] , [2] + [0] * sentence_len + [1] * sentence_len )
34
0
import math import sys def A ( _lowercase ): SCREAMING_SNAKE_CASE : Optional[int] = "" try: with open(__SCREAMING_SNAKE_CASE , '''rb''' ) as binary_file: SCREAMING_SNAKE_CASE : str = binary_file.read() for dat in data: SCREAMING_SNAKE_CASE : Union[str, Any] = f"""{dat:08b}""" result += curr_byte return result except OSError: print('''File not accessible''' ) sys.exit() def A ( _lowercase ): SCREAMING_SNAKE_CASE : Tuple = {"0": "0", "1": "1"} SCREAMING_SNAKE_CASE : Any = "", "" SCREAMING_SNAKE_CASE : List[Any] = len(__SCREAMING_SNAKE_CASE ) for i in range(len(__SCREAMING_SNAKE_CASE ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue SCREAMING_SNAKE_CASE : Union[str, Any] = lexicon[curr_string] result += last_match_id SCREAMING_SNAKE_CASE : Any = last_match_id + "0" if math.loga(__SCREAMING_SNAKE_CASE ).is_integer(): SCREAMING_SNAKE_CASE : Any = {} for curr_key in list(__SCREAMING_SNAKE_CASE ): SCREAMING_SNAKE_CASE : int = lexicon.pop(__SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE : Dict = new_lex SCREAMING_SNAKE_CASE : Union[str, Any] = last_match_id + "1" index += 1 SCREAMING_SNAKE_CASE : Optional[int] = "" return result def A ( _lowercase , _lowercase ): SCREAMING_SNAKE_CASE : int = 8 try: with open(__SCREAMING_SNAKE_CASE , '''wb''' ) as opened_file: SCREAMING_SNAKE_CASE : str = [ to_write[i : i + byte_length] for i in range(0 , len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append('''10000000''' ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array[:-1]: opened_file.write(int(__SCREAMING_SNAKE_CASE , 2 ).to_bytes(1 , byteorder='''big''' ) ) except OSError: print('''File not accessible''' ) sys.exit() def A ( _lowercase ): SCREAMING_SNAKE_CASE : Union[str, Any] = 0 for letter in data_bits: if letter == "1": break counter += 1 SCREAMING_SNAKE_CASE : List[Any] = data_bits[counter:] SCREAMING_SNAKE_CASE : str = data_bits[counter + 1 :] return data_bits def A ( _lowercase , _lowercase ): SCREAMING_SNAKE_CASE : str = read_file_binary(__SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE : List[str] = remove_prefix(__SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE : Any = decompress_data(__SCREAMING_SNAKE_CASE ) write_file_binary(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
703
import numpy as np import torch from torch.utils.data import Dataset, IterableDataset from ..utils.generic import ModelOutput class lowercase__ ( UpperCamelCase_): def __init__( self : str , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = dataset SCREAMING_SNAKE_CASE : Optional[Any] = process SCREAMING_SNAKE_CASE : Union[str, Any] = params def __len__( self : Tuple ): '''simple docstring''' return len(self.dataset ) def __getitem__( self : List[str] , UpperCamelCase__ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = self.dataset[i] SCREAMING_SNAKE_CASE : Optional[int] = self.process(UpperCamelCase__ , **self.params ) return processed class lowercase__ ( UpperCamelCase_): def __init__( self : Dict , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Dict , UpperCamelCase__ : List[Any]=None ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = loader SCREAMING_SNAKE_CASE : List[Any] = infer SCREAMING_SNAKE_CASE : int = params if loader_batch_size == 1: # Let's spare some time by deactivating altogether SCREAMING_SNAKE_CASE : Optional[int] = None SCREAMING_SNAKE_CASE : List[str] = loader_batch_size # Internal bookkeeping SCREAMING_SNAKE_CASE : Optional[int] = None SCREAMING_SNAKE_CASE : int = None def __len__( self : int ): '''simple docstring''' return len(self.loader ) def __iter__( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = iter(self.loader ) return self def __A ( self : List[str] ): '''simple docstring''' if isinstance(self._loader_batch_data , torch.Tensor ): # Batch data is simple tensor, just fetch the slice SCREAMING_SNAKE_CASE : Optional[Any] = self._loader_batch_data[self._loader_batch_index] else: # Batch data is assumed to be BaseModelOutput (or dict) SCREAMING_SNAKE_CASE : Union[str, Any] = {} for k, element in self._loader_batch_data.items(): if isinstance(UpperCamelCase__ , UpperCamelCase__ ): # Convert ModelOutput to tuple first SCREAMING_SNAKE_CASE : Dict = element.to_tuple() if isinstance(element[0] , torch.Tensor ): SCREAMING_SNAKE_CASE : Dict = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element ) elif isinstance(element[0] , np.ndarray ): SCREAMING_SNAKE_CASE : Union[str, Any] = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element ) continue if k in {"hidden_states", "past_key_values", "attentions"} and isinstance(UpperCamelCase__ , UpperCamelCase__ ): # Those are stored as lists of tensors so need specific unbatching. if isinstance(element[0] , torch.Tensor ): SCREAMING_SNAKE_CASE : Union[str, Any] = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element ) elif isinstance(element[0] , np.ndarray ): SCREAMING_SNAKE_CASE : List[str] = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element ) continue if element is None: # This can happen for optional data that get passed around SCREAMING_SNAKE_CASE : int = None elif isinstance(element[self._loader_batch_index] , torch.Tensor ): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers SCREAMING_SNAKE_CASE : Union[str, Any] = element[self._loader_batch_index].unsqueeze(0 ) elif isinstance(element[self._loader_batch_index] , np.ndarray ): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers SCREAMING_SNAKE_CASE : Tuple = np.expand_dims(element[self._loader_batch_index] , 0 ) else: # This is typically a list, so no need to `unsqueeze`. SCREAMING_SNAKE_CASE : Tuple = element[self._loader_batch_index] # Recreate the element by reusing the original class to make it look # batch_size=1 SCREAMING_SNAKE_CASE : Any = self._loader_batch_data.__class__(UpperCamelCase__ ) self._loader_batch_index += 1 return result def __A ( self : Union[str, Any] ): '''simple docstring''' if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: # We are currently unrolling a batch so we just need to return # the current item within a batch return self.loader_batch_item() # We're out of items within a batch SCREAMING_SNAKE_CASE : Tuple = next(self.iterator ) SCREAMING_SNAKE_CASE : List[Any] = self.infer(UpperCamelCase__ , **self.params ) # We now have a batch of "inferred things". if self.loader_batch_size is not None: # Try to infer the size of the batch if isinstance(UpperCamelCase__ , torch.Tensor ): SCREAMING_SNAKE_CASE : Optional[int] = processed else: SCREAMING_SNAKE_CASE : int = list(processed.keys() )[0] SCREAMING_SNAKE_CASE : int = processed[key] if isinstance(UpperCamelCase__ , UpperCamelCase__ ): SCREAMING_SNAKE_CASE : List[Any] = len(UpperCamelCase__ ) else: SCREAMING_SNAKE_CASE : Dict = first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. SCREAMING_SNAKE_CASE : List[Any] = observed_batch_size # Setting internal index to unwrap the batch SCREAMING_SNAKE_CASE : List[Any] = processed SCREAMING_SNAKE_CASE : int = 0 return self.loader_batch_item() else: # We're not unrolling batches return processed class lowercase__ ( UpperCamelCase_): def __init__( self : str , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Union[str, Any]=None ): '''simple docstring''' super().__init__(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) def __iter__( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = iter(self.loader ) SCREAMING_SNAKE_CASE : List[Any] = None return self def __A ( self : List[str] ): '''simple docstring''' if self.subiterator is None: SCREAMING_SNAKE_CASE : Dict = self.infer(next(self.iterator ) , **self.params ) try: # Try to return next item SCREAMING_SNAKE_CASE : Any = next(self.subiterator ) except StopIteration: # When a preprocess iterator ends, we can start lookig at the next item # ChunkIterator will keep feeding until ALL elements of iterator # all have created their subiterator and have been iterating against. # # Another way to look at it, is we're basically flattening lists of lists # into a single list, but with generators SCREAMING_SNAKE_CASE : Optional[Any] = self.infer(next(self.iterator ) , **self.params ) SCREAMING_SNAKE_CASE : Union[str, Any] = next(self.subiterator ) return processed class lowercase__ ( UpperCamelCase_): def __iter__( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = iter(self.loader ) return self def __A ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = False SCREAMING_SNAKE_CASE : Optional[int] = [] if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: while self._loader_batch_index < self.loader_batch_size: SCREAMING_SNAKE_CASE : Tuple = self.loader_batch_item() SCREAMING_SNAKE_CASE : Any = item.pop('''is_last''' ) accumulator.append(UpperCamelCase__ ) if is_last: return accumulator while not is_last: SCREAMING_SNAKE_CASE : Any = self.infer(next(self.iterator ) , **self.params ) if self.loader_batch_size is not None: if isinstance(UpperCamelCase__ , torch.Tensor ): SCREAMING_SNAKE_CASE : Tuple = processed else: SCREAMING_SNAKE_CASE : Union[str, Any] = list(processed.keys() )[0] SCREAMING_SNAKE_CASE : List[str] = processed[key] if isinstance(UpperCamelCase__ , UpperCamelCase__ ): SCREAMING_SNAKE_CASE : List[Any] = len(UpperCamelCase__ ) else: SCREAMING_SNAKE_CASE : int = first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. SCREAMING_SNAKE_CASE : List[str] = observed_batch_size SCREAMING_SNAKE_CASE : List[Any] = processed SCREAMING_SNAKE_CASE : str = 0 while self._loader_batch_index < self.loader_batch_size: SCREAMING_SNAKE_CASE : Any = self.loader_batch_item() SCREAMING_SNAKE_CASE : List[Any] = item.pop('''is_last''' ) accumulator.append(UpperCamelCase__ ) if is_last: return accumulator else: SCREAMING_SNAKE_CASE : int = processed SCREAMING_SNAKE_CASE : List[str] = item.pop('''is_last''' ) accumulator.append(UpperCamelCase__ ) return accumulator class lowercase__ ( UpperCamelCase_): def __init__( self : Optional[Any] , UpperCamelCase__ : Dataset , UpperCamelCase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = dataset SCREAMING_SNAKE_CASE : Dict = key def __len__( self : Optional[int] ): '''simple docstring''' return len(self.dataset ) def __getitem__( self : Dict , UpperCamelCase__ : Tuple ): '''simple docstring''' return self.dataset[i][self.key] class lowercase__ ( UpperCamelCase_): def __init__( self : List[Any] , UpperCamelCase__ : Dataset , UpperCamelCase__ : str , UpperCamelCase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = dataset SCREAMING_SNAKE_CASE : List[str] = keya SCREAMING_SNAKE_CASE : Tuple = keya def __len__( self : List[str] ): '''simple docstring''' return len(self.dataset ) def __getitem__( self : Union[str, Any] , UpperCamelCase__ : Any ): '''simple docstring''' return {"text": self.dataset[i][self.keya], "text_pair": self.dataset[i][self.keya]}
34
0
import argparse from pathlib import Path import torch from transformers import OPTConfig, OPTModel from transformers.utils import logging logging.set_verbosity_info() __UpperCamelCase : Dict = logging.get_logger(__name__) def A ( _lowercase ): SCREAMING_SNAKE_CASE : List[str] = torch.load(_lowercase , map_location='''cpu''' ) if "model" in sd.keys(): SCREAMING_SNAKE_CASE : Optional[int] = torch.load(_lowercase , map_location='''cpu''' )['''model'''] # pop unnecessary weights SCREAMING_SNAKE_CASE : Optional[Any] = [ '''decoder.version''', '''decoder.output_projection.weight''', ] for key in keys_to_delete: if key in sd: sd.pop(_lowercase ) SCREAMING_SNAKE_CASE : Tuple = { '''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: SCREAMING_SNAKE_CASE : Any = sd.pop(_lowercase ) SCREAMING_SNAKE_CASE : Tuple = list(sd.keys() ) for key in keys: if ".qkv_proj." in key: SCREAMING_SNAKE_CASE : int = sd[key] # We split QKV in separate Q,K,V SCREAMING_SNAKE_CASE : int = key.replace('''.qkv_proj.''' , '''.q_proj.''' ) SCREAMING_SNAKE_CASE : int = key.replace('''.qkv_proj.''' , '''.k_proj.''' ) SCREAMING_SNAKE_CASE : Dict = key.replace('''.qkv_proj.''' , '''.v_proj.''' ) SCREAMING_SNAKE_CASE : Dict = 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 SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = torch.split(_lowercase , depth // 3 , dim=0 ) SCREAMING_SNAKE_CASE : Any = q SCREAMING_SNAKE_CASE : Optional[Any] = k SCREAMING_SNAKE_CASE : int = v del sd[key] return sd @torch.no_grad() def A ( _lowercase , _lowercase , _lowercase=None ): SCREAMING_SNAKE_CASE : List[Any] = load_checkpoint(_lowercase ) if config is not None: SCREAMING_SNAKE_CASE : int = OPTConfig.from_pretrained(_lowercase ) else: SCREAMING_SNAKE_CASE : Optional[Any] = OPTConfig() SCREAMING_SNAKE_CASE : Tuple = OPTModel(_lowercase ).half().eval() model.load_state_dict(_lowercase ) # Check results Path(_lowercase ).mkdir(exist_ok=_lowercase ) model.save_pretrained(_lowercase ) if __name__ == "__main__": __UpperCamelCase : List[Any] = 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.') __UpperCamelCase : Optional[Any] = parser.parse_args() convert_opt_checkpoint(args.fairseq_path, args.pytorch_dump_folder_path, config=args.hf_config)
704
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging if TYPE_CHECKING: from ... import FeatureExtractionMixin, PreTrainedTokenizerBase, TensorType __UpperCamelCase : Optional[Any] = logging.get_logger(__name__) __UpperCamelCase : Optional[Any] = { 'microsoft/deberta-v2-xlarge': 'https://huggingface.co/microsoft/deberta-v2-xlarge/resolve/main/config.json', 'microsoft/deberta-v2-xxlarge': 'https://huggingface.co/microsoft/deberta-v2-xxlarge/resolve/main/config.json', 'microsoft/deberta-v2-xlarge-mnli': ( 'https://huggingface.co/microsoft/deberta-v2-xlarge-mnli/resolve/main/config.json' ), 'microsoft/deberta-v2-xxlarge-mnli': ( 'https://huggingface.co/microsoft/deberta-v2-xxlarge-mnli/resolve/main/config.json' ), } class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = """deberta-v2""" def __init__( self : Optional[Any] , UpperCamelCase__ : Any=12_8100 , UpperCamelCase__ : Optional[int]=1536 , UpperCamelCase__ : Dict=24 , UpperCamelCase__ : List[str]=24 , UpperCamelCase__ : Tuple=6144 , UpperCamelCase__ : List[Any]="gelu" , UpperCamelCase__ : Optional[int]=0.1 , UpperCamelCase__ : List[str]=0.1 , UpperCamelCase__ : Optional[int]=512 , UpperCamelCase__ : Optional[Any]=0 , UpperCamelCase__ : Union[str, Any]=0.02 , UpperCamelCase__ : List[Any]=1E-7 , UpperCamelCase__ : List[str]=False , UpperCamelCase__ : str=-1 , UpperCamelCase__ : List[Any]=0 , UpperCamelCase__ : List[Any]=True , UpperCamelCase__ : Optional[Any]=None , UpperCamelCase__ : Tuple=0 , UpperCamelCase__ : str="gelu" , **UpperCamelCase__ : Optional[int] , ): '''simple docstring''' super().__init__(**UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[Any] = hidden_size SCREAMING_SNAKE_CASE : int = num_hidden_layers SCREAMING_SNAKE_CASE : Union[str, Any] = num_attention_heads SCREAMING_SNAKE_CASE : List[Any] = intermediate_size SCREAMING_SNAKE_CASE : Any = hidden_act SCREAMING_SNAKE_CASE : Dict = hidden_dropout_prob SCREAMING_SNAKE_CASE : Optional[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : str = max_position_embeddings SCREAMING_SNAKE_CASE : Dict = type_vocab_size SCREAMING_SNAKE_CASE : str = initializer_range SCREAMING_SNAKE_CASE : Optional[Any] = relative_attention SCREAMING_SNAKE_CASE : Optional[Any] = max_relative_positions SCREAMING_SNAKE_CASE : Optional[int] = pad_token_id SCREAMING_SNAKE_CASE : Optional[Any] = position_biased_input # Backwards compatibility if type(UpperCamelCase__ ) == str: SCREAMING_SNAKE_CASE : Optional[int] = [x.strip() for x in pos_att_type.lower().split('''|''' )] SCREAMING_SNAKE_CASE : Any = pos_att_type SCREAMING_SNAKE_CASE : int = vocab_size SCREAMING_SNAKE_CASE : Dict = layer_norm_eps SCREAMING_SNAKE_CASE : Tuple = kwargs.get('''pooler_hidden_size''' , UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Any = pooler_dropout SCREAMING_SNAKE_CASE : Union[str, Any] = pooler_hidden_act class lowercase__ ( UpperCamelCase_): @property def __A ( self : Union[str, Any] ): '''simple docstring''' if self.task == "multiple-choice": SCREAMING_SNAKE_CASE : Optional[int] = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: SCREAMING_SNAKE_CASE : Optional[Any] = {0: '''batch''', 1: '''sequence'''} if self._config.type_vocab_size > 0: return OrderedDict( [('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ('''token_type_ids''', dynamic_axis)] ) else: return OrderedDict([('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis)] ) @property def __A ( self : Union[str, Any] ): '''simple docstring''' return 12 def __A ( self : Dict , UpperCamelCase__ : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , UpperCamelCase__ : int = -1 , UpperCamelCase__ : int = -1 , UpperCamelCase__ : int = -1 , UpperCamelCase__ : bool = False , UpperCamelCase__ : Optional["TensorType"] = None , UpperCamelCase__ : int = 3 , UpperCamelCase__ : int = 40 , UpperCamelCase__ : int = 40 , UpperCamelCase__ : "PreTrainedTokenizerBase" = None , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = super().generate_dummy_inputs(preprocessor=UpperCamelCase__ , framework=UpperCamelCase__ ) if self._config.type_vocab_size == 0 and "token_type_ids" in dummy_inputs: del dummy_inputs["token_type_ids"] return dummy_inputs
34
0
from __future__ import annotations def A ( _lowercase , _lowercase ): if len(_lowerCamelCase ) < k or k < 0: raise ValueError('''Invalid Input''' ) SCREAMING_SNAKE_CASE : Optional[Any] = sum(array[:k] ) for i in range(len(_lowerCamelCase ) - k ): SCREAMING_SNAKE_CASE : Optional[int] = current_sum - array[i] + array[i + k] SCREAMING_SNAKE_CASE : List[Any] = max(_lowerCamelCase , _lowerCamelCase ) return max_sum if __name__ == "__main__": from doctest import testmod from random import randint testmod() __UpperCamelCase : List[str] = [randint(-1000, 1000) for i in range(100)] __UpperCamelCase : int = randint(0, 110) print(f"""The maximum sum of {k} consecutive elements is {max_sum_in_array(array,k)}""")
705
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from timm import create_model from timm.data import resolve_data_config from timm.data.transforms_factory import create_transform from transformers import BitConfig, BitForImageClassification, BitImageProcessor from transformers.image_utils import PILImageResampling from transformers.utils import logging logging.set_verbosity_info() __UpperCamelCase : str = logging.get_logger(__name__) def A ( _lowercase ): SCREAMING_SNAKE_CASE : Any = '''huggingface/label-files''' SCREAMING_SNAKE_CASE : Any = '''imagenet-1k-id2label.json''' SCREAMING_SNAKE_CASE : Any = json.load(open(hf_hub_download(_lowercase , _lowercase , repo_type='''dataset''' ) , '''r''' ) ) SCREAMING_SNAKE_CASE : Union[str, Any] = {int(_lowercase ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE : Dict = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE : str = '''std_conv''' if '''bit''' in model_name else False # note that when using BiT as backbone for ViT-hybrid checkpoints, # one needs to additionally set config.layer_type = "bottleneck", config.stem_type = "same", # config.conv_layer = "std_conv_same" SCREAMING_SNAKE_CASE : Optional[int] = BitConfig( conv_layer=_lowercase , num_labels=1_000 , idalabel=_lowercase , labelaid=_lowercase , ) return config def A ( _lowercase ): if "stem.conv" in name: SCREAMING_SNAKE_CASE : Optional[int] = name.replace('''stem.conv''' , '''bit.embedder.convolution''' ) if "blocks" in name: SCREAMING_SNAKE_CASE : Tuple = name.replace('''blocks''' , '''layers''' ) if "head.fc" in name: SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace('''head.fc''' , '''classifier.1''' ) if name.startswith('''norm''' ): SCREAMING_SNAKE_CASE : str = '''bit.''' + name if "bit" not in name and "classifier" not in name: SCREAMING_SNAKE_CASE : Union[str, Any] = '''bit.encoder.''' + name return name def A ( ): SCREAMING_SNAKE_CASE : Any = '''http://images.cocodataset.org/val2017/000000039769.jpg''' SCREAMING_SNAKE_CASE : List[str] = Image.open(requests.get(_lowercase , stream=_lowercase ).raw ) return im @torch.no_grad() def A ( _lowercase , _lowercase , _lowercase=False ): SCREAMING_SNAKE_CASE : List[Any] = get_config(_lowercase ) # load original model from timm SCREAMING_SNAKE_CASE : Optional[Any] = create_model(_lowercase , pretrained=_lowercase ) timm_model.eval() # load state_dict of original model SCREAMING_SNAKE_CASE : Optional[int] = timm_model.state_dict() for key in state_dict.copy().keys(): SCREAMING_SNAKE_CASE : Dict = state_dict.pop(_lowercase ) SCREAMING_SNAKE_CASE : Optional[int] = val.squeeze() if '''head''' in key else val # load HuggingFace model SCREAMING_SNAKE_CASE : str = BitForImageClassification(_lowercase ) model.eval() model.load_state_dict(_lowercase ) # create image processor SCREAMING_SNAKE_CASE : Optional[Any] = create_transform(**resolve_data_config({} , model=_lowercase ) ) SCREAMING_SNAKE_CASE : List[str] = transform.transforms SCREAMING_SNAKE_CASE : Union[str, Any] = { '''bilinear''': PILImageResampling.BILINEAR, '''bicubic''': PILImageResampling.BICUBIC, '''nearest''': PILImageResampling.NEAREST, } SCREAMING_SNAKE_CASE : Tuple = BitImageProcessor( do_resize=_lowercase , size={'''shortest_edge''': timm_transforms[0].size} , resample=pillow_resamplings[timm_transforms[0].interpolation.value] , do_center_crop=_lowercase , crop_size={'''height''': timm_transforms[1].size[0], '''width''': timm_transforms[1].size[1]} , do_normalize=_lowercase , image_mean=timm_transforms[-1].mean.tolist() , image_std=timm_transforms[-1].std.tolist() , ) SCREAMING_SNAKE_CASE : Any = prepare_img() SCREAMING_SNAKE_CASE : Union[str, Any] = transform(_lowercase ).unsqueeze(0 ) SCREAMING_SNAKE_CASE : Optional[int] = processor(_lowercase , return_tensors='''pt''' ).pixel_values # verify pixel values assert torch.allclose(_lowercase , _lowercase ) # verify logits with torch.no_grad(): SCREAMING_SNAKE_CASE : Dict = model(_lowercase ) SCREAMING_SNAKE_CASE : Optional[Any] = outputs.logits print('''Logits:''' , logits[0, :3] ) print('''Predicted class:''' , model.config.idalabel[logits.argmax(-1 ).item()] ) SCREAMING_SNAKE_CASE : List[Any] = timm_model(_lowercase ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(_lowercase , outputs.logits , atol=1e-3 ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: Path(_lowercase ).mkdir(exist_ok=_lowercase ) print(f"""Saving model {model_name} and processor to {pytorch_dump_folder_path}""" ) model.save_pretrained(_lowercase ) processor.save_pretrained(_lowercase ) if push_to_hub: print(f"""Pushing model {model_name} and processor to the hub""" ) model.push_to_hub(f"""ybelkada/{model_name}""" ) processor.push_to_hub(f"""ybelkada/{model_name}""" ) if __name__ == "__main__": __UpperCamelCase : Any = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='resnetv2_50x1_bitm', type=str, help='Name of the BiT 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.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether to push the model to the hub.', ) __UpperCamelCase : Optional[int] = parser.parse_args() convert_bit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
34
0
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCamelCase : Tuple = logging.get_logger(__name__) class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = """encoder-decoder""" UpperCamelCase_ = True def __init__( self : Tuple , **UpperCamelCase__ : Optional[Any] ): '''simple docstring''' super().__init__(**__UpperCamelCase ) assert ( "encoder" in kwargs and "decoder" in kwargs ), "Config has to be initialized with encoder and decoder config" SCREAMING_SNAKE_CASE : Dict = kwargs.pop('''encoder''' ) SCREAMING_SNAKE_CASE : List[str] = encoder_config.pop('''model_type''' ) SCREAMING_SNAKE_CASE : Tuple = kwargs.pop('''decoder''' ) SCREAMING_SNAKE_CASE : Optional[int] = decoder_config.pop('''model_type''' ) from ..auto.configuration_auto import AutoConfig SCREAMING_SNAKE_CASE : str = AutoConfig.for_model(__UpperCamelCase , **__UpperCamelCase ) SCREAMING_SNAKE_CASE : Any = AutoConfig.for_model(__UpperCamelCase , **__UpperCamelCase ) SCREAMING_SNAKE_CASE : Union[str, Any] = True @classmethod def __A ( cls : Optional[int] , UpperCamelCase__ : PretrainedConfig , UpperCamelCase__ : PretrainedConfig , **UpperCamelCase__ : str ): '''simple docstring''' logger.info('''Set `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config''' ) SCREAMING_SNAKE_CASE : Tuple = True SCREAMING_SNAKE_CASE : Union[str, Any] = True return cls(encoder=encoder_config.to_dict() , decoder=decoder_config.to_dict() , **__UpperCamelCase ) def __A ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE : List[Any] = self.encoder.to_dict() SCREAMING_SNAKE_CASE : int = self.decoder.to_dict() SCREAMING_SNAKE_CASE : List[Any] = self.__class__.model_type return output
706
import argparse import json import logging import os import sys from unittest.mock import patch from transformers.testing_utils import TestCasePlus, get_gpu_count, slow __UpperCamelCase : str = [ os.path.join(os.path.dirname(__file__), dirname) for dirname in [ 'text-classification', 'language-modeling', 'summarization', 'token-classification', 'question-answering', ] ] sys.path.extend(SRC_DIRS) if SRC_DIRS is not None: import run_clm_flax import run_flax_glue import run_flax_ner import run_mlm_flax import run_qa import run_summarization_flax import run_ta_mlm_flax logging.basicConfig(level=logging.DEBUG) __UpperCamelCase : int = logging.getLogger() def A ( ): SCREAMING_SNAKE_CASE : str = argparse.ArgumentParser() parser.add_argument('''-f''' ) SCREAMING_SNAKE_CASE : List[str] = parser.parse_args() return args.f def A ( _lowercase , _lowercase="eval" ): SCREAMING_SNAKE_CASE : Dict = os.path.join(_lowercase , f"""{split}_results.json""" ) if os.path.exists(_lowercase ): with open(_lowercase , '''r''' ) as f: return json.load(_lowercase ) raise ValueError(f"""can't find {path}""" ) __UpperCamelCase : Optional[Any] = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class lowercase__ ( UpperCamelCase_): def __A ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE : Tuple = f""" run_glue.py --model_name_or_path distilbert-base-uncased --output_dir {tmp_dir} --train_file ./tests/fixtures/tests_samples/MRPC/train.csv --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --learning_rate=1e-4 --eval_steps=2 --warmup_steps=2 --seed=42 --max_seq_length=128 """.split() with patch.object(UpperCamelCase__ , '''argv''' , UpperCamelCase__ ): run_flax_glue.main() SCREAMING_SNAKE_CASE : Union[str, Any] = get_results(UpperCamelCase__ ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 ) @slow def __A ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE : str = f""" run_clm_flax.py --model_name_or_path distilgpt2 --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --do_train --do_eval --block_size 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --num_train_epochs 2 --logging_steps 2 --eval_steps 2 --output_dir {tmp_dir} --overwrite_output_dir """.split() with patch.object(UpperCamelCase__ , '''argv''' , UpperCamelCase__ ): run_clm_flax.main() SCREAMING_SNAKE_CASE : Dict = get_results(UpperCamelCase__ ) self.assertLess(result['''eval_perplexity'''] , 100 ) @slow def __A ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE : Union[str, Any] = f""" run_summarization.py --model_name_or_path t5-small --train_file tests/fixtures/tests_samples/xsum/sample.json --validation_file tests/fixtures/tests_samples/xsum/sample.json --test_file tests/fixtures/tests_samples/xsum/sample.json --output_dir {tmp_dir} --overwrite_output_dir --num_train_epochs=3 --warmup_steps=8 --do_train --do_eval --do_predict --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --predict_with_generate """.split() with patch.object(UpperCamelCase__ , '''argv''' , UpperCamelCase__ ): run_summarization_flax.main() SCREAMING_SNAKE_CASE : Union[str, Any] = get_results(UpperCamelCase__ , split='''test''' ) self.assertGreaterEqual(result['''test_rouge1'''] , 10 ) self.assertGreaterEqual(result['''test_rouge2'''] , 2 ) self.assertGreaterEqual(result['''test_rougeL'''] , 7 ) self.assertGreaterEqual(result['''test_rougeLsum'''] , 7 ) @slow def __A ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE : Dict = f""" run_mlm.py --model_name_or_path distilroberta-base --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --output_dir {tmp_dir} --overwrite_output_dir --max_seq_length 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --logging_steps 2 --eval_steps 2 --do_train --do_eval --num_train_epochs=1 """.split() with patch.object(UpperCamelCase__ , '''argv''' , UpperCamelCase__ ): run_mlm_flax.main() SCREAMING_SNAKE_CASE : List[Any] = get_results(UpperCamelCase__ ) self.assertLess(result['''eval_perplexity'''] , 42 ) @slow def __A ( self : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE : Union[str, Any] = f""" run_t5_mlm_flax.py --model_name_or_path t5-small --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --do_train --do_eval --max_seq_length 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --num_train_epochs 2 --logging_steps 2 --eval_steps 2 --output_dir {tmp_dir} --overwrite_output_dir """.split() with patch.object(UpperCamelCase__ , '''argv''' , UpperCamelCase__ ): run_ta_mlm_flax.main() SCREAMING_SNAKE_CASE : Optional[int] = get_results(UpperCamelCase__ ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.42 ) @slow def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = 7 if get_gpu_count() > 1 else 2 SCREAMING_SNAKE_CASE : Dict = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE : Any = f""" run_flax_ner.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/conll/sample.json --validation_file tests/fixtures/tests_samples/conll/sample.json --output_dir {tmp_dir} --overwrite_output_dir --do_train --do_eval --warmup_steps=2 --learning_rate=2e-4 --logging_steps 2 --eval_steps 2 --per_device_train_batch_size=2 --per_device_eval_batch_size=2 --num_train_epochs={epochs} --seed 7 """.split() with patch.object(UpperCamelCase__ , '''argv''' , UpperCamelCase__ ): run_flax_ner.main() SCREAMING_SNAKE_CASE : List[str] = get_results(UpperCamelCase__ ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 ) self.assertGreaterEqual(result['''eval_f1'''] , 0.3 ) @slow def __A ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE : Union[str, Any] = f""" run_qa.py --model_name_or_path bert-base-uncased --version_2_with_negative --train_file tests/fixtures/tests_samples/SQUAD/sample.json --validation_file tests/fixtures/tests_samples/SQUAD/sample.json --output_dir {tmp_dir} --overwrite_output_dir --num_train_epochs=3 --warmup_steps=2 --do_train --do_eval --logging_steps 2 --eval_steps 2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 """.split() with patch.object(UpperCamelCase__ , '''argv''' , UpperCamelCase__ ): run_qa.main() SCREAMING_SNAKE_CASE : str = get_results(UpperCamelCase__ ) self.assertGreaterEqual(result['''eval_f1'''] , 30 ) self.assertGreaterEqual(result['''eval_exact'''] , 30 )
34
0
import math def A ( _lowercase , _lowercase ): if 0 not in (x, y): # We use the relation x^y = y*log10(x), where 10 is the base. return y * math.logaa(_lowercase ) else: if x == 0: # 0 raised to any number is 0 return 0 elif y == 0: return 1 # any number raised to 0 is 1 raise AssertionError('''This should never happen''' ) if __name__ == "__main__": # Main function # Read two numbers from input and typecast them to int using map function. # Here x is the base and y is the power. __UpperCamelCase : Tuple = 'Enter the base and the power separated by a comma: ' __UpperCamelCase , __UpperCamelCase : Optional[Any] = map(int, input(prompt).split(',')) __UpperCamelCase , __UpperCamelCase : List[str] = map(int, input(prompt).split(',')) # We find the log of each number, using the function res(), which takes two # arguments. __UpperCamelCase : Any = res(xa, ya) __UpperCamelCase : Any = res(xa, ya) # We check for the largest number if resa > resa: print('Largest number is', xa, '^', ya) elif resa > resa: print('Largest number is', xa, '^', ya) else: print('Both are equal')
707
import itertools import os import random import tempfile import unittest import numpy as np from transformers import TvltFeatureExtractor, is_datasets_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_torch_available(): import torch if is_datasets_available(): from datasets import load_dataset __UpperCamelCase : Dict = random.Random() def A ( _lowercase , _lowercase=1.0 , _lowercase=None , _lowercase=None ): if rng is None: SCREAMING_SNAKE_CASE : Any = global_rng SCREAMING_SNAKE_CASE : int = [] 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 : List[Any] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : str=7 , UpperCamelCase__ : Any=400 , UpperCamelCase__ : List[str]=2000 , UpperCamelCase__ : List[Any]=2048 , UpperCamelCase__ : Any=128 , UpperCamelCase__ : Union[str, Any]=1 , UpperCamelCase__ : List[Any]=512 , UpperCamelCase__ : str=30 , UpperCamelCase__ : Tuple=4_4100 , ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = parent SCREAMING_SNAKE_CASE : str = batch_size SCREAMING_SNAKE_CASE : str = min_seq_length SCREAMING_SNAKE_CASE : Dict = max_seq_length SCREAMING_SNAKE_CASE : Optional[int] = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) SCREAMING_SNAKE_CASE : Optional[Any] = spectrogram_length SCREAMING_SNAKE_CASE : Optional[int] = feature_size SCREAMING_SNAKE_CASE : Tuple = num_audio_channels SCREAMING_SNAKE_CASE : Union[str, Any] = hop_length SCREAMING_SNAKE_CASE : List[Any] = chunk_length SCREAMING_SNAKE_CASE : str = sampling_rate def __A ( self : Optional[Any] ): '''simple docstring''' return { "spectrogram_length": self.spectrogram_length, "feature_size": self.feature_size, "num_audio_channels": self.num_audio_channels, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "sampling_rate": self.sampling_rate, } def __A ( self : Tuple , UpperCamelCase__ : List[str]=False , UpperCamelCase__ : Optional[int]=False ): '''simple docstring''' def _flatten(UpperCamelCase__ : str ): return list(itertools.chain(*UpperCamelCase__ ) ) if equal_length: SCREAMING_SNAKE_CASE : List[str] = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE : int = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE : Optional[Any] = [np.asarray(UpperCamelCase__ ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class lowercase__ ( UpperCamelCase_ , unittest.TestCase): UpperCamelCase_ = TvltFeatureExtractor def __A ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = TvltFeatureExtractionTester(self ) def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = self.feature_extraction_class(**self.feat_extract_dict ) self.assertTrue(hasattr(UpperCamelCase__ , '''spectrogram_length''' ) ) self.assertTrue(hasattr(UpperCamelCase__ , '''feature_size''' ) ) self.assertTrue(hasattr(UpperCamelCase__ , '''num_audio_channels''' ) ) self.assertTrue(hasattr(UpperCamelCase__ , '''hop_length''' ) ) self.assertTrue(hasattr(UpperCamelCase__ , '''chunk_length''' ) ) self.assertTrue(hasattr(UpperCamelCase__ , '''sampling_rate''' ) ) def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE : Optional[Any] = feat_extract_first.save_pretrained(UpperCamelCase__ )[0] check_json_file_has_correct_format(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[Any] = self.feature_extraction_class.from_pretrained(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[Any] = feat_extract_first.to_dict() SCREAMING_SNAKE_CASE : str = feat_extract_second.to_dict() SCREAMING_SNAKE_CASE : Optional[int] = dict_first.pop('''mel_filters''' ) SCREAMING_SNAKE_CASE : Optional[int] = dict_second.pop('''mel_filters''' ) self.assertTrue(np.allclose(UpperCamelCase__ , UpperCamelCase__ ) ) self.assertEqual(UpperCamelCase__ , UpperCamelCase__ ) def __A ( self : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE : Tuple = os.path.join(UpperCamelCase__ , '''feat_extract.json''' ) feat_extract_first.to_json_file(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[str] = self.feature_extraction_class.from_json_file(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Any = feat_extract_first.to_dict() SCREAMING_SNAKE_CASE : str = feat_extract_second.to_dict() SCREAMING_SNAKE_CASE : int = dict_first.pop('''mel_filters''' ) SCREAMING_SNAKE_CASE : Any = dict_second.pop('''mel_filters''' ) self.assertTrue(np.allclose(UpperCamelCase__ , UpperCamelCase__ ) ) self.assertEqual(UpperCamelCase__ , UpperCamelCase__ ) def __A ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = self.feature_extraction_class(**self.feat_extract_dict ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE : List[Any] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE : Optional[int] = [np.asarray(UpperCamelCase__ ) for speech_input in speech_inputs] # Test not batched input SCREAMING_SNAKE_CASE : List[Any] = feature_extractor(np_speech_inputs[0] , return_tensors='''np''' , sampling_rate=4_4100 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test batched SCREAMING_SNAKE_CASE : Optional[Any] = feature_extractor(UpperCamelCase__ , return_tensors='''np''' , sampling_rate=4_4100 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test audio masking SCREAMING_SNAKE_CASE : List[str] = feature_extractor( UpperCamelCase__ , return_tensors='''np''' , sampling_rate=4_4100 , mask_audio=UpperCamelCase__ ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test 2-D numpy arrays are batched. SCREAMING_SNAKE_CASE : Optional[Any] = [floats_list((1, x) )[0] for x in (800, 800, 800)] SCREAMING_SNAKE_CASE : Dict = np.asarray(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : str = feature_extractor(UpperCamelCase__ , return_tensors='''np''' , sampling_rate=4_4100 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) def __A ( self : Optional[int] , UpperCamelCase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = load_dataset('''hf-internal-testing/librispeech_asr_dummy''' , '''clean''' , split='''validation''' ) # automatic decoding with librispeech SCREAMING_SNAKE_CASE : Dict = ds.sort('''id''' ).select(range(UpperCamelCase__ ) )[:num_samples]['''audio'''] return [x["array"] for x in speech_samples] def __A ( self : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE : int = TvltFeatureExtractor() SCREAMING_SNAKE_CASE : List[Any] = feature_extractor(UpperCamelCase__ , return_tensors='''pt''' ).audio_values self.assertEquals(audio_values.shape , (1, 1, 192, 128) ) SCREAMING_SNAKE_CASE : str = torch.tensor([[-0.3032, -0.2708], [-0.4434, -0.4007]] ) self.assertTrue(torch.allclose(audio_values[0, 0, :2, :2] , UpperCamelCase__ , atol=1E-4 ) )
34
0
import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from torchvision import transforms from transformers import BitImageProcessor, FocalNetConfig, FocalNetForImageClassification from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, PILImageResampling def A ( _lowercase ): SCREAMING_SNAKE_CASE : Optional[Any] = [2, 2, 6, 2] if 'tiny' in model_name else [2, 2, 18, 2] SCREAMING_SNAKE_CASE : Dict = True if 'large' in model_name or 'huge' in model_name else False SCREAMING_SNAKE_CASE : Any = True if 'large' in model_name or 'huge' in model_name else False SCREAMING_SNAKE_CASE : Union[str, Any] = True if 'large' in model_name or 'huge' in model_name else False if "large" in model_name or "xlarge" in model_name or "huge" in model_name: if "fl3" in model_name: SCREAMING_SNAKE_CASE : Optional[int] = [3, 3, 3, 3] SCREAMING_SNAKE_CASE : int = [5, 5, 5, 5] elif "fl4" in model_name: SCREAMING_SNAKE_CASE : Any = [4, 4, 4, 4] SCREAMING_SNAKE_CASE : Any = [3, 3, 3, 3] if "tiny" in model_name or "small" in model_name or "base" in model_name: SCREAMING_SNAKE_CASE : List[str] = [3, 3, 3, 3] if "lrf" in model_name: SCREAMING_SNAKE_CASE : Optional[int] = [3, 3, 3, 3] else: SCREAMING_SNAKE_CASE : Any = [2, 2, 2, 2] if "tiny" in model_name: SCREAMING_SNAKE_CASE : Tuple = 96 elif "small" in model_name: SCREAMING_SNAKE_CASE : Tuple = 96 elif "base" in model_name: SCREAMING_SNAKE_CASE : List[str] = 128 elif "large" in model_name: SCREAMING_SNAKE_CASE : Dict = 192 elif "xlarge" in model_name: SCREAMING_SNAKE_CASE : Union[str, Any] = 256 elif "huge" in model_name: SCREAMING_SNAKE_CASE : Union[str, Any] = 352 # set label information SCREAMING_SNAKE_CASE : int = 'huggingface/label-files' if "large" in model_name or "huge" in model_name: SCREAMING_SNAKE_CASE : Union[str, Any] = 'imagenet-22k-id2label.json' else: SCREAMING_SNAKE_CASE : List[str] = 'imagenet-1k-id2label.json' SCREAMING_SNAKE_CASE : Union[str, Any] = json.load(open(hf_hub_download(lowerCAmelCase__ , lowerCAmelCase__ , repo_type='''dataset''' ) , '''r''' ) ) SCREAMING_SNAKE_CASE : Union[str, Any] = {int(lowerCAmelCase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE : int = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE : Tuple = FocalNetConfig( embed_dim=lowerCAmelCase__ , depths=lowerCAmelCase__ , focal_levels=lowerCAmelCase__ , focal_windows=lowerCAmelCase__ , use_conv_embed=lowerCAmelCase__ , idalabel=lowerCAmelCase__ , labelaid=lowerCAmelCase__ , use_post_layernorm=lowerCAmelCase__ , use_layerscale=lowerCAmelCase__ , ) return config def A ( _lowercase ): if "patch_embed.proj" in name: SCREAMING_SNAKE_CASE : Dict = name.replace('''patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' ) if "patch_embed.norm" in name: SCREAMING_SNAKE_CASE : List[str] = name.replace('''patch_embed.norm''' , '''embeddings.norm''' ) if "layers" in name: SCREAMING_SNAKE_CASE : Optional[int] = 'encoder.' + name if "encoder.layers" in name: SCREAMING_SNAKE_CASE : List[Any] = name.replace('''encoder.layers''' , '''encoder.stages''' ) if "downsample.proj" in name: SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace('''downsample.proj''' , '''downsample.projection''' ) if "blocks" in name: SCREAMING_SNAKE_CASE : Optional[int] = name.replace('''blocks''' , '''layers''' ) if "modulation.f.weight" in name or "modulation.f.bias" in name: SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace('''modulation.f''' , '''modulation.projection_in''' ) if "modulation.h.weight" in name or "modulation.h.bias" in name: SCREAMING_SNAKE_CASE : int = name.replace('''modulation.h''' , '''modulation.projection_context''' ) if "modulation.proj.weight" in name or "modulation.proj.bias" in name: SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace('''modulation.proj''' , '''modulation.projection_out''' ) if name == "norm.weight": SCREAMING_SNAKE_CASE : List[str] = 'layernorm.weight' if name == "norm.bias": SCREAMING_SNAKE_CASE : Union[str, Any] = 'layernorm.bias' if "head" in name: SCREAMING_SNAKE_CASE : str = name.replace('''head''' , '''classifier''' ) else: SCREAMING_SNAKE_CASE : Tuple = 'focalnet.' + name return name def A ( _lowercase , _lowercase , _lowercase=False ): SCREAMING_SNAKE_CASE : List[str] = { 'focalnet-tiny': 'https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_tiny_srf.pth', 'focalnet-tiny-lrf': 'https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_tiny_lrf.pth', 'focalnet-small': 'https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_small_srf.pth', 'focalnet-small-lrf': 'https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_small_lrf.pth', 'focalnet-base': 'https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_base_srf.pth', 'focalnet-base-lrf': 'https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_base_lrf.pth', 'focalnet-large-lrf-fl3': 'https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_large_lrf_384.pth', 'focalnet-large-lrf-fl4': 'https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_large_lrf_384_fl4.pth', 'focalnet-xlarge-lrf-fl3': 'https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_xlarge_lrf_384.pth', 'focalnet-xlarge-lrf-fl4': 'https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_xlarge_lrf_384_fl4.pth', } # fmt: on SCREAMING_SNAKE_CASE : Tuple = model_name_to_url[model_name] print('''Checkpoint URL: ''' , lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : List[Any] = torch.hub.load_state_dict_from_url(lowerCAmelCase__ , map_location='''cpu''' )['model'] # rename keys for key in state_dict.copy().keys(): SCREAMING_SNAKE_CASE : Dict = state_dict.pop(lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : int = val SCREAMING_SNAKE_CASE : List[Any] = get_focalnet_config(lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : Tuple = FocalNetForImageClassification(lowerCAmelCase__ ) model.eval() # load state dict model.load_state_dict(lowerCAmelCase__ ) # verify conversion SCREAMING_SNAKE_CASE : Dict = 'http://images.cocodataset.org/val2017/000000039769.jpg' SCREAMING_SNAKE_CASE : Union[str, Any] = BitImageProcessor( do_resize=lowerCAmelCase__ , size={'''shortest_edge''': 256} , resample=PILImageResampling.BILINEAR , do_center_crop=lowerCAmelCase__ , crop_size=224 , do_normalize=lowerCAmelCase__ , image_mean=lowerCAmelCase__ , image_std=lowerCAmelCase__ , ) SCREAMING_SNAKE_CASE : Optional[Any] = Image.open(requests.get(lowerCAmelCase__ , stream=lowerCAmelCase__ ).raw ) SCREAMING_SNAKE_CASE : List[str] = processor(images=lowerCAmelCase__ , return_tensors='''pt''' ) SCREAMING_SNAKE_CASE : Dict = transforms.Compose( [ transforms.Resize(256 ), transforms.CenterCrop(224 ), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406] , std=[0.229, 0.224, 0.225] ), ] ) SCREAMING_SNAKE_CASE : str = image_transforms(lowerCAmelCase__ ).unsqueeze(0 ) # verify pixel_values assert torch.allclose(inputs.pixel_values , lowerCAmelCase__ , atol=1e-4 ) SCREAMING_SNAKE_CASE : Any = model(**lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : Union[str, Any] = outputs.logits.argmax(-1 ).item() print('''Predicted class:''' , model.config.idalabel[predicted_class_idx] ) print('''First values of logits:''' , outputs.logits[0, :3] ) if model_name == "focalnet-tiny": SCREAMING_SNAKE_CASE : Dict = torch.tensor([0.2166, -0.4368, 0.2191] ) elif model_name == "focalnet-tiny-lrf": SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor([1.1669, 0.0125, -0.1695] ) elif model_name == "focalnet-small": SCREAMING_SNAKE_CASE : Any = torch.tensor([0.4917, -0.0430, 0.1341] ) elif model_name == "focalnet-small-lrf": SCREAMING_SNAKE_CASE : Tuple = torch.tensor([-0.2588, -0.5342, -0.2331] ) elif model_name == "focalnet-base": SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([-0.1655, -0.4090, -0.1730] ) elif model_name == "focalnet-base-lrf": SCREAMING_SNAKE_CASE : Any = torch.tensor([0.5306, -0.0483, -0.3928] ) assert torch.allclose(outputs.logits[0, :3] , lowerCAmelCase__ , atol=1e-4 ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: print(f"""Saving model and processor of {model_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(lowerCAmelCase__ ) processor.save_pretrained(lowerCAmelCase__ ) if push_to_hub: print(f"""Pushing model and processor of {model_name} to the hub...""" ) model.push_to_hub(f"""{model_name}""" ) processor.push_to_hub(f"""{model_name}""" ) if __name__ == "__main__": __UpperCamelCase : Dict = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='focalnet-tiny', type=str, help='Name of the FocalNet 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 to push the model and processor to the hub.', ) __UpperCamelCase : int = parser.parse_args() convert_focalnet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
708
import math from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import SchedulerMixin, SchedulerOutput class lowercase__ ( UpperCamelCase_ , UpperCamelCase_): UpperCamelCase_ = 1 @register_to_config def __init__( self : List[str] , UpperCamelCase__ : int = 1000 , UpperCamelCase__ : Optional[Union[np.ndarray, List[float]]] = None ): '''simple docstring''' self.set_timesteps(UpperCamelCase__ ) # standard deviation of the initial noise distribution SCREAMING_SNAKE_CASE : str = 1.0 # For now we only support F-PNDM, i.e. the runge-kutta method # For more information on the algorithm please take a look at the paper: https://arxiv.org/pdf/2202.09778.pdf # mainly at formula (9), (12), (13) and the Algorithm 2. SCREAMING_SNAKE_CASE : Tuple = 4 # running values SCREAMING_SNAKE_CASE : int = [] def __A ( self : Dict , UpperCamelCase__ : int , UpperCamelCase__ : Union[str, torch.device] = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = num_inference_steps SCREAMING_SNAKE_CASE : Union[str, Any] = torch.linspace(1 , 0 , num_inference_steps + 1 )[:-1] SCREAMING_SNAKE_CASE : Tuple = torch.cat([steps, torch.tensor([0.0] )] ) if self.config.trained_betas is not None: SCREAMING_SNAKE_CASE : int = torch.tensor(self.config.trained_betas , dtype=torch.floataa ) else: SCREAMING_SNAKE_CASE : Optional[Any] = torch.sin(steps * math.pi / 2 ) ** 2 SCREAMING_SNAKE_CASE : Dict = (1.0 - self.betas**2) ** 0.5 SCREAMING_SNAKE_CASE : Optional[Any] = (torch.atana(self.betas , self.alphas ) / math.pi * 2)[:-1] SCREAMING_SNAKE_CASE : List[str] = timesteps.to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Any = [] def __A ( self : Tuple , UpperCamelCase__ : torch.FloatTensor , UpperCamelCase__ : int , UpperCamelCase__ : torch.FloatTensor , UpperCamelCase__ : bool = True , ): '''simple docstring''' if self.num_inference_steps is None: raise ValueError( '''Number of inference steps is \'None\', you need to run \'set_timesteps\' after creating the scheduler''' ) SCREAMING_SNAKE_CASE : Optional[int] = (self.timesteps == timestep).nonzero().item() SCREAMING_SNAKE_CASE : Union[str, Any] = timestep_index + 1 SCREAMING_SNAKE_CASE : int = sample * self.betas[timestep_index] + model_output * self.alphas[timestep_index] self.ets.append(UpperCamelCase__ ) if len(self.ets ) == 1: SCREAMING_SNAKE_CASE : Dict = self.ets[-1] elif len(self.ets ) == 2: SCREAMING_SNAKE_CASE : Optional[int] = (3 * self.ets[-1] - self.ets[-2]) / 2 elif len(self.ets ) == 3: SCREAMING_SNAKE_CASE : str = (23 * self.ets[-1] - 16 * self.ets[-2] + 5 * self.ets[-3]) / 12 else: SCREAMING_SNAKE_CASE : Optional[Any] = (1 / 24) * (55 * self.ets[-1] - 59 * self.ets[-2] + 37 * self.ets[-3] - 9 * self.ets[-4]) SCREAMING_SNAKE_CASE : Optional[int] = self._get_prev_sample(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=UpperCamelCase__ ) def __A ( self : Optional[Any] , UpperCamelCase__ : torch.FloatTensor , *UpperCamelCase__ : List[str] , **UpperCamelCase__ : Optional[Any] ): '''simple docstring''' return sample def __A ( self : Union[str, Any] , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Any , UpperCamelCase__ : Tuple , UpperCamelCase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = self.alphas[timestep_index] SCREAMING_SNAKE_CASE : List[str] = self.betas[timestep_index] SCREAMING_SNAKE_CASE : Union[str, Any] = self.alphas[prev_timestep_index] SCREAMING_SNAKE_CASE : Tuple = self.betas[prev_timestep_index] SCREAMING_SNAKE_CASE : Dict = (sample - sigma * ets) / max(UpperCamelCase__ , 1E-8 ) SCREAMING_SNAKE_CASE : Optional[Any] = next_alpha * pred + ets * next_sigma return prev_sample def __len__( self : int ): '''simple docstring''' return self.config.num_train_timesteps
34
0
import datasets from .evaluate import evaluate __UpperCamelCase : List[Any] = '\\n@article{hendrycks2021cuad,\n title={CUAD: An Expert-Annotated NLP Dataset for Legal Contract Review},\n author={Dan Hendrycks and Collin Burns and Anya Chen and Spencer Ball},\n journal={arXiv preprint arXiv:2103.06268},\n year={2021}\n}\n' __UpperCamelCase : Optional[Any] = '\nThis metric wrap the official scoring script for version 1 of the Contract\nUnderstanding Atticus Dataset (CUAD).\nContract Understanding Atticus Dataset (CUAD) v1 is a corpus of more than 13,000 labels in 510\ncommercial legal contracts that have been manually labeled to identify 41 categories of important\nclauses that lawyers look for when reviewing contracts in connection with corporate transactions.\n' __UpperCamelCase : int = '\nComputes CUAD scores (EM, F1, AUPR, Precision@80%Recall, and Precision@90%Recall).\nArgs:\n predictions: List of question-answers dictionaries with the following key-values:\n - \'id\': id of the question-answer pair as given in the references (see below)\n - \'prediction_text\': list of possible texts for the answer, as a list of strings\n depending on a threshold on the confidence probability of each prediction.\n references: List of question-answers dictionaries with the following key-values:\n - \'id\': id of the question-answer pair (see above),\n - \'answers\': a Dict in the CUAD dataset format\n {\n \'text\': list of possible texts for the answer, as a list of strings\n \'answer_start\': list of start positions for the answer, as a list of ints\n }\n Note that answer_start values are not taken into account to compute the metric.\nReturns:\n \'exact_match\': Exact match (the normalized answer exactly match the gold answer)\n \'f1\': The F-score of predicted tokens versus the gold answer\n \'aupr\': Area Under the Precision-Recall curve\n \'prec_at_80_recall\': Precision at 80% recall\n \'prec_at_90_recall\': Precision at 90% recall\nExamples:\n >>> predictions = [{\'prediction_text\': [\'The seller:\', \'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.\'], \'id\': \'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties\'}]\n >>> references = [{\'answers\': {\'answer_start\': [143, 49], \'text\': [\'The seller:\', \'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.\']}, \'id\': \'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties\'}]\n >>> cuad_metric = datasets.load_metric("cuad")\n >>> results = cuad_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'exact_match\': 100.0, \'f1\': 100.0, \'aupr\': 0.0, \'prec_at_80_recall\': 1.0, \'prec_at_90_recall\': 1.0}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class lowercase__ ( datasets.Metric): def __A ( self : Union[str, Any] ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': { '''id''': datasets.Value('''string''' ), '''prediction_text''': datasets.features.Sequence(datasets.Value('''string''' ) ), }, '''references''': { '''id''': datasets.Value('''string''' ), '''answers''': datasets.features.Sequence( { '''text''': datasets.Value('''string''' ), '''answer_start''': datasets.Value('''int32''' ), } ), }, } ) , codebase_urls=['''https://www.atticusprojectai.org/cuad'''] , reference_urls=['''https://www.atticusprojectai.org/cuad'''] , ) def __A ( self : Tuple , UpperCamelCase__ : Tuple , UpperCamelCase__ : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = {prediction['''id''']: prediction['''prediction_text'''] for prediction in predictions} SCREAMING_SNAKE_CASE : str = [ { '''paragraphs''': [ { '''qas''': [ { '''answers''': [{'''text''': answer_text} for answer_text in ref['''answers''']['''text''']], '''id''': ref['''id'''], } for ref in references ] } ] } ] SCREAMING_SNAKE_CASE : List[Any] = evaluate(dataset=lowerCamelCase_ , predictions=lowerCamelCase_ ) return score
709
import gc import random import unittest import torch from diffusers import ( IFImgaImgPipeline, IFImgaImgSuperResolutionPipeline, IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline, IFPipeline, IFSuperResolutionPipeline, ) from diffusers.models.attention_processor import AttnAddedKVProcessor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import floats_tensor, load_numpy, require_torch_gpu, skip_mps, slow, torch_device from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference from . import IFPipelineTesterMixin @skip_mps class lowercase__ ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): UpperCamelCase_ = IFPipeline UpperCamelCase_ = TEXT_TO_IMAGE_PARAMS - {"""width""", """height""", """latents"""} UpperCamelCase_ = TEXT_TO_IMAGE_BATCH_PARAMS UpperCamelCase_ = PipelineTesterMixin.required_optional_params - {"""latents"""} def __A ( self : Tuple ): '''simple docstring''' return self._get_dummy_components() def __A ( self : int , UpperCamelCase__ : Dict , UpperCamelCase__ : int=0 ): '''simple docstring''' if str(UpperCamelCase__ ).startswith('''mps''' ): SCREAMING_SNAKE_CASE : Tuple = torch.manual_seed(UpperCamelCase__ ) else: SCREAMING_SNAKE_CASE : Dict = torch.Generator(device=UpperCamelCase__ ).manual_seed(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : int = { '''prompt''': '''A painting of a squirrel eating a burger''', '''generator''': generator, '''num_inference_steps''': 2, '''output_type''': '''numpy''', } return inputs def __A ( self : List[str] ): '''simple docstring''' self._test_save_load_optional_components() @unittest.skipIf(torch_device != '''cuda''' , reason='''float16 requires CUDA''' ) def __A ( self : Any ): '''simple docstring''' super().test_save_load_floataa(expected_max_diff=1E-1 ) def __A ( self : Union[str, Any] ): '''simple docstring''' self._test_attention_slicing_forward_pass(expected_max_diff=1E-2 ) def __A ( self : List[Any] ): '''simple docstring''' self._test_save_load_local() def __A ( self : List[str] ): '''simple docstring''' self._test_inference_batch_single_identical( expected_max_diff=1E-2 , ) @unittest.skipIf( torch_device != '''cuda''' or not is_xformers_available() , reason='''XFormers attention is only available with CUDA and `xformers` installed''' , ) def __A ( self : Tuple ): '''simple docstring''' self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 ) @slow @require_torch_gpu class lowercase__ ( unittest.TestCase): def __A ( self : Optional[Any] ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = IFPipeline.from_pretrained('''DeepFloyd/IF-I-XL-v1.0''' , variant='''fp16''' , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE : str = IFSuperResolutionPipeline.from_pretrained( '''DeepFloyd/IF-II-L-v1.0''' , variant='''fp16''' , torch_dtype=torch.floataa , text_encoder=UpperCamelCase__ , tokenizer=UpperCamelCase__ ) # pre compute text embeddings and remove T5 to save memory pipe_a.text_encoder.to('''cuda''' ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Dict = pipe_a.encode_prompt('''anime turtle''' , device='''cuda''' ) del pipe_a.tokenizer del pipe_a.text_encoder gc.collect() SCREAMING_SNAKE_CASE : Tuple = None SCREAMING_SNAKE_CASE : str = None pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) pipe_a.remove_all_hooks() pipe_a.remove_all_hooks() # img2img SCREAMING_SNAKE_CASE : Optional[int] = IFImgaImgPipeline(**pipe_a.components ) SCREAMING_SNAKE_CASE : Optional[int] = IFImgaImgSuperResolutionPipeline(**pipe_a.components ) pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if_imgaimg(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) pipe_a.remove_all_hooks() pipe_a.remove_all_hooks() # inpainting SCREAMING_SNAKE_CASE : Tuple = IFInpaintingPipeline(**pipe_a.components ) SCREAMING_SNAKE_CASE : Optional[int] = IFInpaintingSuperResolutionPipeline(**pipe_a.components ) pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if_inpainting(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) def __A ( self : Tuple , UpperCamelCase__ : int , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Dict ): '''simple docstring''' _start_torch_memory_measurement() SCREAMING_SNAKE_CASE : List[str] = torch.Generator(device='''cpu''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[Any] = pipe_a( prompt_embeds=UpperCamelCase__ , negative_prompt_embeds=UpperCamelCase__ , num_inference_steps=2 , generator=UpperCamelCase__ , output_type='''np''' , ) SCREAMING_SNAKE_CASE : Optional[int] = output.images[0] assert image.shape == (64, 64, 3) SCREAMING_SNAKE_CASE : Tuple = torch.cuda.max_memory_allocated() assert mem_bytes < 13 * 10**9 SCREAMING_SNAKE_CASE : Optional[Any] = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if.npy''' ) assert_mean_pixel_difference(UpperCamelCase__ , UpperCamelCase__ ) # pipeline 2 _start_torch_memory_measurement() SCREAMING_SNAKE_CASE : Tuple = torch.Generator(device='''cpu''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE : int = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Any = pipe_a( prompt_embeds=UpperCamelCase__ , negative_prompt_embeds=UpperCamelCase__ , image=UpperCamelCase__ , generator=UpperCamelCase__ , num_inference_steps=2 , output_type='''np''' , ) SCREAMING_SNAKE_CASE : Tuple = output.images[0] assert image.shape == (256, 256, 3) SCREAMING_SNAKE_CASE : Union[str, Any] = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 SCREAMING_SNAKE_CASE : int = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_superresolution_stage_II.npy''' ) assert_mean_pixel_difference(UpperCamelCase__ , UpperCamelCase__ ) def __A ( self : Optional[int] , UpperCamelCase__ : str , UpperCamelCase__ : int , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : str ): '''simple docstring''' _start_torch_memory_measurement() SCREAMING_SNAKE_CASE : Tuple = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Any = torch.Generator(device='''cpu''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE : List[Any] = pipe_a( prompt_embeds=UpperCamelCase__ , negative_prompt_embeds=UpperCamelCase__ , image=UpperCamelCase__ , num_inference_steps=2 , generator=UpperCamelCase__ , output_type='''np''' , ) SCREAMING_SNAKE_CASE : int = output.images[0] assert image.shape == (64, 64, 3) SCREAMING_SNAKE_CASE : Optional[int] = torch.cuda.max_memory_allocated() assert mem_bytes < 10 * 10**9 SCREAMING_SNAKE_CASE : Tuple = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img.npy''' ) assert_mean_pixel_difference(UpperCamelCase__ , UpperCamelCase__ ) # pipeline 2 _start_torch_memory_measurement() SCREAMING_SNAKE_CASE : Union[str, Any] = torch.Generator(device='''cpu''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[Any] = floats_tensor((1, 3, 256, 256) , rng=random.Random(0 ) ).to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[Any] = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : str = pipe_a( prompt_embeds=UpperCamelCase__ , negative_prompt_embeds=UpperCamelCase__ , image=UpperCamelCase__ , original_image=UpperCamelCase__ , generator=UpperCamelCase__ , num_inference_steps=2 , output_type='''np''' , ) SCREAMING_SNAKE_CASE : Optional[int] = output.images[0] assert image.shape == (256, 256, 3) SCREAMING_SNAKE_CASE : List[Any] = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 SCREAMING_SNAKE_CASE : Optional[Any] = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img_superresolution_stage_II.npy''' ) assert_mean_pixel_difference(UpperCamelCase__ , UpperCamelCase__ ) def __A ( self : List[str] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Optional[Any] ): '''simple docstring''' _start_torch_memory_measurement() SCREAMING_SNAKE_CASE : str = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Union[str, Any] = floats_tensor((1, 3, 64, 64) , rng=random.Random(1 ) ).to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[int] = torch.Generator(device='''cpu''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE : int = pipe_a( prompt_embeds=UpperCamelCase__ , negative_prompt_embeds=UpperCamelCase__ , image=UpperCamelCase__ , mask_image=UpperCamelCase__ , num_inference_steps=2 , generator=UpperCamelCase__ , output_type='''np''' , ) SCREAMING_SNAKE_CASE : Any = output.images[0] assert image.shape == (64, 64, 3) SCREAMING_SNAKE_CASE : Any = torch.cuda.max_memory_allocated() assert mem_bytes < 10 * 10**9 SCREAMING_SNAKE_CASE : List[Any] = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting.npy''' ) assert_mean_pixel_difference(UpperCamelCase__ , UpperCamelCase__ ) # pipeline 2 _start_torch_memory_measurement() SCREAMING_SNAKE_CASE : str = torch.Generator(device='''cpu''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE : List[str] = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : int = floats_tensor((1, 3, 256, 256) , rng=random.Random(0 ) ).to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[int] = floats_tensor((1, 3, 256, 256) , rng=random.Random(1 ) ).to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Dict = pipe_a( prompt_embeds=UpperCamelCase__ , negative_prompt_embeds=UpperCamelCase__ , image=UpperCamelCase__ , mask_image=UpperCamelCase__ , original_image=UpperCamelCase__ , generator=UpperCamelCase__ , num_inference_steps=2 , output_type='''np''' , ) SCREAMING_SNAKE_CASE : Optional[Any] = output.images[0] assert image.shape == (256, 256, 3) SCREAMING_SNAKE_CASE : Any = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 SCREAMING_SNAKE_CASE : Tuple = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting_superresolution_stage_II.npy''' ) assert_mean_pixel_difference(UpperCamelCase__ , UpperCamelCase__ ) def A ( ): torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats()
34
0
import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST, OpenAIGPTConfig, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification, OpenAIGPTLMHeadModel, OpenAIGPTModel, ) class lowercase__ : def __init__( self : Any , UpperCamelCase__ : Any , UpperCamelCase__ : int=13 , UpperCamelCase__ : Tuple=7 , UpperCamelCase__ : List[str]=True , UpperCamelCase__ : Any=True , UpperCamelCase__ : List[Any]=True , UpperCamelCase__ : List[Any]=99 , UpperCamelCase__ : List[str]=32 , UpperCamelCase__ : Optional[Any]=5 , UpperCamelCase__ : Any=4 , UpperCamelCase__ : Optional[int]=37 , UpperCamelCase__ : Optional[int]="gelu" , UpperCamelCase__ : List[str]=0.1 , UpperCamelCase__ : List[str]=0.1 , UpperCamelCase__ : List[str]=512 , UpperCamelCase__ : Optional[Any]=16 , UpperCamelCase__ : Optional[Any]=2 , UpperCamelCase__ : int=0.02 , UpperCamelCase__ : List[str]=3 , UpperCamelCase__ : Optional[int]=4 , UpperCamelCase__ : int=None , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = parent SCREAMING_SNAKE_CASE : str = batch_size SCREAMING_SNAKE_CASE : List[str] = seq_length SCREAMING_SNAKE_CASE : Tuple = is_training SCREAMING_SNAKE_CASE : str = use_token_type_ids SCREAMING_SNAKE_CASE : Optional[int] = use_labels SCREAMING_SNAKE_CASE : Dict = vocab_size SCREAMING_SNAKE_CASE : List[str] = hidden_size SCREAMING_SNAKE_CASE : List[str] = num_hidden_layers SCREAMING_SNAKE_CASE : Tuple = num_attention_heads SCREAMING_SNAKE_CASE : Optional[Any] = intermediate_size SCREAMING_SNAKE_CASE : Dict = hidden_act SCREAMING_SNAKE_CASE : Dict = hidden_dropout_prob SCREAMING_SNAKE_CASE : int = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : Optional[int] = max_position_embeddings SCREAMING_SNAKE_CASE : int = type_vocab_size SCREAMING_SNAKE_CASE : Union[str, Any] = type_sequence_label_size SCREAMING_SNAKE_CASE : List[str] = initializer_range SCREAMING_SNAKE_CASE : str = num_labels SCREAMING_SNAKE_CASE : str = num_choices SCREAMING_SNAKE_CASE : Optional[Any] = scope SCREAMING_SNAKE_CASE : Union[str, Any] = self.vocab_size - 1 def __A ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE : List[Any] = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE : Any = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE : Optional[Any] = None SCREAMING_SNAKE_CASE : List[Any] = None SCREAMING_SNAKE_CASE : Optional[int] = None if self.use_labels: SCREAMING_SNAKE_CASE : Any = 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 : Any = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE : List[str] = OpenAIGPTConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , pad_token_id=self.pad_token_id , ) SCREAMING_SNAKE_CASE : int = ids_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 ) return ( config, input_ids, head_mask, token_type_ids, sequence_labels, token_labels, choice_labels, ) def __A ( self : Any , UpperCamelCase__ : List[str] , UpperCamelCase__ : Tuple , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : Tuple , *UpperCamelCase__ : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = OpenAIGPTModel(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() SCREAMING_SNAKE_CASE : int = model(UpperCamelCase__ , token_type_ids=UpperCamelCase__ , head_mask=UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[int] = model(UpperCamelCase__ , token_type_ids=UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[str] = model(UpperCamelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __A ( self : List[Any] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : str , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Union[str, Any] , *UpperCamelCase__ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = OpenAIGPTLMHeadModel(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() SCREAMING_SNAKE_CASE : Optional[int] = model(UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __A ( self : List[Any] , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : Any , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : List[Any] , *UpperCamelCase__ : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = OpenAIGPTDoubleHeadsModel(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() SCREAMING_SNAKE_CASE : Optional[int] = model(UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __A ( self : Dict , UpperCamelCase__ : str , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : List[Any] , *UpperCamelCase__ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = self.num_labels SCREAMING_SNAKE_CASE : str = OpenAIGPTForSequenceClassification(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() SCREAMING_SNAKE_CASE : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE : Union[str, Any] = model(UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __A ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ) : Optional[Any] = config_and_inputs SCREAMING_SNAKE_CASE : str = { '''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''head_mask''': head_mask, } return config, inputs_dict @require_torch class lowercase__ ( lowercase_ , lowercase_ , lowercase_ , unittest.TestCase): UpperCamelCase_ = ( (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification) if is_torch_available() else () ) UpperCamelCase_ = ( (OpenAIGPTLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly UpperCamelCase_ = ( { '''feature-extraction''': OpenAIGPTModel, '''text-classification''': OpenAIGPTForSequenceClassification, '''text-generation''': OpenAIGPTLMHeadModel, '''zero-shot''': OpenAIGPTForSequenceClassification, } if is_torch_available() else {} ) def __A ( self : Union[str, Any] , UpperCamelCase__ : int , UpperCamelCase__ : Dict , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : Dict , UpperCamelCase__ : Union[str, Any] ): '''simple docstring''' if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests": # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers. # `OpenAIGPTConfig` was never used in pipeline tests, either because of a missing checkpoint or because a # tiny config could not be created. return True return False def __A ( self : Any , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Any , UpperCamelCase__ : int=False ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = super()._prepare_for_class(UpperCamelCase__ , UpperCamelCase__ , return_labels=UpperCamelCase__ ) if return_labels: if model_class.__name__ == "OpenAIGPTDoubleHeadsModel": SCREAMING_SNAKE_CASE : Dict = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length) , dtype=torch.long , device=UpperCamelCase__ , ) SCREAMING_SNAKE_CASE : str = inputs_dict['''labels'''] SCREAMING_SNAKE_CASE : Optional[int] = inputs_dict['''labels'''] SCREAMING_SNAKE_CASE : int = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices) , dtype=torch.long , device=UpperCamelCase__ , ) SCREAMING_SNAKE_CASE : str = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=UpperCamelCase__ ) return inputs_dict def __A ( self : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = OpenAIGPTModelTester(self ) SCREAMING_SNAKE_CASE : List[Any] = ConfigTester(self , config_class=UpperCamelCase__ , n_embd=37 ) def __A ( self : int ): '''simple docstring''' self.config_tester.run_common_tests() def __A ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_model(*UpperCamelCase__ ) def __A ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*UpperCamelCase__ ) def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_double_lm_head_model(*UpperCamelCase__ ) def __A ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*UpperCamelCase__ ) @slow def __A ( self : str ): '''simple docstring''' for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE : Tuple = OpenAIGPTModel.from_pretrained(UpperCamelCase__ ) self.assertIsNotNone(UpperCamelCase__ ) @require_torch class lowercase__ ( unittest.TestCase): @slow def __A ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = OpenAIGPTLMHeadModel.from_pretrained('''openai-gpt''' ) model.to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor([[481, 4735, 544]] , dtype=torch.long , device=UpperCamelCase__ ) # the president is SCREAMING_SNAKE_CASE : str = [ 481, 4735, 544, 246, 963, 870, 762, 239, 244, 4_0477, 244, 249, 719, 881, 487, 544, 240, 244, 603, 481, ] # the president is a very good man. " \n " i\'m sure he is, " said the SCREAMING_SNAKE_CASE : List[str] = model.generate(UpperCamelCase__ , do_sample=UpperCamelCase__ ) self.assertListEqual(output_ids[0].tolist() , UpperCamelCase__ )
710
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 : int = logging.get_logger(__name__) def A ( _lowercase , _lowercase , _lowercase , _lowercase ): def constraint_to_multiple_of(_lowercase , _lowercase , _lowercase=0 , _lowercase=None ): SCREAMING_SNAKE_CASE : int = round(val / multiple ) * multiple if max_val is not None and x > max_val: SCREAMING_SNAKE_CASE : Dict = math.floor(val / multiple ) * multiple if x < min_val: SCREAMING_SNAKE_CASE : Optional[Any] = math.ceil(val / multiple ) * multiple return x SCREAMING_SNAKE_CASE : Optional[Any] = (output_size, output_size) if isinstance(_lowercase , _lowercase ) else output_size SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = get_image_size(_lowercase ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = output_size # determine new height and width SCREAMING_SNAKE_CASE : Dict = output_height / input_height SCREAMING_SNAKE_CASE : Optional[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 SCREAMING_SNAKE_CASE : List[Any] = scale_width else: # fit height SCREAMING_SNAKE_CASE : List[Any] = scale_height SCREAMING_SNAKE_CASE : List[str] = constraint_to_multiple_of(scale_height * input_height , multiple=_lowercase ) SCREAMING_SNAKE_CASE : Optional[int] = constraint_to_multiple_of(scale_width * input_width , multiple=_lowercase ) return (new_height, new_width) class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = ["""pixel_values"""] def __init__( self : int , UpperCamelCase__ : bool = True , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : PILImageResampling = PILImageResampling.BILINEAR , UpperCamelCase__ : bool = False , UpperCamelCase__ : int = 1 , UpperCamelCase__ : bool = True , UpperCamelCase__ : Union[int, float] = 1 / 255 , UpperCamelCase__ : bool = True , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , **UpperCamelCase__ : Optional[int] , ): '''simple docstring''' super().__init__(**UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[str] = size if size is not None else {'''height''': 384, '''width''': 384} SCREAMING_SNAKE_CASE : Any = get_size_dict(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Dict = do_resize SCREAMING_SNAKE_CASE : Any = size SCREAMING_SNAKE_CASE : str = keep_aspect_ratio SCREAMING_SNAKE_CASE : List[str] = ensure_multiple_of SCREAMING_SNAKE_CASE : int = resample SCREAMING_SNAKE_CASE : Any = do_rescale SCREAMING_SNAKE_CASE : List[Any] = rescale_factor SCREAMING_SNAKE_CASE : Optional[int] = do_normalize SCREAMING_SNAKE_CASE : str = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN SCREAMING_SNAKE_CASE : Union[str, Any] = image_std if image_std is not None else IMAGENET_STANDARD_STD def __A ( self : Optional[Any] , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Dict[str, int] , UpperCamelCase__ : bool = False , UpperCamelCase__ : int = 1 , UpperCamelCase__ : PILImageResampling = PILImageResampling.BICUBIC , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : Union[str, Any] , ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = get_size_dict(UpperCamelCase__ ) 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()}""" ) SCREAMING_SNAKE_CASE : Any = get_resize_output_image_size( UpperCamelCase__ , output_size=(size['''height'''], size['''width''']) , keep_aspect_ratio=UpperCamelCase__ , multiple=UpperCamelCase__ , ) return resize(UpperCamelCase__ , size=UpperCamelCase__ , resample=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def __A ( self : Dict , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Union[int, float] , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : str , ): '''simple docstring''' return rescale(UpperCamelCase__ , scale=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def __A ( self : Any , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Union[float, List[float]] , UpperCamelCase__ : Union[float, List[float]] , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : List[str] , ): '''simple docstring''' return normalize(UpperCamelCase__ , mean=UpperCamelCase__ , std=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def __A ( self : Optional[Any] , UpperCamelCase__ : ImageInput , UpperCamelCase__ : bool = None , UpperCamelCase__ : int = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : int = None , UpperCamelCase__ : PILImageResampling = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : float = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : Optional[Union[str, TensorType]] = None , UpperCamelCase__ : ChannelDimension = ChannelDimension.FIRST , **UpperCamelCase__ : Optional[int] , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE : Optional[Any] = size if size is not None else self.size SCREAMING_SNAKE_CASE : Union[str, Any] = get_size_dict(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[Any] = keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio SCREAMING_SNAKE_CASE : List[str] = ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of SCREAMING_SNAKE_CASE : Tuple = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE : Optional[Any] = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE : Union[str, Any] = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE : str = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE : List[Any] = image_mean if image_mean is not None else self.image_mean SCREAMING_SNAKE_CASE : List[Any] = image_std if image_std is not None else self.image_std SCREAMING_SNAKE_CASE : Dict = make_list_of_images(UpperCamelCase__ ) if not valid_images(UpperCamelCase__ ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None or resample is None: raise ValueError('''Size and resample must be specified if do_resize is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('''Image mean and std must be specified if do_normalize is True.''' ) # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE : Tuple = [to_numpy_array(UpperCamelCase__ ) for image in images] if do_resize: SCREAMING_SNAKE_CASE : Dict = [self.resize(image=UpperCamelCase__ , size=UpperCamelCase__ , resample=UpperCamelCase__ ) for image in images] if do_rescale: SCREAMING_SNAKE_CASE : Any = [self.rescale(image=UpperCamelCase__ , scale=UpperCamelCase__ ) for image in images] if do_normalize: SCREAMING_SNAKE_CASE : Any = [self.normalize(image=UpperCamelCase__ , mean=UpperCamelCase__ , std=UpperCamelCase__ ) for image in images] SCREAMING_SNAKE_CASE : Optional[int] = [to_channel_dimension_format(UpperCamelCase__ , UpperCamelCase__ ) for image in images] SCREAMING_SNAKE_CASE : Tuple = {'''pixel_values''': images} return BatchFeature(data=UpperCamelCase__ , tensor_type=UpperCamelCase__ ) def __A ( self : Tuple , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : List[Tuple] = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(UpperCamelCase__ ) != len(UpperCamelCase__ ): raise ValueError( '''Make sure that you pass in as many target sizes as the batch dimension of the logits''' ) if is_torch_tensor(UpperCamelCase__ ): SCREAMING_SNAKE_CASE : List[Any] = target_sizes.numpy() SCREAMING_SNAKE_CASE : Optional[int] = [] for idx in range(len(UpperCamelCase__ ) ): SCREAMING_SNAKE_CASE : List[str] = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode='''bilinear''' , align_corners=UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Dict = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(UpperCamelCase__ ) else: SCREAMING_SNAKE_CASE : List[Any] = logits.argmax(dim=1 ) SCREAMING_SNAKE_CASE : List[Any] = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
34
0
from typing import TYPE_CHECKING from ...utils import _LazyModule __UpperCamelCase : List[Any] = {"tokenization_bertweet": ["BertweetTokenizer"]} if TYPE_CHECKING: from .tokenization_bertweet import BertweetTokenizer else: import sys __UpperCamelCase : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
711
import random def A ( _lowercase , _lowercase ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = [], [], [] for element in data: if element < pivot: less.append(_lowercase ) elif element > pivot: greater.append(_lowercase ) else: equal.append(_lowercase ) return less, equal, greater def A ( _lowercase , _lowercase ): # index = len(items) // 2 when trying to find the median # (value of index when items is sorted) # invalid input if index >= len(_lowercase ) or index < 0: return None SCREAMING_SNAKE_CASE : Dict = items[random.randint(0 , len(_lowercase ) - 1 )] SCREAMING_SNAKE_CASE : int = 0 SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = _partition(_lowercase , _lowercase ) SCREAMING_SNAKE_CASE : List[Any] = len(_lowercase ) SCREAMING_SNAKE_CASE : Optional[Any] = len(_lowercase ) # index is the pivot if m <= index < m + count: return pivot # must be in smaller elif m > index: return quick_select(_lowercase , _lowercase ) # must be in larger else: return quick_select(_lowercase , index - (m + count) )
34
0
def A ( _lowercase ): '''simple docstring''' stooge(a_ , 0 , len(a_ ) - 1 ) return arr def A ( _lowercase , _lowercase , _lowercase ): '''simple docstring''' if i >= h: return # If first element is smaller than the last then swap them if arr[i] > arr[h]: SCREAMING_SNAKE_CASE : int = arr[h], arr[i] # If there are more than 2 elements in the array if h - i + 1 > 2: SCREAMING_SNAKE_CASE : str = (int)((h - i + 1) / 3 ) # Recursively sort first 2/3 elements stooge(a_ , a_ , (h - t) ) # Recursively sort last 2/3 elements stooge(a_ , i + t , (a_) ) # Recursively sort first 2/3 elements stooge(a_ , a_ , (h - t) ) if __name__ == "__main__": __UpperCamelCase : Tuple = input('Enter numbers separated by a comma:\n').strip() __UpperCamelCase : Optional[int] = [int(item) for item in user_input.split(',')] print(stooge_sort(unsorted))
712
from dataclasses import asdict, dataclass from typing import Optional from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCamelCase : Tuple = logging.get_logger(__name__) # TODO Update this __UpperCamelCase : List[str] = { 'facebook/esm-1b': 'https://huggingface.co/facebook/esm-1b/resolve/main/config.json', # See all ESM models at https://huggingface.co/models?filter=esm } class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = """esm""" def __init__( self : Tuple , UpperCamelCase__ : Optional[Any]=None , UpperCamelCase__ : int=None , UpperCamelCase__ : List[str]=None , UpperCamelCase__ : Any=768 , UpperCamelCase__ : Optional[Any]=12 , UpperCamelCase__ : str=12 , UpperCamelCase__ : Optional[int]=3072 , UpperCamelCase__ : Optional[Any]=0.1 , UpperCamelCase__ : Any=0.1 , UpperCamelCase__ : Union[str, Any]=1026 , UpperCamelCase__ : Dict=0.02 , UpperCamelCase__ : Any=1E-12 , UpperCamelCase__ : Dict="absolute" , UpperCamelCase__ : Optional[Any]=True , UpperCamelCase__ : int=None , UpperCamelCase__ : Optional[int]=False , UpperCamelCase__ : Tuple=False , UpperCamelCase__ : List[str]=None , UpperCamelCase__ : Optional[Any]=None , **UpperCamelCase__ : Any , ): '''simple docstring''' super().__init__(pad_token_id=UpperCamelCase__ , mask_token_id=UpperCamelCase__ , **UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[Any] = vocab_size SCREAMING_SNAKE_CASE : Any = hidden_size SCREAMING_SNAKE_CASE : Union[str, Any] = num_hidden_layers SCREAMING_SNAKE_CASE : Dict = num_attention_heads SCREAMING_SNAKE_CASE : Any = intermediate_size SCREAMING_SNAKE_CASE : str = hidden_dropout_prob SCREAMING_SNAKE_CASE : List[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : str = max_position_embeddings SCREAMING_SNAKE_CASE : Tuple = initializer_range SCREAMING_SNAKE_CASE : Optional[int] = layer_norm_eps SCREAMING_SNAKE_CASE : Dict = position_embedding_type SCREAMING_SNAKE_CASE : Any = use_cache SCREAMING_SNAKE_CASE : Dict = emb_layer_norm_before SCREAMING_SNAKE_CASE : List[str] = token_dropout SCREAMING_SNAKE_CASE : List[Any] = is_folding_model if is_folding_model: if esmfold_config is None: logger.info('''No esmfold_config supplied for folding model, using default values.''' ) SCREAMING_SNAKE_CASE : List[Any] = EsmFoldConfig() elif isinstance(UpperCamelCase__ , UpperCamelCase__ ): SCREAMING_SNAKE_CASE : Union[str, Any] = EsmFoldConfig(**UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[Any] = esmfold_config if vocab_list is None: logger.warning('''No vocab_list supplied for folding model, assuming the ESM-2 vocabulary!''' ) SCREAMING_SNAKE_CASE : Optional[int] = get_default_vocab_list() else: SCREAMING_SNAKE_CASE : Optional[Any] = vocab_list else: SCREAMING_SNAKE_CASE : str = None SCREAMING_SNAKE_CASE : int = None if self.esmfold_config is not None and getattr(self.esmfold_config , '''use_esm_attn_map''' , UpperCamelCase__ ): raise ValueError('''The HuggingFace port of ESMFold does not support use_esm_attn_map at this time!''' ) def __A ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = super().to_dict() if isinstance(self.esmfold_config , UpperCamelCase__ ): SCREAMING_SNAKE_CASE : Optional[Any] = self.esmfold_config.to_dict() return output @dataclass class lowercase__ : UpperCamelCase_ = None UpperCamelCase_ = True UpperCamelCase_ = False UpperCamelCase_ = False UpperCamelCase_ = False UpperCamelCase_ = 0 UpperCamelCase_ = True UpperCamelCase_ = False UpperCamelCase_ = 128 UpperCamelCase_ = None def __A ( self : Optional[int] ): '''simple docstring''' if self.trunk is None: SCREAMING_SNAKE_CASE : Optional[Any] = TrunkConfig() elif isinstance(self.trunk , UpperCamelCase__ ): SCREAMING_SNAKE_CASE : Tuple = TrunkConfig(**self.trunk ) def __A ( self : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = asdict(self ) SCREAMING_SNAKE_CASE : Tuple = self.trunk.to_dict() return output @dataclass class lowercase__ : UpperCamelCase_ = 48 UpperCamelCase_ = 1_024 UpperCamelCase_ = 128 UpperCamelCase_ = 32 UpperCamelCase_ = 32 UpperCamelCase_ = 32 UpperCamelCase_ = 0 UpperCamelCase_ = 0 UpperCamelCase_ = False UpperCamelCase_ = 4 UpperCamelCase_ = 128 UpperCamelCase_ = None def __A ( self : Any ): '''simple docstring''' if self.structure_module is None: SCREAMING_SNAKE_CASE : Optional[int] = StructureModuleConfig() elif isinstance(self.structure_module , UpperCamelCase__ ): SCREAMING_SNAKE_CASE : Optional[Any] = StructureModuleConfig(**self.structure_module ) if self.max_recycles <= 0: raise ValueError(f"""`max_recycles` should be positive, got {self.max_recycles}.""" ) if self.sequence_state_dim % self.sequence_state_dim != 0: raise ValueError( '''`sequence_state_dim` should be a round multiple of `sequence_state_dim`, got''' f""" {self.sequence_state_dim} and {self.sequence_state_dim}.""" ) if self.pairwise_state_dim % self.pairwise_state_dim != 0: raise ValueError( '''`pairwise_state_dim` should be a round multiple of `pairwise_state_dim`, got''' f""" {self.pairwise_state_dim} and {self.pairwise_state_dim}.""" ) SCREAMING_SNAKE_CASE : Dict = self.sequence_state_dim // self.sequence_head_width SCREAMING_SNAKE_CASE : Tuple = self.pairwise_state_dim // self.pairwise_head_width if self.sequence_state_dim != sequence_num_heads * self.sequence_head_width: raise ValueError( '''`sequence_state_dim` should be equal to `sequence_num_heads * sequence_head_width, got''' f""" {self.sequence_state_dim} != {sequence_num_heads} * {self.sequence_head_width}.""" ) if self.pairwise_state_dim != pairwise_num_heads * self.pairwise_head_width: raise ValueError( '''`pairwise_state_dim` should be equal to `pairwise_num_heads * pairwise_head_width, got''' f""" {self.pairwise_state_dim} != {pairwise_num_heads} * {self.pairwise_head_width}.""" ) if self.pairwise_state_dim % 2 != 0: raise ValueError(f"""`pairwise_state_dim` should be even, got {self.pairwise_state_dim}.""" ) if self.dropout >= 0.4: raise ValueError(f"""`dropout` should not be greater than 0.4, got {self.dropout}.""" ) def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = asdict(self ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.structure_module.to_dict() return output @dataclass class lowercase__ : UpperCamelCase_ = 384 UpperCamelCase_ = 128 UpperCamelCase_ = 16 UpperCamelCase_ = 128 UpperCamelCase_ = 12 UpperCamelCase_ = 4 UpperCamelCase_ = 8 UpperCamelCase_ = 0.1 UpperCamelCase_ = 8 UpperCamelCase_ = 1 UpperCamelCase_ = 2 UpperCamelCase_ = 7 UpperCamelCase_ = 10 UpperCamelCase_ = 1E-8 UpperCamelCase_ = 1E5 def __A ( self : Dict ): '''simple docstring''' return asdict(self ) def A ( ): return ( "<cls>", "<pad>", "<eos>", "<unk>", "L", "A", "G", "V", "S", "E", "R", "T", "I", "D", "P", "K", "Q", "N", "F", "Y", "M", "H", "W", "C", "X", "B", "U", "Z", "O", ".", "-", "<null_1>", "<mask>", )
34
0
from __future__ import annotations def A ( _lowercase , _lowercase = None , _lowercase = None , _lowercase = False , ) -> Tuple: SCREAMING_SNAKE_CASE : List[str] = cipher_alphabet or [chr(UpperCAmelCase__ ) for i in range(97 , 123 )] # If the argument is None or the user provided an empty dictionary if not frequencies_dict: # Frequencies of letters in the english language (how much they show up) SCREAMING_SNAKE_CASE : Optional[int] = { '''a''': 0.0_8497, '''b''': 0.0_1492, '''c''': 0.0_2202, '''d''': 0.0_4253, '''e''': 0.1_1162, '''f''': 0.0_2228, '''g''': 0.0_2015, '''h''': 0.0_6094, '''i''': 0.0_7546, '''j''': 0.0_0153, '''k''': 0.0_1292, '''l''': 0.0_4025, '''m''': 0.0_2406, '''n''': 0.0_6749, '''o''': 0.0_7507, '''p''': 0.0_1929, '''q''': 0.0_0095, '''r''': 0.0_7587, '''s''': 0.0_6327, '''t''': 0.0_9356, '''u''': 0.0_2758, '''v''': 0.0_0978, '''w''': 0.0_2560, '''x''': 0.0_0150, '''y''': 0.0_1994, '''z''': 0.0_0077, } else: # Custom frequencies dictionary SCREAMING_SNAKE_CASE : Any = frequencies_dict if not case_sensitive: SCREAMING_SNAKE_CASE : Optional[Any] = ciphertext.lower() # Chi squared statistic values SCREAMING_SNAKE_CASE : Optional[int] = {} # cycle through all of the shifts for shift in range(len(UpperCAmelCase__ ) ): SCREAMING_SNAKE_CASE : Dict = '''''' # decrypt the message with the shift for letter in ciphertext: try: # Try to index the letter in the alphabet SCREAMING_SNAKE_CASE : Dict = (alphabet_letters.index(letter.lower() ) - shift) % len( UpperCAmelCase__ ) decrypted_with_shift += ( alphabet_letters[new_key].upper() if case_sensitive and letter.isupper() else alphabet_letters[new_key] ) except ValueError: # Append the character if it isn't in the alphabet decrypted_with_shift += letter SCREAMING_SNAKE_CASE : Optional[int] = 0.0 # Loop through each letter in the decoded message with the shift for letter in decrypted_with_shift: if case_sensitive: SCREAMING_SNAKE_CASE : str = letter.lower() if letter in frequencies: # Get the amount of times the letter occurs in the message SCREAMING_SNAKE_CASE : List[Any] = decrypted_with_shift.lower().count(UpperCAmelCase__ ) # Get the excepcted amount of times the letter should appear based # on letter frequencies SCREAMING_SNAKE_CASE : List[str] = frequencies[letter] * occurrences # Complete the chi squared statistic formula SCREAMING_SNAKE_CASE : Tuple = ((occurrences - expected) ** 2) / expected # Add the margin of error to the total chi squared statistic chi_squared_statistic += chi_letter_value else: if letter.lower() in frequencies: # Get the amount of times the letter occurs in the message SCREAMING_SNAKE_CASE : Optional[Any] = decrypted_with_shift.count(UpperCAmelCase__ ) # Get the excepcted amount of times the letter should appear based # on letter frequencies SCREAMING_SNAKE_CASE : Union[str, Any] = frequencies[letter] * occurrences # Complete the chi squared statistic formula SCREAMING_SNAKE_CASE : Optional[Any] = ((occurrences - expected) ** 2) / expected # Add the margin of error to the total chi squared statistic chi_squared_statistic += chi_letter_value # Add the data to the chi_squared_statistic_values dictionary SCREAMING_SNAKE_CASE : Optional[Any] = ( chi_squared_statistic, decrypted_with_shift, ) # Get the most likely cipher by finding the cipher with the smallest chi squared # statistic def chi_squared_statistic_values_sorting_key(_lowercase ) -> tuple[float, str]: return chi_squared_statistic_values[key] SCREAMING_SNAKE_CASE : Tuple = min( UpperCAmelCase__ , key=UpperCAmelCase__ , ) # Get all the data from the most likely cipher (key, decoded message) ( ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ) : Optional[int] = chi_squared_statistic_values[most_likely_cipher] # Return the data on the most likely shift return ( most_likely_cipher, most_likely_cipher_chi_squared_value, decoded_most_likely_cipher, )
713
import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv("""TEST_SAGEMAKER""" , """False""")) is not True , reason="""Skipping test because should only be run when releasing minor transformers version""" , ) @pytest.mark.usefixtures("""sm_env""") @parameterized_class( [ { """framework""": """pytorch""", """script""": """run_glue.py""", """model_name_or_path""": """distilbert-base-cased""", """instance_type""": """ml.p3.16xlarge""", """results""": {"""train_runtime""": 650, """eval_accuracy""": 0.7, """eval_loss""": 0.6}, }, { """framework""": """pytorch""", """script""": """run_ddp.py""", """model_name_or_path""": """distilbert-base-cased""", """instance_type""": """ml.p3.16xlarge""", """results""": {"""train_runtime""": 600, """eval_accuracy""": 0.7, """eval_loss""": 0.6}, }, { """framework""": """tensorflow""", """script""": """run_tf_dist.py""", """model_name_or_path""": """distilbert-base-cased""", """instance_type""": """ml.p3.16xlarge""", """results""": {"""train_runtime""": 600, """eval_accuracy""": 0.6, """eval_loss""": 0.7}, }, ]) class lowercase__ ( unittest.TestCase): def __A ( self : Any ): '''simple docstring''' if self.framework == "pytorch": subprocess.run( f"""cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py""".split() , encoding='''utf-8''' , check=UpperCamelCase__ , ) assert hasattr(self , '''env''' ) def __A ( self : str , UpperCamelCase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = f"""{self.env.base_job_name}-{instance_count}-{'ddp' if 'ddp' in self.script else 'smd'}""" # distributed data settings SCREAMING_SNAKE_CASE : Any = {'''smdistributed''': {'''dataparallel''': {'''enabled''': True}}} if self.script != '''run_ddp.py''' else None # creates estimator return HuggingFace( entry_point=self.script , source_dir=self.env.test_path , role=self.env.role , image_uri=self.env.image_uri , base_job_name=UpperCamelCase__ , instance_count=UpperCamelCase__ , instance_type=self.instance_type , debugger_hook_config=UpperCamelCase__ , hyperparameters={**self.env.distributed_hyperparameters, '''model_name_or_path''': self.model_name_or_path} , metric_definitions=self.env.metric_definitions , distribution=UpperCamelCase__ , py_version='''py36''' , ) def __A ( self : Optional[Any] , UpperCamelCase__ : List[str] ): '''simple docstring''' TrainingJobAnalytics(UpperCamelCase__ ).export_csv(f"""{self.env.test_path}/{job_name}_metrics.csv""" ) @parameterized.expand([(2,)] ) def __A ( self : Tuple , UpperCamelCase__ : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = self.create_estimator(UpperCamelCase__ ) # run training estimator.fit() # result dataframe SCREAMING_SNAKE_CASE : Optional[Any] = TrainingJobAnalytics(estimator.latest_training_job.name ).dataframe() # extract kpis SCREAMING_SNAKE_CASE : List[str] = list(result_metrics_df[result_metrics_df.metric_name == '''eval_accuracy''']['''value'''] ) SCREAMING_SNAKE_CASE : Dict = list(result_metrics_df[result_metrics_df.metric_name == '''eval_loss''']['''value'''] ) # get train time from SageMaker job, this includes starting, preprocessing, stopping SCREAMING_SNAKE_CASE : List[Any] = ( Session().describe_training_job(estimator.latest_training_job.name ).get('''TrainingTimeInSeconds''' , 99_9999 ) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results['''eval_accuracy'''] for t in eval_accuracy ) assert all(t <= self.results['''eval_loss'''] for t in eval_loss ) # dump tests result into json file to share in PR with open(f"""{estimator.latest_training_job.name}.json""" , '''w''' ) as outfile: json.dump({'''train_time''': train_runtime, '''eval_accuracy''': eval_accuracy, '''eval_loss''': eval_loss} , UpperCamelCase__ )
34
0
import inspect import unittest from transformers import MobileNetVaConfig 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 MobileNetVaForImageClassification, MobileNetVaModel from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileNetVaImageProcessor class lowercase__ ( UpperCamelCase_): def __A ( self : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(__UpperCamelCase , '''tf_padding''' ) ) self.parent.assertTrue(hasattr(__UpperCamelCase , '''depth_multiplier''' ) ) class lowercase__ : def __init__( self : str , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : int=13 , UpperCamelCase__ : Dict=3 , UpperCamelCase__ : int=32 , UpperCamelCase__ : Any=0.25 , UpperCamelCase__ : Tuple=8 , UpperCamelCase__ : int=True , UpperCamelCase__ : str=1024 , UpperCamelCase__ : List[Any]=32 , UpperCamelCase__ : Union[str, Any]="relu6" , UpperCamelCase__ : Optional[Any]=0.1 , UpperCamelCase__ : int=0.02 , UpperCamelCase__ : List[Any]=True , UpperCamelCase__ : Any=True , UpperCamelCase__ : List[Any]=10 , UpperCamelCase__ : List[Any]=None , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = parent SCREAMING_SNAKE_CASE : str = batch_size SCREAMING_SNAKE_CASE : List[str] = num_channels SCREAMING_SNAKE_CASE : Optional[int] = image_size SCREAMING_SNAKE_CASE : Tuple = depth_multiplier SCREAMING_SNAKE_CASE : Union[str, Any] = min_depth SCREAMING_SNAKE_CASE : Any = tf_padding SCREAMING_SNAKE_CASE : List[str] = int(last_hidden_size * depth_multiplier ) SCREAMING_SNAKE_CASE : List[Any] = output_stride SCREAMING_SNAKE_CASE : List[Any] = hidden_act SCREAMING_SNAKE_CASE : str = classifier_dropout_prob SCREAMING_SNAKE_CASE : str = use_labels SCREAMING_SNAKE_CASE : List[str] = is_training SCREAMING_SNAKE_CASE : Dict = num_labels SCREAMING_SNAKE_CASE : List[str] = initializer_range SCREAMING_SNAKE_CASE : Dict = scope def __A ( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE : Union[str, Any] = None SCREAMING_SNAKE_CASE : List[str] = None if self.use_labels: SCREAMING_SNAKE_CASE : str = ids_tensor([self.batch_size] , self.num_labels ) SCREAMING_SNAKE_CASE : Optional[Any] = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_config() return config, pixel_values, labels, pixel_labels def __A ( self : int ): '''simple docstring''' return MobileNetVaConfig( num_channels=self.num_channels , image_size=self.image_size , depth_multiplier=self.depth_multiplier , min_depth=self.min_depth , tf_padding=self.tf_padding , hidden_act=self.hidden_act , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , ) def __A ( self : int , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : List[Any] , UpperCamelCase__ : List[str] , UpperCamelCase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = MobileNetVaModel(config=__UpperCamelCase ) model.to(__UpperCamelCase ) model.eval() SCREAMING_SNAKE_CASE : List[Any] = model(__UpperCamelCase ) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def __A ( self : List[str] , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = self.num_labels SCREAMING_SNAKE_CASE : str = MobileNetVaForImageClassification(__UpperCamelCase ) model.to(__UpperCamelCase ) model.eval() SCREAMING_SNAKE_CASE : Any = model(__UpperCamelCase , labels=__UpperCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __A ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Dict = config_and_inputs SCREAMING_SNAKE_CASE : Tuple = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class lowercase__ ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): UpperCamelCase_ = (MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else () UpperCamelCase_ = ( {"""feature-extraction""": MobileNetVaModel, """image-classification""": MobileNetVaForImageClassification} if is_torch_available() else {} ) UpperCamelCase_ = False UpperCamelCase_ = False UpperCamelCase_ = False UpperCamelCase_ = False def __A ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = MobileNetVaModelTester(self ) SCREAMING_SNAKE_CASE : Any = MobileNetVaConfigTester(self , config_class=__UpperCamelCase , has_text_modality=__UpperCamelCase ) def __A ( self : Optional[int] ): '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason='''MobileNetV1 does not use inputs_embeds''' ) def __A ( self : Optional[Any] ): '''simple docstring''' pass @unittest.skip(reason='''MobileNetV1 does not support input and output embeddings''' ) def __A ( self : Union[str, Any] ): '''simple docstring''' pass @unittest.skip(reason='''MobileNetV1 does not output attentions''' ) def __A ( self : int ): '''simple docstring''' pass def __A ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : Union[str, Any] = model_class(__UpperCamelCase ) SCREAMING_SNAKE_CASE : Tuple = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE : Dict = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE : str = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , __UpperCamelCase ) def __A ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__UpperCamelCase ) def __A ( self : List[Any] ): '''simple docstring''' def check_hidden_states_output(UpperCamelCase__ : Tuple , UpperCamelCase__ : Dict , UpperCamelCase__ : int ): SCREAMING_SNAKE_CASE : Optional[Any] = model_class(__UpperCamelCase ) model.to(__UpperCamelCase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE : Optional[int] = model(**self._prepare_for_class(__UpperCamelCase , __UpperCamelCase ) ) SCREAMING_SNAKE_CASE : str = outputs.hidden_states SCREAMING_SNAKE_CASE : Any = 26 self.assertEqual(len(__UpperCamelCase ) , __UpperCamelCase ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : str = True check_hidden_states_output(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE : Optional[Any] = True check_hidden_states_output(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) def __A ( self : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__UpperCamelCase ) @slow def __A ( self : Union[str, Any] ): '''simple docstring''' for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE : Union[str, Any] = MobileNetVaModel.from_pretrained(__UpperCamelCase ) self.assertIsNotNone(__UpperCamelCase ) def A ( ): SCREAMING_SNAKE_CASE : Union[str, Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class lowercase__ ( unittest.TestCase): @cached_property def __A ( self : Union[str, Any] ): '''simple docstring''' return ( MobileNetVaImageProcessor.from_pretrained('''google/mobilenet_v1_1.0_224''' ) if is_vision_available() else None ) @slow def __A ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = MobileNetVaForImageClassification.from_pretrained('''google/mobilenet_v1_1.0_224''' ).to(__UpperCamelCase ) SCREAMING_SNAKE_CASE : int = self.default_image_processor SCREAMING_SNAKE_CASE : Tuple = prepare_img() SCREAMING_SNAKE_CASE : Optional[int] = image_processor(images=__UpperCamelCase , return_tensors='''pt''' ).to(__UpperCamelCase ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE : str = model(**__UpperCamelCase ) # verify the logits SCREAMING_SNAKE_CASE : List[Any] = torch.Size((1, 1001) ) self.assertEqual(outputs.logits.shape , __UpperCamelCase ) SCREAMING_SNAKE_CASE : Dict = torch.tensor([-4.1739, -1.1233, 3.1205] ).to(__UpperCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __UpperCamelCase , atol=1E-4 ) )
714
import os try: from .build_directory_md import good_file_paths except ImportError: from build_directory_md import good_file_paths # type: ignore __UpperCamelCase : Dict = list(good_file_paths()) assert filepaths, "good_file_paths() failed!" __UpperCamelCase : Tuple = [file for file in filepaths if file != file.lower()] if upper_files: print(f"""{len(upper_files)} files contain uppercase characters:""") print('\n'.join(upper_files) + '\n') __UpperCamelCase : List[Any] = [file for file in filepaths if ' ' in file] if space_files: print(f"""{len(space_files)} files contain space characters:""") print('\n'.join(space_files) + '\n') __UpperCamelCase : List[Any] = [file for file in filepaths if '-' in file] if hyphen_files: print(f"""{len(hyphen_files)} files contain hyphen characters:""") print('\n'.join(hyphen_files) + '\n') __UpperCamelCase : List[Any] = [file for file in filepaths if os.sep not in file] if nodir_files: print(f"""{len(nodir_files)} files are not in a directory:""") print('\n'.join(nodir_files) + '\n') __UpperCamelCase : Optional[Any] = len(upper_files + space_files + hyphen_files + nodir_files) if bad_files: import sys sys.exit(bad_files)
34
0
def A ( _lowercase ): if n_term == "": return [] SCREAMING_SNAKE_CASE : Optional[int] = [] for temp in range(int(_UpperCamelCase ) ): series.append(f"""1/{temp + 1}""" if series else '''1''' ) return series if __name__ == "__main__": __UpperCamelCase : List[Any] = input('Enter the last number (nth term) of the Harmonic Series') print('Formula of Harmonic Series => 1+1/2+1/3 ..... 1/n') print(harmonic_series(nth_term))
715
import os import re import warnings from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_ta import TaTokenizer else: __UpperCamelCase : Dict = None __UpperCamelCase : Tuple = logging.get_logger(__name__) __UpperCamelCase : Optional[int] = {'vocab_file': 'spiece.model', 'tokenizer_file': 'tokenizer.json'} __UpperCamelCase : Optional[int] = { 'vocab_file': { 't5-small': 'https://huggingface.co/t5-small/resolve/main/spiece.model', 't5-base': 'https://huggingface.co/t5-base/resolve/main/spiece.model', 't5-large': 'https://huggingface.co/t5-large/resolve/main/spiece.model', 't5-3b': 'https://huggingface.co/t5-3b/resolve/main/spiece.model', 't5-11b': 'https://huggingface.co/t5-11b/resolve/main/spiece.model', }, 'tokenizer_file': { 't5-small': 'https://huggingface.co/t5-small/resolve/main/tokenizer.json', 't5-base': 'https://huggingface.co/t5-base/resolve/main/tokenizer.json', 't5-large': 'https://huggingface.co/t5-large/resolve/main/tokenizer.json', 't5-3b': 'https://huggingface.co/t5-3b/resolve/main/tokenizer.json', 't5-11b': 'https://huggingface.co/t5-11b/resolve/main/tokenizer.json', }, } # TODO(PVP) - this should be removed in Transformers v5 __UpperCamelCase : Union[str, Any] = { 't5-small': 512, 't5-base': 512, 't5-large': 512, 't5-3b': 512, 't5-11b': 512, } class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = VOCAB_FILES_NAMES UpperCamelCase_ = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase_ = ["""input_ids""", """attention_mask"""] UpperCamelCase_ = TaTokenizer UpperCamelCase_ = [] def __init__( self : str , UpperCamelCase__ : Optional[int]=None , UpperCamelCase__ : Dict=None , UpperCamelCase__ : str="</s>" , UpperCamelCase__ : str="<unk>" , UpperCamelCase__ : Optional[int]="<pad>" , UpperCamelCase__ : Optional[Any]=100 , UpperCamelCase__ : List[Any]=None , **UpperCamelCase__ : str , ): '''simple docstring''' if extra_ids > 0 and additional_special_tokens is None: SCREAMING_SNAKE_CASE : List[str] = [f"""<extra_id_{i}>""" for i in range(UpperCamelCase__ )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra special tokens SCREAMING_SNAKE_CASE : int = len(set(filter(lambda UpperCamelCase__ : bool('''extra_id_''' in str(UpperCamelCase__ ) ) , UpperCamelCase__ ) ) ) if extra_tokens != extra_ids: raise ValueError( f"""Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are""" ''' provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids''' ''' tokens''' ) super().__init__( UpperCamelCase__ , tokenizer_file=UpperCamelCase__ , eos_token=UpperCamelCase__ , unk_token=UpperCamelCase__ , pad_token=UpperCamelCase__ , extra_ids=UpperCamelCase__ , additional_special_tokens=UpperCamelCase__ , **UpperCamelCase__ , ) SCREAMING_SNAKE_CASE : str = vocab_file SCREAMING_SNAKE_CASE : int = False if not self.vocab_file else True SCREAMING_SNAKE_CASE : str = extra_ids @staticmethod def __A ( UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Optional[Any] ): '''simple docstring''' if pretrained_model_name_or_path in TaTokenizerFast.max_model_input_sizes: SCREAMING_SNAKE_CASE : List[str] = TaTokenizerFast.max_model_input_sizes[pretrained_model_name_or_path] if init_max_model_length is not None and init_max_model_length != max_model_length: return init_max_model_length elif init_max_model_length is None: warnings.warn( '''This tokenizer was incorrectly instantiated with a model max length of''' f""" {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this""" ''' behavior is kept to avoid breaking backwards compatibility when padding/encoding with''' ''' `truncation is True`.\n- Be aware that you SHOULD NOT rely on''' f""" {pretrained_model_name_or_path} automatically truncating your input to""" f""" {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences""" f""" longer than {deprecated_max_model_length} you can either instantiate this tokenizer with""" ''' `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please''' ''' instantiate this tokenizer with `model_max_length` set to your preferred value.''' , UpperCamelCase__ , ) return max_model_length def __A ( self : Tuple , UpperCamelCase__ : str , UpperCamelCase__ : Optional[str] = None ): '''simple docstring''' if not self.can_save_slow_tokenizer: raise ValueError( '''Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ''' '''tokenizer.''' ) if not os.path.isdir(UpperCamelCase__ ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return SCREAMING_SNAKE_CASE : Any = os.path.join( UpperCamelCase__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCamelCase__ ): copyfile(self.vocab_file , UpperCamelCase__ ) logger.info(f"""Copy vocab file to {out_vocab_file}""" ) return (out_vocab_file,) def __A ( self : Optional[Any] , UpperCamelCase__ : List[int] , UpperCamelCase__ : Optional[List[int]] = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = token_ids_a + [self.eos_token_id] if token_ids_a is None: return self.prefix_tokens + token_ids_a else: SCREAMING_SNAKE_CASE : Tuple = token_ids_a + [self.eos_token_id] return self.prefix_tokens + token_ids_a + token_ids_a def __A ( self : Any , UpperCamelCase__ : List[int] , UpperCamelCase__ : Optional[List[int]] = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def __A ( self : Dict ): '''simple docstring''' return list( set(filter(lambda UpperCamelCase__ : bool(re.search(r'''<extra_id_\d+>''' , UpperCamelCase__ ) ) is not None , self.additional_special_tokens ) ) ) def __A ( self : List[Any] ): '''simple docstring''' return [self.convert_tokens_to_ids(UpperCamelCase__ ) for token in self.get_sentinel_tokens()]
34
0
from math import factorial, pi def A ( _lowercase , _lowercase = 30 ): if not isinstance(_lowercase , (int, float) ): raise ValueError('''maclaurin_sin() requires either an int or float for theta''' ) if not isinstance(_lowercase , _lowercase ) or accuracy <= 0: raise ValueError('''maclaurin_sin() requires a positive int for accuracy''' ) SCREAMING_SNAKE_CASE : List[Any] = float(_lowercase ) SCREAMING_SNAKE_CASE : str = theta // (2 * pi) theta -= 2 * div * pi return sum( (-1) ** r * theta ** (2 * r + 1) / factorial(2 * r + 1 ) for r in range(_lowercase ) ) def A ( _lowercase , _lowercase = 30 ): if not isinstance(_lowercase , (int, float) ): raise ValueError('''maclaurin_cos() requires either an int or float for theta''' ) if not isinstance(_lowercase , _lowercase ) or accuracy <= 0: raise ValueError('''maclaurin_cos() requires a positive int for accuracy''' ) SCREAMING_SNAKE_CASE : Union[str, Any] = float(_lowercase ) SCREAMING_SNAKE_CASE : Any = theta // (2 * pi) theta -= 2 * div * pi return sum((-1) ** r * theta ** (2 * r) / factorial(2 * r ) for r in range(_lowercase ) ) if __name__ == "__main__": import doctest doctest.testmod() print(maclaurin_sin(10)) print(maclaurin_sin(-10)) print(maclaurin_sin(10, 15)) print(maclaurin_sin(-10, 15)) print(maclaurin_cos(5)) print(maclaurin_cos(-5)) print(maclaurin_cos(10, 15)) print(maclaurin_cos(-10, 15))
716
import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionPipeline from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device __UpperCamelCase : str = False class lowercase__ ( unittest.TestCase): pass @nightly @require_torch_gpu class lowercase__ ( unittest.TestCase): def __A ( self : Union[str, Any] ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = VersatileDiffusionPipeline.from_pretrained('''shi-labs/versatile-diffusion''' , torch_dtype=torch.floataa ) pipe.to(UpperCamelCase__ ) pipe.set_progress_bar_config(disable=UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[Any] = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg''' ) SCREAMING_SNAKE_CASE : Optional[Any] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Dict = pipe.dual_guided( prompt='''first prompt''' , image=UpperCamelCase__ , text_to_image_strength=0.75 , generator=UpperCamelCase__ , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' , ).images with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[Any] = VersatileDiffusionPipeline.from_pretrained(UpperCamelCase__ , torch_dtype=torch.floataa ) pipe.to(UpperCamelCase__ ) pipe.set_progress_bar_config(disable=UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[Any] = generator.manual_seed(0 ) SCREAMING_SNAKE_CASE : int = pipe.dual_guided( prompt='''first prompt''' , image=UpperCamelCase__ , text_to_image_strength=0.75 , generator=UpperCamelCase__ , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' , ).images assert np.abs(image - new_image ).sum() < 1E-5, "Models don't have the same forward pass" def __A ( self : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = VersatileDiffusionPipeline.from_pretrained('''shi-labs/versatile-diffusion''' , torch_dtype=torch.floataa ) pipe.to(UpperCamelCase__ ) pipe.set_progress_bar_config(disable=UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[int] = '''cyberpunk 2077''' SCREAMING_SNAKE_CASE : Tuple = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg''' ) SCREAMING_SNAKE_CASE : List[Any] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Tuple = pipe.dual_guided( prompt=UpperCamelCase__ , image=UpperCamelCase__ , text_to_image_strength=0.75 , generator=UpperCamelCase__ , guidance_scale=7.5 , num_inference_steps=50 , output_type='''numpy''' , ).images SCREAMING_SNAKE_CASE : Tuple = image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE : int = np.array([0.1448, 0.1619, 0.1741, 0.1086, 0.1147, 0.1128, 0.1199, 0.1165, 0.1001] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 SCREAMING_SNAKE_CASE : Optional[Any] = '''A painting of a squirrel eating a burger ''' SCREAMING_SNAKE_CASE : Optional[Any] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Any = pipe.text_to_image( prompt=UpperCamelCase__ , generator=UpperCamelCase__ , guidance_scale=7.5 , num_inference_steps=50 , output_type='''numpy''' ).images SCREAMING_SNAKE_CASE : List[str] = image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE : Any = np.array([0.3367, 0.3169, 0.2656, 0.3870, 0.4790, 0.3796, 0.4009, 0.4878, 0.4778] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 SCREAMING_SNAKE_CASE : Optional[Any] = pipe.image_variation(UpperCamelCase__ , generator=UpperCamelCase__ , output_type='''numpy''' ).images SCREAMING_SNAKE_CASE : Optional[int] = image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE : Union[str, Any] = np.array([0.3076, 0.3123, 0.3284, 0.3782, 0.3770, 0.3894, 0.4297, 0.4331, 0.4456] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1
34
0
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __UpperCamelCase : Any = logging.get_logger(__name__) __UpperCamelCase : Union[str, Any] = { "bert-base-uncased": "https://huggingface.co/bert-base-uncased/resolve/main/config.json", "bert-large-uncased": "https://huggingface.co/bert-large-uncased/resolve/main/config.json", "bert-base-cased": "https://huggingface.co/bert-base-cased/resolve/main/config.json", "bert-large-cased": "https://huggingface.co/bert-large-cased/resolve/main/config.json", "bert-base-multilingual-uncased": "https://huggingface.co/bert-base-multilingual-uncased/resolve/main/config.json", "bert-base-multilingual-cased": "https://huggingface.co/bert-base-multilingual-cased/resolve/main/config.json", "bert-base-chinese": "https://huggingface.co/bert-base-chinese/resolve/main/config.json", "bert-base-german-cased": "https://huggingface.co/bert-base-german-cased/resolve/main/config.json", "bert-large-uncased-whole-word-masking": ( "https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/config.json" ), "bert-large-cased-whole-word-masking": ( "https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/config.json" ), "bert-large-uncased-whole-word-masking-finetuned-squad": ( "https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/config.json" ), "bert-large-cased-whole-word-masking-finetuned-squad": ( "https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/config.json" ), "bert-base-cased-finetuned-mrpc": "https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/config.json", "bert-base-german-dbmdz-cased": "https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/config.json", "bert-base-german-dbmdz-uncased": "https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/config.json", "cl-tohoku/bert-base-japanese": "https://huggingface.co/cl-tohoku/bert-base-japanese/resolve/main/config.json", "cl-tohoku/bert-base-japanese-whole-word-masking": ( "https://huggingface.co/cl-tohoku/bert-base-japanese-whole-word-masking/resolve/main/config.json" ), "cl-tohoku/bert-base-japanese-char": ( "https://huggingface.co/cl-tohoku/bert-base-japanese-char/resolve/main/config.json" ), "cl-tohoku/bert-base-japanese-char-whole-word-masking": ( "https://huggingface.co/cl-tohoku/bert-base-japanese-char-whole-word-masking/resolve/main/config.json" ), "TurkuNLP/bert-base-finnish-cased-v1": ( "https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/config.json" ), "TurkuNLP/bert-base-finnish-uncased-v1": ( "https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/config.json" ), "wietsedv/bert-base-dutch-cased": "https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/config.json", # See all BERT models at https://huggingface.co/models?filter=bert } class lowercase__ ( __lowerCAmelCase): UpperCamelCase_ = "bert" def __init__( self : Optional[int] , UpperCamelCase__ : List[str]=3_0522 , UpperCamelCase__ : Union[str, Any]=768 , UpperCamelCase__ : Tuple=12 , UpperCamelCase__ : Tuple=12 , UpperCamelCase__ : Any=3072 , UpperCamelCase__ : Union[str, Any]="gelu" , UpperCamelCase__ : Optional[int]=0.1 , UpperCamelCase__ : Any=0.1 , UpperCamelCase__ : Tuple=512 , UpperCamelCase__ : Dict=2 , UpperCamelCase__ : Dict=0.02 , UpperCamelCase__ : Union[str, Any]=1E-12 , UpperCamelCase__ : int=0 , UpperCamelCase__ : Tuple="absolute" , UpperCamelCase__ : str=True , UpperCamelCase__ : int=None , **UpperCamelCase__ : Tuple , ): '''simple docstring''' super().__init__(pad_token_id=lowerCamelCase__ , **lowerCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[int] = vocab_size SCREAMING_SNAKE_CASE : Union[str, Any] = hidden_size SCREAMING_SNAKE_CASE : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE : Dict = num_attention_heads SCREAMING_SNAKE_CASE : Any = hidden_act SCREAMING_SNAKE_CASE : List[str] = intermediate_size SCREAMING_SNAKE_CASE : int = hidden_dropout_prob SCREAMING_SNAKE_CASE : List[str] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : Tuple = max_position_embeddings SCREAMING_SNAKE_CASE : Dict = type_vocab_size SCREAMING_SNAKE_CASE : Optional[Any] = initializer_range SCREAMING_SNAKE_CASE : List[str] = layer_norm_eps SCREAMING_SNAKE_CASE : List[str] = position_embedding_type SCREAMING_SNAKE_CASE : List[str] = use_cache SCREAMING_SNAKE_CASE : Optional[Any] = classifier_dropout class lowercase__ ( __lowerCAmelCase): @property def __A ( self : List[str] ): '''simple docstring''' if self.task == "multiple-choice": SCREAMING_SNAKE_CASE : List[Any] = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: SCREAMING_SNAKE_CASE : List[str] = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ('''token_type_ids''', dynamic_axis), ] )
717
from __future__ import annotations import math from collections import Counter from string import ascii_lowercase def A ( _lowercase ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = analyze_text(_lowercase ) SCREAMING_SNAKE_CASE : Any = list(''' ''' + ascii_lowercase ) # what is our total sum of probabilities. SCREAMING_SNAKE_CASE : Tuple = sum(single_char_strings.values() ) # one length string SCREAMING_SNAKE_CASE : Tuple = 0 # for each alpha we go in our dict and if it is in it we calculate entropy for ch in my_alphas: if ch in single_char_strings: SCREAMING_SNAKE_CASE : Tuple = single_char_strings[ch] SCREAMING_SNAKE_CASE : List[str] = my_str / all_sum my_fir_sum += prob * math.loga(_lowercase ) # entropy formula. # print entropy print(f"""{round(-1 * my_fir_sum ):.1f}""" ) # two len string SCREAMING_SNAKE_CASE : Optional[Any] = sum(two_char_strings.values() ) SCREAMING_SNAKE_CASE : List[str] = 0 # for each alpha (two in size) calculate entropy. for cha in my_alphas: for cha in my_alphas: SCREAMING_SNAKE_CASE : Union[str, Any] = cha + cha if sequence in two_char_strings: SCREAMING_SNAKE_CASE : Any = two_char_strings[sequence] SCREAMING_SNAKE_CASE : Dict = int(_lowercase ) / all_sum my_sec_sum += prob * math.loga(_lowercase ) # print second entropy print(f"""{round(-1 * my_sec_sum ):.1f}""" ) # print the difference between them print(f"""{round((-1 * my_sec_sum) - (-1 * my_fir_sum) ):.1f}""" ) def A ( _lowercase ): SCREAMING_SNAKE_CASE : Tuple = Counter() # type: ignore SCREAMING_SNAKE_CASE : Any = Counter() # type: ignore single_char_strings[text[-1]] += 1 # first case when we have space at start. two_char_strings[" " + text[0]] += 1 for i in range(0 , len(_lowercase ) - 1 ): single_char_strings[text[i]] += 1 two_char_strings[text[i : i + 2]] += 1 return single_char_strings, two_char_strings def A ( ): import doctest doctest.testmod() # text = ( # "Had repulsive dashwoods suspicion sincerity but advantage now him. Remark " # "easily garret nor nay. Civil those mrs enjoy shy fat merry. You greatest " # "jointure saw horrible. He private he on be imagine suppose. Fertile " # "beloved evident through no service elderly is. Blind there if every no so " # "at. Own neglected you preferred way sincerity delivered his attempted. To " # "of message cottage windows do besides against uncivil. Delightful " # "unreserved impossible few estimating men favourable see entreaties. She " # "propriety immediate was improving. He or entrance humoured likewise " # "moderate. Much nor game son say feel. Fat make met can must form into " # "gate. Me we offending prevailed discovery. " # ) # calculate_prob(text) if __name__ == "__main__": main()
34
0
'''simple docstring''' from collections import deque class lowercase__ : def __init__( self : Union[str, Any] , UpperCamelCase__ : List[Any] , UpperCamelCase__ : int , UpperCamelCase__ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = process_name # process name SCREAMING_SNAKE_CASE : Tuple = arrival_time # arrival time of the process # completion time of finished process or last interrupted time SCREAMING_SNAKE_CASE : Any = arrival_time SCREAMING_SNAKE_CASE : Dict = burst_time # remaining burst time SCREAMING_SNAKE_CASE : int = 0 # total time of the process wait in ready queue SCREAMING_SNAKE_CASE : str = 0 # time from arrival time to completion time class lowercase__ : def __init__( self : int , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : List[str] , UpperCamelCase__ : Any , UpperCamelCase__ : str , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = number_of_queues # time slice of queues that round robin algorithm applied SCREAMING_SNAKE_CASE : Optional[int] = time_slices # unfinished process is in this ready_queue SCREAMING_SNAKE_CASE : List[str] = queue # current time SCREAMING_SNAKE_CASE : List[Any] = current_time # finished process is in this sequence queue SCREAMING_SNAKE_CASE : deque[Process] = deque() def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = [] for i in range(len(self.finish_queue ) ): sequence.append(self.finish_queue[i].process_name ) return sequence def __A ( self : Union[str, Any] , UpperCamelCase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = [] for i in range(len(UpperCamelCase__ ) ): waiting_times.append(queue[i].waiting_time ) return waiting_times def __A ( self : List[Any] , UpperCamelCase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = [] for i in range(len(UpperCamelCase__ ) ): turnaround_times.append(queue[i].turnaround_time ) return turnaround_times def __A ( self : Union[str, Any] , UpperCamelCase__ : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = [] for i in range(len(UpperCamelCase__ ) ): completion_times.append(queue[i].stop_time ) return completion_times def __A ( self : List[Any] , UpperCamelCase__ : Tuple ): '''simple docstring''' return [q.burst_time for q in queue] def __A ( self : Optional[Any] , UpperCamelCase__ : Optional[Any] ): '''simple docstring''' process.waiting_time += self.current_time - process.stop_time return process.waiting_time def __A ( self : Any , UpperCamelCase__ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : deque[Process] = deque() # sequence deque of finished process while len(UpperCamelCase__ ) != 0: SCREAMING_SNAKE_CASE : Optional[int] = ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time # update waiting time of current process self.update_waiting_time(UpperCamelCase__ ) # update current time self.current_time += cp.burst_time # finish the process and set the process's burst-time 0 SCREAMING_SNAKE_CASE : List[Any] = 0 # set the process's turnaround time because it is finished SCREAMING_SNAKE_CASE : List[str] = self.current_time - cp.arrival_time # set the completion time SCREAMING_SNAKE_CASE : Tuple = self.current_time # add the process to queue that has finished queue finished.append(UpperCamelCase__ ) self.finish_queue.extend(UpperCamelCase__ ) # add finished process to finish queue # FCFS will finish all remaining processes return finished def __A ( self : str , UpperCamelCase__ : List[Any] , UpperCamelCase__ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : deque[Process] = deque() # sequence deque of terminated process # just for 1 cycle and unfinished processes will go back to queue for _ in range(len(UpperCamelCase__ ) ): SCREAMING_SNAKE_CASE : Tuple = ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time # update waiting time of unfinished processes self.update_waiting_time(UpperCamelCase__ ) # if the burst time of process is bigger than time-slice if cp.burst_time > time_slice: # use CPU for only time-slice self.current_time += time_slice # update remaining burst time cp.burst_time -= time_slice # update end point time SCREAMING_SNAKE_CASE : List[str] = self.current_time # locate the process behind the queue because it is not finished ready_queue.append(UpperCamelCase__ ) else: # use CPU for remaining burst time self.current_time += cp.burst_time # set burst time 0 because the process is finished SCREAMING_SNAKE_CASE : str = 0 # set the finish time SCREAMING_SNAKE_CASE : Tuple = self.current_time # update the process' turnaround time because it is finished SCREAMING_SNAKE_CASE : str = self.current_time - cp.arrival_time # add the process to queue that has finished queue finished.append(UpperCamelCase__ ) self.finish_queue.extend(UpperCamelCase__ ) # add finished process to finish queue # return finished processes queue and remaining processes queue return finished, ready_queue def __A ( self : Dict ): '''simple docstring''' for i in range(self.number_of_queues - 1 ): SCREAMING_SNAKE_CASE : str = self.round_robin( self.ready_queue , self.time_slices[i] ) # the last queue has first_come_first_served algorithm self.first_come_first_served(self.ready_queue ) return self.finish_queue if __name__ == "__main__": import doctest __UpperCamelCase : int = Process('P1', 0, 53) __UpperCamelCase : str = Process('P2', 0, 17) __UpperCamelCase : List[Any] = Process('P3', 0, 68) __UpperCamelCase : int = Process('P4', 0, 24) __UpperCamelCase : Optional[int] = 3 __UpperCamelCase : List[Any] = [17, 25] __UpperCamelCase : Union[str, Any] = deque([Pa, Pa, Pa, Pa]) if len(time_slices) != number_of_queues - 1: raise SystemExit(0) doctest.testmod(extraglobs={'queue': deque([Pa, Pa, Pa, Pa])}) __UpperCamelCase : int = Process('P1', 0, 53) __UpperCamelCase : Optional[int] = Process('P2', 0, 17) __UpperCamelCase : str = Process('P3', 0, 68) __UpperCamelCase : List[str] = Process('P4', 0, 24) __UpperCamelCase : str = 3 __UpperCamelCase : Union[str, Any] = [17, 25] __UpperCamelCase : int = deque([Pa, Pa, Pa, Pa]) __UpperCamelCase : Dict = MLFQ(number_of_queues, time_slices, queue, 0) __UpperCamelCase : Optional[int] = mlfq.multi_level_feedback_queue() # print total waiting times of processes(P1, P2, P3, P4) print( f"""waiting time:\ \t\t\t{MLFQ.calculate_waiting_time(mlfq, [Pa, Pa, Pa, Pa])}""" ) # print completion times of processes(P1, P2, P3, P4) print( f"""completion time:\ \t\t{MLFQ.calculate_completion_time(mlfq, [Pa, Pa, Pa, Pa])}""" ) # print total turnaround times of processes(P1, P2, P3, P4) print( f"""turnaround time:\ \t\t{MLFQ.calculate_turnaround_time(mlfq, [Pa, Pa, Pa, Pa])}""" ) # print sequence of finished processes print( f"""sequence of finished processes:\ {mlfq.calculate_sequence_of_finish_queue()}""" )
718
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __UpperCamelCase : Tuple = { 'configuration_ctrl': ['CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP', 'CTRLConfig'], 'tokenization_ctrl': ['CTRLTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Dict = [ 'CTRL_PRETRAINED_MODEL_ARCHIVE_LIST', 'CTRLForSequenceClassification', 'CTRLLMHeadModel', 'CTRLModel', 'CTRLPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Any = [ 'TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFCTRLForSequenceClassification', 'TFCTRLLMHeadModel', 'TFCTRLModel', 'TFCTRLPreTrainedModel', ] if TYPE_CHECKING: from .configuration_ctrl import CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRLConfig from .tokenization_ctrl import CTRLTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ctrl import ( CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, CTRLForSequenceClassification, CTRLLMHeadModel, CTRLModel, CTRLPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_ctrl import ( TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, TFCTRLForSequenceClassification, TFCTRLLMHeadModel, TFCTRLModel, TFCTRLPreTrainedModel, ) else: import sys __UpperCamelCase : Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
34
0
import json import os from typing import Optional, Tuple import regex as re from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging __UpperCamelCase : Tuple = logging.get_logger(__name__) __UpperCamelCase : Tuple = { """vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", } __UpperCamelCase : Optional[Any] = { """vocab_file""": {"""ctrl""": """https://raw.githubusercontent.com/salesforce/ctrl/master/ctrl-vocab.json"""}, """merges_file""": {"""ctrl""": """https://raw.githubusercontent.com/salesforce/ctrl/master/ctrl-merges.txt"""}, } __UpperCamelCase : List[Any] = { """ctrl""": 256, } __UpperCamelCase : Union[str, Any] = { """Pregnancy""": 16_8629, """Christianity""": 7675, """Explain""": 10_6423, """Fitness""": 6_3440, """Saving""": 6_3163, """Ask""": 2_7171, """Ass""": 9_5985, """Joke""": 16_3509, """Questions""": 4_5622, """Thoughts""": 4_9605, """Retail""": 5_2342, """Feminism""": 16_4338, """Writing""": 1_1992, """Atheism""": 19_2263, """Netflix""": 4_8616, """Computing""": 3_9639, """Opinion""": 4_3213, """Alone""": 4_4967, """Funny""": 5_8917, """Gaming""": 4_0358, """Human""": 4088, """India""": 1331, """Joker""": 7_7138, """Diet""": 3_6206, """Legal""": 1_1859, """Norman""": 4939, """Tip""": 7_2689, """Weight""": 5_2343, """Movies""": 4_6273, """Running""": 2_3425, """Science""": 2090, """Horror""": 3_7793, """Confession""": 6_0572, """Finance""": 1_2250, """Politics""": 1_6360, """Scary""": 19_1985, """Support""": 1_2654, """Technologies""": 3_2516, """Teenage""": 6_6160, """Event""": 3_2769, """Learned""": 6_7460, """Notion""": 18_2770, """Wikipedia""": 3_7583, """Books""": 6665, """Extract""": 7_6050, """Confessions""": 10_2701, """Conspiracy""": 7_5932, """Links""": 6_3674, """Narcissus""": 15_0425, """Relationship""": 5_4766, """Relationships""": 13_4796, """Reviews""": 4_1671, """News""": 4256, """Translation""": 2_6820, """multilingual""": 12_8406, } def A ( _lowercase ): SCREAMING_SNAKE_CASE : List[str] = set() SCREAMING_SNAKE_CASE : Optional[int] = word[0] for char in word[1:]: pairs.add((prev_char, char) ) SCREAMING_SNAKE_CASE : Any = char SCREAMING_SNAKE_CASE : List[str] = set(UpperCamelCase__ ) return pairs class lowercase__ ( lowercase_): UpperCamelCase_ = VOCAB_FILES_NAMES UpperCamelCase_ = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase_ = CONTROL_CODES def __init__( self : int , UpperCamelCase__ : List[str] , UpperCamelCase__ : int , UpperCamelCase__ : Dict="<unk>" , **UpperCamelCase__ : Optional[Any] ): '''simple docstring''' super().__init__(unk_token=UpperCamelCase__ , **UpperCamelCase__ ) with open(UpperCamelCase__ , encoding='''utf-8''' ) as vocab_handle: SCREAMING_SNAKE_CASE : Any = json.load(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : str = {v: k for k, v in self.encoder.items()} with open(UpperCamelCase__ , encoding='''utf-8''' ) as merges_handle: SCREAMING_SNAKE_CASE : List[Any] = merges_handle.read().split('''\n''' )[1:-1] SCREAMING_SNAKE_CASE : List[str] = [tuple(merge.split() ) for merge in merges] SCREAMING_SNAKE_CASE : Optional[int] = dict(zip(UpperCamelCase__ , range(len(UpperCamelCase__ ) ) ) ) SCREAMING_SNAKE_CASE : Any = {} @property def __A ( self : Optional[Any] ): '''simple docstring''' return len(self.encoder ) def __A ( self : int ): '''simple docstring''' return dict(self.encoder , **self.added_tokens_encoder ) def __A ( self : str , UpperCamelCase__ : Optional[int] ): '''simple docstring''' if token in self.cache: return self.cache[token] SCREAMING_SNAKE_CASE : List[Any] = tuple(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[str] = tuple(list(word[:-1] ) + [word[-1] + '''</w>'''] ) SCREAMING_SNAKE_CASE : List[str] = get_pairs(UpperCamelCase__ ) if not pairs: return token while True: SCREAMING_SNAKE_CASE : Optional[Any] = min(UpperCamelCase__ , key=lambda UpperCamelCase__ : self.bpe_ranks.get(UpperCamelCase__ , float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = bigram SCREAMING_SNAKE_CASE : List[Any] = [] SCREAMING_SNAKE_CASE : Optional[Any] = 0 while i < len(UpperCamelCase__ ): try: SCREAMING_SNAKE_CASE : List[Any] = word.index(UpperCamelCase__ , UpperCamelCase__ ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) SCREAMING_SNAKE_CASE : Dict = j if word[i] == first and i < len(UpperCamelCase__ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 SCREAMING_SNAKE_CASE : str = tuple(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Dict = new_word if len(UpperCamelCase__ ) == 1: break else: SCREAMING_SNAKE_CASE : Tuple = get_pairs(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : str = '''@@ '''.join(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : str = word[:-4] SCREAMING_SNAKE_CASE : Dict = word return word def __A ( self : List[str] , UpperCamelCase__ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = [] SCREAMING_SNAKE_CASE : int = re.findall(r'''\S+\n?''' , UpperCamelCase__ ) for token in words: split_tokens.extend(list(self.bpe(UpperCamelCase__ ).split(''' ''' ) ) ) return split_tokens def __A ( self : Tuple , UpperCamelCase__ : Tuple ): '''simple docstring''' return self.encoder.get(UpperCamelCase__ , self.encoder.get(self.unk_token ) ) def __A ( self : Optional[Any] , UpperCamelCase__ : Dict ): '''simple docstring''' return self.decoder.get(UpperCamelCase__ , self.unk_token ) def __A ( self : List[str] , UpperCamelCase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = ''' '''.join(UpperCamelCase__ ).replace('''@@ ''' , '''''' ).strip() return out_string def __A ( self : Dict , UpperCamelCase__ : int , UpperCamelCase__ : int = None ): '''simple docstring''' if not os.path.isdir(UpperCamelCase__ ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return SCREAMING_SNAKE_CASE : List[Any] = os.path.join( UpperCamelCase__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) SCREAMING_SNAKE_CASE : Dict = os.path.join( UpperCamelCase__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) with open(UpperCamelCase__ , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=UpperCamelCase__ , ensure_ascii=UpperCamelCase__ ) + '''\n''' ) SCREAMING_SNAKE_CASE : str = 0 with open(UpperCamelCase__ , '''w''' , encoding='''utf-8''' ) as writer: writer.write('''#version: 0.2\n''' ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda UpperCamelCase__ : kv[1] ): if index != token_index: logger.warning( f"""Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.""" ''' Please check that the tokenizer is not corrupted!''' ) SCREAMING_SNAKE_CASE : Any = token_index writer.write(''' '''.join(UpperCamelCase__ ) + '''\n''' ) index += 1 return vocab_file, merge_file # def decode(self, token_ids, skip_special_tokens=False, clean_up_tokenization_spaces=True): # filtered_tokens = ' '.join(self.convert_ids_to_tokens(token_ids, skip_special_tokens=skip_special_tokens)) # tokens_generated_so_far = re.sub('(@@ )', '', string=filtered_tokens) # tokens_generated_so_far = re.sub('(@@ ?$)', '', string=tokens_generated_so_far) # return ''.join(tokens_generated_so_far)
719
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __UpperCamelCase : Tuple = { 'configuration_maskformer': ['MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MaskFormerConfig'], 'configuration_maskformer_swin': ['MaskFormerSwinConfig'], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Optional[Any] = ['MaskFormerFeatureExtractor'] __UpperCamelCase : List[Any] = ['MaskFormerImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Optional[int] = [ 'MASKFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'MaskFormerForInstanceSegmentation', 'MaskFormerModel', 'MaskFormerPreTrainedModel', ] __UpperCamelCase : Union[str, Any] = [ 'MaskFormerSwinBackbone', 'MaskFormerSwinModel', 'MaskFormerSwinPreTrainedModel', ] if TYPE_CHECKING: from .configuration_maskformer import MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskFormerConfig from .configuration_maskformer_swin import MaskFormerSwinConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_maskformer import MaskFormerFeatureExtractor from .image_processing_maskformer import MaskFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskformer import ( MASKFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskFormerForInstanceSegmentation, MaskFormerModel, MaskFormerPreTrainedModel, ) from .modeling_maskformer_swin import ( MaskFormerSwinBackbone, MaskFormerSwinModel, MaskFormerSwinPreTrainedModel, ) else: import sys __UpperCamelCase : List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure)
34
0
import unittest from transformers import DebertaVaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DebertaVaForMaskedLM, DebertaVaForMultipleChoice, DebertaVaForQuestionAnswering, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaModel, ) from transformers.models.deberta_va.modeling_deberta_va import DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST class lowercase__ ( UpperCamelCase_): def __init__( self : Tuple , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Tuple=13 , UpperCamelCase__ : Tuple=7 , UpperCamelCase__ : List[Any]=True , UpperCamelCase__ : int=True , UpperCamelCase__ : int=True , UpperCamelCase__ : Tuple=True , UpperCamelCase__ : Optional[int]=99 , UpperCamelCase__ : Optional[Any]=32 , UpperCamelCase__ : Any=5 , UpperCamelCase__ : str=4 , UpperCamelCase__ : Union[str, Any]=37 , UpperCamelCase__ : int="gelu" , UpperCamelCase__ : List[str]=0.1 , UpperCamelCase__ : Union[str, Any]=0.1 , UpperCamelCase__ : List[str]=512 , UpperCamelCase__ : Any=16 , UpperCamelCase__ : str=2 , UpperCamelCase__ : Any=0.02 , UpperCamelCase__ : Tuple=False , UpperCamelCase__ : Optional[Any]=True , UpperCamelCase__ : Dict="None" , UpperCamelCase__ : Tuple=3 , UpperCamelCase__ : Union[str, Any]=4 , UpperCamelCase__ : Union[str, Any]=None , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = parent SCREAMING_SNAKE_CASE : Union[str, Any] = batch_size SCREAMING_SNAKE_CASE : List[str] = seq_length SCREAMING_SNAKE_CASE : Optional[int] = is_training SCREAMING_SNAKE_CASE : Dict = use_input_mask SCREAMING_SNAKE_CASE : Optional[Any] = use_token_type_ids SCREAMING_SNAKE_CASE : Optional[int] = use_labels SCREAMING_SNAKE_CASE : Union[str, Any] = vocab_size SCREAMING_SNAKE_CASE : str = hidden_size SCREAMING_SNAKE_CASE : List[Any] = num_hidden_layers SCREAMING_SNAKE_CASE : int = num_attention_heads SCREAMING_SNAKE_CASE : Tuple = intermediate_size SCREAMING_SNAKE_CASE : str = hidden_act SCREAMING_SNAKE_CASE : Optional[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE : List[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : Union[str, Any] = max_position_embeddings SCREAMING_SNAKE_CASE : str = type_vocab_size SCREAMING_SNAKE_CASE : List[str] = type_sequence_label_size SCREAMING_SNAKE_CASE : Tuple = initializer_range SCREAMING_SNAKE_CASE : List[str] = num_labels SCREAMING_SNAKE_CASE : Tuple = num_choices SCREAMING_SNAKE_CASE : Union[str, Any] = relative_attention SCREAMING_SNAKE_CASE : Any = position_biased_input SCREAMING_SNAKE_CASE : str = pos_att_type SCREAMING_SNAKE_CASE : List[Any] = scope def __A ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE : Optional[Any] = None if self.use_input_mask: SCREAMING_SNAKE_CASE : int = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) SCREAMING_SNAKE_CASE : int = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE : List[Any] = None SCREAMING_SNAKE_CASE : int = None SCREAMING_SNAKE_CASE : Dict = None if self.use_labels: SCREAMING_SNAKE_CASE : List[str] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE : Union[str, Any] = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE : List[Any] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __A ( self : str ): '''simple docstring''' return DebertaVaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , pos_att_type=self.pos_att_type , ) def __A ( self : int , UpperCamelCase__ : List[Any] ): '''simple docstring''' self.parent.assertListEqual(list(result.loss.size() ) , [] ) def __A ( self : str , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Tuple , UpperCamelCase__ : Dict , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : str , UpperCamelCase__ : str , UpperCamelCase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = DebertaVaModel(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() SCREAMING_SNAKE_CASE : Any = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ )[0] SCREAMING_SNAKE_CASE : int = model(UpperCamelCase__ , token_type_ids=UpperCamelCase__ )[0] SCREAMING_SNAKE_CASE : Dict = model(UpperCamelCase__ )[0] self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] ) def __A ( self : int , UpperCamelCase__ : Any , UpperCamelCase__ : Tuple , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Dict , UpperCamelCase__ : int , UpperCamelCase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = DebertaVaForMaskedLM(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() SCREAMING_SNAKE_CASE : Any = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __A ( self : Any , UpperCamelCase__ : List[str] , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : str , UpperCamelCase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = self.num_labels SCREAMING_SNAKE_CASE : List[Any] = DebertaVaForSequenceClassification(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() SCREAMING_SNAKE_CASE : str = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ ) self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] ) self.check_loss_output(UpperCamelCase__ ) def __A ( self : int , UpperCamelCase__ : str , UpperCamelCase__ : Dict , UpperCamelCase__ : int , UpperCamelCase__ : List[str] , UpperCamelCase__ : Tuple , UpperCamelCase__ : List[str] , UpperCamelCase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = self.num_labels SCREAMING_SNAKE_CASE : List[str] = DebertaVaForTokenClassification(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() SCREAMING_SNAKE_CASE : Optional[Any] = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __A ( self : Union[str, Any] , UpperCamelCase__ : Tuple , UpperCamelCase__ : int , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : List[Any] , UpperCamelCase__ : int , UpperCamelCase__ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = DebertaVaForQuestionAnswering(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() SCREAMING_SNAKE_CASE : Tuple = model( UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , start_positions=UpperCamelCase__ , end_positions=UpperCamelCase__ , ) 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 __A ( self : int , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : Tuple , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : str , UpperCamelCase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = DebertaVaForMultipleChoice(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() SCREAMING_SNAKE_CASE : List[Any] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE : Union[str, Any] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE : Optional[int] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE : Union[str, Any] = model( UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __A ( self : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ) : Tuple = config_and_inputs SCREAMING_SNAKE_CASE : Optional[Any] = {'''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_ = ( ( DebertaVaModel, DebertaVaForMaskedLM, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaForQuestionAnswering, DebertaVaForMultipleChoice, ) if is_torch_available() else () ) UpperCamelCase_ = ( { """feature-extraction""": DebertaVaModel, """fill-mask""": DebertaVaForMaskedLM, """question-answering""": DebertaVaForQuestionAnswering, """text-classification""": DebertaVaForSequenceClassification, """token-classification""": DebertaVaForTokenClassification, """zero-shot""": DebertaVaForSequenceClassification, } if is_torch_available() else {} ) UpperCamelCase_ = True UpperCamelCase_ = False UpperCamelCase_ = False UpperCamelCase_ = False UpperCamelCase_ = False def __A ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = DebertaVaModelTester(self ) SCREAMING_SNAKE_CASE : Optional[Any] = ConfigTester(self , config_class=UpperCamelCase__ , hidden_size=37 ) def __A ( self : List[str] ): '''simple docstring''' self.config_tester.run_common_tests() def __A ( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*UpperCamelCase__ ) def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*UpperCamelCase__ ) def __A ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*UpperCamelCase__ ) def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*UpperCamelCase__ ) def __A ( self : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*UpperCamelCase__ ) def __A ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_multiple_choice(*UpperCamelCase__ ) @slow def __A ( self : Dict ): '''simple docstring''' for model_name in DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE : str = DebertaVaModel.from_pretrained(UpperCamelCase__ ) self.assertIsNotNone(UpperCamelCase__ ) @require_torch @require_sentencepiece @require_tokenizers class lowercase__ ( unittest.TestCase): @unittest.skip(reason='''Model not available yet''' ) def __A ( self : Optional[Any] ): '''simple docstring''' pass @slow def __A ( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = DebertaVaModel.from_pretrained('''microsoft/deberta-v2-xlarge''' ) SCREAMING_SNAKE_CASE : Any = torch.tensor([[0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2]] ) SCREAMING_SNAKE_CASE : str = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): SCREAMING_SNAKE_CASE : Tuple = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ )[0] # compare the actual values for a slice. SCREAMING_SNAKE_CASE : int = torch.tensor( [[[0.2356, 0.1948, 0.0369], [-0.1063, 0.3586, -0.5152], [-0.6399, -0.0259, -0.2525]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , UpperCamelCase__ , atol=1E-4 ) , f"""{output[:, 1:4, 1:4]}""" )
720
# 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 from ...utils.dataclasses import ( ComputeEnvironment, DistributedType, DynamoBackend, PrecisionType, SageMakerDistributedType, ) from ..menu import BulletMenu __UpperCamelCase : Dict = [ 'EAGER', 'AOT_EAGER', 'INDUCTOR', 'NVFUSER', 'AOT_NVFUSER', 'AOT_CUDAGRAPHS', 'OFI', 'FX2TRT', 'ONNXRT', 'IPEX', ] def A ( _lowercase , _lowercase=None , _lowercase=None , _lowercase=None ): SCREAMING_SNAKE_CASE : Union[str, Any] = True while ask_again: SCREAMING_SNAKE_CASE : Optional[Any] = input(_lowercase ) try: if default is not None and len(_lowercase ) == 0: return default return convert_value(_lowercase ) if convert_value is not None else result except Exception: if error_message is not None: print(_lowercase ) def A ( _lowercase , _lowercase=[] , _lowercase=None , _lowercase=0 ): SCREAMING_SNAKE_CASE : Dict = BulletMenu(_lowercase , _lowercase ) SCREAMING_SNAKE_CASE : str = menu.run(default_choice=_lowercase ) return convert_value(_lowercase ) if convert_value is not None else result def A ( _lowercase ): SCREAMING_SNAKE_CASE : Dict = int(_lowercase ) return ComputeEnvironment(['''LOCAL_MACHINE''', '''AMAZON_SAGEMAKER'''][value] ) def A ( _lowercase ): SCREAMING_SNAKE_CASE : Any = int(_lowercase ) return DistributedType(['''NO''', '''MULTI_CPU''', '''MULTI_XPU''', '''MULTI_GPU''', '''MULTI_NPU''', '''TPU'''][value] ) def A ( _lowercase ): SCREAMING_SNAKE_CASE : Union[str, Any] = int(_lowercase ) return DynamoBackend(DYNAMO_BACKENDS[value] ).value def A ( _lowercase ): SCREAMING_SNAKE_CASE : Union[str, Any] = int(_lowercase ) return PrecisionType(['''no''', '''fp16''', '''bf16''', '''fp8'''][value] ) def A ( _lowercase ): SCREAMING_SNAKE_CASE : Dict = int(_lowercase ) return SageMakerDistributedType(['''NO''', '''DATA_PARALLEL''', '''MODEL_PARALLEL'''][value] ) def A ( _lowercase ): return {"yes": True, "no": False}[value.lower()] class lowercase__ ( argparse.RawDescriptionHelpFormatter): def __A ( self : List[str] , UpperCamelCase__ : List[str] , UpperCamelCase__ : Dict , UpperCamelCase__ : Dict , UpperCamelCase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = super()._format_usage(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[Any] = usage.replace('''<command> [<args>] ''' , '''''' ) return usage
34
0
from __future__ import annotations import json import requests from bsa import BeautifulSoup from fake_useragent import UserAgent __UpperCamelCase : Optional[int] = {'UserAgent': UserAgent().random} def A ( _lowercase ): SCREAMING_SNAKE_CASE : List[str] = script.contents[0] SCREAMING_SNAKE_CASE : Any = json.loads(data[data.find('''{"config"''' ) : -1] ) return info["entry_data"]["ProfilePage"][0]["graphql"]["user"] class lowercase__ : def __init__( self : Optional[int] , UpperCamelCase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = f"""https://www.instagram.com/{username}/""" SCREAMING_SNAKE_CASE : Any = self.get_json() def __A ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = requests.get(self.url , headers=_SCREAMING_SNAKE_CASE ).text SCREAMING_SNAKE_CASE : Any = BeautifulSoup(_SCREAMING_SNAKE_CASE , '''html.parser''' ).find_all('''script''' ) try: return extract_user_profile(scripts[4] ) except (json.decoder.JSONDecodeError, KeyError): return extract_user_profile(scripts[3] ) def __repr__( self : Optional[int] ): '''simple docstring''' return f"""{self.__class__.__name__}(\'{self.username}\')""" def __str__( self : Any ): '''simple docstring''' return f"""{self.fullname} ({self.username}) is {self.biography}""" @property def __A ( self : Union[str, Any] ): '''simple docstring''' return self.user_data["username"] @property def __A ( self : Dict ): '''simple docstring''' return self.user_data["full_name"] @property def __A ( self : Any ): '''simple docstring''' return self.user_data["biography"] @property def __A ( self : int ): '''simple docstring''' return self.user_data["business_email"] @property def __A ( self : Any ): '''simple docstring''' return self.user_data["external_url"] @property def __A ( self : Any ): '''simple docstring''' return self.user_data["edge_followed_by"]["count"] @property def __A ( self : Optional[Any] ): '''simple docstring''' return self.user_data["edge_follow"]["count"] @property def __A ( self : str ): '''simple docstring''' return self.user_data["edge_owner_to_timeline_media"]["count"] @property def __A ( self : int ): '''simple docstring''' return self.user_data["profile_pic_url_hd"] @property def __A ( self : Optional[int] ): '''simple docstring''' return self.user_data["is_verified"] @property def __A ( self : Union[str, Any] ): '''simple docstring''' return self.user_data["is_private"] def A ( _lowercase = "github" ): import os if os.environ.get('''CI''' ): return # test failing on GitHub Actions SCREAMING_SNAKE_CASE : int = InstagramUser(_lowercase ) assert instagram_user.user_data assert isinstance(instagram_user.user_data , _lowercase ) assert instagram_user.username == username if username != "github": return assert instagram_user.fullname == "GitHub" assert instagram_user.biography == "Built for developers." assert instagram_user.number_of_posts > 150 assert instagram_user.number_of_followers > 120_000 assert instagram_user.number_of_followings > 15 assert instagram_user.email == "support@github.com" assert instagram_user.website == "https://github.com/readme" assert instagram_user.profile_picture_url.startswith('''https://instagram.''' ) assert instagram_user.is_verified is True assert instagram_user.is_private is False if __name__ == "__main__": import doctest doctest.testmod() __UpperCamelCase : List[Any] = InstagramUser('github') print(instagram_user) print(f"""{instagram_user.number_of_posts = }""") print(f"""{instagram_user.number_of_followers = }""") print(f"""{instagram_user.number_of_followings = }""") print(f"""{instagram_user.email = }""") print(f"""{instagram_user.website = }""") print(f"""{instagram_user.profile_picture_url = }""") print(f"""{instagram_user.is_verified = }""") print(f"""{instagram_user.is_private = }""")
721
from __future__ import annotations from typing import Any class lowercase__ ( UpperCamelCase_): pass class lowercase__ : def __init__( self : Union[str, Any] , UpperCamelCase__ : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = data SCREAMING_SNAKE_CASE : Node | None = None def __iter__( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = self SCREAMING_SNAKE_CASE : Tuple = [] while node: if node in visited: raise ContainsLoopError visited.append(UpperCamelCase__ ) yield node.data SCREAMING_SNAKE_CASE : Dict = node.next_node @property def __A ( self : Optional[int] ): '''simple docstring''' try: list(self ) return False except ContainsLoopError: return True if __name__ == "__main__": __UpperCamelCase : List[Any] = Node(1) __UpperCamelCase : str = Node(2) __UpperCamelCase : Dict = Node(3) __UpperCamelCase : List[Any] = Node(4) print(root_node.has_loop) # False __UpperCamelCase : int = root_node.next_node print(root_node.has_loop) # True __UpperCamelCase : Union[str, Any] = Node(5) __UpperCamelCase : Union[str, Any] = Node(6) __UpperCamelCase : List[Any] = Node(5) __UpperCamelCase : List[str] = Node(6) print(root_node.has_loop) # False __UpperCamelCase : List[Any] = Node(1) print(root_node.has_loop) # False
34
0
import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import SPIECE_UNDERLINE, logging __UpperCamelCase : Tuple = logging.get_logger(__name__) __UpperCamelCase : Dict = {'vocab_file': 'spiece.model'} __UpperCamelCase : Dict = { 'vocab_file': { 'xlnet-base-cased': 'https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model', 'xlnet-large-cased': 'https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model', } } __UpperCamelCase : Optional[Any] = { 'xlnet-base-cased': None, 'xlnet-large-cased': None, } # Segments (not really needed) __UpperCamelCase : List[str] = 0 __UpperCamelCase : Tuple = 1 __UpperCamelCase : Dict = 2 __UpperCamelCase : Optional[Any] = 3 __UpperCamelCase : List[Any] = 4 class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = VOCAB_FILES_NAMES UpperCamelCase_ = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase_ = """left""" def __init__( self : Union[str, Any] , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Any=False , UpperCamelCase__ : str=True , UpperCamelCase__ : List[Any]=False , UpperCamelCase__ : str="<s>" , UpperCamelCase__ : Optional[int]="</s>" , UpperCamelCase__ : Optional[Any]="<unk>" , UpperCamelCase__ : Optional[int]="<sep>" , UpperCamelCase__ : List[str]="<pad>" , UpperCamelCase__ : Tuple="<cls>" , UpperCamelCase__ : Union[str, Any]="<mask>" , UpperCamelCase__ : List[Any]=["<eop>", "<eod>"] , UpperCamelCase__ : Optional[Dict[str, Any]] = None , **UpperCamelCase__ : List[str] , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = AddedToken(UpperCamelCase__ , lstrip=UpperCamelCase__ , rstrip=UpperCamelCase__ ) if isinstance(UpperCamelCase__ , UpperCamelCase__ ) else mask_token SCREAMING_SNAKE_CASE : str = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=UpperCamelCase__ , remove_space=UpperCamelCase__ , keep_accents=UpperCamelCase__ , bos_token=UpperCamelCase__ , eos_token=UpperCamelCase__ , unk_token=UpperCamelCase__ , sep_token=UpperCamelCase__ , pad_token=UpperCamelCase__ , cls_token=UpperCamelCase__ , mask_token=UpperCamelCase__ , additional_special_tokens=UpperCamelCase__ , sp_model_kwargs=self.sp_model_kwargs , **UpperCamelCase__ , ) SCREAMING_SNAKE_CASE : List[str] = 3 SCREAMING_SNAKE_CASE : Tuple = do_lower_case SCREAMING_SNAKE_CASE : Dict = remove_space SCREAMING_SNAKE_CASE : Optional[int] = keep_accents SCREAMING_SNAKE_CASE : List[Any] = vocab_file SCREAMING_SNAKE_CASE : Any = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(UpperCamelCase__ ) @property def __A ( self : str ): '''simple docstring''' return len(self.sp_model ) def __A ( self : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = {self.convert_ids_to_tokens(UpperCamelCase__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = self.__dict__.copy() SCREAMING_SNAKE_CASE : Tuple = None return state def __setstate__( self : Optional[int] , UpperCamelCase__ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): SCREAMING_SNAKE_CASE : Optional[Any] = {} SCREAMING_SNAKE_CASE : Dict = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def __A ( self : Tuple , UpperCamelCase__ : List[str] ): '''simple docstring''' if self.remove_space: SCREAMING_SNAKE_CASE : List[Any] = ''' '''.join(inputs.strip().split() ) else: SCREAMING_SNAKE_CASE : List[str] = inputs SCREAMING_SNAKE_CASE : List[str] = outputs.replace('''``''' , '''"''' ).replace('''\'\'''' , '''"''' ) if not self.keep_accents: SCREAMING_SNAKE_CASE : Any = unicodedata.normalize('''NFKD''' , UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[str] = ''''''.join([c for c in outputs if not unicodedata.combining(UpperCamelCase__ )] ) if self.do_lower_case: SCREAMING_SNAKE_CASE : Union[str, Any] = outputs.lower() return outputs def __A ( self : Any , UpperCamelCase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = self.preprocess_text(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[Any] = self.sp_model.encode(UpperCamelCase__ , out_type=UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[int] = [] for piece in pieces: if len(UpperCamelCase__ ) > 1 and piece[-1] == str(''',''' ) and piece[-2].isdigit(): SCREAMING_SNAKE_CASE : str = self.sp_model.EncodeAsPieces(piece[:-1].replace(UpperCamelCase__ , '''''' ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: SCREAMING_SNAKE_CASE : Tuple = cur_pieces[1:] else: SCREAMING_SNAKE_CASE : Union[str, Any] = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(UpperCamelCase__ ) else: new_pieces.append(UpperCamelCase__ ) return new_pieces def __A ( self : Any , UpperCamelCase__ : List[str] ): '''simple docstring''' return self.sp_model.PieceToId(UpperCamelCase__ ) def __A ( self : Any , UpperCamelCase__ : List[Any] ): '''simple docstring''' return self.sp_model.IdToPiece(UpperCamelCase__ ) def __A ( self : List[str] , UpperCamelCase__ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = ''''''.join(UpperCamelCase__ ).replace(UpperCamelCase__ , ''' ''' ).strip() return out_string def __A ( self : Optional[int] , UpperCamelCase__ : List[int] , UpperCamelCase__ : bool = False , UpperCamelCase__ : bool = None , UpperCamelCase__ : bool = True , **UpperCamelCase__ : Optional[int] , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = kwargs.pop('''use_source_tokenizer''' , UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Tuple = self.convert_ids_to_tokens(UpperCamelCase__ , skip_special_tokens=UpperCamelCase__ ) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 SCREAMING_SNAKE_CASE : Tuple = [] SCREAMING_SNAKE_CASE : Optional[int] = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE : List[str] = [] sub_texts.append(UpperCamelCase__ ) else: current_sub_text.append(UpperCamelCase__ ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(UpperCamelCase__ ) ) # Mimic the behavior of the Rust tokenizer: # By default, there are no spaces between special tokens SCREAMING_SNAKE_CASE : Any = ''''''.join(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[int] = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: SCREAMING_SNAKE_CASE : Dict = self.clean_up_tokenization(UpperCamelCase__ ) return clean_text else: return text def __A ( self : List[str] , UpperCamelCase__ : List[int] , UpperCamelCase__ : Optional[List[int]] = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = [self.sep_token_id] SCREAMING_SNAKE_CASE : List[Any] = [self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def __A ( self : List[str] , UpperCamelCase__ : List[int] , UpperCamelCase__ : Optional[List[int]] = None , UpperCamelCase__ : bool = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=UpperCamelCase__ , token_ids_a=UpperCamelCase__ , already_has_special_tokens=UpperCamelCase__ ) if token_ids_a is not None: return ([0] * len(UpperCamelCase__ )) + [1] + ([0] * len(UpperCamelCase__ )) + [1, 1] return ([0] * len(UpperCamelCase__ )) + [1, 1] def __A ( self : Optional[Any] , UpperCamelCase__ : List[int] , UpperCamelCase__ : Optional[List[int]] = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = [self.sep_token_id] SCREAMING_SNAKE_CASE : Dict = [2] if token_ids_a is None: return len(token_ids_a + sep ) * [0] + cls_segment_id return len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] + cls_segment_id def __A ( self : List[Any] , UpperCamelCase__ : str , UpperCamelCase__ : Optional[str] = None ): '''simple docstring''' if not os.path.isdir(UpperCamelCase__ ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return SCREAMING_SNAKE_CASE : List[Any] = os.path.join( UpperCamelCase__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCamelCase__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , UpperCamelCase__ ) elif not os.path.isfile(self.vocab_file ): with open(UpperCamelCase__ , '''wb''' ) as fi: SCREAMING_SNAKE_CASE : Union[str, Any] = self.sp_model.serialized_model_proto() fi.write(UpperCamelCase__ ) return (out_vocab_file,)
700
import copy from typing import Any, Dict, List, Optional, Union import numpy as np import torch from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import TensorType, logging __UpperCamelCase : Union[str, Any] = logging.get_logger(__name__) class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = ["""input_features""", """is_longer"""] def __init__( self : Optional[Any] , UpperCamelCase__ : Dict=64 , UpperCamelCase__ : Optional[Any]=4_8000 , UpperCamelCase__ : Tuple=480 , UpperCamelCase__ : Union[str, Any]=10 , UpperCamelCase__ : List[Any]=1024 , UpperCamelCase__ : Tuple=0.0 , UpperCamelCase__ : int=False , UpperCamelCase__ : float = 0 , UpperCamelCase__ : float = 1_4000 , UpperCamelCase__ : int = None , UpperCamelCase__ : str = "fusion" , UpperCamelCase__ : str = "repeatpad" , **UpperCamelCase__ : Union[str, Any] , ): '''simple docstring''' super().__init__( feature_size=UpperCamelCase__ , sampling_rate=UpperCamelCase__ , padding_value=UpperCamelCase__ , return_attention_mask=UpperCamelCase__ , **UpperCamelCase__ , ) SCREAMING_SNAKE_CASE : Union[str, Any] = top_db SCREAMING_SNAKE_CASE : Union[str, Any] = truncation SCREAMING_SNAKE_CASE : str = padding SCREAMING_SNAKE_CASE : List[Any] = fft_window_size SCREAMING_SNAKE_CASE : Tuple = (fft_window_size >> 1) + 1 SCREAMING_SNAKE_CASE : List[str] = hop_length SCREAMING_SNAKE_CASE : List[Any] = max_length_s SCREAMING_SNAKE_CASE : Tuple = max_length_s * sampling_rate SCREAMING_SNAKE_CASE : List[Any] = sampling_rate SCREAMING_SNAKE_CASE : List[str] = frequency_min SCREAMING_SNAKE_CASE : Any = frequency_max SCREAMING_SNAKE_CASE : List[Any] = mel_filter_bank( num_frequency_bins=self.nb_frequency_bins , num_mel_filters=UpperCamelCase__ , min_frequency=UpperCamelCase__ , max_frequency=UpperCamelCase__ , sampling_rate=UpperCamelCase__ , norm=UpperCamelCase__ , mel_scale='''htk''' , ) SCREAMING_SNAKE_CASE : Optional[Any] = mel_filter_bank( num_frequency_bins=self.nb_frequency_bins , num_mel_filters=UpperCamelCase__ , min_frequency=UpperCamelCase__ , max_frequency=UpperCamelCase__ , sampling_rate=UpperCamelCase__ , norm='''slaney''' , mel_scale='''slaney''' , ) def __A ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE : Optional[Any] = self.__class__.__name__ if "mel_filters" in output: del output["mel_filters"] if "mel_filters_slaney" in output: del output["mel_filters_slaney"] return output def __A ( self : Optional[int] , UpperCamelCase__ : np.array , UpperCamelCase__ : Optional[np.array] = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = spectrogram( UpperCamelCase__ , window_function(self.fft_window_size , '''hann''' ) , frame_length=self.fft_window_size , hop_length=self.hop_length , power=2.0 , mel_filters=UpperCamelCase__ , log_mel='''dB''' , ) return log_mel_spectrogram.T def __A ( self : Union[str, Any] , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Dict , UpperCamelCase__ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = np.array_split(list(range(0 , total_frames - chunk_frames + 1 ) ) , 3 ) if len(ranges[1] ) == 0: # if the audio is too short, we just use the first chunk SCREAMING_SNAKE_CASE : int = [0] if len(ranges[2] ) == 0: # if the audio is too short, we just use the first chunk SCREAMING_SNAKE_CASE : Any = [0] # randomly choose index for each part SCREAMING_SNAKE_CASE : Union[str, Any] = np.random.choice(ranges[0] ) SCREAMING_SNAKE_CASE : List[Any] = np.random.choice(ranges[1] ) SCREAMING_SNAKE_CASE : int = np.random.choice(ranges[2] ) SCREAMING_SNAKE_CASE : Optional[int] = mel[idx_front : idx_front + chunk_frames, :] SCREAMING_SNAKE_CASE : Optional[Any] = mel[idx_middle : idx_middle + chunk_frames, :] SCREAMING_SNAKE_CASE : Tuple = mel[idx_back : idx_back + chunk_frames, :] SCREAMING_SNAKE_CASE : str = torch.tensor(mel[None, None, :] ) SCREAMING_SNAKE_CASE : Optional[int] = torch.nn.functional.interpolate( UpperCamelCase__ , size=[chunk_frames, 64] , mode='''bilinear''' , align_corners=UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[Any] = mel_shrink[0][0].numpy() SCREAMING_SNAKE_CASE : Union[str, Any] = np.stack([mel_shrink, mel_chunk_front, mel_chunk_middle, mel_chunk_back] , axis=0 ) return mel_fusion def __A ( self : Dict , UpperCamelCase__ : np.array , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Dict , UpperCamelCase__ : List[str] ): '''simple docstring''' if waveform.shape[0] > max_length: if truncation == "rand_trunc": SCREAMING_SNAKE_CASE : Optional[Any] = True # random crop to max_length (for compatibility) -> this should be handled by self.pad SCREAMING_SNAKE_CASE : List[Any] = len(UpperCamelCase__ ) - max_length SCREAMING_SNAKE_CASE : Dict = np.random.randint(0 , overflow + 1 ) SCREAMING_SNAKE_CASE : Optional[Any] = waveform[idx : idx + max_length] SCREAMING_SNAKE_CASE : Any = self._np_extract_fbank_features(UpperCamelCase__ , self.mel_filters_slaney )[None, :] elif truncation == "fusion": SCREAMING_SNAKE_CASE : Any = self._np_extract_fbank_features(UpperCamelCase__ , self.mel_filters ) SCREAMING_SNAKE_CASE : List[str] = max_length // self.hop_length + 1 # the +1 related to how the spectrogram is computed SCREAMING_SNAKE_CASE : List[Any] = mel.shape[0] if chunk_frames == total_frames: # there is a corner case where the audio length is larger than max_length but smaller than max_length+hop_length. # In this case, we just use the whole audio. SCREAMING_SNAKE_CASE : Optional[Any] = np.stack([mel, mel, mel, mel] , axis=0 ) SCREAMING_SNAKE_CASE : Tuple = False else: SCREAMING_SNAKE_CASE : str = self._random_mel_fusion(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[int] = True else: raise NotImplementedError(f"""data_truncating {truncation} not implemented""" ) else: SCREAMING_SNAKE_CASE : List[str] = False # only use repeat as a new possible value for padding. you repeat the audio before applying the usual max_length padding if waveform.shape[0] < max_length: if padding == "repeat": SCREAMING_SNAKE_CASE : Tuple = int(max_length / len(UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE : Any = np.stack(np.tile(UpperCamelCase__ , n_repeat + 1 ) )[:max_length] if padding == "repeatpad": SCREAMING_SNAKE_CASE : List[Any] = int(max_length / len(UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE : Dict = np.stack(np.tile(UpperCamelCase__ , UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE : Dict = np.pad(UpperCamelCase__ , (0, max_length - waveform.shape[0]) , mode='''constant''' , constant_values=0 ) if truncation == "fusion": SCREAMING_SNAKE_CASE : List[Any] = self._np_extract_fbank_features(UpperCamelCase__ , self.mel_filters ) SCREAMING_SNAKE_CASE : Union[str, Any] = np.stack([input_mel, input_mel, input_mel, input_mel] , axis=0 ) else: SCREAMING_SNAKE_CASE : List[str] = self._np_extract_fbank_features(UpperCamelCase__ , self.mel_filters_slaney )[None, :] return input_mel, longer def __call__( self : Union[str, Any] , UpperCamelCase__ : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , UpperCamelCase__ : str = None , UpperCamelCase__ : Optional[str] = None , UpperCamelCase__ : Optional[int] = None , UpperCamelCase__ : Optional[int] = None , UpperCamelCase__ : Optional[Union[str, TensorType]] = None , **UpperCamelCase__ : Any , ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = truncation if truncation is not None else self.truncation SCREAMING_SNAKE_CASE : List[str] = padding if padding else self.padding if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f"""The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a""" f""" sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input""" f""" was sampled with {self.sampling_rate} and not {sampling_rate}.""" ) else: logger.warning( '''It is strongly recommended to pass the `sampling_rate` argument to this function. ''' '''Failing to do so can result in silent errors that might be hard to debug.''' ) SCREAMING_SNAKE_CASE : List[str] = isinstance(UpperCamelCase__ , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f"""Only mono-channel audio is supported for input to {self}""" ) SCREAMING_SNAKE_CASE : int = is_batched_numpy or ( isinstance(UpperCamelCase__ , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: SCREAMING_SNAKE_CASE : Any = [np.asarray(UpperCamelCase__ , dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(UpperCamelCase__ , np.ndarray ): SCREAMING_SNAKE_CASE : List[Any] = np.asarray(UpperCamelCase__ , dtype=np.floataa ) elif isinstance(UpperCamelCase__ , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): SCREAMING_SNAKE_CASE : Union[str, Any] = raw_speech.astype(np.floataa ) # always return batch if not is_batched: SCREAMING_SNAKE_CASE : List[str] = [np.asarray(UpperCamelCase__ )] # convert to mel spectrogram, truncate and pad if needed. SCREAMING_SNAKE_CASE : int = [ self._get_input_mel(UpperCamelCase__ , max_length if max_length else self.nb_max_samples , UpperCamelCase__ , UpperCamelCase__ ) for waveform in raw_speech ] SCREAMING_SNAKE_CASE : str = [] SCREAMING_SNAKE_CASE : List[str] = [] for mel, longer in padded_inputs: input_mel.append(UpperCamelCase__ ) is_longer.append(UpperCamelCase__ ) if truncation == "fusion" and sum(UpperCamelCase__ ) == 0: # if no audio is longer than 10s, then randomly select one audio to be longer SCREAMING_SNAKE_CASE : Union[str, Any] = np.random.randint(0 , len(UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE : Optional[Any] = True if isinstance(input_mel[0] , UpperCamelCase__ ): SCREAMING_SNAKE_CASE : Union[str, Any] = [np.asarray(UpperCamelCase__ , dtype=np.floataa ) for feature in input_mel] # is_longer is a list of bool SCREAMING_SNAKE_CASE : Optional[Any] = [[longer] for longer in is_longer] SCREAMING_SNAKE_CASE : Union[str, Any] = {'''input_features''': input_mel, '''is_longer''': is_longer} SCREAMING_SNAKE_CASE : int = BatchFeature(UpperCamelCase__ ) if return_tensors is not None: SCREAMING_SNAKE_CASE : int = input_features.convert_to_tensors(UpperCamelCase__ ) return input_features
34
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __UpperCamelCase : Union[str, Any] = logging.get_logger(__name__) __UpperCamelCase : int = { 'facebook/data2vec-text-base': 'https://huggingface.co/data2vec/resolve/main/config.json', } class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = """data2vec-text""" def __init__( self : Optional[Any] , UpperCamelCase__ : List[str]=3_0522 , UpperCamelCase__ : Tuple=768 , UpperCamelCase__ : Optional[int]=12 , UpperCamelCase__ : str=12 , UpperCamelCase__ : int=3072 , UpperCamelCase__ : Any="gelu" , UpperCamelCase__ : str=0.1 , UpperCamelCase__ : str=0.1 , UpperCamelCase__ : Optional[int]=512 , UpperCamelCase__ : Optional[Any]=2 , UpperCamelCase__ : List[Any]=0.02 , UpperCamelCase__ : Union[str, Any]=1E-12 , UpperCamelCase__ : Tuple=1 , UpperCamelCase__ : Union[str, Any]=0 , UpperCamelCase__ : Dict=2 , UpperCamelCase__ : Any="absolute" , UpperCamelCase__ : Optional[int]=True , UpperCamelCase__ : List[Any]=None , **UpperCamelCase__ : Optional[Any] , ): '''simple docstring''' super().__init__(pad_token_id=UpperCamelCase__ , bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ , **UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Union[str, Any] = vocab_size SCREAMING_SNAKE_CASE : List[Any] = hidden_size SCREAMING_SNAKE_CASE : Union[str, Any] = num_hidden_layers SCREAMING_SNAKE_CASE : Optional[int] = num_attention_heads SCREAMING_SNAKE_CASE : Tuple = hidden_act SCREAMING_SNAKE_CASE : Optional[Any] = intermediate_size SCREAMING_SNAKE_CASE : str = hidden_dropout_prob SCREAMING_SNAKE_CASE : Any = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : Tuple = max_position_embeddings SCREAMING_SNAKE_CASE : str = type_vocab_size SCREAMING_SNAKE_CASE : Union[str, Any] = initializer_range SCREAMING_SNAKE_CASE : Union[str, Any] = layer_norm_eps SCREAMING_SNAKE_CASE : Union[str, Any] = position_embedding_type SCREAMING_SNAKE_CASE : Any = use_cache SCREAMING_SNAKE_CASE : str = classifier_dropout class lowercase__ ( UpperCamelCase_): @property def __A ( self : Tuple ): '''simple docstring''' if self.task == "multiple-choice": SCREAMING_SNAKE_CASE : Optional[Any] = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: SCREAMING_SNAKE_CASE : int = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ] )
701
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...utils import logging if TYPE_CHECKING: from ...processing_utils import ProcessorMixin from ...utils import TensorType __UpperCamelCase : str = logging.get_logger(__name__) __UpperCamelCase : str = { 'microsoft/layoutlmv3-base': 'https://huggingface.co/microsoft/layoutlmv3-base/resolve/main/config.json', } class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = """layoutlmv3""" def __init__( self : Optional[int] , UpperCamelCase__ : Union[str, Any]=5_0265 , UpperCamelCase__ : List[Any]=768 , UpperCamelCase__ : Union[str, Any]=12 , UpperCamelCase__ : Union[str, Any]=12 , UpperCamelCase__ : Tuple=3072 , UpperCamelCase__ : List[Any]="gelu" , UpperCamelCase__ : List[Any]=0.1 , UpperCamelCase__ : List[str]=0.1 , UpperCamelCase__ : Any=512 , UpperCamelCase__ : List[Any]=2 , UpperCamelCase__ : List[Any]=0.02 , UpperCamelCase__ : Optional[Any]=1E-5 , UpperCamelCase__ : List[str]=1 , UpperCamelCase__ : int=0 , UpperCamelCase__ : str=2 , UpperCamelCase__ : List[str]=1024 , UpperCamelCase__ : str=128 , UpperCamelCase__ : str=128 , UpperCamelCase__ : Tuple=True , UpperCamelCase__ : Optional[int]=32 , UpperCamelCase__ : Any=128 , UpperCamelCase__ : Optional[Any]=64 , UpperCamelCase__ : Dict=256 , UpperCamelCase__ : List[Any]=True , UpperCamelCase__ : str=True , UpperCamelCase__ : Dict=True , UpperCamelCase__ : Dict=224 , UpperCamelCase__ : Optional[Any]=3 , UpperCamelCase__ : Any=16 , UpperCamelCase__ : Any=None , **UpperCamelCase__ : Optional[Any] , ): '''simple docstring''' super().__init__( vocab_size=UpperCamelCase__ , hidden_size=UpperCamelCase__ , num_hidden_layers=UpperCamelCase__ , num_attention_heads=UpperCamelCase__ , intermediate_size=UpperCamelCase__ , hidden_act=UpperCamelCase__ , hidden_dropout_prob=UpperCamelCase__ , attention_probs_dropout_prob=UpperCamelCase__ , max_position_embeddings=UpperCamelCase__ , type_vocab_size=UpperCamelCase__ , initializer_range=UpperCamelCase__ , layer_norm_eps=UpperCamelCase__ , pad_token_id=UpperCamelCase__ , bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ , **UpperCamelCase__ , ) SCREAMING_SNAKE_CASE : Union[str, Any] = max_ad_position_embeddings SCREAMING_SNAKE_CASE : List[Any] = coordinate_size SCREAMING_SNAKE_CASE : List[str] = shape_size SCREAMING_SNAKE_CASE : Optional[int] = has_relative_attention_bias SCREAMING_SNAKE_CASE : List[Any] = rel_pos_bins SCREAMING_SNAKE_CASE : str = max_rel_pos SCREAMING_SNAKE_CASE : Any = has_spatial_attention_bias SCREAMING_SNAKE_CASE : Union[str, Any] = rel_ad_pos_bins SCREAMING_SNAKE_CASE : Union[str, Any] = max_rel_ad_pos SCREAMING_SNAKE_CASE : Union[str, Any] = text_embed SCREAMING_SNAKE_CASE : List[str] = visual_embed SCREAMING_SNAKE_CASE : Optional[Any] = input_size SCREAMING_SNAKE_CASE : Optional[Any] = num_channels SCREAMING_SNAKE_CASE : List[Any] = patch_size SCREAMING_SNAKE_CASE : List[Any] = classifier_dropout class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = version.parse("""1.12""") @property def __A ( self : str ): '''simple docstring''' if self.task in ["question-answering", "sequence-classification"]: return OrderedDict( [ ('''input_ids''', {0: '''batch''', 1: '''sequence'''}), ('''attention_mask''', {0: '''batch''', 1: '''sequence'''}), ('''bbox''', {0: '''batch''', 1: '''sequence'''}), ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) else: return OrderedDict( [ ('''input_ids''', {0: '''batch''', 1: '''sequence'''}), ('''bbox''', {0: '''batch''', 1: '''sequence'''}), ('''attention_mask''', {0: '''batch''', 1: '''sequence'''}), ('''pixel_values''', {0: '''batch''', 1: '''num_channels'''}), ] ) @property def __A ( self : int ): '''simple docstring''' return 1E-5 @property def __A ( self : Union[str, Any] ): '''simple docstring''' return 12 def __A ( self : Optional[Any] , UpperCamelCase__ : "ProcessorMixin" , UpperCamelCase__ : int = -1 , UpperCamelCase__ : int = -1 , UpperCamelCase__ : bool = False , UpperCamelCase__ : Optional["TensorType"] = None , UpperCamelCase__ : int = 3 , UpperCamelCase__ : int = 40 , UpperCamelCase__ : int = 40 , ): '''simple docstring''' setattr(processor.image_processor , '''apply_ocr''' , UpperCamelCase__ ) # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX SCREAMING_SNAKE_CASE : Any = compute_effective_axis_dimension( UpperCamelCase__ , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX SCREAMING_SNAKE_CASE : List[Any] = processor.tokenizer.num_special_tokens_to_add(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Tuple = compute_effective_axis_dimension( UpperCamelCase__ , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=UpperCamelCase__ ) # Generate dummy inputs according to compute batch and sequence SCREAMING_SNAKE_CASE : Union[str, Any] = [[''' '''.join([processor.tokenizer.unk_token] ) * seq_length]] * batch_size # Generate dummy bounding boxes SCREAMING_SNAKE_CASE : Any = [[[48, 84, 73, 128]]] * batch_size # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX # batch_size = compute_effective_axis_dimension(batch_size, fixed_dimension=OnnxConfig.default_fixed_batch) SCREAMING_SNAKE_CASE : List[Any] = self._generate_dummy_images(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[int] = dict( processor( UpperCamelCase__ , text=UpperCamelCase__ , boxes=UpperCamelCase__ , return_tensors=UpperCamelCase__ , ) ) return inputs
34
0
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DetrConfig, DetrForObjectDetection, DetrForSegmentation, DetrImageProcessor, ResNetConfig from transformers.utils import logging logging.set_verbosity_info() __UpperCamelCase : Union[str, Any] = logging.get_logger(__name__) def A ( _lowercase ): # initialize config if "resnet-50" in model_name: SCREAMING_SNAKE_CASE : str = ResNetConfig.from_pretrained('''microsoft/resnet-50''' ) elif "resnet-101" in model_name: SCREAMING_SNAKE_CASE : str = ResNetConfig.from_pretrained('''microsoft/resnet-101''' ) else: raise ValueError('''Model name should include either resnet50 or resnet101''' ) SCREAMING_SNAKE_CASE : int = DetrConfig(use_timm_backbone=_lowercase , backbone_config=_lowercase ) # set label attributes SCREAMING_SNAKE_CASE : Dict = '''panoptic''' in model_name if is_panoptic: SCREAMING_SNAKE_CASE : str = 250 else: SCREAMING_SNAKE_CASE : Any = 91 SCREAMING_SNAKE_CASE : Optional[int] = '''huggingface/label-files''' SCREAMING_SNAKE_CASE : Dict = '''coco-detection-id2label.json''' SCREAMING_SNAKE_CASE : Tuple = json.load(open(hf_hub_download(_lowercase , _lowercase , repo_type='''dataset''' ) , '''r''' ) ) SCREAMING_SNAKE_CASE : int = {int(_lowercase ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE : str = idalabel SCREAMING_SNAKE_CASE : Optional[int] = {v: k for k, v in idalabel.items()} return config, is_panoptic def A ( _lowercase ): # here we list all keys to be renamed (original name on the left, our name on the right) SCREAMING_SNAKE_CASE : List[Any] = [] # stem # fmt: off rename_keys.append(('''backbone.0.body.conv1.weight''', '''backbone.conv_encoder.model.embedder.embedder.convolution.weight''') ) rename_keys.append(('''backbone.0.body.bn1.weight''', '''backbone.conv_encoder.model.embedder.embedder.normalization.weight''') ) rename_keys.append(('''backbone.0.body.bn1.bias''', '''backbone.conv_encoder.model.embedder.embedder.normalization.bias''') ) rename_keys.append(('''backbone.0.body.bn1.running_mean''', '''backbone.conv_encoder.model.embedder.embedder.normalization.running_mean''') ) rename_keys.append(('''backbone.0.body.bn1.running_var''', '''backbone.conv_encoder.model.embedder.embedder.normalization.running_var''') ) # stages for stage_idx in range(len(config.backbone_config.depths ) ): for layer_idx in range(config.backbone_config.depths[stage_idx] ): # shortcut if layer_idx == 0: rename_keys.append( ( f"""backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.0.weight""", f"""backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.convolution.weight""", ) ) rename_keys.append( ( f"""backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.weight""", f"""backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.weight""", ) ) rename_keys.append( ( f"""backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.bias""", f"""backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.bias""", ) ) rename_keys.append( ( f"""backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.running_mean""", f"""backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.running_mean""", ) ) rename_keys.append( ( f"""backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.running_var""", f"""backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.running_var""", ) ) # 3 convs for i in range(3 ): rename_keys.append( ( f"""backbone.0.body.layer{stage_idx + 1}.{layer_idx}.conv{i+1}.weight""", f"""backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.convolution.weight""", ) ) rename_keys.append( ( f"""backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.weight""", f"""backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.weight""", ) ) rename_keys.append( ( f"""backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.bias""", f"""backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.bias""", ) ) rename_keys.append( ( f"""backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.running_mean""", f"""backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_mean""", ) ) rename_keys.append( ( f"""backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.running_var""", f"""backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_var""", ) ) # fmt: on for i in range(config.encoder_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append( ( f"""transformer.encoder.layers.{i}.self_attn.out_proj.weight""", f"""encoder.layers.{i}.self_attn.out_proj.weight""", ) ) rename_keys.append( (f"""transformer.encoder.layers.{i}.self_attn.out_proj.bias""", f"""encoder.layers.{i}.self_attn.out_proj.bias""") ) rename_keys.append((f"""transformer.encoder.layers.{i}.linear1.weight""", f"""encoder.layers.{i}.fc1.weight""") ) rename_keys.append((f"""transformer.encoder.layers.{i}.linear1.bias""", f"""encoder.layers.{i}.fc1.bias""") ) rename_keys.append((f"""transformer.encoder.layers.{i}.linear2.weight""", f"""encoder.layers.{i}.fc2.weight""") ) rename_keys.append((f"""transformer.encoder.layers.{i}.linear2.bias""", f"""encoder.layers.{i}.fc2.bias""") ) rename_keys.append( (f"""transformer.encoder.layers.{i}.norm1.weight""", f"""encoder.layers.{i}.self_attn_layer_norm.weight""") ) rename_keys.append( (f"""transformer.encoder.layers.{i}.norm1.bias""", f"""encoder.layers.{i}.self_attn_layer_norm.bias""") ) rename_keys.append( (f"""transformer.encoder.layers.{i}.norm2.weight""", f"""encoder.layers.{i}.final_layer_norm.weight""") ) rename_keys.append((f"""transformer.encoder.layers.{i}.norm2.bias""", f"""encoder.layers.{i}.final_layer_norm.bias""") ) # decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms rename_keys.append( ( f"""transformer.decoder.layers.{i}.self_attn.out_proj.weight""", f"""decoder.layers.{i}.self_attn.out_proj.weight""", ) ) rename_keys.append( (f"""transformer.decoder.layers.{i}.self_attn.out_proj.bias""", f"""decoder.layers.{i}.self_attn.out_proj.bias""") ) rename_keys.append( ( f"""transformer.decoder.layers.{i}.multihead_attn.out_proj.weight""", f"""decoder.layers.{i}.encoder_attn.out_proj.weight""", ) ) rename_keys.append( ( f"""transformer.decoder.layers.{i}.multihead_attn.out_proj.bias""", f"""decoder.layers.{i}.encoder_attn.out_proj.bias""", ) ) rename_keys.append((f"""transformer.decoder.layers.{i}.linear1.weight""", f"""decoder.layers.{i}.fc1.weight""") ) rename_keys.append((f"""transformer.decoder.layers.{i}.linear1.bias""", f"""decoder.layers.{i}.fc1.bias""") ) rename_keys.append((f"""transformer.decoder.layers.{i}.linear2.weight""", f"""decoder.layers.{i}.fc2.weight""") ) rename_keys.append((f"""transformer.decoder.layers.{i}.linear2.bias""", f"""decoder.layers.{i}.fc2.bias""") ) rename_keys.append( (f"""transformer.decoder.layers.{i}.norm1.weight""", f"""decoder.layers.{i}.self_attn_layer_norm.weight""") ) rename_keys.append( (f"""transformer.decoder.layers.{i}.norm1.bias""", f"""decoder.layers.{i}.self_attn_layer_norm.bias""") ) rename_keys.append( (f"""transformer.decoder.layers.{i}.norm2.weight""", f"""decoder.layers.{i}.encoder_attn_layer_norm.weight""") ) rename_keys.append( (f"""transformer.decoder.layers.{i}.norm2.bias""", f"""decoder.layers.{i}.encoder_attn_layer_norm.bias""") ) rename_keys.append( (f"""transformer.decoder.layers.{i}.norm3.weight""", f"""decoder.layers.{i}.final_layer_norm.weight""") ) rename_keys.append((f"""transformer.decoder.layers.{i}.norm3.bias""", f"""decoder.layers.{i}.final_layer_norm.bias""") ) # convolutional projection + query embeddings + layernorm of decoder + class and bounding box heads rename_keys.extend( [ ('''input_proj.weight''', '''input_projection.weight'''), ('''input_proj.bias''', '''input_projection.bias'''), ('''query_embed.weight''', '''query_position_embeddings.weight'''), ('''transformer.decoder.norm.weight''', '''decoder.layernorm.weight'''), ('''transformer.decoder.norm.bias''', '''decoder.layernorm.bias'''), ('''class_embed.weight''', '''class_labels_classifier.weight'''), ('''class_embed.bias''', '''class_labels_classifier.bias'''), ('''bbox_embed.layers.0.weight''', '''bbox_predictor.layers.0.weight'''), ('''bbox_embed.layers.0.bias''', '''bbox_predictor.layers.0.bias'''), ('''bbox_embed.layers.1.weight''', '''bbox_predictor.layers.1.weight'''), ('''bbox_embed.layers.1.bias''', '''bbox_predictor.layers.1.bias'''), ('''bbox_embed.layers.2.weight''', '''bbox_predictor.layers.2.weight'''), ('''bbox_embed.layers.2.bias''', '''bbox_predictor.layers.2.bias'''), ] ) return rename_keys def A ( _lowercase , _lowercase , _lowercase ): SCREAMING_SNAKE_CASE : int = state_dict.pop(_lowercase ) SCREAMING_SNAKE_CASE : List[str] = val def A ( _lowercase , _lowercase=False ): SCREAMING_SNAKE_CASE : Tuple = '''''' if is_panoptic: SCREAMING_SNAKE_CASE : List[Any] = '''detr.''' # first: transformer encoder for i in range(6 ): # read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias) SCREAMING_SNAKE_CASE : int = state_dict.pop(f"""{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight""" ) SCREAMING_SNAKE_CASE : List[str] = state_dict.pop(f"""{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias""" ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE : Any = in_proj_weight[:256, :] SCREAMING_SNAKE_CASE : int = in_proj_bias[:256] SCREAMING_SNAKE_CASE : Any = in_proj_weight[256:512, :] SCREAMING_SNAKE_CASE : Union[str, Any] = in_proj_bias[256:512] SCREAMING_SNAKE_CASE : int = in_proj_weight[-256:, :] SCREAMING_SNAKE_CASE : int = in_proj_bias[-256:] # next: transformer decoder (which is a bit more complex because it also includes cross-attention) for i in range(6 ): # read in weights + bias of input projection layer of self-attention SCREAMING_SNAKE_CASE : Optional[int] = state_dict.pop(f"""{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight""" ) SCREAMING_SNAKE_CASE : str = state_dict.pop(f"""{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_bias""" ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE : Optional[int] = in_proj_weight[:256, :] SCREAMING_SNAKE_CASE : Tuple = in_proj_bias[:256] SCREAMING_SNAKE_CASE : Union[str, Any] = in_proj_weight[256:512, :] SCREAMING_SNAKE_CASE : int = in_proj_bias[256:512] SCREAMING_SNAKE_CASE : List[str] = in_proj_weight[-256:, :] SCREAMING_SNAKE_CASE : Optional[Any] = in_proj_bias[-256:] # read in weights + bias of input projection layer of cross-attention SCREAMING_SNAKE_CASE : Dict = state_dict.pop( f"""{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight""" ) SCREAMING_SNAKE_CASE : Any = state_dict.pop(f"""{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_bias""" ) # next, add query, keys and values (in that order) of cross-attention to the state dict SCREAMING_SNAKE_CASE : Union[str, Any] = in_proj_weight_cross_attn[:256, :] SCREAMING_SNAKE_CASE : int = in_proj_bias_cross_attn[:256] SCREAMING_SNAKE_CASE : Tuple = in_proj_weight_cross_attn[256:512, :] SCREAMING_SNAKE_CASE : List[Any] = in_proj_bias_cross_attn[256:512] SCREAMING_SNAKE_CASE : Union[str, Any] = in_proj_weight_cross_attn[-256:, :] SCREAMING_SNAKE_CASE : Any = in_proj_bias_cross_attn[-256:] def A ( ): SCREAMING_SNAKE_CASE : Tuple = '''http://images.cocodataset.org/val2017/000000039769.jpg''' SCREAMING_SNAKE_CASE : Dict = Image.open(requests.get(_lowercase , stream=_lowercase ).raw ) return im @torch.no_grad() def A ( _lowercase , _lowercase=None , _lowercase=False ): SCREAMING_SNAKE_CASE : str = get_detr_config(_lowercase ) # load original model from torch hub SCREAMING_SNAKE_CASE : Optional[int] = { '''detr-resnet-50''': '''detr_resnet50''', '''detr-resnet-101''': '''detr_resnet101''', } logger.info(f"""Converting model {model_name}...""" ) SCREAMING_SNAKE_CASE : str = torch.hub.load('''facebookresearch/detr''' , model_name_to_original_name[model_name] , pretrained=_lowercase ).eval() SCREAMING_SNAKE_CASE : int = detr.state_dict() # rename keys for src, dest in create_rename_keys(_lowercase ): if is_panoptic: SCREAMING_SNAKE_CASE : List[str] = '''detr.''' + src rename_key(_lowercase , _lowercase , _lowercase ) # query, key and value matrices need special treatment read_in_q_k_v(_lowercase , is_panoptic=_lowercase ) # important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them SCREAMING_SNAKE_CASE : Optional[Any] = '''detr.model.''' if is_panoptic else '''model.''' for key in state_dict.copy().keys(): if is_panoptic: if ( key.startswith('''detr''' ) and not key.startswith('''class_labels_classifier''' ) and not key.startswith('''bbox_predictor''' ) ): SCREAMING_SNAKE_CASE : str = state_dict.pop(_lowercase ) SCREAMING_SNAKE_CASE : Any = val elif "class_labels_classifier" in key or "bbox_predictor" in key: SCREAMING_SNAKE_CASE : Optional[Any] = state_dict.pop(_lowercase ) SCREAMING_SNAKE_CASE : Optional[int] = val elif key.startswith('''bbox_attention''' ) or key.startswith('''mask_head''' ): continue else: SCREAMING_SNAKE_CASE : Optional[Any] = state_dict.pop(_lowercase ) SCREAMING_SNAKE_CASE : Union[str, Any] = val else: if not key.startswith('''class_labels_classifier''' ) and not key.startswith('''bbox_predictor''' ): SCREAMING_SNAKE_CASE : Optional[Any] = state_dict.pop(_lowercase ) SCREAMING_SNAKE_CASE : List[str] = val # finally, create HuggingFace model and load state dict SCREAMING_SNAKE_CASE : List[str] = DetrForSegmentation(_lowercase ) if is_panoptic else DetrForObjectDetection(_lowercase ) model.load_state_dict(_lowercase ) model.eval() # verify our conversion on an image SCREAMING_SNAKE_CASE : List[Any] = '''coco_panoptic''' if is_panoptic else '''coco_detection''' SCREAMING_SNAKE_CASE : List[str] = DetrImageProcessor(format=_lowercase ) SCREAMING_SNAKE_CASE : List[str] = processor(images=prepare_img() , return_tensors='''pt''' ) SCREAMING_SNAKE_CASE : Optional[int] = encoding['''pixel_values'''] SCREAMING_SNAKE_CASE : List[str] = detr(_lowercase ) SCREAMING_SNAKE_CASE : List[Any] = model(_lowercase ) assert torch.allclose(outputs.logits , original_outputs['''pred_logits'''] , atol=1e-3 ) assert torch.allclose(outputs.pred_boxes , original_outputs['''pred_boxes'''] , atol=1e-3 ) if is_panoptic: assert torch.allclose(outputs.pred_masks , original_outputs['''pred_masks'''] , atol=1e-4 ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: # Save model and image processor logger.info(f"""Saving PyTorch model and image processor to {pytorch_dump_folder_path}...""" ) Path(_lowercase ).mkdir(exist_ok=_lowercase ) model.save_pretrained(_lowercase ) processor.save_pretrained(_lowercase ) if push_to_hub: # Upload model and image processor to the hub logger.info('''Uploading PyTorch model and image processor to the hub...''' ) model.push_to_hub(f"""nielsr/{model_name}""" ) processor.push_to_hub(f"""nielsr/{model_name}""" ) if __name__ == "__main__": __UpperCamelCase : List[Any] = argparse.ArgumentParser() parser.add_argument( '--model_name', default='detr-resnet-50', type=str, choices=['detr-resnet-50', 'detr-resnet-101'], help='Name of the DETR model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the folder to output PyTorch model.' ) parser.add_argument('--push_to_hub', action='store_true', help='Whether to push the model to the hub or not.') __UpperCamelCase : List[str] = parser.parse_args() convert_detr_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
702
import os import unittest from transformers import FunnelTokenizer, FunnelTokenizerFast from transformers.models.funnel.tokenization_funnel import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowercase__ ( UpperCamelCase_ , unittest.TestCase): UpperCamelCase_ = FunnelTokenizer UpperCamelCase_ = FunnelTokenizerFast UpperCamelCase_ = True UpperCamelCase_ = True def __A ( self : Union[str, Any] ): '''simple docstring''' super().setUp() SCREAMING_SNAKE_CASE : Optional[Any] = [ '''<unk>''', '''<cls>''', '''<sep>''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] SCREAMING_SNAKE_CASE : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) def __A ( self : int , **UpperCamelCase__ : List[Any] ): '''simple docstring''' return FunnelTokenizer.from_pretrained(self.tmpdirname , **UpperCamelCase__ ) def __A ( self : int , **UpperCamelCase__ : List[Any] ): '''simple docstring''' return FunnelTokenizerFast.from_pretrained(self.tmpdirname , **UpperCamelCase__ ) def __A ( self : Any , UpperCamelCase__ : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = '''UNwant\u00E9d,running''' SCREAMING_SNAKE_CASE : int = '''unwanted, running''' return input_text, output_text def __A ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = self.tokenizer_class(self.vocab_file ) SCREAMING_SNAKE_CASE : int = tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(UpperCamelCase__ , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCamelCase__ ) , [7, 4, 5, 10, 8, 9] ) def __A ( self : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self.get_tokenizers(do_lower_case=UpperCamelCase__ ) for tokenizer in tokenizers: SCREAMING_SNAKE_CASE : int = tokenizer('''UNwant\u00E9d,running''' ) SCREAMING_SNAKE_CASE : Optional[Any] = len(inputs['''input_ids'''] ) - 1 self.assertListEqual(inputs['''token_type_ids'''] , [2] + [0] * sentence_len ) SCREAMING_SNAKE_CASE : List[Any] = tokenizer('''UNwant\u00E9d,running''' , '''UNwant\u00E9d,running''' ) self.assertListEqual(inputs['''token_type_ids'''] , [2] + [0] * sentence_len + [1] * sentence_len )
34
0
def A ( _lowercase ): SCREAMING_SNAKE_CASE : Tuple = int(_lowercase ) if n_element < 1: SCREAMING_SNAKE_CASE : Dict = ValueError('''a should be a positive number''' ) raise my_error SCREAMING_SNAKE_CASE : Optional[int] = [1] SCREAMING_SNAKE_CASE : List[str] = (0, 0, 0) SCREAMING_SNAKE_CASE : int = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2 , hamming_list[j] * 3 , hamming_list[k] * 5 ) ) index += 1 return hamming_list if __name__ == "__main__": __UpperCamelCase : List[str] = input('Enter the last number (nth term) of the Hamming Number Series: ') print('Formula of Hamming Number Series => 2^i * 3^j * 5^k') __UpperCamelCase : Dict = hamming(int(n)) print('-----------------------------------------------------') print(f"""The list with nth numbers is: {hamming_numbers}""") print('-----------------------------------------------------')
703
import numpy as np import torch from torch.utils.data import Dataset, IterableDataset from ..utils.generic import ModelOutput class lowercase__ ( UpperCamelCase_): def __init__( self : str , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = dataset SCREAMING_SNAKE_CASE : Optional[Any] = process SCREAMING_SNAKE_CASE : Union[str, Any] = params def __len__( self : Tuple ): '''simple docstring''' return len(self.dataset ) def __getitem__( self : List[str] , UpperCamelCase__ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = self.dataset[i] SCREAMING_SNAKE_CASE : Optional[int] = self.process(UpperCamelCase__ , **self.params ) return processed class lowercase__ ( UpperCamelCase_): def __init__( self : Dict , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Dict , UpperCamelCase__ : List[Any]=None ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = loader SCREAMING_SNAKE_CASE : List[Any] = infer SCREAMING_SNAKE_CASE : int = params if loader_batch_size == 1: # Let's spare some time by deactivating altogether SCREAMING_SNAKE_CASE : Optional[int] = None SCREAMING_SNAKE_CASE : List[str] = loader_batch_size # Internal bookkeeping SCREAMING_SNAKE_CASE : Optional[int] = None SCREAMING_SNAKE_CASE : int = None def __len__( self : int ): '''simple docstring''' return len(self.loader ) def __iter__( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = iter(self.loader ) return self def __A ( self : List[str] ): '''simple docstring''' if isinstance(self._loader_batch_data , torch.Tensor ): # Batch data is simple tensor, just fetch the slice SCREAMING_SNAKE_CASE : Optional[Any] = self._loader_batch_data[self._loader_batch_index] else: # Batch data is assumed to be BaseModelOutput (or dict) SCREAMING_SNAKE_CASE : Union[str, Any] = {} for k, element in self._loader_batch_data.items(): if isinstance(UpperCamelCase__ , UpperCamelCase__ ): # Convert ModelOutput to tuple first SCREAMING_SNAKE_CASE : Dict = element.to_tuple() if isinstance(element[0] , torch.Tensor ): SCREAMING_SNAKE_CASE : Dict = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element ) elif isinstance(element[0] , np.ndarray ): SCREAMING_SNAKE_CASE : Union[str, Any] = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element ) continue if k in {"hidden_states", "past_key_values", "attentions"} and isinstance(UpperCamelCase__ , UpperCamelCase__ ): # Those are stored as lists of tensors so need specific unbatching. if isinstance(element[0] , torch.Tensor ): SCREAMING_SNAKE_CASE : Union[str, Any] = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element ) elif isinstance(element[0] , np.ndarray ): SCREAMING_SNAKE_CASE : List[str] = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element ) continue if element is None: # This can happen for optional data that get passed around SCREAMING_SNAKE_CASE : int = None elif isinstance(element[self._loader_batch_index] , torch.Tensor ): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers SCREAMING_SNAKE_CASE : Union[str, Any] = element[self._loader_batch_index].unsqueeze(0 ) elif isinstance(element[self._loader_batch_index] , np.ndarray ): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers SCREAMING_SNAKE_CASE : Tuple = np.expand_dims(element[self._loader_batch_index] , 0 ) else: # This is typically a list, so no need to `unsqueeze`. SCREAMING_SNAKE_CASE : Tuple = element[self._loader_batch_index] # Recreate the element by reusing the original class to make it look # batch_size=1 SCREAMING_SNAKE_CASE : Any = self._loader_batch_data.__class__(UpperCamelCase__ ) self._loader_batch_index += 1 return result def __A ( self : Union[str, Any] ): '''simple docstring''' if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: # We are currently unrolling a batch so we just need to return # the current item within a batch return self.loader_batch_item() # We're out of items within a batch SCREAMING_SNAKE_CASE : Tuple = next(self.iterator ) SCREAMING_SNAKE_CASE : List[Any] = self.infer(UpperCamelCase__ , **self.params ) # We now have a batch of "inferred things". if self.loader_batch_size is not None: # Try to infer the size of the batch if isinstance(UpperCamelCase__ , torch.Tensor ): SCREAMING_SNAKE_CASE : Optional[int] = processed else: SCREAMING_SNAKE_CASE : int = list(processed.keys() )[0] SCREAMING_SNAKE_CASE : int = processed[key] if isinstance(UpperCamelCase__ , UpperCamelCase__ ): SCREAMING_SNAKE_CASE : List[Any] = len(UpperCamelCase__ ) else: SCREAMING_SNAKE_CASE : Dict = first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. SCREAMING_SNAKE_CASE : List[Any] = observed_batch_size # Setting internal index to unwrap the batch SCREAMING_SNAKE_CASE : List[Any] = processed SCREAMING_SNAKE_CASE : int = 0 return self.loader_batch_item() else: # We're not unrolling batches return processed class lowercase__ ( UpperCamelCase_): def __init__( self : str , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Union[str, Any]=None ): '''simple docstring''' super().__init__(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) def __iter__( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = iter(self.loader ) SCREAMING_SNAKE_CASE : List[Any] = None return self def __A ( self : List[str] ): '''simple docstring''' if self.subiterator is None: SCREAMING_SNAKE_CASE : Dict = self.infer(next(self.iterator ) , **self.params ) try: # Try to return next item SCREAMING_SNAKE_CASE : Any = next(self.subiterator ) except StopIteration: # When a preprocess iterator ends, we can start lookig at the next item # ChunkIterator will keep feeding until ALL elements of iterator # all have created their subiterator and have been iterating against. # # Another way to look at it, is we're basically flattening lists of lists # into a single list, but with generators SCREAMING_SNAKE_CASE : Optional[Any] = self.infer(next(self.iterator ) , **self.params ) SCREAMING_SNAKE_CASE : Union[str, Any] = next(self.subiterator ) return processed class lowercase__ ( UpperCamelCase_): def __iter__( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = iter(self.loader ) return self def __A ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = False SCREAMING_SNAKE_CASE : Optional[int] = [] if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: while self._loader_batch_index < self.loader_batch_size: SCREAMING_SNAKE_CASE : Tuple = self.loader_batch_item() SCREAMING_SNAKE_CASE : Any = item.pop('''is_last''' ) accumulator.append(UpperCamelCase__ ) if is_last: return accumulator while not is_last: SCREAMING_SNAKE_CASE : Any = self.infer(next(self.iterator ) , **self.params ) if self.loader_batch_size is not None: if isinstance(UpperCamelCase__ , torch.Tensor ): SCREAMING_SNAKE_CASE : Tuple = processed else: SCREAMING_SNAKE_CASE : Union[str, Any] = list(processed.keys() )[0] SCREAMING_SNAKE_CASE : List[str] = processed[key] if isinstance(UpperCamelCase__ , UpperCamelCase__ ): SCREAMING_SNAKE_CASE : List[Any] = len(UpperCamelCase__ ) else: SCREAMING_SNAKE_CASE : int = first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. SCREAMING_SNAKE_CASE : List[str] = observed_batch_size SCREAMING_SNAKE_CASE : List[Any] = processed SCREAMING_SNAKE_CASE : str = 0 while self._loader_batch_index < self.loader_batch_size: SCREAMING_SNAKE_CASE : Any = self.loader_batch_item() SCREAMING_SNAKE_CASE : List[Any] = item.pop('''is_last''' ) accumulator.append(UpperCamelCase__ ) if is_last: return accumulator else: SCREAMING_SNAKE_CASE : int = processed SCREAMING_SNAKE_CASE : List[str] = item.pop('''is_last''' ) accumulator.append(UpperCamelCase__ ) return accumulator class lowercase__ ( UpperCamelCase_): def __init__( self : Optional[Any] , UpperCamelCase__ : Dataset , UpperCamelCase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = dataset SCREAMING_SNAKE_CASE : Dict = key def __len__( self : Optional[int] ): '''simple docstring''' return len(self.dataset ) def __getitem__( self : Dict , UpperCamelCase__ : Tuple ): '''simple docstring''' return self.dataset[i][self.key] class lowercase__ ( UpperCamelCase_): def __init__( self : List[Any] , UpperCamelCase__ : Dataset , UpperCamelCase__ : str , UpperCamelCase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = dataset SCREAMING_SNAKE_CASE : List[str] = keya SCREAMING_SNAKE_CASE : Tuple = keya def __len__( self : List[str] ): '''simple docstring''' return len(self.dataset ) def __getitem__( self : Union[str, Any] , UpperCamelCase__ : Any ): '''simple docstring''' return {"text": self.dataset[i][self.keya], "text_pair": self.dataset[i][self.keya]}
34
0
import os import unittest from tempfile import TemporaryDirectory import torch import torch.nn as nn from accelerate.utils import ( OffloadedWeightsLoader, extract_submodules_state_dict, load_offloaded_weight, offload_state_dict, offload_weight, ) class lowercase__ ( nn.Module): def __init__( self : Union[str, Any] ): '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE : Tuple = nn.Linear(3 , 4 ) SCREAMING_SNAKE_CASE : List[Any] = nn.BatchNormad(4 ) SCREAMING_SNAKE_CASE : Dict = nn.Linear(4 , 5 ) def __A ( self : Tuple , UpperCamelCase__ : List[Any] ): '''simple docstring''' return self.lineara(self.batchnorm(self.lineara(UpperCamelCase__ ) ) ) class lowercase__ ( unittest.TestCase): def __A ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = ModelForTest() with TemporaryDirectory() as tmp_dir: offload_state_dict(UpperCamelCase__ , model.state_dict() ) SCREAMING_SNAKE_CASE : List[Any] = os.path.join(UpperCamelCase__ , '''index.json''' ) self.assertTrue(os.path.isfile(UpperCamelCase__ ) ) # TODO: add tests on what is inside the index for key in ["linear1.weight", "linear1.bias", "linear2.weight", "linear2.bias"]: SCREAMING_SNAKE_CASE : Optional[Any] = os.path.join(UpperCamelCase__ , f"""{key}.dat""" ) self.assertTrue(os.path.isfile(UpperCamelCase__ ) ) # TODO: add tests on the fact weights are properly loaded def __A ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = [torch.floataa, torch.floataa, torch.bfloataa] for dtype in dtypes: SCREAMING_SNAKE_CASE : List[str] = torch.randn(2 , 3 , dtype=UpperCamelCase__ ) with TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE : Tuple = offload_weight(UpperCamelCase__ , '''weight''' , UpperCamelCase__ , {} ) SCREAMING_SNAKE_CASE : Tuple = os.path.join(UpperCamelCase__ , '''weight.dat''' ) self.assertTrue(os.path.isfile(UpperCamelCase__ ) ) self.assertDictEqual(UpperCamelCase__ , {'''weight''': {'''shape''': [2, 3], '''dtype''': str(UpperCamelCase__ ).split('''.''' )[1]}} ) SCREAMING_SNAKE_CASE : Optional[Any] = load_offloaded_weight(UpperCamelCase__ , index['''weight'''] ) self.assertTrue(torch.equal(UpperCamelCase__ , UpperCamelCase__ ) ) def __A ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = ModelForTest() SCREAMING_SNAKE_CASE : Any = model.state_dict() SCREAMING_SNAKE_CASE : Tuple = {k: v for k, v in state_dict.items() if '''linear2''' not in k} SCREAMING_SNAKE_CASE : Tuple = {k: v for k, v in state_dict.items() if '''linear2''' in k} with TemporaryDirectory() as tmp_dir: offload_state_dict(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Any = OffloadedWeightsLoader(state_dict=UpperCamelCase__ , save_folder=UpperCamelCase__ ) # Every key is there with the right value self.assertEqual(sorted(UpperCamelCase__ ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(UpperCamelCase__ , weight_map[key] ) ) SCREAMING_SNAKE_CASE : List[Any] = {k: v for k, v in state_dict.items() if '''weight''' in k} SCREAMING_SNAKE_CASE : List[Any] = {k: v for k, v in state_dict.items() if '''weight''' not in k} with TemporaryDirectory() as tmp_dir: offload_state_dict(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[Any] = OffloadedWeightsLoader(state_dict=UpperCamelCase__ , save_folder=UpperCamelCase__ ) # Every key is there with the right value self.assertEqual(sorted(UpperCamelCase__ ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(UpperCamelCase__ , weight_map[key] ) ) with TemporaryDirectory() as tmp_dir: offload_state_dict(UpperCamelCase__ , UpperCamelCase__ ) # Duplicates are removed SCREAMING_SNAKE_CASE : int = OffloadedWeightsLoader(state_dict=UpperCamelCase__ , save_folder=UpperCamelCase__ ) # Every key is there with the right value self.assertEqual(sorted(UpperCamelCase__ ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(UpperCamelCase__ , weight_map[key] ) ) def __A ( self : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = {'''a.1''': 0, '''a.10''': 1, '''a.2''': 2} SCREAMING_SNAKE_CASE : int = extract_submodules_state_dict(UpperCamelCase__ , ['''a.1''', '''a.2'''] ) self.assertDictEqual(UpperCamelCase__ , {'''a.1''': 0, '''a.2''': 2} ) SCREAMING_SNAKE_CASE : Dict = {'''a.1.a''': 0, '''a.10.a''': 1, '''a.2.a''': 2} SCREAMING_SNAKE_CASE : Optional[int] = extract_submodules_state_dict(UpperCamelCase__ , ['''a.1''', '''a.2'''] ) self.assertDictEqual(UpperCamelCase__ , {'''a.1.a''': 0, '''a.2.a''': 2} )
704
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging if TYPE_CHECKING: from ... import FeatureExtractionMixin, PreTrainedTokenizerBase, TensorType __UpperCamelCase : Optional[Any] = logging.get_logger(__name__) __UpperCamelCase : Optional[Any] = { 'microsoft/deberta-v2-xlarge': 'https://huggingface.co/microsoft/deberta-v2-xlarge/resolve/main/config.json', 'microsoft/deberta-v2-xxlarge': 'https://huggingface.co/microsoft/deberta-v2-xxlarge/resolve/main/config.json', 'microsoft/deberta-v2-xlarge-mnli': ( 'https://huggingface.co/microsoft/deberta-v2-xlarge-mnli/resolve/main/config.json' ), 'microsoft/deberta-v2-xxlarge-mnli': ( 'https://huggingface.co/microsoft/deberta-v2-xxlarge-mnli/resolve/main/config.json' ), } class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = """deberta-v2""" def __init__( self : Optional[Any] , UpperCamelCase__ : Any=12_8100 , UpperCamelCase__ : Optional[int]=1536 , UpperCamelCase__ : Dict=24 , UpperCamelCase__ : List[str]=24 , UpperCamelCase__ : Tuple=6144 , UpperCamelCase__ : List[Any]="gelu" , UpperCamelCase__ : Optional[int]=0.1 , UpperCamelCase__ : List[str]=0.1 , UpperCamelCase__ : Optional[int]=512 , UpperCamelCase__ : Optional[Any]=0 , UpperCamelCase__ : Union[str, Any]=0.02 , UpperCamelCase__ : List[Any]=1E-7 , UpperCamelCase__ : List[str]=False , UpperCamelCase__ : str=-1 , UpperCamelCase__ : List[Any]=0 , UpperCamelCase__ : List[Any]=True , UpperCamelCase__ : Optional[Any]=None , UpperCamelCase__ : Tuple=0 , UpperCamelCase__ : str="gelu" , **UpperCamelCase__ : Optional[int] , ): '''simple docstring''' super().__init__(**UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[Any] = hidden_size SCREAMING_SNAKE_CASE : int = num_hidden_layers SCREAMING_SNAKE_CASE : Union[str, Any] = num_attention_heads SCREAMING_SNAKE_CASE : List[Any] = intermediate_size SCREAMING_SNAKE_CASE : Any = hidden_act SCREAMING_SNAKE_CASE : Dict = hidden_dropout_prob SCREAMING_SNAKE_CASE : Optional[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : str = max_position_embeddings SCREAMING_SNAKE_CASE : Dict = type_vocab_size SCREAMING_SNAKE_CASE : str = initializer_range SCREAMING_SNAKE_CASE : Optional[Any] = relative_attention SCREAMING_SNAKE_CASE : Optional[Any] = max_relative_positions SCREAMING_SNAKE_CASE : Optional[int] = pad_token_id SCREAMING_SNAKE_CASE : Optional[Any] = position_biased_input # Backwards compatibility if type(UpperCamelCase__ ) == str: SCREAMING_SNAKE_CASE : Optional[int] = [x.strip() for x in pos_att_type.lower().split('''|''' )] SCREAMING_SNAKE_CASE : Any = pos_att_type SCREAMING_SNAKE_CASE : int = vocab_size SCREAMING_SNAKE_CASE : Dict = layer_norm_eps SCREAMING_SNAKE_CASE : Tuple = kwargs.get('''pooler_hidden_size''' , UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Any = pooler_dropout SCREAMING_SNAKE_CASE : Union[str, Any] = pooler_hidden_act class lowercase__ ( UpperCamelCase_): @property def __A ( self : Union[str, Any] ): '''simple docstring''' if self.task == "multiple-choice": SCREAMING_SNAKE_CASE : Optional[int] = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: SCREAMING_SNAKE_CASE : Optional[Any] = {0: '''batch''', 1: '''sequence'''} if self._config.type_vocab_size > 0: return OrderedDict( [('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ('''token_type_ids''', dynamic_axis)] ) else: return OrderedDict([('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis)] ) @property def __A ( self : Union[str, Any] ): '''simple docstring''' return 12 def __A ( self : Dict , UpperCamelCase__ : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , UpperCamelCase__ : int = -1 , UpperCamelCase__ : int = -1 , UpperCamelCase__ : int = -1 , UpperCamelCase__ : bool = False , UpperCamelCase__ : Optional["TensorType"] = None , UpperCamelCase__ : int = 3 , UpperCamelCase__ : int = 40 , UpperCamelCase__ : int = 40 , UpperCamelCase__ : "PreTrainedTokenizerBase" = None , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = super().generate_dummy_inputs(preprocessor=UpperCamelCase__ , framework=UpperCamelCase__ ) if self._config.type_vocab_size == 0 and "token_type_ids" in dummy_inputs: del dummy_inputs["token_type_ids"] return dummy_inputs
34
0
from decimal import Decimal, getcontext from math import ceil, factorial def A ( _lowercase ): if not isinstance(_lowercase , _lowercase ): raise TypeError('''Undefined for non-integers''' ) elif precision < 1: raise ValueError('''Undefined for non-natural numbers''' ) SCREAMING_SNAKE_CASE : List[str] = precision SCREAMING_SNAKE_CASE : str = ceil(precision / 14 ) SCREAMING_SNAKE_CASE : Tuple = 426_880 * Decimal(10_005 ).sqrt() SCREAMING_SNAKE_CASE : Tuple = 1 SCREAMING_SNAKE_CASE : int = 13_591_409 SCREAMING_SNAKE_CASE : Optional[int] = Decimal(_lowercase ) for k in range(1 , _lowercase ): SCREAMING_SNAKE_CASE : Any = factorial(6 * k ) // (factorial(3 * k ) * factorial(_lowercase ) ** 3) linear_term += 545_140_134 exponential_term *= -262_537_412_640_768_000 partial_sum += Decimal(multinomial_term * linear_term ) / exponential_term return str(constant_term / partial_sum )[:-1] if __name__ == "__main__": __UpperCamelCase : List[str] = 50 print(f"""The first {n} digits of pi is: {pi(n)}""")
705
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from timm import create_model from timm.data import resolve_data_config from timm.data.transforms_factory import create_transform from transformers import BitConfig, BitForImageClassification, BitImageProcessor from transformers.image_utils import PILImageResampling from transformers.utils import logging logging.set_verbosity_info() __UpperCamelCase : str = logging.get_logger(__name__) def A ( _lowercase ): SCREAMING_SNAKE_CASE : Any = '''huggingface/label-files''' SCREAMING_SNAKE_CASE : Any = '''imagenet-1k-id2label.json''' SCREAMING_SNAKE_CASE : Any = json.load(open(hf_hub_download(_lowercase , _lowercase , repo_type='''dataset''' ) , '''r''' ) ) SCREAMING_SNAKE_CASE : Union[str, Any] = {int(_lowercase ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE : Dict = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE : str = '''std_conv''' if '''bit''' in model_name else False # note that when using BiT as backbone for ViT-hybrid checkpoints, # one needs to additionally set config.layer_type = "bottleneck", config.stem_type = "same", # config.conv_layer = "std_conv_same" SCREAMING_SNAKE_CASE : Optional[int] = BitConfig( conv_layer=_lowercase , num_labels=1_000 , idalabel=_lowercase , labelaid=_lowercase , ) return config def A ( _lowercase ): if "stem.conv" in name: SCREAMING_SNAKE_CASE : Optional[int] = name.replace('''stem.conv''' , '''bit.embedder.convolution''' ) if "blocks" in name: SCREAMING_SNAKE_CASE : Tuple = name.replace('''blocks''' , '''layers''' ) if "head.fc" in name: SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace('''head.fc''' , '''classifier.1''' ) if name.startswith('''norm''' ): SCREAMING_SNAKE_CASE : str = '''bit.''' + name if "bit" not in name and "classifier" not in name: SCREAMING_SNAKE_CASE : Union[str, Any] = '''bit.encoder.''' + name return name def A ( ): SCREAMING_SNAKE_CASE : Any = '''http://images.cocodataset.org/val2017/000000039769.jpg''' SCREAMING_SNAKE_CASE : List[str] = Image.open(requests.get(_lowercase , stream=_lowercase ).raw ) return im @torch.no_grad() def A ( _lowercase , _lowercase , _lowercase=False ): SCREAMING_SNAKE_CASE : List[Any] = get_config(_lowercase ) # load original model from timm SCREAMING_SNAKE_CASE : Optional[Any] = create_model(_lowercase , pretrained=_lowercase ) timm_model.eval() # load state_dict of original model SCREAMING_SNAKE_CASE : Optional[int] = timm_model.state_dict() for key in state_dict.copy().keys(): SCREAMING_SNAKE_CASE : Dict = state_dict.pop(_lowercase ) SCREAMING_SNAKE_CASE : Optional[int] = val.squeeze() if '''head''' in key else val # load HuggingFace model SCREAMING_SNAKE_CASE : str = BitForImageClassification(_lowercase ) model.eval() model.load_state_dict(_lowercase ) # create image processor SCREAMING_SNAKE_CASE : Optional[Any] = create_transform(**resolve_data_config({} , model=_lowercase ) ) SCREAMING_SNAKE_CASE : List[str] = transform.transforms SCREAMING_SNAKE_CASE : Union[str, Any] = { '''bilinear''': PILImageResampling.BILINEAR, '''bicubic''': PILImageResampling.BICUBIC, '''nearest''': PILImageResampling.NEAREST, } SCREAMING_SNAKE_CASE : Tuple = BitImageProcessor( do_resize=_lowercase , size={'''shortest_edge''': timm_transforms[0].size} , resample=pillow_resamplings[timm_transforms[0].interpolation.value] , do_center_crop=_lowercase , crop_size={'''height''': timm_transforms[1].size[0], '''width''': timm_transforms[1].size[1]} , do_normalize=_lowercase , image_mean=timm_transforms[-1].mean.tolist() , image_std=timm_transforms[-1].std.tolist() , ) SCREAMING_SNAKE_CASE : Any = prepare_img() SCREAMING_SNAKE_CASE : Union[str, Any] = transform(_lowercase ).unsqueeze(0 ) SCREAMING_SNAKE_CASE : Optional[int] = processor(_lowercase , return_tensors='''pt''' ).pixel_values # verify pixel values assert torch.allclose(_lowercase , _lowercase ) # verify logits with torch.no_grad(): SCREAMING_SNAKE_CASE : Dict = model(_lowercase ) SCREAMING_SNAKE_CASE : Optional[Any] = outputs.logits print('''Logits:''' , logits[0, :3] ) print('''Predicted class:''' , model.config.idalabel[logits.argmax(-1 ).item()] ) SCREAMING_SNAKE_CASE : List[Any] = timm_model(_lowercase ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(_lowercase , outputs.logits , atol=1e-3 ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: Path(_lowercase ).mkdir(exist_ok=_lowercase ) print(f"""Saving model {model_name} and processor to {pytorch_dump_folder_path}""" ) model.save_pretrained(_lowercase ) processor.save_pretrained(_lowercase ) if push_to_hub: print(f"""Pushing model {model_name} and processor to the hub""" ) model.push_to_hub(f"""ybelkada/{model_name}""" ) processor.push_to_hub(f"""ybelkada/{model_name}""" ) if __name__ == "__main__": __UpperCamelCase : Any = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='resnetv2_50x1_bitm', type=str, help='Name of the BiT 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.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether to push the model to the hub.', ) __UpperCamelCase : Optional[int] = parser.parse_args() convert_bit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
34
0
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 A ( _lowercase ): SCREAMING_SNAKE_CASE : Optional[Any] = [] SCREAMING_SNAKE_CASE : int = [] SCREAMING_SNAKE_CASE : str = [] for rt in rc.restypes: SCREAMING_SNAKE_CASE : str = 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] ) SCREAMING_SNAKE_CASE : List[Any] = {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] * 14 ) restype_atomaa_to_atomaa_list.append([0] * 37 ) restype_atomaa_mask_list.append([0.0] * 14 ) SCREAMING_SNAKE_CASE : Dict = torch.tensor( _lowercase , dtype=torch.intaa , device=protein['''aatype'''].device , ) SCREAMING_SNAKE_CASE : int = torch.tensor( _lowercase , dtype=torch.intaa , device=protein['''aatype'''].device , ) SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor( _lowercase , dtype=torch.floataa , device=protein['''aatype'''].device , ) SCREAMING_SNAKE_CASE : Optional[int] = 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 SCREAMING_SNAKE_CASE : Optional[int] = restype_atomaa_to_atomaa[protein_aatype] SCREAMING_SNAKE_CASE : Optional[int] = restype_atomaa_mask[protein_aatype] SCREAMING_SNAKE_CASE : List[Any] = residx_atomaa_mask SCREAMING_SNAKE_CASE : Optional[int] = residx_atomaa_to_atomaa.long() # create the gather indices for mapping back SCREAMING_SNAKE_CASE : List[str] = restype_atomaa_to_atomaa[protein_aatype] SCREAMING_SNAKE_CASE : Union[str, Any] = residx_atomaa_to_atomaa.long() # create the corresponding mask SCREAMING_SNAKE_CASE : Optional[Any] = torch.zeros([21, 37] , dtype=torch.floataa , device=protein['''aatype'''].device ) for restype, restype_letter in enumerate(rc.restypes ): SCREAMING_SNAKE_CASE : str = rc.restype_atoa[restype_letter] SCREAMING_SNAKE_CASE : Optional[Any] = rc.residue_atoms[restype_name] for atom_name in atom_names: SCREAMING_SNAKE_CASE : Union[str, Any] = rc.atom_order[atom_name] SCREAMING_SNAKE_CASE : Optional[int] = 1 SCREAMING_SNAKE_CASE : Optional[int] = restype_atomaa_mask[protein_aatype] SCREAMING_SNAKE_CASE : Union[str, Any] = residx_atomaa_mask return protein def A ( _lowercase ): SCREAMING_SNAKE_CASE : Tuple = tree_map(lambda _lowercase : torch.tensor(_lowercase , device=batch['''aatype'''].device ) , _lowercase , np.ndarray ) SCREAMING_SNAKE_CASE : Optional[int] = tensor_tree_map(lambda _lowercase : np.array(_lowercase ) , make_atomaa_masks(_lowercase ) ) return out
706
import argparse import json import logging import os import sys from unittest.mock import patch from transformers.testing_utils import TestCasePlus, get_gpu_count, slow __UpperCamelCase : str = [ os.path.join(os.path.dirname(__file__), dirname) for dirname in [ 'text-classification', 'language-modeling', 'summarization', 'token-classification', 'question-answering', ] ] sys.path.extend(SRC_DIRS) if SRC_DIRS is not None: import run_clm_flax import run_flax_glue import run_flax_ner import run_mlm_flax import run_qa import run_summarization_flax import run_ta_mlm_flax logging.basicConfig(level=logging.DEBUG) __UpperCamelCase : int = logging.getLogger() def A ( ): SCREAMING_SNAKE_CASE : str = argparse.ArgumentParser() parser.add_argument('''-f''' ) SCREAMING_SNAKE_CASE : List[str] = parser.parse_args() return args.f def A ( _lowercase , _lowercase="eval" ): SCREAMING_SNAKE_CASE : Dict = os.path.join(_lowercase , f"""{split}_results.json""" ) if os.path.exists(_lowercase ): with open(_lowercase , '''r''' ) as f: return json.load(_lowercase ) raise ValueError(f"""can't find {path}""" ) __UpperCamelCase : Optional[Any] = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class lowercase__ ( UpperCamelCase_): def __A ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE : Tuple = f""" run_glue.py --model_name_or_path distilbert-base-uncased --output_dir {tmp_dir} --train_file ./tests/fixtures/tests_samples/MRPC/train.csv --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --learning_rate=1e-4 --eval_steps=2 --warmup_steps=2 --seed=42 --max_seq_length=128 """.split() with patch.object(UpperCamelCase__ , '''argv''' , UpperCamelCase__ ): run_flax_glue.main() SCREAMING_SNAKE_CASE : Union[str, Any] = get_results(UpperCamelCase__ ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 ) @slow def __A ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE : str = f""" run_clm_flax.py --model_name_or_path distilgpt2 --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --do_train --do_eval --block_size 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --num_train_epochs 2 --logging_steps 2 --eval_steps 2 --output_dir {tmp_dir} --overwrite_output_dir """.split() with patch.object(UpperCamelCase__ , '''argv''' , UpperCamelCase__ ): run_clm_flax.main() SCREAMING_SNAKE_CASE : Dict = get_results(UpperCamelCase__ ) self.assertLess(result['''eval_perplexity'''] , 100 ) @slow def __A ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE : Union[str, Any] = f""" run_summarization.py --model_name_or_path t5-small --train_file tests/fixtures/tests_samples/xsum/sample.json --validation_file tests/fixtures/tests_samples/xsum/sample.json --test_file tests/fixtures/tests_samples/xsum/sample.json --output_dir {tmp_dir} --overwrite_output_dir --num_train_epochs=3 --warmup_steps=8 --do_train --do_eval --do_predict --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --predict_with_generate """.split() with patch.object(UpperCamelCase__ , '''argv''' , UpperCamelCase__ ): run_summarization_flax.main() SCREAMING_SNAKE_CASE : Union[str, Any] = get_results(UpperCamelCase__ , split='''test''' ) self.assertGreaterEqual(result['''test_rouge1'''] , 10 ) self.assertGreaterEqual(result['''test_rouge2'''] , 2 ) self.assertGreaterEqual(result['''test_rougeL'''] , 7 ) self.assertGreaterEqual(result['''test_rougeLsum'''] , 7 ) @slow def __A ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE : Dict = f""" run_mlm.py --model_name_or_path distilroberta-base --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --output_dir {tmp_dir} --overwrite_output_dir --max_seq_length 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --logging_steps 2 --eval_steps 2 --do_train --do_eval --num_train_epochs=1 """.split() with patch.object(UpperCamelCase__ , '''argv''' , UpperCamelCase__ ): run_mlm_flax.main() SCREAMING_SNAKE_CASE : List[Any] = get_results(UpperCamelCase__ ) self.assertLess(result['''eval_perplexity'''] , 42 ) @slow def __A ( self : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE : Union[str, Any] = f""" run_t5_mlm_flax.py --model_name_or_path t5-small --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --do_train --do_eval --max_seq_length 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --num_train_epochs 2 --logging_steps 2 --eval_steps 2 --output_dir {tmp_dir} --overwrite_output_dir """.split() with patch.object(UpperCamelCase__ , '''argv''' , UpperCamelCase__ ): run_ta_mlm_flax.main() SCREAMING_SNAKE_CASE : Optional[int] = get_results(UpperCamelCase__ ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.42 ) @slow def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = 7 if get_gpu_count() > 1 else 2 SCREAMING_SNAKE_CASE : Dict = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE : Any = f""" run_flax_ner.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/conll/sample.json --validation_file tests/fixtures/tests_samples/conll/sample.json --output_dir {tmp_dir} --overwrite_output_dir --do_train --do_eval --warmup_steps=2 --learning_rate=2e-4 --logging_steps 2 --eval_steps 2 --per_device_train_batch_size=2 --per_device_eval_batch_size=2 --num_train_epochs={epochs} --seed 7 """.split() with patch.object(UpperCamelCase__ , '''argv''' , UpperCamelCase__ ): run_flax_ner.main() SCREAMING_SNAKE_CASE : List[str] = get_results(UpperCamelCase__ ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 ) self.assertGreaterEqual(result['''eval_f1'''] , 0.3 ) @slow def __A ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE : Union[str, Any] = f""" run_qa.py --model_name_or_path bert-base-uncased --version_2_with_negative --train_file tests/fixtures/tests_samples/SQUAD/sample.json --validation_file tests/fixtures/tests_samples/SQUAD/sample.json --output_dir {tmp_dir} --overwrite_output_dir --num_train_epochs=3 --warmup_steps=2 --do_train --do_eval --logging_steps 2 --eval_steps 2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 """.split() with patch.object(UpperCamelCase__ , '''argv''' , UpperCamelCase__ ): run_qa.main() SCREAMING_SNAKE_CASE : str = get_results(UpperCamelCase__ ) self.assertGreaterEqual(result['''eval_f1'''] , 30 ) self.assertGreaterEqual(result['''eval_exact'''] , 30 )
34
0
import doctest import glob import importlib import inspect import os import re from contextlib import contextmanager from functools import wraps from unittest.mock import patch import numpy as np import pytest from absl.testing import parameterized import datasets from datasets import load_metric from .utils import for_all_test_methods, local, slow # mark all tests as integration __UpperCamelCase : Optional[int] = pytest.mark.integration __UpperCamelCase : int = {'comet'} __UpperCamelCase : Optional[int] = importlib.util.find_spec('fairseq') is not None __UpperCamelCase : Optional[Any] = {'code_eval'} __UpperCamelCase : List[str] = os.name == 'nt' __UpperCamelCase : Optional[Any] = {'bertscore', 'frugalscore', 'perplexity'} __UpperCamelCase : Dict = importlib.util.find_spec('transformers') is not None def A ( _lowercase ): @wraps(_lowercase ) def wrapper(self , _lowercase ): if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ: self.skipTest('''"test requires Fairseq"''' ) else: test_case(self , _lowercase ) return wrapper def A ( _lowercase ): @wraps(_lowercase ) def wrapper(self , _lowercase ): if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS: self.skipTest('''"test requires transformers"''' ) else: test_case(self , _lowercase ) return wrapper def A ( _lowercase ): @wraps(_lowercase ) def wrapper(self , _lowercase ): if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS: self.skipTest('''"test not supported on Windows"''' ) else: test_case(self , _lowercase ) return wrapper def A ( ): SCREAMING_SNAKE_CASE : List[Any] = [metric_dir.split(os.sep )[-2] for metric_dir in glob.glob('''./metrics/*/''' )] return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"] # gleu is unfinished @parameterized.named_parameters(get_local_metric_names()) @for_all_test_methods( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_) @local class lowercase__ ( parameterized.TestCase): UpperCamelCase_ = {} UpperCamelCase_ = None @pytest.mark.filterwarnings('''ignore:metric_module_factory is deprecated:FutureWarning''' ) @pytest.mark.filterwarnings('''ignore:load_metric is deprecated:FutureWarning''' ) def __A ( self : Dict , UpperCamelCase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = '''[...]''' SCREAMING_SNAKE_CASE : List[Any] = importlib.import_module( datasets.load.metric_module_factory(os.path.join('''metrics''' , UpperCamelCase__ ) ).module_path ) SCREAMING_SNAKE_CASE : List[str] = datasets.load.import_main_class(metric_module.__name__ , dataset=UpperCamelCase__ ) # check parameters SCREAMING_SNAKE_CASE : Optional[int] = inspect.signature(metric._compute ).parameters self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values() ) ) # no **kwargs # run doctest with self.patch_intensive_calls(UpperCamelCase__ , metric_module.__name__ ): with self.use_local_metrics(): try: SCREAMING_SNAKE_CASE : Tuple = doctest.testmod(UpperCamelCase__ , verbose=UpperCamelCase__ , raise_on_error=UpperCamelCase__ ) except doctest.UnexpectedException as e: raise e.exc_info[1] # raise the exception that doctest caught self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @slow def __A ( self : Optional[Any] , UpperCamelCase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = '''[...]''' SCREAMING_SNAKE_CASE : Dict = importlib.import_module( datasets.load.metric_module_factory(os.path.join('''metrics''' , UpperCamelCase__ ) ).module_path ) # run doctest with self.use_local_metrics(): SCREAMING_SNAKE_CASE : Optional[Any] = doctest.testmod(UpperCamelCase__ , verbose=UpperCamelCase__ , raise_on_error=UpperCamelCase__ ) self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @contextmanager def __A ( self : int , UpperCamelCase__ : Any , UpperCamelCase__ : List[str] ): '''simple docstring''' if metric_name in self.INTENSIVE_CALLS_PATCHER: with self.INTENSIVE_CALLS_PATCHER[metric_name](UpperCamelCase__ ): yield else: yield @contextmanager def __A ( self : Optional[Any] ): '''simple docstring''' def load_local_metric(UpperCamelCase__ : List[Any] , *UpperCamelCase__ : str , **UpperCamelCase__ : Any ): return load_metric(os.path.join('''metrics''' , UpperCamelCase__ ) , *UpperCamelCase__ , **UpperCamelCase__ ) with patch('''datasets.load_metric''' ) as mock_load_metric: SCREAMING_SNAKE_CASE : Optional[Any] = load_local_metric yield @classmethod def __A ( cls : str , UpperCamelCase__ : Dict ): '''simple docstring''' def wrapper(UpperCamelCase__ : Dict ): SCREAMING_SNAKE_CASE : Optional[Any] = contextmanager(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Dict = patcher return patcher return wrapper @LocalMetricTest.register_intensive_calls_patcher('''bleurt''' ) def A ( _lowercase ): import tensorflow.compat.va as tf from bleurt.score import Predictor tf.flags.DEFINE_string('''sv''' , '''''' , '''''' ) # handle pytest cli flags class lowercase__ ( UpperCamelCase_): def __A ( self : Optional[int] , UpperCamelCase__ : str ): '''simple docstring''' assert len(input_dict['''input_ids'''] ) == 2 return np.array([1.03, 1.04] ) # mock predict_fn which is supposed to do a forward pass with a bleurt model with patch('''bleurt.score._create_predictor''' ) as mock_create_predictor: SCREAMING_SNAKE_CASE : List[str] = MockedPredictor() yield @LocalMetricTest.register_intensive_calls_patcher('''bertscore''' ) def A ( _lowercase ): import torch def bert_cos_score_idf(_lowercase , _lowercase , *_lowercase , **_lowercase ): return torch.tensor([[1.0, 1.0, 1.0]] * len(_lowercase ) ) # mock get_model which is supposed to do download a bert model # mock bert_cos_score_idf which is supposed to do a forward pass with a bert model with patch('''bert_score.scorer.get_model''' ), patch( '''bert_score.scorer.bert_cos_score_idf''' ) as mock_bert_cos_score_idf: SCREAMING_SNAKE_CASE : Any = bert_cos_score_idf yield @LocalMetricTest.register_intensive_calls_patcher('''comet''' ) def A ( _lowercase ): def load_from_checkpoint(_lowercase ): class lowercase__ : def __A ( self : Any , UpperCamelCase__ : Optional[int] , *UpperCamelCase__ : List[str] , **UpperCamelCase__ : int ): '''simple docstring''' assert len(UpperCamelCase__ ) == 2 SCREAMING_SNAKE_CASE : str = [0.19, 0.92] return scores, sum(UpperCamelCase__ ) / len(UpperCamelCase__ ) return Model() # mock load_from_checkpoint which is supposed to do download a bert model # mock load_from_checkpoint which is supposed to do download a bert model with patch('''comet.download_model''' ) as mock_download_model: SCREAMING_SNAKE_CASE : int = None with patch('''comet.load_from_checkpoint''' ) as mock_load_from_checkpoint: SCREAMING_SNAKE_CASE : Any = load_from_checkpoint yield def A ( ): SCREAMING_SNAKE_CASE : int = load_metric(os.path.join('''metrics''' , '''seqeval''' ) ) SCREAMING_SNAKE_CASE : List[Any] = '''ERROR''' SCREAMING_SNAKE_CASE : Optional[Any] = f"""Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}""" with pytest.raises(_lowercase , match=re.escape(_lowercase ) ): metric.compute(predictions=[] , references=[] , scheme=_lowercase )
707
import itertools import os import random import tempfile import unittest import numpy as np from transformers import TvltFeatureExtractor, is_datasets_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_torch_available(): import torch if is_datasets_available(): from datasets import load_dataset __UpperCamelCase : Dict = random.Random() def A ( _lowercase , _lowercase=1.0 , _lowercase=None , _lowercase=None ): if rng is None: SCREAMING_SNAKE_CASE : Any = global_rng SCREAMING_SNAKE_CASE : int = [] 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 : List[Any] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : str=7 , UpperCamelCase__ : Any=400 , UpperCamelCase__ : List[str]=2000 , UpperCamelCase__ : List[Any]=2048 , UpperCamelCase__ : Any=128 , UpperCamelCase__ : Union[str, Any]=1 , UpperCamelCase__ : List[Any]=512 , UpperCamelCase__ : str=30 , UpperCamelCase__ : Tuple=4_4100 , ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = parent SCREAMING_SNAKE_CASE : str = batch_size SCREAMING_SNAKE_CASE : str = min_seq_length SCREAMING_SNAKE_CASE : Dict = max_seq_length SCREAMING_SNAKE_CASE : Optional[int] = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) SCREAMING_SNAKE_CASE : Optional[Any] = spectrogram_length SCREAMING_SNAKE_CASE : Optional[int] = feature_size SCREAMING_SNAKE_CASE : Tuple = num_audio_channels SCREAMING_SNAKE_CASE : Union[str, Any] = hop_length SCREAMING_SNAKE_CASE : List[Any] = chunk_length SCREAMING_SNAKE_CASE : str = sampling_rate def __A ( self : Optional[Any] ): '''simple docstring''' return { "spectrogram_length": self.spectrogram_length, "feature_size": self.feature_size, "num_audio_channels": self.num_audio_channels, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "sampling_rate": self.sampling_rate, } def __A ( self : Tuple , UpperCamelCase__ : List[str]=False , UpperCamelCase__ : Optional[int]=False ): '''simple docstring''' def _flatten(UpperCamelCase__ : str ): return list(itertools.chain(*UpperCamelCase__ ) ) if equal_length: SCREAMING_SNAKE_CASE : List[str] = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE : int = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE : Optional[Any] = [np.asarray(UpperCamelCase__ ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class lowercase__ ( UpperCamelCase_ , unittest.TestCase): UpperCamelCase_ = TvltFeatureExtractor def __A ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = TvltFeatureExtractionTester(self ) def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = self.feature_extraction_class(**self.feat_extract_dict ) self.assertTrue(hasattr(UpperCamelCase__ , '''spectrogram_length''' ) ) self.assertTrue(hasattr(UpperCamelCase__ , '''feature_size''' ) ) self.assertTrue(hasattr(UpperCamelCase__ , '''num_audio_channels''' ) ) self.assertTrue(hasattr(UpperCamelCase__ , '''hop_length''' ) ) self.assertTrue(hasattr(UpperCamelCase__ , '''chunk_length''' ) ) self.assertTrue(hasattr(UpperCamelCase__ , '''sampling_rate''' ) ) def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE : Optional[Any] = feat_extract_first.save_pretrained(UpperCamelCase__ )[0] check_json_file_has_correct_format(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[Any] = self.feature_extraction_class.from_pretrained(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[Any] = feat_extract_first.to_dict() SCREAMING_SNAKE_CASE : str = feat_extract_second.to_dict() SCREAMING_SNAKE_CASE : Optional[int] = dict_first.pop('''mel_filters''' ) SCREAMING_SNAKE_CASE : Optional[int] = dict_second.pop('''mel_filters''' ) self.assertTrue(np.allclose(UpperCamelCase__ , UpperCamelCase__ ) ) self.assertEqual(UpperCamelCase__ , UpperCamelCase__ ) def __A ( self : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE : Tuple = os.path.join(UpperCamelCase__ , '''feat_extract.json''' ) feat_extract_first.to_json_file(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[str] = self.feature_extraction_class.from_json_file(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Any = feat_extract_first.to_dict() SCREAMING_SNAKE_CASE : str = feat_extract_second.to_dict() SCREAMING_SNAKE_CASE : int = dict_first.pop('''mel_filters''' ) SCREAMING_SNAKE_CASE : Any = dict_second.pop('''mel_filters''' ) self.assertTrue(np.allclose(UpperCamelCase__ , UpperCamelCase__ ) ) self.assertEqual(UpperCamelCase__ , UpperCamelCase__ ) def __A ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = self.feature_extraction_class(**self.feat_extract_dict ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE : List[Any] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE : Optional[int] = [np.asarray(UpperCamelCase__ ) for speech_input in speech_inputs] # Test not batched input SCREAMING_SNAKE_CASE : List[Any] = feature_extractor(np_speech_inputs[0] , return_tensors='''np''' , sampling_rate=4_4100 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test batched SCREAMING_SNAKE_CASE : Optional[Any] = feature_extractor(UpperCamelCase__ , return_tensors='''np''' , sampling_rate=4_4100 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test audio masking SCREAMING_SNAKE_CASE : List[str] = feature_extractor( UpperCamelCase__ , return_tensors='''np''' , sampling_rate=4_4100 , mask_audio=UpperCamelCase__ ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test 2-D numpy arrays are batched. SCREAMING_SNAKE_CASE : Optional[Any] = [floats_list((1, x) )[0] for x in (800, 800, 800)] SCREAMING_SNAKE_CASE : Dict = np.asarray(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : str = feature_extractor(UpperCamelCase__ , return_tensors='''np''' , sampling_rate=4_4100 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) def __A ( self : Optional[int] , UpperCamelCase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = load_dataset('''hf-internal-testing/librispeech_asr_dummy''' , '''clean''' , split='''validation''' ) # automatic decoding with librispeech SCREAMING_SNAKE_CASE : Dict = ds.sort('''id''' ).select(range(UpperCamelCase__ ) )[:num_samples]['''audio'''] return [x["array"] for x in speech_samples] def __A ( self : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE : int = TvltFeatureExtractor() SCREAMING_SNAKE_CASE : List[Any] = feature_extractor(UpperCamelCase__ , return_tensors='''pt''' ).audio_values self.assertEquals(audio_values.shape , (1, 1, 192, 128) ) SCREAMING_SNAKE_CASE : str = torch.tensor([[-0.3032, -0.2708], [-0.4434, -0.4007]] ) self.assertTrue(torch.allclose(audio_values[0, 0, :2, :2] , UpperCamelCase__ , atol=1E-4 ) )
34
0
import csv from collections import defaultdict from dataclasses import dataclass, field from typing import List, Optional import matplotlib.pyplot as plt import numpy as np from matplotlib.ticker import ScalarFormatter from transformers import HfArgumentParser def A ( _lowercase=None , _lowercase=None ): return field(default_factory=lambda: default , metadata=_lowercase ) @dataclass class lowercase__ : UpperCamelCase_ = field( metadata={"""help""": """The csv file to plot."""} , ) UpperCamelCase_ = field( default=UpperCamelCase_ , metadata={"""help""": """Whether to plot along batch size or sequence length. Defaults to sequence length."""} , ) UpperCamelCase_ = field( default=UpperCamelCase_ , metadata={"""help""": """Whether the csv file has time results or memory results. Defaults to memory results."""} , ) UpperCamelCase_ = field( default=UpperCamelCase_ , metadata={"""help""": """Disable logarithmic scale when plotting"""} , ) UpperCamelCase_ = field( default=UpperCamelCase_ , metadata={ """help""": """Whether the csv file has training results or inference results. Defaults to inference results.""" } , ) UpperCamelCase_ = field( default=UpperCamelCase_ , metadata={"""help""": """Filename under which the plot will be saved. If unused no plot is saved."""} , ) UpperCamelCase_ = list_field( default=UpperCamelCase_ , metadata={"""help""": """List of model names that are used instead of the ones in the csv file."""}) def A ( _lowercase ): try: int(_lowercase ) return True except ValueError: return False def A ( _lowercase ): try: float(_lowercase ) return True except ValueError: return False class lowercase__ : def __init__( self : Any , UpperCamelCase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = args SCREAMING_SNAKE_CASE : Optional[Any] = defaultdict(lambda: {"bsz": [], "seq_len": [], "result": {}} ) with open(self.args.csv_file , newline='''''' ) as csv_file: SCREAMING_SNAKE_CASE : List[Any] = csv.DictReader(UpperCamelCase__ ) for row in reader: SCREAMING_SNAKE_CASE : Dict = row['''model'''] self.result_dict[model_name]["bsz"].append(int(row['''batch_size'''] ) ) self.result_dict[model_name]["seq_len"].append(int(row['''sequence_length'''] ) ) if can_convert_to_int(row['''result'''] ): # value is not None SCREAMING_SNAKE_CASE : Tuple = int(row['''result'''] ) elif can_convert_to_float(row['''result'''] ): # value is not None SCREAMING_SNAKE_CASE : Dict = float(row['''result'''] ) def __A ( self : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = plt.subplots() SCREAMING_SNAKE_CASE : List[str] = '''Time usage''' if self.args.is_time else '''Memory usage''' SCREAMING_SNAKE_CASE : Tuple = title_str + ''' for training''' if self.args.is_train else title_str + ''' for inference''' if not self.args.no_log_scale: # set logarithm scales ax.set_xscale('''log''' ) ax.set_yscale('''log''' ) for axis in [ax.xaxis, ax.yaxis]: axis.set_major_formatter(ScalarFormatter() ) for model_name_idx, model_name in enumerate(self.result_dict.keys() ): SCREAMING_SNAKE_CASE : Any = sorted(set(self.result_dict[model_name]['''bsz'''] ) ) SCREAMING_SNAKE_CASE : int = sorted(set(self.result_dict[model_name]['''seq_len'''] ) ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.result_dict[model_name]['''result'''] (SCREAMING_SNAKE_CASE) : List[str] = ( (batch_sizes, sequence_lengths) if self.args.plot_along_batch else (sequence_lengths, batch_sizes) ) SCREAMING_SNAKE_CASE : str = ( model_name if self.args.short_model_names is None else self.args.short_model_names[model_name_idx] ) for inner_loop_value in inner_loop_array: if self.args.plot_along_batch: SCREAMING_SNAKE_CASE : str = np.asarray( [results[(x, inner_loop_value)] for x in x_axis_array if (x, inner_loop_value) in results] , dtype=UpperCamelCase__ , ) else: SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray( [results[(inner_loop_value, x)] for x in x_axis_array if (inner_loop_value, x) in results] , dtype=np.floataa , ) (SCREAMING_SNAKE_CASE) : Any = ( ('''batch_size''', '''len''') if self.args.plot_along_batch else ('''in #tokens''', '''bsz''') ) SCREAMING_SNAKE_CASE : List[str] = np.asarray(UpperCamelCase__ , UpperCamelCase__ )[: len(UpperCamelCase__ )] plt.scatter( UpperCamelCase__ , UpperCamelCase__ , label=f"""{label_model_name} - {inner_loop_label}: {inner_loop_value}""" ) plt.plot(UpperCamelCase__ , UpperCamelCase__ , '''--''' ) title_str += f""" {label_model_name} vs.""" SCREAMING_SNAKE_CASE : List[Any] = title_str[:-4] SCREAMING_SNAKE_CASE : str = '''Time in s''' if self.args.is_time else '''Memory in MB''' # plot plt.title(UpperCamelCase__ ) plt.xlabel(UpperCamelCase__ ) plt.ylabel(UpperCamelCase__ ) plt.legend() if self.args.figure_png_file is not None: plt.savefig(self.args.figure_png_file ) else: plt.show() def A ( ): SCREAMING_SNAKE_CASE : Optional[int] = HfArgumentParser(_lowercase ) SCREAMING_SNAKE_CASE : Dict = parser.parse_args_into_dataclasses()[0] SCREAMING_SNAKE_CASE : str = Plot(args=_lowercase ) plot.plot() if __name__ == "__main__": main()
708
import math from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import SchedulerMixin, SchedulerOutput class lowercase__ ( UpperCamelCase_ , UpperCamelCase_): UpperCamelCase_ = 1 @register_to_config def __init__( self : List[str] , UpperCamelCase__ : int = 1000 , UpperCamelCase__ : Optional[Union[np.ndarray, List[float]]] = None ): '''simple docstring''' self.set_timesteps(UpperCamelCase__ ) # standard deviation of the initial noise distribution SCREAMING_SNAKE_CASE : str = 1.0 # For now we only support F-PNDM, i.e. the runge-kutta method # For more information on the algorithm please take a look at the paper: https://arxiv.org/pdf/2202.09778.pdf # mainly at formula (9), (12), (13) and the Algorithm 2. SCREAMING_SNAKE_CASE : Tuple = 4 # running values SCREAMING_SNAKE_CASE : int = [] def __A ( self : Dict , UpperCamelCase__ : int , UpperCamelCase__ : Union[str, torch.device] = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = num_inference_steps SCREAMING_SNAKE_CASE : Union[str, Any] = torch.linspace(1 , 0 , num_inference_steps + 1 )[:-1] SCREAMING_SNAKE_CASE : Tuple = torch.cat([steps, torch.tensor([0.0] )] ) if self.config.trained_betas is not None: SCREAMING_SNAKE_CASE : int = torch.tensor(self.config.trained_betas , dtype=torch.floataa ) else: SCREAMING_SNAKE_CASE : Optional[Any] = torch.sin(steps * math.pi / 2 ) ** 2 SCREAMING_SNAKE_CASE : Dict = (1.0 - self.betas**2) ** 0.5 SCREAMING_SNAKE_CASE : Optional[Any] = (torch.atana(self.betas , self.alphas ) / math.pi * 2)[:-1] SCREAMING_SNAKE_CASE : List[str] = timesteps.to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Any = [] def __A ( self : Tuple , UpperCamelCase__ : torch.FloatTensor , UpperCamelCase__ : int , UpperCamelCase__ : torch.FloatTensor , UpperCamelCase__ : bool = True , ): '''simple docstring''' if self.num_inference_steps is None: raise ValueError( '''Number of inference steps is \'None\', you need to run \'set_timesteps\' after creating the scheduler''' ) SCREAMING_SNAKE_CASE : Optional[int] = (self.timesteps == timestep).nonzero().item() SCREAMING_SNAKE_CASE : Union[str, Any] = timestep_index + 1 SCREAMING_SNAKE_CASE : int = sample * self.betas[timestep_index] + model_output * self.alphas[timestep_index] self.ets.append(UpperCamelCase__ ) if len(self.ets ) == 1: SCREAMING_SNAKE_CASE : Dict = self.ets[-1] elif len(self.ets ) == 2: SCREAMING_SNAKE_CASE : Optional[int] = (3 * self.ets[-1] - self.ets[-2]) / 2 elif len(self.ets ) == 3: SCREAMING_SNAKE_CASE : str = (23 * self.ets[-1] - 16 * self.ets[-2] + 5 * self.ets[-3]) / 12 else: SCREAMING_SNAKE_CASE : Optional[Any] = (1 / 24) * (55 * self.ets[-1] - 59 * self.ets[-2] + 37 * self.ets[-3] - 9 * self.ets[-4]) SCREAMING_SNAKE_CASE : Optional[int] = self._get_prev_sample(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=UpperCamelCase__ ) def __A ( self : Optional[Any] , UpperCamelCase__ : torch.FloatTensor , *UpperCamelCase__ : List[str] , **UpperCamelCase__ : Optional[Any] ): '''simple docstring''' return sample def __A ( self : Union[str, Any] , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Any , UpperCamelCase__ : Tuple , UpperCamelCase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = self.alphas[timestep_index] SCREAMING_SNAKE_CASE : List[str] = self.betas[timestep_index] SCREAMING_SNAKE_CASE : Union[str, Any] = self.alphas[prev_timestep_index] SCREAMING_SNAKE_CASE : Tuple = self.betas[prev_timestep_index] SCREAMING_SNAKE_CASE : Dict = (sample - sigma * ets) / max(UpperCamelCase__ , 1E-8 ) SCREAMING_SNAKE_CASE : Optional[Any] = next_alpha * pred + ets * next_sigma return prev_sample def __len__( self : int ): '''simple docstring''' return self.config.num_train_timesteps
34
0
import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, ) from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST class lowercase__ : def __init__( self : List[str] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Union[str, Any]=13 , UpperCamelCase__ : List[Any]=7 , UpperCamelCase__ : int=True , UpperCamelCase__ : Optional[int]=True , UpperCamelCase__ : int=True , UpperCamelCase__ : List[Any]=True , UpperCamelCase__ : List[Any]=99 , UpperCamelCase__ : Union[str, Any]=24 , UpperCamelCase__ : Any=2 , UpperCamelCase__ : str=6 , UpperCamelCase__ : Optional[Any]=37 , UpperCamelCase__ : str="gelu" , UpperCamelCase__ : Dict=0.1 , UpperCamelCase__ : int=0.1 , UpperCamelCase__ : int=512 , UpperCamelCase__ : Dict=16 , UpperCamelCase__ : List[Any]=2 , UpperCamelCase__ : Dict=0.02 , UpperCamelCase__ : Union[str, Any]=3 , UpperCamelCase__ : str=None , UpperCamelCase__ : str=1000 , ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = parent SCREAMING_SNAKE_CASE : List[str] = batch_size SCREAMING_SNAKE_CASE : Dict = seq_length SCREAMING_SNAKE_CASE : Tuple = is_training SCREAMING_SNAKE_CASE : List[str] = use_input_mask SCREAMING_SNAKE_CASE : Dict = use_token_type_ids SCREAMING_SNAKE_CASE : List[str] = use_labels SCREAMING_SNAKE_CASE : Union[str, Any] = vocab_size SCREAMING_SNAKE_CASE : str = hidden_size SCREAMING_SNAKE_CASE : Tuple = num_hidden_layers SCREAMING_SNAKE_CASE : int = num_attention_heads SCREAMING_SNAKE_CASE : List[str] = intermediate_size SCREAMING_SNAKE_CASE : Dict = hidden_act SCREAMING_SNAKE_CASE : Dict = hidden_dropout_prob SCREAMING_SNAKE_CASE : Union[str, Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : int = max_position_embeddings SCREAMING_SNAKE_CASE : List[Any] = type_vocab_size SCREAMING_SNAKE_CASE : List[Any] = type_sequence_label_size SCREAMING_SNAKE_CASE : int = initializer_range SCREAMING_SNAKE_CASE : List[Any] = num_labels SCREAMING_SNAKE_CASE : Dict = scope SCREAMING_SNAKE_CASE : Dict = range_bbox def __A ( self : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE : List[str] = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox ) # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: SCREAMING_SNAKE_CASE : Tuple = bbox[i, j, 3] SCREAMING_SNAKE_CASE : str = bbox[i, j, 1] SCREAMING_SNAKE_CASE : int = t if bbox[i, j, 2] < bbox[i, j, 0]: SCREAMING_SNAKE_CASE : Dict = bbox[i, j, 2] SCREAMING_SNAKE_CASE : Union[str, Any] = bbox[i, j, 0] SCREAMING_SNAKE_CASE : Union[str, Any] = t SCREAMING_SNAKE_CASE : List[str] = None if self.use_input_mask: SCREAMING_SNAKE_CASE : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) SCREAMING_SNAKE_CASE : Any = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE : Any = None SCREAMING_SNAKE_CASE : Union[str, Any] = None if self.use_labels: SCREAMING_SNAKE_CASE : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE : str = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE : Optional[Any] = self.get_config() return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels def __A ( self : Union[str, Any] ): '''simple docstring''' return LiltConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) def __A ( self : List[Any] , UpperCamelCase__ : Dict , UpperCamelCase__ : List[Any] , UpperCamelCase__ : int , UpperCamelCase__ : Tuple , UpperCamelCase__ : str , UpperCamelCase__ : str , UpperCamelCase__ : Dict , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = LiltModel(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() SCREAMING_SNAKE_CASE : Optional[int] = model(UpperCamelCase__ , bbox=UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Any = model(UpperCamelCase__ , bbox=UpperCamelCase__ , token_type_ids=UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Any = model(UpperCamelCase__ , bbox=UpperCamelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def __A ( self : Any , UpperCamelCase__ : List[Any] , UpperCamelCase__ : int , UpperCamelCase__ : List[str] , UpperCamelCase__ : List[Any] , UpperCamelCase__ : str , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : Any , ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = self.num_labels SCREAMING_SNAKE_CASE : Any = LiltForTokenClassification(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() SCREAMING_SNAKE_CASE : Optional[Any] = model( UpperCamelCase__ , bbox=UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __A ( self : Optional[Any] , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Tuple , UpperCamelCase__ : List[str] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : str , UpperCamelCase__ : Dict , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = LiltForQuestionAnswering(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() SCREAMING_SNAKE_CASE : List[Any] = model( UpperCamelCase__ , bbox=UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , start_positions=UpperCamelCase__ , end_positions=UpperCamelCase__ , ) 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 __A ( self : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = self.prepare_config_and_inputs() ( SCREAMING_SNAKE_CASE ) : List[Any] = config_and_inputs SCREAMING_SNAKE_CASE : List[str] = { '''input_ids''': input_ids, '''bbox''': bbox, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask, } return config, inputs_dict @require_torch class lowercase__ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): UpperCamelCase_ = ( ( LiltModel, LiltForSequenceClassification, LiltForTokenClassification, LiltForQuestionAnswering, ) if is_torch_available() else () ) UpperCamelCase_ = ( { """feature-extraction""": LiltModel, """question-answering""": LiltForQuestionAnswering, """text-classification""": LiltForSequenceClassification, """token-classification""": LiltForTokenClassification, """zero-shot""": LiltForSequenceClassification, } if is_torch_available() else {} ) UpperCamelCase_ = False UpperCamelCase_ = False def __A ( self : List[Any] , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : str , UpperCamelCase__ : List[str] , UpperCamelCase__ : List[str] ): '''simple docstring''' return True def __A ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = LiltModelTester(self ) SCREAMING_SNAKE_CASE : Dict = ConfigTester(self , config_class=UpperCamelCase__ , hidden_size=37 ) def __A ( self : Any ): '''simple docstring''' self.config_tester.run_common_tests() def __A ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCamelCase__ ) def __A ( self : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE : Any = type self.model_tester.create_and_check_model(*UpperCamelCase__ ) def __A ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*UpperCamelCase__ ) def __A ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*UpperCamelCase__ ) @slow def __A ( self : str ): '''simple docstring''' for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE : Union[str, Any] = LiltModel.from_pretrained(UpperCamelCase__ ) self.assertIsNotNone(UpperCamelCase__ ) @require_torch @slow class lowercase__ ( unittest.TestCase): def __A ( self : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = LiltModel.from_pretrained('''SCUT-DLVCLab/lilt-roberta-en-base''' ).to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Dict = torch.tensor([[1, 2]] , device=UpperCamelCase__ ) SCREAMING_SNAKE_CASE : str = torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]] , device=UpperCamelCase__ ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE : Dict = model(input_ids=UpperCamelCase__ , bbox=UpperCamelCase__ ) SCREAMING_SNAKE_CASE : str = torch.Size([1, 2, 768] ) SCREAMING_SNAKE_CASE : Tuple = torch.tensor( [[-0.0653, 0.0950, -0.0061], [-0.0545, 0.0926, -0.0324]] , device=UpperCamelCase__ , ) self.assertTrue(outputs.last_hidden_state.shape , UpperCamelCase__ ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3] , UpperCamelCase__ , atol=1E-3 ) )
709
import gc import random import unittest import torch from diffusers import ( IFImgaImgPipeline, IFImgaImgSuperResolutionPipeline, IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline, IFPipeline, IFSuperResolutionPipeline, ) from diffusers.models.attention_processor import AttnAddedKVProcessor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import floats_tensor, load_numpy, require_torch_gpu, skip_mps, slow, torch_device from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference from . import IFPipelineTesterMixin @skip_mps class lowercase__ ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): UpperCamelCase_ = IFPipeline UpperCamelCase_ = TEXT_TO_IMAGE_PARAMS - {"""width""", """height""", """latents"""} UpperCamelCase_ = TEXT_TO_IMAGE_BATCH_PARAMS UpperCamelCase_ = PipelineTesterMixin.required_optional_params - {"""latents"""} def __A ( self : Tuple ): '''simple docstring''' return self._get_dummy_components() def __A ( self : int , UpperCamelCase__ : Dict , UpperCamelCase__ : int=0 ): '''simple docstring''' if str(UpperCamelCase__ ).startswith('''mps''' ): SCREAMING_SNAKE_CASE : Tuple = torch.manual_seed(UpperCamelCase__ ) else: SCREAMING_SNAKE_CASE : Dict = torch.Generator(device=UpperCamelCase__ ).manual_seed(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : int = { '''prompt''': '''A painting of a squirrel eating a burger''', '''generator''': generator, '''num_inference_steps''': 2, '''output_type''': '''numpy''', } return inputs def __A ( self : List[str] ): '''simple docstring''' self._test_save_load_optional_components() @unittest.skipIf(torch_device != '''cuda''' , reason='''float16 requires CUDA''' ) def __A ( self : Any ): '''simple docstring''' super().test_save_load_floataa(expected_max_diff=1E-1 ) def __A ( self : Union[str, Any] ): '''simple docstring''' self._test_attention_slicing_forward_pass(expected_max_diff=1E-2 ) def __A ( self : List[Any] ): '''simple docstring''' self._test_save_load_local() def __A ( self : List[str] ): '''simple docstring''' self._test_inference_batch_single_identical( expected_max_diff=1E-2 , ) @unittest.skipIf( torch_device != '''cuda''' or not is_xformers_available() , reason='''XFormers attention is only available with CUDA and `xformers` installed''' , ) def __A ( self : Tuple ): '''simple docstring''' self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 ) @slow @require_torch_gpu class lowercase__ ( unittest.TestCase): def __A ( self : Optional[Any] ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = IFPipeline.from_pretrained('''DeepFloyd/IF-I-XL-v1.0''' , variant='''fp16''' , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE : str = IFSuperResolutionPipeline.from_pretrained( '''DeepFloyd/IF-II-L-v1.0''' , variant='''fp16''' , torch_dtype=torch.floataa , text_encoder=UpperCamelCase__ , tokenizer=UpperCamelCase__ ) # pre compute text embeddings and remove T5 to save memory pipe_a.text_encoder.to('''cuda''' ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Dict = pipe_a.encode_prompt('''anime turtle''' , device='''cuda''' ) del pipe_a.tokenizer del pipe_a.text_encoder gc.collect() SCREAMING_SNAKE_CASE : Tuple = None SCREAMING_SNAKE_CASE : str = None pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) pipe_a.remove_all_hooks() pipe_a.remove_all_hooks() # img2img SCREAMING_SNAKE_CASE : Optional[int] = IFImgaImgPipeline(**pipe_a.components ) SCREAMING_SNAKE_CASE : Optional[int] = IFImgaImgSuperResolutionPipeline(**pipe_a.components ) pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if_imgaimg(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) pipe_a.remove_all_hooks() pipe_a.remove_all_hooks() # inpainting SCREAMING_SNAKE_CASE : Tuple = IFInpaintingPipeline(**pipe_a.components ) SCREAMING_SNAKE_CASE : Optional[int] = IFInpaintingSuperResolutionPipeline(**pipe_a.components ) pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if_inpainting(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) def __A ( self : Tuple , UpperCamelCase__ : int , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Dict ): '''simple docstring''' _start_torch_memory_measurement() SCREAMING_SNAKE_CASE : List[str] = torch.Generator(device='''cpu''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[Any] = pipe_a( prompt_embeds=UpperCamelCase__ , negative_prompt_embeds=UpperCamelCase__ , num_inference_steps=2 , generator=UpperCamelCase__ , output_type='''np''' , ) SCREAMING_SNAKE_CASE : Optional[int] = output.images[0] assert image.shape == (64, 64, 3) SCREAMING_SNAKE_CASE : Tuple = torch.cuda.max_memory_allocated() assert mem_bytes < 13 * 10**9 SCREAMING_SNAKE_CASE : Optional[Any] = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if.npy''' ) assert_mean_pixel_difference(UpperCamelCase__ , UpperCamelCase__ ) # pipeline 2 _start_torch_memory_measurement() SCREAMING_SNAKE_CASE : Tuple = torch.Generator(device='''cpu''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE : int = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Any = pipe_a( prompt_embeds=UpperCamelCase__ , negative_prompt_embeds=UpperCamelCase__ , image=UpperCamelCase__ , generator=UpperCamelCase__ , num_inference_steps=2 , output_type='''np''' , ) SCREAMING_SNAKE_CASE : Tuple = output.images[0] assert image.shape == (256, 256, 3) SCREAMING_SNAKE_CASE : Union[str, Any] = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 SCREAMING_SNAKE_CASE : int = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_superresolution_stage_II.npy''' ) assert_mean_pixel_difference(UpperCamelCase__ , UpperCamelCase__ ) def __A ( self : Optional[int] , UpperCamelCase__ : str , UpperCamelCase__ : int , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : str ): '''simple docstring''' _start_torch_memory_measurement() SCREAMING_SNAKE_CASE : Tuple = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Any = torch.Generator(device='''cpu''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE : List[Any] = pipe_a( prompt_embeds=UpperCamelCase__ , negative_prompt_embeds=UpperCamelCase__ , image=UpperCamelCase__ , num_inference_steps=2 , generator=UpperCamelCase__ , output_type='''np''' , ) SCREAMING_SNAKE_CASE : int = output.images[0] assert image.shape == (64, 64, 3) SCREAMING_SNAKE_CASE : Optional[int] = torch.cuda.max_memory_allocated() assert mem_bytes < 10 * 10**9 SCREAMING_SNAKE_CASE : Tuple = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img.npy''' ) assert_mean_pixel_difference(UpperCamelCase__ , UpperCamelCase__ ) # pipeline 2 _start_torch_memory_measurement() SCREAMING_SNAKE_CASE : Union[str, Any] = torch.Generator(device='''cpu''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[Any] = floats_tensor((1, 3, 256, 256) , rng=random.Random(0 ) ).to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[Any] = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : str = pipe_a( prompt_embeds=UpperCamelCase__ , negative_prompt_embeds=UpperCamelCase__ , image=UpperCamelCase__ , original_image=UpperCamelCase__ , generator=UpperCamelCase__ , num_inference_steps=2 , output_type='''np''' , ) SCREAMING_SNAKE_CASE : Optional[int] = output.images[0] assert image.shape == (256, 256, 3) SCREAMING_SNAKE_CASE : List[Any] = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 SCREAMING_SNAKE_CASE : Optional[Any] = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img_superresolution_stage_II.npy''' ) assert_mean_pixel_difference(UpperCamelCase__ , UpperCamelCase__ ) def __A ( self : List[str] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Optional[Any] ): '''simple docstring''' _start_torch_memory_measurement() SCREAMING_SNAKE_CASE : str = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Union[str, Any] = floats_tensor((1, 3, 64, 64) , rng=random.Random(1 ) ).to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[int] = torch.Generator(device='''cpu''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE : int = pipe_a( prompt_embeds=UpperCamelCase__ , negative_prompt_embeds=UpperCamelCase__ , image=UpperCamelCase__ , mask_image=UpperCamelCase__ , num_inference_steps=2 , generator=UpperCamelCase__ , output_type='''np''' , ) SCREAMING_SNAKE_CASE : Any = output.images[0] assert image.shape == (64, 64, 3) SCREAMING_SNAKE_CASE : Any = torch.cuda.max_memory_allocated() assert mem_bytes < 10 * 10**9 SCREAMING_SNAKE_CASE : List[Any] = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting.npy''' ) assert_mean_pixel_difference(UpperCamelCase__ , UpperCamelCase__ ) # pipeline 2 _start_torch_memory_measurement() SCREAMING_SNAKE_CASE : str = torch.Generator(device='''cpu''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE : List[str] = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : int = floats_tensor((1, 3, 256, 256) , rng=random.Random(0 ) ).to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[int] = floats_tensor((1, 3, 256, 256) , rng=random.Random(1 ) ).to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Dict = pipe_a( prompt_embeds=UpperCamelCase__ , negative_prompt_embeds=UpperCamelCase__ , image=UpperCamelCase__ , mask_image=UpperCamelCase__ , original_image=UpperCamelCase__ , generator=UpperCamelCase__ , num_inference_steps=2 , output_type='''np''' , ) SCREAMING_SNAKE_CASE : Optional[Any] = output.images[0] assert image.shape == (256, 256, 3) SCREAMING_SNAKE_CASE : Any = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 SCREAMING_SNAKE_CASE : Tuple = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting_superresolution_stage_II.npy''' ) assert_mean_pixel_difference(UpperCamelCase__ , UpperCamelCase__ ) def A ( ): torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats()
34
0
from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCamelCase : List[str] = logging.get_logger(__name__) __UpperCamelCase : Optional[int] = { 'microsoft/biogpt': 'https://huggingface.co/microsoft/biogpt/resolve/main/config.json', # See all BioGPT models at https://huggingface.co/models?filter=biogpt } class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = """biogpt""" def __init__( self : List[str] , UpperCamelCase__ : Union[str, Any]=4_2384 , UpperCamelCase__ : List[Any]=1024 , UpperCamelCase__ : Optional[int]=24 , UpperCamelCase__ : List[Any]=16 , UpperCamelCase__ : List[str]=4096 , UpperCamelCase__ : str="gelu" , UpperCamelCase__ : str=0.1 , UpperCamelCase__ : Optional[Any]=0.1 , UpperCamelCase__ : Union[str, Any]=1024 , UpperCamelCase__ : List[str]=0.02 , UpperCamelCase__ : Tuple=1E-12 , UpperCamelCase__ : Optional[Any]=True , UpperCamelCase__ : List[Any]=True , UpperCamelCase__ : str=0.0 , UpperCamelCase__ : Any=0.0 , UpperCamelCase__ : str=1 , UpperCamelCase__ : List[str]=0 , UpperCamelCase__ : Dict=2 , **UpperCamelCase__ : Optional[Any] , ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = vocab_size SCREAMING_SNAKE_CASE : Dict = max_position_embeddings SCREAMING_SNAKE_CASE : Tuple = hidden_size SCREAMING_SNAKE_CASE : List[Any] = num_hidden_layers SCREAMING_SNAKE_CASE : Tuple = num_attention_heads SCREAMING_SNAKE_CASE : Dict = intermediate_size SCREAMING_SNAKE_CASE : int = hidden_act SCREAMING_SNAKE_CASE : Dict = hidden_dropout_prob SCREAMING_SNAKE_CASE : Optional[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : int = initializer_range SCREAMING_SNAKE_CASE : Optional[int] = layer_norm_eps SCREAMING_SNAKE_CASE : int = scale_embedding SCREAMING_SNAKE_CASE : Tuple = use_cache SCREAMING_SNAKE_CASE : Union[str, Any] = layerdrop SCREAMING_SNAKE_CASE : List[str] = activation_dropout super().__init__(pad_token_id=UpperCamelCase__ , bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ , **UpperCamelCase__ )
710
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 : int = logging.get_logger(__name__) def A ( _lowercase , _lowercase , _lowercase , _lowercase ): def constraint_to_multiple_of(_lowercase , _lowercase , _lowercase=0 , _lowercase=None ): SCREAMING_SNAKE_CASE : int = round(val / multiple ) * multiple if max_val is not None and x > max_val: SCREAMING_SNAKE_CASE : Dict = math.floor(val / multiple ) * multiple if x < min_val: SCREAMING_SNAKE_CASE : Optional[Any] = math.ceil(val / multiple ) * multiple return x SCREAMING_SNAKE_CASE : Optional[Any] = (output_size, output_size) if isinstance(_lowercase , _lowercase ) else output_size SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = get_image_size(_lowercase ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = output_size # determine new height and width SCREAMING_SNAKE_CASE : Dict = output_height / input_height SCREAMING_SNAKE_CASE : Optional[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 SCREAMING_SNAKE_CASE : List[Any] = scale_width else: # fit height SCREAMING_SNAKE_CASE : List[Any] = scale_height SCREAMING_SNAKE_CASE : List[str] = constraint_to_multiple_of(scale_height * input_height , multiple=_lowercase ) SCREAMING_SNAKE_CASE : Optional[int] = constraint_to_multiple_of(scale_width * input_width , multiple=_lowercase ) return (new_height, new_width) class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = ["""pixel_values"""] def __init__( self : int , UpperCamelCase__ : bool = True , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : PILImageResampling = PILImageResampling.BILINEAR , UpperCamelCase__ : bool = False , UpperCamelCase__ : int = 1 , UpperCamelCase__ : bool = True , UpperCamelCase__ : Union[int, float] = 1 / 255 , UpperCamelCase__ : bool = True , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , **UpperCamelCase__ : Optional[int] , ): '''simple docstring''' super().__init__(**UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[str] = size if size is not None else {'''height''': 384, '''width''': 384} SCREAMING_SNAKE_CASE : Any = get_size_dict(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Dict = do_resize SCREAMING_SNAKE_CASE : Any = size SCREAMING_SNAKE_CASE : str = keep_aspect_ratio SCREAMING_SNAKE_CASE : List[str] = ensure_multiple_of SCREAMING_SNAKE_CASE : int = resample SCREAMING_SNAKE_CASE : Any = do_rescale SCREAMING_SNAKE_CASE : List[Any] = rescale_factor SCREAMING_SNAKE_CASE : Optional[int] = do_normalize SCREAMING_SNAKE_CASE : str = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN SCREAMING_SNAKE_CASE : Union[str, Any] = image_std if image_std is not None else IMAGENET_STANDARD_STD def __A ( self : Optional[Any] , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Dict[str, int] , UpperCamelCase__ : bool = False , UpperCamelCase__ : int = 1 , UpperCamelCase__ : PILImageResampling = PILImageResampling.BICUBIC , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : Union[str, Any] , ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = get_size_dict(UpperCamelCase__ ) 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()}""" ) SCREAMING_SNAKE_CASE : Any = get_resize_output_image_size( UpperCamelCase__ , output_size=(size['''height'''], size['''width''']) , keep_aspect_ratio=UpperCamelCase__ , multiple=UpperCamelCase__ , ) return resize(UpperCamelCase__ , size=UpperCamelCase__ , resample=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def __A ( self : Dict , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Union[int, float] , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : str , ): '''simple docstring''' return rescale(UpperCamelCase__ , scale=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def __A ( self : Any , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Union[float, List[float]] , UpperCamelCase__ : Union[float, List[float]] , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : List[str] , ): '''simple docstring''' return normalize(UpperCamelCase__ , mean=UpperCamelCase__ , std=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def __A ( self : Optional[Any] , UpperCamelCase__ : ImageInput , UpperCamelCase__ : bool = None , UpperCamelCase__ : int = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : int = None , UpperCamelCase__ : PILImageResampling = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : float = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : Optional[Union[str, TensorType]] = None , UpperCamelCase__ : ChannelDimension = ChannelDimension.FIRST , **UpperCamelCase__ : Optional[int] , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE : Optional[Any] = size if size is not None else self.size SCREAMING_SNAKE_CASE : Union[str, Any] = get_size_dict(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Optional[Any] = keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio SCREAMING_SNAKE_CASE : List[str] = ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of SCREAMING_SNAKE_CASE : Tuple = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE : Optional[Any] = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE : Union[str, Any] = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE : str = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE : List[Any] = image_mean if image_mean is not None else self.image_mean SCREAMING_SNAKE_CASE : List[Any] = image_std if image_std is not None else self.image_std SCREAMING_SNAKE_CASE : Dict = make_list_of_images(UpperCamelCase__ ) if not valid_images(UpperCamelCase__ ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None or resample is None: raise ValueError('''Size and resample must be specified if do_resize is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('''Image mean and std must be specified if do_normalize is True.''' ) # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE : Tuple = [to_numpy_array(UpperCamelCase__ ) for image in images] if do_resize: SCREAMING_SNAKE_CASE : Dict = [self.resize(image=UpperCamelCase__ , size=UpperCamelCase__ , resample=UpperCamelCase__ ) for image in images] if do_rescale: SCREAMING_SNAKE_CASE : Any = [self.rescale(image=UpperCamelCase__ , scale=UpperCamelCase__ ) for image in images] if do_normalize: SCREAMING_SNAKE_CASE : Any = [self.normalize(image=UpperCamelCase__ , mean=UpperCamelCase__ , std=UpperCamelCase__ ) for image in images] SCREAMING_SNAKE_CASE : Optional[int] = [to_channel_dimension_format(UpperCamelCase__ , UpperCamelCase__ ) for image in images] SCREAMING_SNAKE_CASE : Tuple = {'''pixel_values''': images} return BatchFeature(data=UpperCamelCase__ , tensor_type=UpperCamelCase__ ) def __A ( self : Tuple , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : List[Tuple] = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(UpperCamelCase__ ) != len(UpperCamelCase__ ): raise ValueError( '''Make sure that you pass in as many target sizes as the batch dimension of the logits''' ) if is_torch_tensor(UpperCamelCase__ ): SCREAMING_SNAKE_CASE : List[Any] = target_sizes.numpy() SCREAMING_SNAKE_CASE : Optional[int] = [] for idx in range(len(UpperCamelCase__ ) ): SCREAMING_SNAKE_CASE : List[str] = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode='''bilinear''' , align_corners=UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Dict = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(UpperCamelCase__ ) else: SCREAMING_SNAKE_CASE : List[Any] = logits.argmax(dim=1 ) SCREAMING_SNAKE_CASE : List[Any] = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
34
0