code
stringlengths
82
53.2k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available _SCREAMING_SNAKE_CASE = { """configuration_data2vec_audio""": ["""DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecAudioConfig"""], """configuration_data2vec_text""": [ """DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecTextConfig""", """Data2VecTextOnnxConfig""", ], """configuration_data2vec_vision""": [ """DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecVisionConfig""", """Data2VecVisionOnnxConfig""", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE = [ """DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecAudioForAudioFrameClassification""", """Data2VecAudioForCTC""", """Data2VecAudioForSequenceClassification""", """Data2VecAudioForXVector""", """Data2VecAudioModel""", """Data2VecAudioPreTrainedModel""", ] _SCREAMING_SNAKE_CASE = [ """DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecTextForCausalLM""", """Data2VecTextForMaskedLM""", """Data2VecTextForMultipleChoice""", """Data2VecTextForQuestionAnswering""", """Data2VecTextForSequenceClassification""", """Data2VecTextForTokenClassification""", """Data2VecTextModel""", """Data2VecTextPreTrainedModel""", ] _SCREAMING_SNAKE_CASE = [ """DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecVisionForImageClassification""", """Data2VecVisionForMaskedImageModeling""", """Data2VecVisionForSemanticSegmentation""", """Data2VecVisionModel""", """Data2VecVisionPreTrainedModel""", ] if is_tf_available(): _SCREAMING_SNAKE_CASE = [ """TFData2VecVisionForImageClassification""", """TFData2VecVisionForSemanticSegmentation""", """TFData2VecVisionModel""", """TFData2VecVisionPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_dataavec_audio import DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecAudioConfig from .configuration_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecTextConfig, DataaVecTextOnnxConfig, ) from .configuration_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecVisionConfig, DataaVecVisionOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_dataavec_audio import ( DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecAudioForAudioFrameClassification, DataaVecAudioForCTC, DataaVecAudioForSequenceClassification, DataaVecAudioForXVector, DataaVecAudioModel, DataaVecAudioPreTrainedModel, ) from .modeling_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecTextForCausalLM, DataaVecTextForMaskedLM, DataaVecTextForMultipleChoice, DataaVecTextForQuestionAnswering, DataaVecTextForSequenceClassification, DataaVecTextForTokenClassification, DataaVecTextModel, DataaVecTextPreTrainedModel, ) from .modeling_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecVisionForImageClassification, DataaVecVisionForMaskedImageModeling, DataaVecVisionForSemanticSegmentation, DataaVecVisionModel, DataaVecVisionPreTrainedModel, ) if is_tf_available(): from .modeling_tf_dataavec_vision import ( TFDataaVecVisionForImageClassification, TFDataaVecVisionForSemanticSegmentation, TFDataaVecVisionModel, TFDataaVecVisionPreTrainedModel, ) else: import sys _SCREAMING_SNAKE_CASE = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
502
'''simple docstring''' from typing import List, Optional, Union import torch from transformers import ( XLMRobertaTokenizer, ) from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDIMScheduler, DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) from .text_encoder import MultilingualCLIP lowercase : Union[str, Any] = logging.get_logger(__name__) # pylint: disable=invalid-name lowercase : List[str] = """ Examples: ```py >>> from diffusers import KandinskyPipeline, KandinskyPriorPipeline >>> import torch >>> pipe_prior = KandinskyPriorPipeline.from_pretrained(\"kandinsky-community/Kandinsky-2-1-prior\") >>> pipe_prior.to(\"cuda\") >>> prompt = \"red cat, 4k photo\" >>> out = pipe_prior(prompt) >>> image_emb = out.image_embeds >>> negative_image_emb = out.negative_image_embeds >>> pipe = KandinskyPipeline.from_pretrained(\"kandinsky-community/kandinsky-2-1\") >>> pipe.to(\"cuda\") >>> image = pipe( ... prompt, ... image_embeds=image_emb, ... negative_image_embeds=negative_image_emb, ... height=768, ... width=768, ... num_inference_steps=100, ... ).images >>> image[0].save(\"cat.png\") ``` """ def lowerCamelCase__ ( __lowercase , __lowercase , __lowercase=8 ): snake_case : int = h // scale_factor**2 if h % scale_factor**2 != 0: new_h += 1 snake_case : Tuple = w // scale_factor**2 if w % scale_factor**2 != 0: new_w += 1 return new_h * scale_factor, new_w * scale_factor class _a (a__ ): '''simple docstring''' def __init__( self ,__a ,__a ,__a ,__a ,__a ,) -> Optional[Any]: super().__init__() self.register_modules( text_encoder=__a ,tokenizer=__a ,unet=__a ,scheduler=__a ,movq=__a ,) snake_case : int = 2 ** (len(self.movq.config.block_out_channels ) - 1) def snake_case_ ( self ,__a ,__a ,__a ,__a ,__a ,__a ) -> Dict: if latents is None: snake_case : Optional[int] = randn_tensor(__a ,generator=__a ,device=__a ,dtype=__a ) else: if latents.shape != shape: raise ValueError(F'''Unexpected latents shape, got {latents.shape}, expected {shape}''' ) snake_case : Any = latents.to(__a ) snake_case : Tuple = latents * scheduler.init_noise_sigma return latents def snake_case_ ( self ,__a ,__a ,__a ,__a ,__a=None ,) -> int: snake_case : Tuple = len(__a ) if isinstance(__a ,__a ) else 1 # get prompt text embeddings snake_case : str = self.tokenizer( __a ,padding="""max_length""" ,truncation=__a ,max_length=77 ,return_attention_mask=__a ,add_special_tokens=__a ,return_tensors="""pt""" ,) snake_case : str = text_inputs.input_ids snake_case : List[Any] = self.tokenizer(__a ,padding="""longest""" ,return_tensors="""pt""" ).input_ids if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(__a ,__a ): snake_case : str = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1] ) logger.warning( """The following part of your input was truncated because CLIP can only handle sequences up to""" F''' {self.tokenizer.model_max_length} tokens: {removed_text}''' ) snake_case : str = text_input_ids.to(__a ) snake_case : Tuple = text_inputs.attention_mask.to(__a ) snake_case , snake_case : Optional[Any] = self.text_encoder( input_ids=__a ,attention_mask=__a ) snake_case : Optional[Any] = prompt_embeds.repeat_interleave(__a ,dim=0 ) snake_case : str = text_encoder_hidden_states.repeat_interleave(__a ,dim=0 ) snake_case : str = text_mask.repeat_interleave(__a ,dim=0 ) if do_classifier_free_guidance: snake_case : List[str] if negative_prompt is None: snake_case : List[str] = [""""""] * batch_size elif type(__a ) is not type(__a ): raise TypeError( F'''`negative_prompt` should be the same type to `prompt`, but got {type(__a )} !=''' F''' {type(__a )}.''' ) elif isinstance(__a ,__a ): snake_case : Dict = [negative_prompt] elif batch_size != len(__a ): raise ValueError( F'''`negative_prompt`: {negative_prompt} has batch size {len(__a )}, but `prompt`:''' F''' {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches''' """ the batch size of `prompt`.""" ) else: snake_case : Optional[int] = negative_prompt snake_case : Union[str, Any] = self.tokenizer( __a ,padding="""max_length""" ,max_length=77 ,truncation=__a ,return_attention_mask=__a ,add_special_tokens=__a ,return_tensors="""pt""" ,) snake_case : int = uncond_input.input_ids.to(__a ) snake_case : str = uncond_input.attention_mask.to(__a ) snake_case , snake_case : str = self.text_encoder( input_ids=__a ,attention_mask=__a ) # duplicate unconditional embeddings for each generation per prompt, using mps friendly method snake_case : List[str] = negative_prompt_embeds.shape[1] snake_case : Any = negative_prompt_embeds.repeat(1 ,__a ) snake_case : Dict = negative_prompt_embeds.view(batch_size * num_images_per_prompt ,__a ) snake_case : List[str] = uncond_text_encoder_hidden_states.shape[1] snake_case : Any = uncond_text_encoder_hidden_states.repeat(1 ,__a ,1 ) snake_case : List[Any] = uncond_text_encoder_hidden_states.view( batch_size * num_images_per_prompt ,__a ,-1 ) snake_case : Any = uncond_text_mask.repeat_interleave(__a ,dim=0 ) # done duplicates # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes snake_case : List[str] = torch.cat([negative_prompt_embeds, prompt_embeds] ) snake_case : Optional[Any] = torch.cat([uncond_text_encoder_hidden_states, text_encoder_hidden_states] ) snake_case : List[str] = torch.cat([uncond_text_mask, text_mask] ) return prompt_embeds, text_encoder_hidden_states, text_mask def snake_case_ ( self ,__a=0 ) -> Tuple: if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("""Please install accelerate via `pip install accelerate`""" ) snake_case : List[Any] = torch.device(F'''cuda:{gpu_id}''' ) snake_case : Tuple = [ self.unet, self.text_encoder, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(__a ,__a ) def snake_case_ ( self ,__a=0 ) -> List[Any]: if is_accelerate_available() and is_accelerate_version(""">=""" ,"""0.17.0.dev0""" ): from accelerate import cpu_offload_with_hook else: raise ImportError("""`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.""" ) snake_case : Union[str, Any] = torch.device(F'''cuda:{gpu_id}''' ) if self.device.type != "cpu": self.to("""cpu""" ,silence_dtype_warnings=__a ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) snake_case : Any = None for cpu_offloaded_model in [self.text_encoder, self.unet, self.movq]: snake_case , snake_case : Optional[int] = cpu_offload_with_hook(__a ,__a ,prev_module_hook=__a ) if self.safety_checker is not None: snake_case , snake_case : List[str] = cpu_offload_with_hook(self.safety_checker ,__a ,prev_module_hook=__a ) # We'll offload the last model manually. snake_case : Any = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def snake_case_ ( self ) -> List[Any]: if not hasattr(self.unet ,"""_hf_hook""" ): return self.device for module in self.unet.modules(): if ( hasattr(__a ,"""_hf_hook""" ) and hasattr(module._hf_hook ,"""execution_device""" ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(__a ) def __call__( self ,__a ,__a ,__a ,__a = None ,__a = 512 ,__a = 512 ,__a = 100 ,__a = 4.0 ,__a = 1 ,__a = None ,__a = None ,__a = "pil" ,__a = True ,) -> List[str]: if isinstance(__a ,__a ): snake_case : Optional[Any] = 1 elif isinstance(__a ,__a ): snake_case : List[Any] = len(__a ) else: raise ValueError(F'''`prompt` has to be of type `str` or `list` but is {type(__a )}''' ) snake_case : Optional[Any] = self._execution_device snake_case : Optional[Any] = batch_size * num_images_per_prompt snake_case : str = guidance_scale > 1.0 snake_case , snake_case , snake_case : List[str] = self._encode_prompt( __a ,__a ,__a ,__a ,__a ) if isinstance(__a ,__a ): snake_case : Union[str, Any] = torch.cat(__a ,dim=0 ) if isinstance(__a ,__a ): snake_case : Any = torch.cat(__a ,dim=0 ) if do_classifier_free_guidance: snake_case : Dict = image_embeds.repeat_interleave(__a ,dim=0 ) snake_case : Dict = negative_image_embeds.repeat_interleave(__a ,dim=0 ) snake_case : Union[str, Any] = torch.cat([negative_image_embeds, image_embeds] ,dim=0 ).to( dtype=prompt_embeds.dtype ,device=__a ) self.scheduler.set_timesteps(__a ,device=__a ) snake_case : Union[str, Any] = self.scheduler.timesteps snake_case : Optional[int] = self.unet.config.in_channels snake_case , snake_case : str = get_new_h_w(__a ,__a ,self.movq_scale_factor ) # create initial latent snake_case : int = self.prepare_latents( (batch_size, num_channels_latents, height, width) ,text_encoder_hidden_states.dtype ,__a ,__a ,__a ,self.scheduler ,) for i, t in enumerate(self.progress_bar(__a ) ): # expand the latents if we are doing classifier free guidance snake_case : int = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents snake_case : Any = {"""text_embeds""": prompt_embeds, """image_embeds""": image_embeds} snake_case : List[str] = self.unet( sample=__a ,timestep=__a ,encoder_hidden_states=__a ,added_cond_kwargs=__a ,return_dict=__a ,)[0] if do_classifier_free_guidance: snake_case , snake_case : Any = noise_pred.split(latents.shape[1] ,dim=1 ) snake_case , snake_case : Any = noise_pred.chunk(2 ) snake_case , snake_case : Union[str, Any] = variance_pred.chunk(2 ) snake_case : List[Any] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) snake_case : Any = torch.cat([noise_pred, variance_pred_text] ,dim=1 ) if not ( hasattr(self.scheduler.config ,"""variance_type""" ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): snake_case , snake_case : Tuple = noise_pred.split(latents.shape[1] ,dim=1 ) # compute the previous noisy sample x_t -> x_t-1 snake_case : Tuple = self.scheduler.step( __a ,__a ,__a ,generator=__a ,).prev_sample # post-processing snake_case : Optional[int] = self.movq.decode(__a ,force_not_quantize=__a )["""sample"""] if output_type not in ["pt", "np", "pil"]: raise ValueError(F'''Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}''' ) if output_type in ["np", "pil"]: snake_case : Tuple = image * 0.5 + 0.5 snake_case : List[Any] = image.clamp(0 ,1 ) snake_case : Tuple = image.cpu().permute(0 ,2 ,3 ,1 ).float().numpy() if output_type == "pil": snake_case : Dict = self.numpy_to_pil(__a ) if not return_dict: return (image,) return ImagePipelineOutput(images=__a )
116
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCamelCase : Union[str, Any] = {"""configuration_timm_backbone""": ["""TimmBackboneConfig"""]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Union[str, Any] = ["""TimmBackbone"""] if TYPE_CHECKING: from .configuration_timm_backbone import TimmBackboneConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_timm_backbone import TimmBackbone else: import sys lowerCamelCase : Optional[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
720
"""simple docstring""" from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descriptor_pool from google.protobuf import symbol_database as _symbol_database from google.protobuf.internal import builder as _builder # @@protoc_insertion_point(imports) lowerCamelCase : str = _symbol_database.Default() lowerCamelCase : Any = _descriptor_pool.Default().AddSerializedFile( b"""\n\x19sentencepiece_model.proto\x12\rsentencepiece\"\x80\x0c\n\x0bTrainerSpec\x12\r\n\x05input\x18\x01 \x03(\t\x12\x14\n\x0cinput_format\x18\x07 \x01(\t\x12\x14\n\x0cmodel_prefix\x18\x02 \x01(\t\x12\x41\n\nmodel_type\x18\x03 \x01(\x0e\x32$.sentencepiece.TrainerSpec.ModelType:\x07UNIGRAM\x12\x18\n\nvocab_size\x18\x04 \x01(\x05:\x04\x38\x30\x30\x30\x12\x17\n\x0f\x61\x63\x63\x65pt_language\x18\x05 \x03(\t\x12 \n\x15self_test_sample_size\x18\x06 \x01(\x05:\x01\x30\x12*\n\x1b\x65nable_differential_privacy\x18\x32 \x01(\x08:\x05\x66\x61lse\x12+\n differential_privacy_noise_level\x18\x33 \x01(\x02:\x01\x30\x12\x32\n\'differential_privacy_clipping_threshold\x18\x34 \x01(\x04:\x01\x30\x12\"\n\x12\x63haracter_coverage\x18\n \x01(\x02:\x06\x30.9995\x12\x1e\n\x13input_sentence_size\x18\x0b \x01(\x04:\x01\x30\x12$\n\x16shuffle_input_sentence\x18\x13 \x01(\x08:\x04true\x12 \n\x14mining_sentence_size\x18\x0c \x01(\x05\x42\x02\x18\x01\x12\"\n\x16training_sentence_size\x18\r \x01(\x05\x42\x02\x18\x01\x12(\n\x17seed_sentencepiece_size\x18\x0e \x01(\x05:\x07\x31\x30\x30\x30\x30\x30\x30\x12\x1e\n\x10shrinking_factor\x18\x0f \x01(\x02:\x04\x30.75\x12!\n\x13max_sentence_length\x18\x12 \x01(\x05:\x04\x34\x31\x39\x32\x12\x17\n\x0bnum_threads\x18\x10 \x01(\x05:\x02\x31\x36\x12\x1d\n\x12num_sub_iterations\x18\x11 \x01(\x05:\x01\x32\x12$\n\x18max_sentencepiece_length\x18\x14 \x01(\x05:\x02\x31\x36\x12%\n\x17split_by_unicode_script\x18\x15 \x01(\x08:\x04true\x12\x1d\n\x0fsplit_by_number\x18\x17 \x01(\x08:\x04true\x12!\n\x13split_by_whitespace\x18\x16 \x01(\x08:\x04true\x12)\n\x1atreat_whitespace_as_suffix\x18\x18 \x01(\x08:\x05\x66\x61lse\x12+\n\x1c\x61llow_whitespace_only_pieces\x18\x1a \x01(\x08:\x05\x66\x61lse\x12\x1b\n\x0csplit_digits\x18\x19 \x01(\x08:\x05\x66\x61lse\x12#\n\x19pretokenization_delimiter\x18\x35 \x01(\t:\x00\x12\x17\n\x0f\x63ontrol_symbols\x18\x1e \x03(\t\x12\x1c\n\x14user_defined_symbols\x18\x1f \x03(\t\x12\x16\n\x0erequired_chars\x18$ \x01(\t\x12\x1c\n\rbyte_fallback\x18# \x01(\x08:\x05\x66\x61lse\x12+\n\x1dvocabulary_output_piece_score\x18 \x01(\x08:\x04true\x12\x1e\n\x10hard_vocab_limit\x18! \x01(\x08:\x04true\x12\x1c\n\ruse_all_vocab\x18\" \x01(\x08:\x05\x66\x61lse\x12\x11\n\x06unk_id\x18( \x01(\x05:\x01\x30\x12\x11\n\x06\x62os_id\x18) \x01(\x05:\x01\x31\x12\x11\n\x06\x65os_id\x18* \x01(\x05:\x01\x32\x12\x12\n\x06pad_id\x18+ \x01(\x05:\x02-1\x12\x18\n\tunk_piece\x18- \x01(\t:\x05<unk>\x12\x16\n\tbos_piece\x18. \x01(\t:\x03<s>\x12\x17\n\teos_piece\x18/ \x01(\t:\x04</s>\x12\x18\n\tpad_piece\x18\x30 \x01(\t:\x05<pad>\x12\x1a\n\x0bunk_surface\x18, \x01(\t:\x05 \xe2\x81\x87 \x12+\n\x1ctrain_extremely_large_corpus\x18\x31 \x01(\x08:\x05\x66\x61lse\"5\n\tModelType\x12\x0b\n\x07UNIGRAM\x10\x01\x12\x07\n\x03\x42PE\x10\x02\x12\x08\n\x04WORD\x10\x03\x12\x08\n\x04\x43HAR\x10\x04*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\"\xd1\x01\n\x0eNormalizerSpec\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x1c\n\x14precompiled_charsmap\x18\x02 \x01(\x0c\x12\x1e\n\x10\x61\x64\x64_dummy_prefix\x18\x03 \x01(\x08:\x04true\x12&\n\x18remove_extra_whitespaces\x18\x04 \x01(\x08:\x04true\x12 \n\x12\x65scape_whitespaces\x18\x05 \x01(\x08:\x04true\x12\x1e\n\x16normalization_rule_tsv\x18\x06 \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\"y\n\x0cSelfTestData\x12\x33\n\x07samples\x18\x01 \x03(\x0b\x32\".sentencepiece.SelfTestData.Sample\x1a)\n\x06Sample\x12\r\n\x05input\x18\x01 \x01(\t\x12\x10\n\x08\x65xpected\x18\x02 \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\"\xfe\x03\n\nModelProto\x12\x37\n\x06pieces\x18\x01 \x03(\x0b\x32\'.sentencepiece.ModelProto.SentencePiece\x12\x30\n\x0ctrainer_spec\x18\x02 \x01(\x0b\x32\x1a.sentencepiece.TrainerSpec\x12\x36\n\x0fnormalizer_spec\x18\x03 \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x12\x33\n\x0eself_test_data\x18\x04 \x01(\x0b\x32\x1b.sentencepiece.SelfTestData\x12\x38\n\x11\x64\x65normalizer_spec\x18\x05 \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x1a\xd2\x01\n\rSentencePiece\x12\r\n\x05piece\x18\x01 \x01(\t\x12\r\n\x05score\x18\x02 \x01(\x02\x12\x42\n\x04type\x18\x03 \x01(\x0e\x32,.sentencepiece.ModelProto.SentencePiece.Type:\x06NORMAL\"T\n\x04Type\x12\n\n\x06NORMAL\x10\x01\x12\x0b\n\x07UNKNOWN\x10\x02\x12\x0b\n\x07\x43ONTROL\x10\x03\x12\x10\n\x0cUSER_DEFINED\x10\x04\x12\x08\n\x04\x42YTE\x10\x06\x12\n\n\x06UNUSED\x10\x05*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\x42\x02H\x03""" ) lowerCamelCase : List[str] = globals() _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, """sentencepiece_model_pb2""", _globals) if _descriptor._USE_C_DESCRIPTORS is False: lowerCamelCase : List[str] = None lowerCamelCase : List[str] = b"""H\003""" # (generated by protobuf compiler, but `_TRAINERSPEC` is not defined) # _TRAINERSPEC.fields_by_name["mining_sentence_size"]._options = None # _TRAINERSPEC.fields_by_name["mining_sentence_size"]._serialized_options = b"\030\001" # _TRAINERSPEC.fields_by_name["training_sentence_size"]._options = None # _TRAINERSPEC.fields_by_name["training_sentence_size"]._serialized_options = b"\030\001" lowerCamelCase : Optional[int] = 4_5 lowerCamelCase : Tuple = 1_5_8_1 lowerCamelCase : Optional[int] = 1_5_1_7 lowerCamelCase : List[Any] = 1_5_7_0 lowerCamelCase : Dict = 1_5_8_4 lowerCamelCase : Dict = 1_7_9_3 lowerCamelCase : Optional[Any] = 1_7_9_5 lowerCamelCase : List[Any] = 1_9_1_6 lowerCamelCase : int = 1_8_6_4 lowerCamelCase : int = 1_9_0_5 lowerCamelCase : Dict = 1_9_1_9 lowerCamelCase : str = 2_4_2_9 lowerCamelCase : str = 2_2_0_8 lowerCamelCase : int = 2_4_1_8 lowerCamelCase : Dict = 2_3_2_3 lowerCamelCase : int = 2_4_0_7 # @@protoc_insertion_point(module_scope)
168
0
'''simple docstring''' import os def a ( UpperCamelCase_ : str = "matrix.txt" ) -> int: with open(os.path.join(os.path.dirname(lowercase_ ) , lowercase_ ) ) as in_file: snake_case__ =in_file.read() snake_case__ =[[int(lowercase_ ) for cell in row.split(',' )] for row in data.strip().splitlines()] snake_case__ =[[0 for cell in row] for row in grid] snake_case__ =len(grid[0] ) snake_case__ =[[0 for i in range(lowercase_ )] for j in range(lowercase_ )] snake_case__ =grid[0][0] for i in range(1 , lowercase_ ): snake_case__ =grid[0][i] + dp[0][i - 1] for i in range(1 , lowercase_ ): snake_case__ =grid[i][0] + dp[i - 1][0] for i in range(1 , lowercase_ ): for j in range(1 , lowercase_ ): snake_case__ =grid[i][j] + min(dp[i - 1][j] , dp[i][j - 1] ) return dp[-1][-1] if __name__ == "__main__": print(f"""{solution() = }""")
538
from typing import List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase = logging.get_logger(__name__) lowerCAmelCase = { """huggingface/autoformer-tourism-monthly""": """https://huggingface.co/huggingface/autoformer-tourism-monthly/resolve/main/config.json""", } class lowerCamelCase ( _UpperCamelCase ): _lowerCAmelCase : Optional[int] = '''autoformer''' _lowerCAmelCase : Any = { '''hidden_size''': '''d_model''', '''num_attention_heads''': '''encoder_attention_heads''', '''num_hidden_layers''': '''encoder_layers''', } def __init__( self , lowercase__ = None , lowercase__ = None , lowercase__ = "student_t" , lowercase__ = "nll" , lowercase__ = 1 , lowercase__ = [1, 2, 3, 4, 5, 6, 7] , lowercase__ = True , lowercase__ = 0 , lowercase__ = 0 , lowercase__ = 0 , lowercase__ = 0 , lowercase__ = None , lowercase__ = None , lowercase__ = 6_4 , lowercase__ = 2 , lowercase__ = 2 , lowercase__ = 2 , lowercase__ = 2 , lowercase__ = 3_2 , lowercase__ = 3_2 , lowercase__ = "gelu" , lowercase__ = 0.1 , lowercase__ = 0.1 , lowercase__ = 0.1 , lowercase__ = 0.1 , lowercase__ = 0.1 , lowercase__ = 1_0_0 , lowercase__ = 0.0_2 , lowercase__ = True , lowercase__=True , lowercase__ = 1_0 , lowercase__ = 2_5 , lowercase__ = 3 , **lowercase__ , ): # time series specific configuration __UpperCAmelCase : Optional[int] = prediction_length __UpperCAmelCase : Tuple = context_length if context_length is not None else prediction_length __UpperCAmelCase : Tuple = distribution_output __UpperCAmelCase : Tuple = loss __UpperCAmelCase : Dict = input_size __UpperCAmelCase : str = num_time_features __UpperCAmelCase : str = lags_sequence __UpperCAmelCase : int = scaling __UpperCAmelCase : int = num_dynamic_real_features __UpperCAmelCase : List[str] = num_static_real_features __UpperCAmelCase : List[str] = num_static_categorical_features if cardinality is not None and num_static_categorical_features > 0: if len(lowercase__) != num_static_categorical_features: raise ValueError( '''The cardinality should be a list of the same length as `num_static_categorical_features`''') __UpperCAmelCase : Union[str, Any] = cardinality else: __UpperCAmelCase : List[Any] = [0] if embedding_dimension is not None and num_static_categorical_features > 0: if len(lowercase__) != num_static_categorical_features: raise ValueError( '''The embedding dimension should be a list of the same length as `num_static_categorical_features`''') __UpperCAmelCase : Union[str, Any] = embedding_dimension else: __UpperCAmelCase : int = [min(5_0 , (cat + 1) // 2) for cat in self.cardinality] __UpperCAmelCase : Tuple = num_parallel_samples # Transformer architecture configuration __UpperCAmelCase : Dict = input_size * len(self.lags_sequence) + self._number_of_features __UpperCAmelCase : Optional[int] = d_model __UpperCAmelCase : List[Any] = encoder_attention_heads __UpperCAmelCase : int = decoder_attention_heads __UpperCAmelCase : str = encoder_ffn_dim __UpperCAmelCase : int = decoder_ffn_dim __UpperCAmelCase : List[Any] = encoder_layers __UpperCAmelCase : Tuple = decoder_layers __UpperCAmelCase : Union[str, Any] = dropout __UpperCAmelCase : int = attention_dropout __UpperCAmelCase : int = activation_dropout __UpperCAmelCase : str = encoder_layerdrop __UpperCAmelCase : Dict = decoder_layerdrop __UpperCAmelCase : int = activation_function __UpperCAmelCase : Optional[int] = init_std __UpperCAmelCase : Optional[int] = use_cache # Autoformer __UpperCAmelCase : str = label_length __UpperCAmelCase : int = moving_average __UpperCAmelCase : Optional[int] = autocorrelation_factor super().__init__(is_encoder_decoder=lowercase__ , **lowercase__) @property def A( self): return ( sum(self.embedding_dimension) + self.num_dynamic_real_features + self.num_time_features + self.num_static_real_features + self.input_size * 2 # the log1p(abs(loc)) and log(scale) features )
462
0
import gc import unittest from parameterized import parameterized from diffusers import FlaxUNetaDConditionModel from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import load_hf_numpy, require_flax, slow if is_flax_available(): import jax import jax.numpy as jnp @slow @require_flax class __lowercase (unittest.TestCase ): """simple docstring""" def UpperCAmelCase ( self , A , A ) -> List[Any]: return f"""gaussian_noise_s={seed}_shape={"_".join([str(UpperCamelCase__ ) for s in shape] )}.npy""" def UpperCAmelCase ( self ) -> Tuple: super().tearDown() gc.collect() def UpperCAmelCase ( self , A=0 , A=(4, 4, 6_4, 6_4) , A=False ) -> Tuple: snake_case : Union[str, Any] = jnp.bfloataa if fpaa else jnp.floataa snake_case : List[str] = jnp.array(load_hf_numpy(self.get_file_format(UpperCamelCase__ , UpperCamelCase__ ) ) , dtype=UpperCamelCase__ ) return image def UpperCAmelCase ( self , A=False , A="CompVis/stable-diffusion-v1-4" ) -> str: snake_case : Tuple = jnp.bfloataa if fpaa else jnp.floataa snake_case : Dict = """bf16""" if fpaa else None snake_case , snake_case : str = FlaxUNetaDConditionModel.from_pretrained( UpperCamelCase__ , subfolder="""unet""" , dtype=UpperCamelCase__ , revision=UpperCamelCase__ ) return model, params def UpperCAmelCase ( self , A=0 , A=(4, 7_7, 7_6_8) , A=False ) -> str: snake_case : List[Any] = jnp.bfloataa if fpaa else jnp.floataa snake_case : List[str] = jnp.array(load_hf_numpy(self.get_file_format(UpperCamelCase__ , UpperCamelCase__ ) ) , dtype=UpperCamelCase__ ) return hidden_states @parameterized.expand( [ # fmt: off [8_3, 4, [-0.23_23, -0.13_04, 0.08_13, -0.30_93, -0.09_19, -0.15_71, -0.11_25, -0.58_06]], [1_7, 0.55, [-0.08_31, -0.24_43, 0.09_01, -0.09_19, 0.33_96, 0.01_03, -0.37_43, 0.07_01]], [8, 0.89, [-0.48_63, 0.08_59, 0.08_75, -0.16_58, 0.91_99, -0.01_14, 0.48_39, 0.46_39]], [3, 1_0_0_0, [-0.56_49, 0.24_02, -0.55_18, 0.12_48, 1.13_28, -0.24_43, -0.03_25, -1.00_78]], # fmt: on ] ) def UpperCAmelCase ( self , A , A , A ) -> str: snake_case , snake_case : Any = self.get_unet_model(model_id="""CompVis/stable-diffusion-v1-4""" , fpaa=UpperCamelCase__ ) snake_case : Tuple = self.get_latents(UpperCamelCase__ , fpaa=UpperCamelCase__ ) snake_case : Optional[int] = self.get_encoder_hidden_states(UpperCamelCase__ , fpaa=UpperCamelCase__ ) snake_case : Any = model.apply( {"""params""": params} , UpperCamelCase__ , jnp.array(UpperCamelCase__ , dtype=jnp.intaa ) , encoder_hidden_states=UpperCamelCase__ , ).sample assert sample.shape == latents.shape snake_case : Union[str, Any] = jnp.asarray(jax.device_get((sample[-1, -2:, -2:, :2].flatten()) ) , dtype=jnp.floataa ) snake_case : Any = jnp.array(UpperCamelCase__ , dtype=jnp.floataa ) # Found torch (float16) and flax (bfloat16) outputs to be within this tolerance, in the same hardware assert jnp.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1e-2 ) @parameterized.expand( [ # fmt: off [8_3, 4, [0.15_14, 0.08_07, 0.16_24, 0.10_16, -0.18_96, 0.02_63, 0.06_77, 0.23_10]], [1_7, 0.55, [0.11_64, -0.02_16, 0.01_70, 0.15_89, -0.31_20, 0.10_05, -0.05_81, -0.14_58]], [8, 0.89, [-0.17_58, -0.01_69, 0.10_04, -0.14_11, 0.13_12, 0.11_03, -0.19_96, 0.21_39]], [3, 1_0_0_0, [0.12_14, 0.03_52, -0.07_31, -0.15_62, -0.09_94, -0.09_06, -0.23_40, -0.05_39]], # fmt: on ] ) def UpperCAmelCase ( self , A , A , A ) -> str: snake_case , snake_case : Dict = self.get_unet_model(model_id="""stabilityai/stable-diffusion-2""" , fpaa=UpperCamelCase__ ) snake_case : Union[str, Any] = self.get_latents(UpperCamelCase__ , shape=(4, 4, 9_6, 9_6) , fpaa=UpperCamelCase__ ) snake_case : Optional[Any] = self.get_encoder_hidden_states(UpperCamelCase__ , shape=(4, 7_7, 1_0_2_4) , fpaa=UpperCamelCase__ ) snake_case : Optional[int] = model.apply( {"""params""": params} , UpperCamelCase__ , jnp.array(UpperCamelCase__ , dtype=jnp.intaa ) , encoder_hidden_states=UpperCamelCase__ , ).sample assert sample.shape == latents.shape snake_case : Tuple = jnp.asarray(jax.device_get((sample[-1, -2:, -2:, :2].flatten()) ) , dtype=jnp.floataa ) snake_case : List[str] = jnp.array(UpperCamelCase__ , dtype=jnp.floataa ) # Found torch (float16) and flax (bfloat16) outputs to be within this tolerance, on the same hardware assert jnp.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1e-2 )
711
import enum import warnings from ..tokenization_utils import TruncationStrategy from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING lowerCamelCase : Any = logging.get_logger(__name__) class __lowercase (enum.Enum ): """simple docstring""" _snake_case = 0 _snake_case = 1 @add_end_docstrings(UpperCamelCase__ ) class __lowercase (UpperCamelCase__ ): """simple docstring""" _snake_case = """generated""" def __init__( self , *A , **A ) -> Optional[Any]: super().__init__(*A , **A ) self.check_model_type( TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING if self.framework == """tf""" else MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING ) def UpperCAmelCase ( self , A=None , A=None , A=None , A=None , A=None , A=None , **A , ) -> Optional[int]: snake_case : Tuple = {} if truncation is not None: snake_case : Union[str, Any] = truncation snake_case : Dict = generate_kwargs snake_case : int = {} if return_tensors is not None and return_type is None: snake_case : List[Any] = ReturnType.TENSORS if return_tensors else ReturnType.TEXT if return_type is not None: snake_case : List[str] = return_type if clean_up_tokenization_spaces is not None: snake_case : int = clean_up_tokenization_spaces if stop_sequence is not None: snake_case : Tuple = self.tokenizer.encode(A , add_special_tokens=A ) if len(A ) > 1: warnings.warn( """Stopping on a multiple token sequence is not yet supported on transformers. The first token of""" """ the stop sequence will be used as the stop sequence string in the interim.""" ) snake_case : List[str] = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def UpperCAmelCase ( self , A , A , A ) -> Union[str, Any]: return True def UpperCAmelCase ( self , *A , A ) -> Tuple: snake_case : Union[str, Any] = self.model.config.prefix if self.model.config.prefix is not None else """""" if isinstance(args[0] , A ): if self.tokenizer.pad_token_id is None: raise ValueError("""Please make sure that the tokenizer has a pad_token_id when using a batch input""" ) snake_case : Union[str, Any] = ([prefix + arg for arg in args[0]],) snake_case : List[Any] = True elif isinstance(args[0] , A ): snake_case : str = (prefix + args[0],) snake_case : str = False else: raise ValueError( f""" `args[0]`: {args[0]} have the wrong format. The should be either of type `str` or type `list`""" ) snake_case : Optional[Any] = self.tokenizer(*A , padding=A , truncation=A , return_tensors=self.framework ) # This is produced by tokenizers but is an invalid generate kwargs if "token_type_ids" in inputs: del inputs["token_type_ids"] return inputs def __call__( self , *A , **A ) -> Union[str, Any]: snake_case : Tuple = super().__call__(*A , **A ) if ( isinstance(args[0] , A ) and all(isinstance(A , A ) for el in args[0] ) and all(len(A ) == 1 for res in result ) ): return [res[0] for res in result] return result def UpperCAmelCase ( self , A , A=TruncationStrategy.DO_NOT_TRUNCATE , **A ) -> str: snake_case : Optional[Any] = self._parse_and_tokenize(A , truncation=A , **A ) return inputs def UpperCAmelCase ( self , A , **A ) -> Tuple: if self.framework == "pt": snake_case , snake_case : List[str] = model_inputs["""input_ids"""].shape elif self.framework == "tf": snake_case , snake_case : Optional[Any] = tf.shape(model_inputs["""input_ids"""] ).numpy() snake_case : Dict = generate_kwargs.get("""min_length""" , self.model.config.min_length ) snake_case : str = generate_kwargs.get("""max_length""" , self.model.config.max_length ) self.check_inputs(A , generate_kwargs["""min_length"""] , generate_kwargs["""max_length"""] ) snake_case : List[str] = self.model.generate(**A , **A ) snake_case : Dict = output_ids.shape[0] if self.framework == "pt": snake_case : List[Any] = output_ids.reshape(A , out_b // in_b , *output_ids.shape[1:] ) elif self.framework == "tf": snake_case : Any = tf.reshape(A , (in_b, out_b // in_b, *output_ids.shape[1:]) ) return {"output_ids": output_ids} def UpperCAmelCase ( self , A , A=ReturnType.TEXT , A=False ) -> Union[str, Any]: snake_case : Tuple = [] for output_ids in model_outputs["output_ids"][0]: if return_type == ReturnType.TENSORS: snake_case : Dict = {f"""{self.return_name}_token_ids""": output_ids} elif return_type == ReturnType.TEXT: snake_case : int = { f"""{self.return_name}_text""": self.tokenizer.decode( A , skip_special_tokens=A , clean_up_tokenization_spaces=A , ) } records.append(A ) return records @add_end_docstrings(UpperCamelCase__ ) class __lowercase (UpperCamelCase__ ): """simple docstring""" _snake_case = """summary""" def __call__( self , *A , **A ) -> str: return super().__call__(*A , **A ) def UpperCAmelCase ( self , A , A , A ) -> bool: if max_length < min_length: logger.warning(f"""Your min_length={min_length} must be inferior than your max_length={max_length}.""" ) if input_length < max_length: logger.warning( f"""Your max_length is set to {max_length}, but your input_length is only {input_length}. Since this is """ """a summarization task, where outputs shorter than the input are typically wanted, you might """ f"""consider decreasing max_length manually, e.g. summarizer('...', max_length={input_length//2})""" ) @add_end_docstrings(UpperCamelCase__ ) class __lowercase (UpperCamelCase__ ): """simple docstring""" _snake_case = """translation""" def UpperCAmelCase ( self , A , A , A ) -> Union[str, Any]: if input_length > 0.9 * max_length: logger.warning( f"""Your input_length: {input_length} is bigger than 0.9 * max_length: {max_length}. You might consider """ """increasing your max_length manually, e.g. translator('...', max_length=400)""" ) return True def UpperCAmelCase ( self , *A , A=TruncationStrategy.DO_NOT_TRUNCATE , A=None , A=None ) -> Optional[int]: if getattr(self.tokenizer , """_build_translation_inputs""" , A ): return self.tokenizer._build_translation_inputs( *A , return_tensors=self.framework , truncation=A , src_lang=A , tgt_lang=A ) else: return super()._parse_and_tokenize(*A , truncation=A ) def UpperCAmelCase ( self , A=None , A=None , **A ) -> Union[str, Any]: snake_case , snake_case , snake_case : str = super()._sanitize_parameters(**A ) if src_lang is not None: snake_case : Tuple = src_lang if tgt_lang is not None: snake_case : str = tgt_lang if src_lang is None and tgt_lang is None: # Backward compatibility, direct arguments use is preferred. snake_case : Union[str, Any] = kwargs.get("""task""" , self.task ) snake_case : Any = task.split("""_""" ) if task and len(A ) == 4: # translation, XX, to YY snake_case : Optional[Any] = items[1] snake_case : Dict = items[3] return preprocess_params, forward_params, postprocess_params def __call__( self , *A , **A ) -> str: return super().__call__(*A , **A )
684
0
"""simple docstring""" import numpy as np import qiskit def _UpperCamelCase ( UpperCamelCase = 8 , UpperCamelCase = None ) -> str: """simple docstring""" __UpperCAmelCase : Any = np.random.default_rng(seed=SCREAMING_SNAKE_CASE__ ) # Roughly 25% of the qubits will contribute to the key. # So we take more than we need. __UpperCAmelCase : Optional[int] = 6 * key_len # Measurement basis for Alice's qubits. __UpperCAmelCase : Optional[int] = rng.integers(2 , size=SCREAMING_SNAKE_CASE__ ) # The set of states Alice will prepare. __UpperCAmelCase : Optional[int] = rng.integers(2 , size=SCREAMING_SNAKE_CASE__ ) # Measurement basis for Bob's qubits. __UpperCAmelCase : Tuple = rng.integers(2 , size=SCREAMING_SNAKE_CASE__ ) # Quantum Circuit to simulate BB84 __UpperCAmelCase : Optional[int] = qiskit.QuantumCircuit(SCREAMING_SNAKE_CASE__ , name="BB84" ) # Alice prepares her qubits according to rules above. for index, _ in enumerate(SCREAMING_SNAKE_CASE__ ): if alice_state[index] == 1: bbaa_circ.x(SCREAMING_SNAKE_CASE__ ) if alice_basis[index] == 1: bbaa_circ.h(SCREAMING_SNAKE_CASE__ ) bbaa_circ.barrier() # Bob measures the received qubits according to rules above. for index, _ in enumerate(SCREAMING_SNAKE_CASE__ ): if bob_basis[index] == 1: bbaa_circ.h(SCREAMING_SNAKE_CASE__ ) bbaa_circ.barrier() bbaa_circ.measure_all() # Simulate the quantum circuit. __UpperCAmelCase : Union[str, Any] = qiskit.Aer.get_backend("aer_simulator" ) # We only need to run one shot because the key is unique. # Multiple shots will produce the same key. __UpperCAmelCase : int = qiskit.execute(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , shots=1 , seed_simulator=SCREAMING_SNAKE_CASE__ ) # Returns the result of measurement. __UpperCAmelCase : str = job.result().get_counts(SCREAMING_SNAKE_CASE__ ).most_frequent() # Extracting the generated key from the simulation results. # Only keep measurement results where Alice and Bob chose the same basis. __UpperCAmelCase : Optional[Any] = "".join( [ result_bit for alice_basis_bit, bob_basis_bit, result_bit in zip( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if alice_basis_bit == bob_basis_bit ] ) # Get final key. Pad with 0 if too short, otherwise truncate. __UpperCAmelCase : Optional[Any] = gen_key[:key_len] if len(SCREAMING_SNAKE_CASE__ ) >= key_len else gen_key.ljust(SCREAMING_SNAKE_CASE__ , "0" ) return key if __name__ == "__main__": print(f'''The generated key is : {bbaa(8, seed=0)}''') from doctest import testmod testmod()
77
"""simple docstring""" import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class snake_case_ ( a_ ): __lowerCAmelCase = (DEISMultistepScheduler,) __lowerCAmelCase = (("num_inference_steps", 2_5),) def snake_case_ ( self , **a_ ): a_ : Optional[Any] = { "num_train_timesteps": 1_0_0_0, "beta_start": 0.0_001, "beta_end": 0.02, "beta_schedule": "linear", "solver_order": 2, } config.update(**a_ ) return config def snake_case_ ( self , a_=0 , **a_ ): a_ : Union[str, Any] = dict(self.forward_default_kwargs ) a_ : Union[str, Any] = kwargs.pop("num_inference_steps" , a_ ) a_ : List[str] = self.dummy_sample a_ : Union[str, Any] = 0.1 * sample a_ : List[Any] = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: a_ : Any = self.get_scheduler_config(**a_ ) a_ : Dict = scheduler_class(**a_ ) scheduler.set_timesteps(a_ ) # copy over dummy past residuals a_ : Optional[Any] = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(a_ ) a_ : Dict = scheduler_class.from_pretrained(a_ ) new_scheduler.set_timesteps(a_ ) # copy over dummy past residuals a_ : List[Any] = dummy_past_residuals[: new_scheduler.config.solver_order] a_ , a_ : List[str] = sample, sample for t in range(a_ , time_step + scheduler.config.solver_order + 1 ): a_ : Dict = scheduler.step(a_ , a_ , a_ , **a_ ).prev_sample a_ : List[str] = new_scheduler.step(a_ , a_ , a_ , **a_ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def snake_case_ ( self ): pass def snake_case_ ( self , a_=0 , **a_ ): a_ : List[str] = dict(self.forward_default_kwargs ) a_ : Dict = kwargs.pop("num_inference_steps" , a_ ) a_ : List[str] = self.dummy_sample a_ : str = 0.1 * sample a_ : Tuple = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: a_ : Union[str, Any] = self.get_scheduler_config() a_ : Optional[Any] = scheduler_class(**a_ ) scheduler.set_timesteps(a_ ) # copy over dummy past residuals (must be after setting timesteps) a_ : Optional[int] = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(a_ ) a_ : List[Any] = scheduler_class.from_pretrained(a_ ) # copy over dummy past residuals new_scheduler.set_timesteps(a_ ) # copy over dummy past residual (must be after setting timesteps) a_ : Dict = dummy_past_residuals[: new_scheduler.config.solver_order] a_ : Optional[int] = scheduler.step(a_ , a_ , a_ , **a_ ).prev_sample a_ : Tuple = new_scheduler.step(a_ , a_ , a_ , **a_ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def snake_case_ ( self , a_=None , **a_ ): if scheduler is None: a_ : Optional[Any] = self.scheduler_classes[0] a_ : Dict = self.get_scheduler_config(**a_ ) a_ : Union[str, Any] = scheduler_class(**a_ ) a_ : Optional[int] = self.scheduler_classes[0] a_ : List[str] = self.get_scheduler_config(**a_ ) a_ : Tuple = scheduler_class(**a_ ) a_ : Optional[int] = 1_0 a_ : Optional[Any] = self.dummy_model() a_ : Tuple = self.dummy_sample_deter scheduler.set_timesteps(a_ ) for i, t in enumerate(scheduler.timesteps ): a_ : str = model(a_ , a_ ) a_ : str = scheduler.step(a_ , a_ , a_ ).prev_sample return sample def snake_case_ ( self ): a_ : Union[str, Any] = dict(self.forward_default_kwargs ) a_ : Tuple = kwargs.pop("num_inference_steps" , a_ ) for scheduler_class in self.scheduler_classes: a_ : List[Any] = self.get_scheduler_config() a_ : str = scheduler_class(**a_ ) a_ : Any = self.dummy_sample a_ : int = 0.1 * sample if num_inference_steps is not None and hasattr(a_ , "set_timesteps" ): scheduler.set_timesteps(a_ ) elif num_inference_steps is not None and not hasattr(a_ , "set_timesteps" ): a_ : Union[str, Any] = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) a_ : Optional[int] = [residual + 0.2, residual + 0.15, residual + 0.10] a_ : str = dummy_past_residuals[: scheduler.config.solver_order] a_ : str = scheduler.timesteps[5] a_ : Dict = scheduler.timesteps[6] a_ : Dict = scheduler.step(a_ , a_ , a_ , **a_ ).prev_sample a_ : Any = scheduler.step(a_ , a_ , a_ , **a_ ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def snake_case_ ( self ): # make sure that iterating over schedulers with same config names gives same results # for defaults a_ : Dict = DEISMultistepScheduler(**self.get_scheduler_config() ) a_ : List[str] = self.full_loop(scheduler=a_ ) a_ : Tuple = torch.mean(torch.abs(a_ ) ) assert abs(result_mean.item() - 0.23_916 ) < 1e-3 a_ : int = DPMSolverSinglestepScheduler.from_config(scheduler.config ) a_ : Tuple = DPMSolverMultistepScheduler.from_config(scheduler.config ) a_ : Tuple = UniPCMultistepScheduler.from_config(scheduler.config ) a_ : Any = DEISMultistepScheduler.from_config(scheduler.config ) a_ : str = self.full_loop(scheduler=a_ ) a_ : Any = torch.mean(torch.abs(a_ ) ) assert abs(result_mean.item() - 0.23_916 ) < 1e-3 def snake_case_ ( self ): for timesteps in [2_5, 5_0, 1_0_0, 9_9_9, 1_0_0_0]: self.check_over_configs(num_train_timesteps=a_ ) def snake_case_ ( self ): self.check_over_configs(thresholding=a_ ) for order in [1, 2, 3]: for solver_type in ["logrho"]: for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( thresholding=a_ , prediction_type=a_ , sample_max_value=a_ , algorithm_type="deis" , solver_order=a_ , solver_type=a_ , ) def snake_case_ ( self ): for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=a_ ) def snake_case_ ( self ): for algorithm_type in ["deis"]: for solver_type in ["logrho"]: for order in [1, 2, 3]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( solver_order=a_ , solver_type=a_ , prediction_type=a_ , algorithm_type=a_ , ) a_ : List[Any] = self.full_loop( solver_order=a_ , solver_type=a_ , prediction_type=a_ , algorithm_type=a_ , ) assert not torch.isnan(a_ ).any(), "Samples have nan numbers" def snake_case_ ( self ): self.check_over_configs(lower_order_final=a_ ) self.check_over_configs(lower_order_final=a_ ) def snake_case_ ( self ): for num_inference_steps in [1, 2, 3, 5, 1_0, 5_0, 1_0_0, 9_9_9, 1_0_0_0]: self.check_over_forward(num_inference_steps=a_ , time_step=0 ) def snake_case_ ( self ): a_ : str = self.full_loop() a_ : Dict = torch.mean(torch.abs(a_ ) ) assert abs(result_mean.item() - 0.23_916 ) < 1e-3 def snake_case_ ( self ): a_ : Optional[Any] = self.full_loop(prediction_type="v_prediction" ) a_ : Union[str, Any] = torch.mean(torch.abs(a_ ) ) assert abs(result_mean.item() - 0.091 ) < 1e-3 def snake_case_ ( self ): a_ : List[str] = self.scheduler_classes[0] a_ : str = self.get_scheduler_config(thresholding=a_ , dynamic_thresholding_ratio=0 ) a_ : Dict = scheduler_class(**a_ ) a_ : int = 1_0 a_ : List[str] = self.dummy_model() a_ : Optional[int] = self.dummy_sample_deter.half() scheduler.set_timesteps(a_ ) for i, t in enumerate(scheduler.timesteps ): a_ : Optional[int] = model(a_ , a_ ) a_ : Optional[Any] = scheduler.step(a_ , a_ , a_ ).prev_sample assert sample.dtype == torch.floataa
237
0
import inspect import unittest import numpy as np from transformers import ViTConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor if is_flax_available(): import jax from transformers.models.vit.modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __init__( self , lowercase , lowercase=13 , lowercase=30 , lowercase=2 , lowercase=3 , lowercase=True , lowercase=True , lowercase=32 , lowercase=5 , lowercase=4 , lowercase=37 , lowercase="gelu" , lowercase=0.1 , lowercase=0.1 , lowercase=10 , lowercase=0.0_2 , ) -> Tuple: lowerCamelCase_ = parent lowerCamelCase_ = batch_size lowerCamelCase_ = image_size lowerCamelCase_ = patch_size lowerCamelCase_ = num_channels lowerCamelCase_ = is_training lowerCamelCase_ = use_labels lowerCamelCase_ = hidden_size lowerCamelCase_ = num_hidden_layers lowerCamelCase_ = num_attention_heads lowerCamelCase_ = intermediate_size lowerCamelCase_ = hidden_act lowerCamelCase_ = hidden_dropout_prob lowerCamelCase_ = attention_probs_dropout_prob lowerCamelCase_ = type_sequence_label_size lowerCamelCase_ = initializer_range # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) lowerCamelCase_ = (image_size // patch_size) ** 2 lowerCamelCase_ = num_patches + 1 def SCREAMING_SNAKE_CASE_( self ) -> str: lowerCamelCase_ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCamelCase_ = ViTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=lowercase , initializer_range=self.initializer_range , ) return config, pixel_values def SCREAMING_SNAKE_CASE_( self , lowercase , lowercase ) -> Dict: lowerCamelCase_ = FlaxViTModel(config=lowercase ) lowerCamelCase_ = model(lowercase ) # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token) lowerCamelCase_ = (self.image_size, self.image_size) lowerCamelCase_ = (self.patch_size, self.patch_size) lowerCamelCase_ = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, num_patches + 1, self.hidden_size) ) def SCREAMING_SNAKE_CASE_( self , lowercase , lowercase ) -> List[Any]: lowerCamelCase_ = self.type_sequence_label_size lowerCamelCase_ = FlaxViTForImageClassification(config=lowercase ) lowerCamelCase_ = model(lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images lowerCamelCase_ = 1 lowerCamelCase_ = FlaxViTForImageClassification(lowercase ) lowerCamelCase_ = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) lowerCamelCase_ = model(lowercase ) def SCREAMING_SNAKE_CASE_( self ) -> Optional[int]: lowerCamelCase_ = self.prepare_config_and_inputs() ( ( lowerCamelCase_ ) , ( lowerCamelCase_ ) , ) = config_and_inputs lowerCamelCase_ = {"pixel_values": pixel_values} return config, inputs_dict @require_flax class _SCREAMING_SNAKE_CASE ( snake_case_ , unittest.TestCase ): lowerCAmelCase__ = (FlaxViTModel, FlaxViTForImageClassification) if is_flax_available() else () def SCREAMING_SNAKE_CASE_( self ) -> None: lowerCamelCase_ = FlaxViTModelTester(self ) lowerCamelCase_ = ConfigTester(self , config_class=lowercase , has_text_modality=lowercase , hidden_size=37 ) def SCREAMING_SNAKE_CASE_( self ) -> int: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE_( self ) -> List[Any]: lowerCamelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase ) def SCREAMING_SNAKE_CASE_( self ) -> Tuple: lowerCamelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowercase ) def SCREAMING_SNAKE_CASE_( self ) -> Any: lowerCamelCase_ , lowerCamelCase_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase_ = model_class(lowercase ) lowerCamelCase_ = inspect.signature(model.__call__ ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCamelCase_ = [*signature.parameters.keys()] lowerCamelCase_ = ["pixel_values"] self.assertListEqual(arg_names[:1] , lowercase ) def SCREAMING_SNAKE_CASE_( self ) -> List[Any]: lowerCamelCase_ , lowerCamelCase_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): lowerCamelCase_ = self._prepare_for_class(lowercase , lowercase ) lowerCamelCase_ = model_class(lowercase ) @jax.jit def model_jitted(lowercase , **lowercase ): return model(pixel_values=lowercase , **lowercase ) with self.subTest("JIT Enabled" ): lowerCamelCase_ = model_jitted(**lowercase ).to_tuple() with self.subTest("JIT Disabled" ): with jax.disable_jit(): lowerCamelCase_ = model_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 SCREAMING_SNAKE_CASE_( self ) -> List[str]: for model_class_name in self.all_model_classes: lowerCamelCase_ = model_class_name.from_pretrained("google/vit-base-patch16-224" ) lowerCamelCase_ = model(np.ones((1, 3, 224, 224) ) ) self.assertIsNotNone(lowercase )
313
from typing import Tuple, Union from ...modeling_outputs import BackboneOutput from ...modeling_utils import PreTrainedModel from ...utils import is_timm_available, is_torch_available, requires_backends from ...utils.backbone_utils import BackboneMixin from .configuration_timm_backbone import TimmBackboneConfig if is_timm_available(): import timm if is_torch_available(): from torch import Tensor class _SCREAMING_SNAKE_CASE ( snake_case_ , snake_case_ ): lowerCAmelCase__ = 'pixel_values' lowerCAmelCase__ = False lowerCAmelCase__ = TimmBackboneConfig def __init__( self , lowercase , **lowercase ) -> Union[str, Any]: requires_backends(self , "timm" ) super().__init__(lowercase ) lowerCamelCase_ = config if config.backbone is None: raise ValueError("backbone is not set in the config. Please set it to a timm model name." ) if config.backbone not in timm.list_models(): raise ValueError(f'backbone {config.backbone} is not supported by timm.' ) if hasattr(lowercase , "out_features" ) and config.out_features is not None: raise ValueError("out_features is not supported by TimmBackbone. Please use out_indices instead." ) lowerCamelCase_ = getattr(lowercase , "use_pretrained_backbone" , lowercase ) if pretrained is None: raise ValueError("use_pretrained_backbone is not set in the config. Please set it to True or False." ) # We just take the final layer by default. This matches the default for the transformers models. lowerCamelCase_ = config.out_indices if getattr(lowercase , "out_indices" , lowercase ) is not None else (-1,) lowerCamelCase_ = timm.create_model( config.backbone , pretrained=lowercase , features_only=config.features_only , in_chans=config.num_channels , out_indices=lowercase , **lowercase , ) # These are used to control the output of the model when called. If output_hidden_states is True, then # return_layers is modified to include all layers. lowerCamelCase_ = self._backbone.return_layers lowerCamelCase_ = {layer["module"]: str(lowercase ) for i, layer in enumerate(self._backbone.feature_info.info )} super()._init_backbone(lowercase ) @classmethod def SCREAMING_SNAKE_CASE_( cls , lowercase , *lowercase , **lowercase ) -> Tuple: requires_backends(cls , ["vision", "timm"] ) from ...models.timm_backbone import TimmBackboneConfig lowerCamelCase_ = kwargs.pop("config" , TimmBackboneConfig() ) lowerCamelCase_ = kwargs.pop("use_timm_backbone" , lowercase ) if not use_timm: raise ValueError("use_timm_backbone must be True for timm backbones" ) lowerCamelCase_ = kwargs.pop("num_channels" , config.num_channels ) lowerCamelCase_ = kwargs.pop("features_only" , config.features_only ) lowerCamelCase_ = kwargs.pop("use_pretrained_backbone" , config.use_pretrained_backbone ) lowerCamelCase_ = kwargs.pop("out_indices" , config.out_indices ) lowerCamelCase_ = TimmBackboneConfig( backbone=lowercase , num_channels=lowercase , features_only=lowercase , use_pretrained_backbone=lowercase , out_indices=lowercase , ) return super()._from_config(lowercase , **lowercase ) def SCREAMING_SNAKE_CASE_( self , lowercase ) -> List[Any]: pass def SCREAMING_SNAKE_CASE_( self , lowercase , lowercase=None , lowercase=None , lowercase=None , **lowercase ) -> Union[BackboneOutput, Tuple[Tensor, ...]]: lowerCamelCase_ = return_dict if return_dict is not None else self.config.use_return_dict lowerCamelCase_ = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) lowerCamelCase_ = output_attentions if output_attentions is not None else self.config.output_attentions if output_attentions: raise ValueError("Cannot output attentions for timm backbones at the moment" ) if output_hidden_states: # We modify the return layers to include all the stages of the backbone lowerCamelCase_ = self._all_layers lowerCamelCase_ = self._backbone(lowercase , **lowercase ) lowerCamelCase_ = self._return_layers lowerCamelCase_ = tuple(hidden_states[i] for i in self.out_indices ) else: lowerCamelCase_ = self._backbone(lowercase , **lowercase ) lowerCamelCase_ = None lowerCamelCase_ = tuple(lowercase ) lowerCamelCase_ = tuple(lowercase ) if hidden_states is not None else None if not return_dict: lowerCamelCase_ = (feature_maps,) if output_hidden_states: lowerCamelCase_ = output + (hidden_states,) return output return BackboneOutput(feature_maps=lowercase , hidden_states=lowercase , attentions=lowercase )
313
1
"""simple docstring""" from __future__ import annotations import time from collections.abc import Sequence from random import randint from matplotlib import pyplot as plt def lowerCamelCase__ ( _lowerCamelCase : Sequence[float] , _lowerCamelCase : int , _lowerCamelCase : int ) -> tuple[int | None, int | None, float]: if not arr: return None, None, 0 if low == high: return low, high, arr[low] lowerCamelCase_ = (low + high) // 2 lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ = max_subarray(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ = max_subarray(_lowerCamelCase , mid + 1 , _lowerCamelCase ) lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ = max_cross_sum(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) if left_sum >= right_sum and left_sum >= cross_sum: return left_low, left_high, left_sum elif right_sum >= left_sum and right_sum >= cross_sum: return right_low, right_high, right_sum return cross_left, cross_right, cross_sum def lowerCamelCase__ ( _lowerCamelCase : Sequence[float] , _lowerCamelCase : int , _lowerCamelCase : int , _lowerCamelCase : int ) -> tuple[int, int, float]: lowerCamelCase_ , lowerCamelCase_ = float('-inf' ), -1 lowerCamelCase_ , lowerCamelCase_ = float('-inf' ), -1 lowerCamelCase_ = 0 for i in range(_lowerCamelCase , low - 1 , -1 ): summ += arr[i] if summ > left_sum: lowerCamelCase_ = summ lowerCamelCase_ = i lowerCamelCase_ = 0 for i in range(mid + 1 , high + 1 ): summ += arr[i] if summ > right_sum: lowerCamelCase_ = summ lowerCamelCase_ = i return max_left, max_right, (left_sum + right_sum) def lowerCamelCase__ ( _lowerCamelCase : int ) -> float: lowerCamelCase_ = [randint(1 , _lowerCamelCase ) for _ in range(_lowerCamelCase )] lowerCamelCase_ = time.time() max_subarray(_lowerCamelCase , 0 , input_size - 1 ) lowerCamelCase_ = time.time() return end - start def lowerCamelCase__ ( ) -> None: lowerCamelCase_ = [10, 100, 1000, 10000, 50000, 100000, 200000, 300000, 400000, 500000] lowerCamelCase_ = [time_max_subarray(_lowerCamelCase ) for input_size in input_sizes] print('No of Inputs\t\tTime Taken' ) for input_size, runtime in zip(_lowerCamelCase , _lowerCamelCase ): print(_lowerCamelCase , '\t\t' , _lowerCamelCase ) plt.plot(_lowerCamelCase , _lowerCamelCase ) plt.xlabel('Number of Inputs' ) plt.ylabel('Time taken in seconds' ) plt.show() if __name__ == "__main__": from doctest import testmod testmod()
549
"""simple docstring""" import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import XLMRobertaTokenizerFast from diffusers import DDIMScheduler, KandinskyImgaImgPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class a ( __snake_case , unittest.TestCase ): SCREAMING_SNAKE_CASE : Optional[Any] = KandinskyImgaImgPipeline SCREAMING_SNAKE_CASE : Tuple = ["""prompt""", """image_embeds""", """negative_image_embeds""", """image"""] SCREAMING_SNAKE_CASE : int = [ """prompt""", """negative_prompt""", """image_embeds""", """negative_image_embeds""", """image""", ] SCREAMING_SNAKE_CASE : List[str] = [ """generator""", """height""", """width""", """strength""", """guidance_scale""", """negative_prompt""", """num_inference_steps""", """return_dict""", """guidance_scale""", """num_images_per_prompt""", """output_type""", """return_dict""", ] SCREAMING_SNAKE_CASE : Any = False @property def UpperCamelCase ( self : List[str] ) -> str: return 32 @property def UpperCamelCase ( self : Tuple ) -> Optional[Any]: return 32 @property def UpperCamelCase ( self : Optional[int] ) -> str: return self.time_input_dim @property def UpperCamelCase ( self : Optional[int] ) -> Optional[Any]: return self.time_input_dim * 4 @property def UpperCamelCase ( self : int ) -> List[Any]: return 100 @property def UpperCamelCase ( self : Any ) -> List[Any]: lowerCamelCase_ = XLMRobertaTokenizerFast.from_pretrained('YiYiXu/tiny-random-mclip-base' ) return tokenizer @property def UpperCamelCase ( self : str ) -> Optional[Any]: torch.manual_seed(0 ) lowerCamelCase_ = MCLIPConfig( numDims=self.cross_attention_dim , transformerDimensions=self.text_embedder_hidden_size , hidden_size=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=1005 , ) lowerCamelCase_ = MultilingualCLIP(__SCREAMING_SNAKE_CASE ) lowerCamelCase_ = text_encoder.eval() return text_encoder @property def UpperCamelCase ( self : int ) -> List[Any]: torch.manual_seed(0 ) lowerCamelCase_ = { 'in_channels': 4, # Out channels is double in channels because predicts mean and variance 'out_channels': 8, 'addition_embed_type': 'text_image', 'down_block_types': ('ResnetDownsampleBlock2D', 'SimpleCrossAttnDownBlock2D'), 'up_block_types': ('SimpleCrossAttnUpBlock2D', 'ResnetUpsampleBlock2D'), 'mid_block_type': 'UNetMidBlock2DSimpleCrossAttn', 'block_out_channels': (self.block_out_channels_a, self.block_out_channels_a * 2), 'layers_per_block': 1, 'encoder_hid_dim': self.text_embedder_hidden_size, 'encoder_hid_dim_type': 'text_image_proj', 'cross_attention_dim': self.cross_attention_dim, 'attention_head_dim': 4, 'resnet_time_scale_shift': 'scale_shift', 'class_embed_type': None, } lowerCamelCase_ = UNetaDConditionModel(**__SCREAMING_SNAKE_CASE ) return model @property def UpperCamelCase ( self : Tuple ) -> Optional[Any]: return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def UpperCamelCase ( self : Union[str, Any] ) -> Optional[Any]: torch.manual_seed(0 ) lowerCamelCase_ = VQModel(**self.dummy_movq_kwargs ) return model def UpperCamelCase ( self : Union[str, Any] ) -> List[Any]: lowerCamelCase_ = self.dummy_text_encoder lowerCamelCase_ = self.dummy_tokenizer lowerCamelCase_ = self.dummy_unet lowerCamelCase_ = self.dummy_movq lowerCamelCase_ = { 'num_train_timesteps': 1000, 'beta_schedule': 'linear', 'beta_start': 0.00_085, 'beta_end': 0.012, 'clip_sample': False, 'set_alpha_to_one': False, 'steps_offset': 0, 'prediction_type': 'epsilon', 'thresholding': False, } lowerCamelCase_ = DDIMScheduler(**__SCREAMING_SNAKE_CASE ) lowerCamelCase_ = { 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'unet': unet, 'scheduler': scheduler, 'movq': movq, } return components def UpperCamelCase ( self : Dict , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Dict=0 ) -> str: lowerCamelCase_ = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE ) lowerCamelCase_ = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(seed + 1 ) ).to(__SCREAMING_SNAKE_CASE ) # create init_image lowerCamelCase_ = floats_tensor((1, 3, 64, 64) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE ) lowerCamelCase_ = image.cpu().permute(0 , 2 , 3 , 1 )[0] lowerCamelCase_ = Image.fromarray(np.uinta(__SCREAMING_SNAKE_CASE ) ).convert('RGB' ).resize((256, 256) ) if str(__SCREAMING_SNAKE_CASE ).startswith('mps' ): lowerCamelCase_ = torch.manual_seed(__SCREAMING_SNAKE_CASE ) else: lowerCamelCase_ = torch.Generator(device=__SCREAMING_SNAKE_CASE ).manual_seed(__SCREAMING_SNAKE_CASE ) lowerCamelCase_ = { 'prompt': 'horse', 'image': init_image, 'image_embeds': image_embeds, 'negative_image_embeds': negative_image_embeds, 'generator': generator, 'height': 64, 'width': 64, 'num_inference_steps': 10, 'guidance_scale': 7.0, 'strength': 0.2, 'output_type': 'np', } return inputs def UpperCamelCase ( self : Tuple ) -> Any: lowerCamelCase_ = 'cpu' lowerCamelCase_ = self.get_dummy_components() lowerCamelCase_ = self.pipeline_class(**__SCREAMING_SNAKE_CASE ) lowerCamelCase_ = pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) lowerCamelCase_ = pipe(**self.get_dummy_inputs(__SCREAMING_SNAKE_CASE ) ) lowerCamelCase_ = output.images lowerCamelCase_ = pipe( **self.get_dummy_inputs(__SCREAMING_SNAKE_CASE ) , return_dict=__SCREAMING_SNAKE_CASE , )[0] lowerCamelCase_ = image[0, -3:, -3:, -1] lowerCamelCase_ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) lowerCamelCase_ = np.array( [0.61_474_943, 0.6_073_539, 0.43_308_544, 0.5_928_269, 0.47_493_595, 0.46_755_973, 0.4_613_838, 0.45_368_797, 0.50_119_233] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), F''' expected_slice {expected_slice}, but got {image_slice.flatten()}''' assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), F''' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}''' @slow @require_torch_gpu class a ( unittest.TestCase ): def UpperCamelCase ( self : Tuple ) -> List[str]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase ( self : Any ) -> int: lowerCamelCase_ = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinsky/kandinsky_img2img_frog.npy' ) lowerCamelCase_ = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinsky/cat.png' ) lowerCamelCase_ = 'A red cartoon frog, 4k' lowerCamelCase_ = KandinskyPriorPipeline.from_pretrained( 'kandinsky-community/kandinsky-2-1-prior' , torch_dtype=torch.floataa ) pipe_prior.to(__SCREAMING_SNAKE_CASE ) lowerCamelCase_ = KandinskyImgaImgPipeline.from_pretrained( 'kandinsky-community/kandinsky-2-1' , torch_dtype=torch.floataa ) lowerCamelCase_ = pipeline.to(__SCREAMING_SNAKE_CASE ) pipeline.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) lowerCamelCase_ = torch.Generator(device='cpu' ).manual_seed(0 ) lowerCamelCase_ , lowerCamelCase_ = pipe_prior( __SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , num_inference_steps=5 , negative_prompt='' , ).to_tuple() lowerCamelCase_ = pipeline( __SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , image_embeds=__SCREAMING_SNAKE_CASE , negative_image_embeds=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , num_inference_steps=100 , height=768 , width=768 , strength=0.2 , output_type='np' , ) lowerCamelCase_ = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
549
1
import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, MBartaaTokenizer, MBartaaTokenizerFast, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, slow, ) from ...test_tokenization_common import TokenizerTesterMixin a__ : List[Any] = get_tests_dir("""fixtures/test_sentencepiece.model""") if is_torch_available(): from transformers.models.mbart.modeling_mbart import shift_tokens_right a__ : str = 2_5_0_0_0_4 a__ : Tuple = 2_5_0_0_2_0 @require_sentencepiece @require_tokenizers class lowercase ( UpperCAmelCase_ , unittest.TestCase ): """simple docstring""" snake_case_ = MBartaaTokenizer snake_case_ = MBartaaTokenizerFast snake_case_ = True snake_case_ = True def _UpperCamelCase ( self : Tuple ): """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing lowerCamelCase__ = MBartaaTokenizer(__UpperCamelCase , src_lang="""en_XX""" , tgt_lang="""ro_RO""" , keep_accents=__UpperCamelCase ) tokenizer.save_pretrained(self.tmpdirname ) def _UpperCamelCase ( self : str ): """simple docstring""" lowerCamelCase__ = """<s>""" lowerCamelCase__ = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__UpperCamelCase ) , __UpperCamelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__UpperCamelCase ) , __UpperCamelCase ) def _UpperCamelCase ( self : Optional[int] ): """simple docstring""" lowerCamelCase__ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """<s>""" ) self.assertEqual(vocab_keys[1] , """<pad>""" ) self.assertEqual(vocab_keys[-1] , """<mask>""" ) self.assertEqual(len(__UpperCamelCase ) , 10_54 ) def _UpperCamelCase ( self : Optional[Any] ): """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 10_54 ) def _UpperCamelCase ( self : str ): """simple docstring""" lowerCamelCase__ = MBartaaTokenizer(__UpperCamelCase , src_lang="""en_XX""" , tgt_lang="""ro_RO""" , keep_accents=__UpperCamelCase ) lowerCamelCase__ = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(__UpperCamelCase , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__UpperCamelCase ) , [value + tokenizer.fairseq_offset for value in [2_85, 46, 10, 1_70, 3_82]] , ) lowerCamelCase__ = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( __UpperCamelCase , [SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """9""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """é""", """."""] , ) lowerCamelCase__ = tokenizer.convert_tokens_to_ids(__UpperCamelCase ) self.assertListEqual( __UpperCamelCase , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 6_02, 3_47, 3_47, 3_47, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) lowerCamelCase__ = tokenizer.convert_ids_to_tokens(__UpperCamelCase ) self.assertListEqual( __UpperCamelCase , [SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """<unk>""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """<unk>""", """."""] , ) @slow def _UpperCamelCase ( self : Optional[int] ): """simple docstring""" lowerCamelCase__ = {"""input_ids""": [[25_00_04, 1_10_62, 8_27_72, 7, 15, 8_27_72, 5_38, 5_15_29, 2_37, 1_71_98, 12_90, 2_06, 9, 21_51_75, 13_14, 1_36, 1_71_98, 12_90, 2_06, 9, 5_63_59, 42, 12_20_09, 9, 1_64_66, 16, 8_73_44, 45_37, 9, 47_17, 7_83_81, 6, 15_99_58, 7, 15, 2_44_80, 6_18, 4, 5_27, 2_26_93, 54_28, 4, 27_77, 2_44_80, 98_74, 4, 4_35_23, 5_94, 4, 8_03, 1_83_92, 3_31_89, 18, 4, 4_35_23, 2_44_47, 1_23_99, 1_00, 2_49_55, 8_36_58, 96_26, 14_40_57, 15, 8_39, 2_23_35, 16, 1_36, 2_49_55, 8_36_58, 8_34_79, 15, 3_91_02, 7_24, 16, 6_78, 6_45, 27_89, 13_28, 45_89, 42, 12_20_09, 11_57_74, 23, 8_05, 13_28, 4_68_76, 7, 1_36, 5_38_94, 19_40, 4_22_27, 4_11_59, 1_77_21, 8_23, 4_25, 4, 2_75_12, 9_87_22, 2_06, 1_36, 55_31, 49_70, 9_19, 1_73_36, 5, 2], [25_00_04, 2_00_80, 6_18, 83, 8_27_75, 47, 4_79, 9, 15_17, 73, 5_38_94, 3_33, 8_05_81, 11_01_17, 1_88_11, 52_56, 12_95, 51, 15_25_26, 2_97, 79_86, 3_90, 12_44_16, 5_38, 3_54_31, 2_14, 98, 1_50_44, 2_57_37, 1_36, 71_08, 4_37_01, 23, 7_56, 13_53_55, 7, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [25_00_04, 5_81, 6_37_73, 11_94_55, 6, 14_77_97, 8_82_03, 7, 6_45, 70, 21, 32_85, 1_02_69, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], """attention_mask""": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=__UpperCamelCase , model_name="""facebook/mbart-large-50""" , revision="""d3913889c59cd5c9e456b269c376325eabad57e2""" , ) def _UpperCamelCase ( self : Dict ): """simple docstring""" if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return lowerCamelCase__ = (self.rust_tokenizer_class, """hf-internal-testing/tiny-random-mbart50""", {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): lowerCamelCase__ = self.rust_tokenizer_class.from_pretrained(__UpperCamelCase , **__UpperCamelCase ) lowerCamelCase__ = self.tokenizer_class.from_pretrained(__UpperCamelCase , **__UpperCamelCase ) lowerCamelCase__ = tempfile.mkdtemp() lowerCamelCase__ = tokenizer_r.save_pretrained(__UpperCamelCase ) lowerCamelCase__ = tokenizer_p.save_pretrained(__UpperCamelCase ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) lowerCamelCase__ = tuple(f for f in tokenizer_r_files if """tokenizer.json""" not in f ) self.assertSequenceEqual(__UpperCamelCase , __UpperCamelCase ) # Checks everything loads correctly in the same way lowerCamelCase__ = tokenizer_r.from_pretrained(__UpperCamelCase ) lowerCamelCase__ = tokenizer_p.from_pretrained(__UpperCamelCase ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__UpperCamelCase , __UpperCamelCase ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(__UpperCamelCase ) # Save tokenizer rust, legacy_format=True lowerCamelCase__ = tempfile.mkdtemp() lowerCamelCase__ = tokenizer_r.save_pretrained(__UpperCamelCase , legacy_format=__UpperCamelCase ) lowerCamelCase__ = tokenizer_p.save_pretrained(__UpperCamelCase ) # Checks it save with the same files self.assertSequenceEqual(__UpperCamelCase , __UpperCamelCase ) # Checks everything loads correctly in the same way lowerCamelCase__ = tokenizer_r.from_pretrained(__UpperCamelCase ) lowerCamelCase__ = tokenizer_p.from_pretrained(__UpperCamelCase ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__UpperCamelCase , __UpperCamelCase ) ) shutil.rmtree(__UpperCamelCase ) # Save tokenizer rust, legacy_format=False lowerCamelCase__ = tempfile.mkdtemp() lowerCamelCase__ = tokenizer_r.save_pretrained(__UpperCamelCase , legacy_format=__UpperCamelCase ) lowerCamelCase__ = tokenizer_p.save_pretrained(__UpperCamelCase ) # Checks it saved the tokenizer.json file self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way lowerCamelCase__ = tokenizer_r.from_pretrained(__UpperCamelCase ) lowerCamelCase__ = tokenizer_p.from_pretrained(__UpperCamelCase ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__UpperCamelCase , __UpperCamelCase ) ) shutil.rmtree(__UpperCamelCase ) @require_torch @require_sentencepiece @require_tokenizers class lowercase ( unittest.TestCase ): """simple docstring""" snake_case_ = 'facebook/mbart-large-50-one-to-many-mmt' snake_case_ = [ ' UN Chief Says There Is No Military Solution in Syria', ' Secretary-General Ban Ki-moon says his response to Russia\'s stepped up military support for Syria is that "there is no military solution" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.', ] snake_case_ = [ 'Şeful ONU declară că nu există o soluţie militară în Siria', 'Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei' ' pentru Siria este că "nu există o soluţie militară" la conflictul de aproape cinci ani şi că noi arme nu vor' ' face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.', ] snake_case_ = [EN_CODE, 8_2_7_4, 1_2_7_8_7_3, 2_5_9_1_6, 7, 8_6_2_2, 2_0_7_1, 4_3_8, 6_7_4_8_5, 5_3, 1_8_7_8_9_5, 2_3, 5_1_7_1_2, 2] @classmethod def _UpperCamelCase ( cls : Optional[Any] ): """simple docstring""" lowerCamelCase__ = MBartaaTokenizer.from_pretrained( cls.checkpoint_name , src_lang="""en_XX""" , tgt_lang="""ro_RO""" ) lowerCamelCase__ = 1 return cls def _UpperCamelCase ( self : Union[str, Any] ): """simple docstring""" self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ar_AR"""] , 25_00_01 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""en_EN"""] , 25_00_04 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ro_RO"""] , 25_00_20 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""mr_IN"""] , 25_00_38 ) def _UpperCamelCase ( self : Optional[Any] ): """simple docstring""" lowerCamelCase__ = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , __UpperCamelCase ) def _UpperCamelCase ( self : Tuple ): """simple docstring""" self.assertIn(__UpperCamelCase , self.tokenizer.all_special_ids ) lowerCamelCase__ = [RO_CODE, 8_84, 90_19, 96, 9, 9_16, 8_67_92, 36, 1_87_43, 1_55_96, 5, 2] lowerCamelCase__ = self.tokenizer.decode(__UpperCamelCase , skip_special_tokens=__UpperCamelCase ) lowerCamelCase__ = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=__UpperCamelCase ) self.assertEqual(__UpperCamelCase , __UpperCamelCase ) self.assertNotIn(self.tokenizer.eos_token , __UpperCamelCase ) def _UpperCamelCase ( self : Any ): """simple docstring""" lowerCamelCase__ = ["""this is gunna be a long sentence """ * 20] assert isinstance(src_text[0] , __UpperCamelCase ) lowerCamelCase__ = 10 lowerCamelCase__ = self.tokenizer(__UpperCamelCase , max_length=__UpperCamelCase , truncation=__UpperCamelCase ).input_ids[0] self.assertEqual(ids[0] , __UpperCamelCase ) self.assertEqual(ids[-1] , 2 ) self.assertEqual(len(__UpperCamelCase ) , __UpperCamelCase ) def _UpperCamelCase ( self : Any ): """simple docstring""" self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["""<mask>""", """ar_AR"""] ) , [25_00_53, 25_00_01] ) def _UpperCamelCase ( self : Dict ): """simple docstring""" lowerCamelCase__ = tempfile.mkdtemp() lowerCamelCase__ = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(__UpperCamelCase ) lowerCamelCase__ = MBartaaTokenizer.from_pretrained(__UpperCamelCase ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , __UpperCamelCase ) @require_torch def _UpperCamelCase ( self : Optional[Any] ): """simple docstring""" lowerCamelCase__ = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=__UpperCamelCase , return_tensors="""pt""" ) lowerCamelCase__ = shift_tokens_right(batch["""labels"""] , self.tokenizer.pad_token_id ) # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 assert batch.input_ids[1][0] == EN_CODE assert batch.input_ids[1][-1] == 2 assert batch.labels[1][0] == RO_CODE assert batch.labels[1][-1] == 2 assert batch.decoder_input_ids[1][:2].tolist() == [2, RO_CODE] @require_torch def _UpperCamelCase ( self : Optional[int] ): """simple docstring""" lowerCamelCase__ = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=__UpperCamelCase , truncation=__UpperCamelCase , max_length=len(self.expected_src_tokens ) , return_tensors="""pt""" , ) lowerCamelCase__ = shift_tokens_right(batch["""labels"""] , self.tokenizer.pad_token_id ) self.assertIsInstance(__UpperCamelCase , __UpperCamelCase ) self.assertEqual((2, 14) , batch.input_ids.shape ) self.assertEqual((2, 14) , batch.attention_mask.shape ) lowerCamelCase__ = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , __UpperCamelCase ) self.assertEqual(2 , batch.decoder_input_ids[0, 0] ) # decoder_start_token_id # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [EN_CODE] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) def _UpperCamelCase ( self : Union[str, Any] ): """simple docstring""" lowerCamelCase__ = self.tokenizer(self.src_text , padding=__UpperCamelCase , truncation=__UpperCamelCase , max_length=3 , return_tensors="""pt""" ) lowerCamelCase__ = self.tokenizer( text_target=self.tgt_text , padding=__UpperCamelCase , truncation=__UpperCamelCase , max_length=10 , return_tensors="""pt""" ) lowerCamelCase__ = targets["""input_ids"""] lowerCamelCase__ = shift_tokens_right(__UpperCamelCase , self.tokenizer.pad_token_id ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def _UpperCamelCase ( self : Union[str, Any] ): """simple docstring""" lowerCamelCase__ = self.tokenizer._build_translation_inputs( """A test""" , return_tensors="""pt""" , src_lang="""en_XX""" , tgt_lang="""ar_AR""" ) self.assertEqual( nested_simplify(__UpperCamelCase ) , { # en_XX, A, test, EOS """input_ids""": [[25_00_04, 62, 30_34, 2]], """attention_mask""": [[1, 1, 1, 1]], # ar_AR """forced_bos_token_id""": 25_00_01, } , )
715
import unittest from transformers import ( MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TextaTextGenerationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, require_tf, require_torch from transformers.utils import is_torch_available from .test_pipelines_common import ANY if is_torch_available(): import torch @is_pipeline_test class lowercase ( unittest.TestCase ): """simple docstring""" snake_case_ = MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING snake_case_ = TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING def _UpperCamelCase ( self : str , a_ : Optional[int] , a_ : str , a_ : Tuple ): """simple docstring""" lowerCamelCase__ = TextaTextGenerationPipeline(model=a_ , tokenizer=a_ ) return generator, ["Something to write", "Something else"] def _UpperCamelCase ( self : Tuple , a_ : int , a_ : Union[str, Any] ): """simple docstring""" lowerCamelCase__ = generator("""Something there""" ) self.assertEqual(a_ , [{"""generated_text""": ANY(a_ )}] ) # These are encoder decoder, they don't just append to incoming string self.assertFalse(outputs[0]["""generated_text"""].startswith("""Something there""" ) ) lowerCamelCase__ = generator(["""This is great !""", """Something else"""] , num_return_sequences=2 , do_sample=a_ ) self.assertEqual( a_ , [ [{"""generated_text""": ANY(a_ )}, {"""generated_text""": ANY(a_ )}], [{"""generated_text""": ANY(a_ )}, {"""generated_text""": ANY(a_ )}], ] , ) lowerCamelCase__ = generator( ["""This is great !""", """Something else"""] , num_return_sequences=2 , batch_size=2 , do_sample=a_ ) self.assertEqual( a_ , [ [{"""generated_text""": ANY(a_ )}, {"""generated_text""": ANY(a_ )}], [{"""generated_text""": ANY(a_ )}, {"""generated_text""": ANY(a_ )}], ] , ) with self.assertRaises(a_ ): generator(4 ) @require_torch def _UpperCamelCase ( self : List[Any] ): """simple docstring""" lowerCamelCase__ = pipeline("""text2text-generation""" , model="""patrickvonplaten/t5-tiny-random""" , framework="""pt""" ) # do_sample=False necessary for reproducibility lowerCamelCase__ = generator("""Something there""" , do_sample=a_ ) self.assertEqual(a_ , [{"""generated_text""": """"""}] ) lowerCamelCase__ = 3 lowerCamelCase__ = generator( """Something there""" , num_return_sequences=a_ , num_beams=a_ , ) lowerCamelCase__ = [ {"""generated_text""": """Beide Beide Beide Beide Beide Beide Beide Beide Beide"""}, {"""generated_text""": """Beide Beide Beide Beide Beide Beide Beide Beide"""}, {"""generated_text""": """"""}, ] self.assertEqual(a_ , a_ ) lowerCamelCase__ = generator("""This is a test""" , do_sample=a_ , num_return_sequences=2 , return_tensors=a_ ) self.assertEqual( a_ , [ {"""generated_token_ids""": ANY(torch.Tensor )}, {"""generated_token_ids""": ANY(torch.Tensor )}, ] , ) lowerCamelCase__ = generator.model.config.eos_token_id lowerCamelCase__ = """<pad>""" lowerCamelCase__ = generator( ["""This is a test""", """This is a second test"""] , do_sample=a_ , num_return_sequences=2 , batch_size=2 , return_tensors=a_ , ) self.assertEqual( a_ , [ [ {"""generated_token_ids""": ANY(torch.Tensor )}, {"""generated_token_ids""": ANY(torch.Tensor )}, ], [ {"""generated_token_ids""": ANY(torch.Tensor )}, {"""generated_token_ids""": ANY(torch.Tensor )}, ], ] , ) @require_tf def _UpperCamelCase ( self : Union[str, Any] ): """simple docstring""" lowerCamelCase__ = pipeline("""text2text-generation""" , model="""patrickvonplaten/t5-tiny-random""" , framework="""tf""" ) # do_sample=False necessary for reproducibility lowerCamelCase__ = generator("""Something there""" , do_sample=a_ ) self.assertEqual(a_ , [{"""generated_text""": """"""}] )
235
0
"""simple docstring""" def UpperCAmelCase ( A : str = 3 , A : int = 7 , A : Union[str, Any] = 100_0000 ): '''simple docstring''' _UpperCAmelCase = 0 _UpperCAmelCase = 1 for current_denominator in range(1 , limit + 1 ): _UpperCAmelCase = current_denominator * numerator // denominator if current_denominator % denominator == 0: current_numerator -= 1 if current_numerator * max_denominator > current_denominator * max_numerator: _UpperCAmelCase = current_numerator _UpperCAmelCase = current_denominator return max_numerator if __name__ == "__main__": print(solution(numerator=3, denominator=7, limit=1_00_00_00))
573
class SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self , __UpperCamelCase ): """simple docstring""" snake_case_ = val snake_case_ = None snake_case_ = None def __lowerCAmelCase ( self , __UpperCamelCase ): """simple docstring""" if self.val: if val < self.val: if self.left is None: snake_case_ = Node(__UpperCamelCase ) else: self.left.insert(__UpperCamelCase ) elif val > self.val: if self.right is None: snake_case_ = Node(__UpperCamelCase ) else: self.right.insert(__UpperCamelCase ) else: snake_case_ = val def a(lowercase__ , lowercase__ ): '''simple docstring''' # Recursive traversal if root: inorder(root.left , lowercase__ ) res.append(root.val ) inorder(root.right , lowercase__ ) def a(lowercase__ ): '''simple docstring''' # Build BST if len(lowercase__ ) == 0: return arr snake_case_ = Node(arr[0] ) for i in range(1 , len(lowercase__ ) ): root.insert(arr[i] ) # Traverse BST in order. snake_case_ = [] inorder(lowercase__ , lowercase__ ) return res if __name__ == "__main__": print(tree_sort([10, 1, 3, 2, 9, 14, 13]))
187
0
import time import warnings from abc import ABC from copy import deepcopy from typing import Optional import torch from ..utils import add_start_docstrings, logging snake_case_ : str = logging.get_logger(__name__) snake_case_ : Tuple = r"\n Args:\n input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):\n Indices of input sequence tokens in the vocabulary.\n\n Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and\n [`PreTrainedTokenizer.__call__`] for details.\n\n [What are input IDs?](../glossary#input-ids)\n scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`):\n Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax\n or scores for each vocabulary token after SoftMax.\n kwargs (`Dict[str, Any]`, *optional*):\n Additional stopping criteria specific kwargs.\n\n Return:\n `bool`. `False` indicates we should continue, `True` indicates we should stop.\n\n" class __snake_case ( a ): @add_start_docstrings(_snake_case) def __call__( self : Optional[Any] , _snake_case : torch.LongTensor , _snake_case : torch.FloatTensor , **_snake_case : Any): """simple docstring""" raise NotImplementedError('''StoppingCriteria needs to be subclassed''') class __snake_case ( a ): def __init__( self : List[Any] , _snake_case : int , _snake_case : Optional[int] = None): """simple docstring""" UpperCAmelCase_ = max_length UpperCAmelCase_ = max_position_embeddings @add_start_docstrings(_snake_case) def __call__( self : str , _snake_case : torch.LongTensor , _snake_case : torch.FloatTensor , **_snake_case : Union[str, Any]): """simple docstring""" UpperCAmelCase_ = input_ids.shape[-1] UpperCAmelCase_ = cur_len >= self.max_length if self.max_position_embeddings is not None and not is_done and cur_len >= self.max_position_embeddings: logger.warning_once( '''This is a friendly reminder - the current text generation call will exceed the model\'s predefined ''' F"""maximum length ({self.max_position_embeddings}). Depending on the model, you may observe """ '''exceptions, performance degradation, or nothing at all.''') return is_done class __snake_case ( a ): def __init__( self : Dict , _snake_case : int , _snake_case : int): """simple docstring""" warnings.warn( '''The class `MaxNewTokensCriteria` is deprecated. ''' F"""Please use `MaxLengthCriteria(max_length={start_length + max_new_tokens})` """ '''with `max_length = start_length + max_new_tokens` instead.''' , _snake_case , ) UpperCAmelCase_ = start_length UpperCAmelCase_ = max_new_tokens UpperCAmelCase_ = start_length + max_new_tokens @add_start_docstrings(_snake_case) def __call__( self : str , _snake_case : torch.LongTensor , _snake_case : torch.FloatTensor , **_snake_case : str): """simple docstring""" return input_ids.shape[-1] >= self.max_length class __snake_case ( a ): def __init__( self : str , _snake_case : float , _snake_case : Optional[float] = None): """simple docstring""" UpperCAmelCase_ = max_time UpperCAmelCase_ = time.time() if initial_timestamp is None else initial_timestamp @add_start_docstrings(_snake_case) def __call__( self : Union[str, Any] , _snake_case : torch.LongTensor , _snake_case : torch.FloatTensor , **_snake_case : Union[str, Any]): """simple docstring""" return time.time() - self.initial_timestamp > self.max_time class __snake_case ( a ): @add_start_docstrings(_snake_case) def __call__( self : List[Any] , _snake_case : torch.LongTensor , _snake_case : torch.FloatTensor , **_snake_case : Tuple): """simple docstring""" return any(criteria(_snake_case , _snake_case) for criteria in self) @property def lowerCamelCase ( self : List[str]): """simple docstring""" for stopping_criterium in self: if isinstance(_snake_case , _snake_case): return stopping_criterium.max_length elif isinstance(_snake_case , _snake_case): return stopping_criterium.max_length return None def A (__A : StoppingCriteriaList , __A : int ) -> StoppingCriteriaList: """simple docstring""" UpperCAmelCase_ = stopping_criteria.max_length UpperCAmelCase_ = deepcopy(__A ) if stopping_max_length is not None and stopping_max_length != max_length: warnings.warn('''You set different `max_length` for stopping criteria and `max_length` parameter''' , __A ) elif stopping_max_length is None: new_stopping_criteria.append(MaxLengthCriteria(max_length=__A ) ) return new_stopping_criteria
169
from __future__ import annotations def A (__A : list[int] ) -> list[int]: # This function is recursive """simple docstring""" UpperCAmelCase_ = len(__A ) # If the array contains only one element, we return it (it's the stop condition of # recursion) if array_length <= 1: return array # Else UpperCAmelCase_ = array[0] UpperCAmelCase_ = False UpperCAmelCase_ = 1 UpperCAmelCase_ = [] while not is_found and i < array_length: if array[i] < pivot: UpperCAmelCase_ = True UpperCAmelCase_ = [element for element in array[i:] if element >= array[i]] UpperCAmelCase_ = longest_subsequence(__A ) if len(__A ) > len(__A ): UpperCAmelCase_ = temp_array else: i += 1 UpperCAmelCase_ = [element for element in array[1:] if element >= pivot] UpperCAmelCase_ = [pivot, *longest_subsequence(__A )] if len(__A ) > len(__A ): return temp_array else: return longest_subseq if __name__ == "__main__": import doctest doctest.testmod()
169
1
import inspect import re from hashlib import shaaaa from typing import Dict, List from .arrow import arrow from .audiofolder import audiofolder from .csv import csv from .imagefolder import imagefolder from .json import json from .pandas import pandas from .parquet import parquet from .sql import sql # noqa F401 from .text import text def a__ ( lowercase__ ): '''simple docstring''' UpperCAmelCase_ =[] for line in lines: UpperCAmelCase_ =re.sub(R"#.*" , "" , lowercase__ ) # remove comments if line: filtered_lines.append(lowercase__ ) UpperCAmelCase_ ="\n".join(lowercase__ ) # Make a hash from all this code UpperCAmelCase_ =full_str.encode("utf-8" ) return shaaaa(lowercase__ ).hexdigest() # get importable module names and hash for caching __lowercase : Tuple ={ """csv""": (csv.__name__, _hash_python_lines(inspect.getsource(csv).splitlines())), """json""": (json.__name__, _hash_python_lines(inspect.getsource(json).splitlines())), """pandas""": (pandas.__name__, _hash_python_lines(inspect.getsource(pandas).splitlines())), """parquet""": (parquet.__name__, _hash_python_lines(inspect.getsource(parquet).splitlines())), """arrow""": (arrow.__name__, _hash_python_lines(inspect.getsource(arrow).splitlines())), """text""": (text.__name__, _hash_python_lines(inspect.getsource(text).splitlines())), """imagefolder""": (imagefolder.__name__, _hash_python_lines(inspect.getsource(imagefolder).splitlines())), """audiofolder""": (audiofolder.__name__, _hash_python_lines(inspect.getsource(audiofolder).splitlines())), } # Used to infer the module to use based on the data files extensions __lowercase : Optional[int] ={ """.csv""": ("""csv""", {}), """.tsv""": ("""csv""", {"""sep""": """\t"""}), """.json""": ("""json""", {}), """.jsonl""": ("""json""", {}), """.parquet""": ("""parquet""", {}), """.arrow""": ("""arrow""", {}), """.txt""": ("""text""", {}), } _EXTENSION_TO_MODULE.update({ext: ("""imagefolder""", {}) for ext in imagefolder.ImageFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext.upper(): ("""imagefolder""", {}) for ext in imagefolder.ImageFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext: ("""audiofolder""", {}) for ext in audiofolder.AudioFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext.upper(): ("""audiofolder""", {}) for ext in audiofolder.AudioFolder.EXTENSIONS}) __lowercase : Dict ={"""imagefolder""", """audiofolder"""} # Used to filter data files based on extensions given a module name __lowercase : Dict[str, List[str]] ={} for _ext, (_module, _) in _EXTENSION_TO_MODULE.items(): _MODULE_TO_EXTENSIONS.setdefault(_module, []).append(_ext) _MODULE_TO_EXTENSIONS["imagefolder"].append(""".zip""") _MODULE_TO_EXTENSIONS["audiofolder"].append(""".zip""")
54
"""simple docstring""" import argparse import math import os import torch from neural_compressor.utils.pytorch import load from PIL import Image from transformers import CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, StableDiffusionPipeline, UNetaDConditionModel def a__ ( ) -> Optional[int]: __lowerCAmelCase: List[str] = argparse.ArgumentParser() parser.add_argument( "-m" , "--pretrained_model_name_or_path" , type=__SCREAMING_SNAKE_CASE , default=__SCREAMING_SNAKE_CASE , required=__SCREAMING_SNAKE_CASE , help="Path to pretrained model or model identifier from huggingface.co/models." , ) parser.add_argument( "-c" , "--caption" , type=__SCREAMING_SNAKE_CASE , default="robotic cat with wings" , help="Text used to generate images." , ) parser.add_argument( "-n" , "--images_num" , type=__SCREAMING_SNAKE_CASE , default=4 , help="How much images to generate." , ) parser.add_argument( "-s" , "--seed" , type=__SCREAMING_SNAKE_CASE , default=4_2 , help="Seed for random process." , ) parser.add_argument( "-ci" , "--cuda_id" , type=__SCREAMING_SNAKE_CASE , default=0 , help="cuda_id." , ) __lowerCAmelCase: str = parser.parse_args() return args def a__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> List[str]: if not len(__SCREAMING_SNAKE_CASE ) == rows * cols: raise ValueError("The specified number of rows and columns are not correct." ) __lowerCAmelCase , __lowerCAmelCase: str = imgs[0].size __lowerCAmelCase: Tuple = Image.new("RGB" , size=(cols * w, rows * h) ) __lowerCAmelCase , __lowerCAmelCase: Any = grid.size for i, img in enumerate(__SCREAMING_SNAKE_CASE ): grid.paste(__SCREAMING_SNAKE_CASE , box=(i % cols * w, i // cols * h) ) return grid def a__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE="robotic cat with wings" , __SCREAMING_SNAKE_CASE=7.5 , __SCREAMING_SNAKE_CASE=5_0 , __SCREAMING_SNAKE_CASE=1 , __SCREAMING_SNAKE_CASE=4_2 , ) -> Any: __lowerCAmelCase: List[Any] = torch.Generator(pipeline.device ).manual_seed(__SCREAMING_SNAKE_CASE ) __lowerCAmelCase: Optional[int] = pipeline( __SCREAMING_SNAKE_CASE , guidance_scale=__SCREAMING_SNAKE_CASE , num_inference_steps=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , num_images_per_prompt=__SCREAMING_SNAKE_CASE , ).images __lowerCAmelCase: Any = int(math.sqrt(__SCREAMING_SNAKE_CASE ) ) __lowerCAmelCase: Tuple = image_grid(__SCREAMING_SNAKE_CASE , rows=_rows , cols=num_images_per_prompt // _rows ) return grid, images __A = parse_args() # Load models and create wrapper for stable diffusion __A = CLIPTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder="tokenizer") __A = CLIPTextModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="text_encoder") __A = AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder="vae") __A = UNetaDConditionModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="unet") __A = StableDiffusionPipeline.from_pretrained( args.pretrained_model_name_or_path, text_encoder=text_encoder, vae=vae, unet=unet, tokenizer=tokenizer ) __A = lambda images, clip_input: (images, False) if os.path.exists(os.path.join(args.pretrained_model_name_or_path, "best_model.pt")): __A = load(args.pretrained_model_name_or_path, model=unet) unet.eval() setattr(pipeline, "unet", unet) else: __A = unet.to(torch.device("cuda", args.cuda_id)) __A = pipeline.to(unet.device) __A , __A = generate_images(pipeline, prompt=args.caption, num_images_per_prompt=args.images_num, seed=args.seed) grid.save(os.path.join(args.pretrained_model_name_or_path, "{}.png".format("_".join(args.caption.split())))) __A = os.path.join(args.pretrained_model_name_or_path, "_".join(args.caption.split())) os.makedirs(dirname, exist_ok=True) for idx, image in enumerate(images): image.save(os.path.join(dirname, "{}.png".format(idx + 1)))
346
0
import unittest import numpy as np from transformers import is_flax_available from transformers.testing_utils import require_flax from ..test_modeling_flax_common import ids_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.generation import ( FlaxForcedBOSTokenLogitsProcessor, FlaxForcedEOSTokenLogitsProcessor, FlaxLogitsProcessorList, FlaxMinLengthLogitsProcessor, FlaxTemperatureLogitsWarper, FlaxTopKLogitsWarper, FlaxTopPLogitsWarper, ) @require_flax class _UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self : List[Any] , lowercase_ : int , lowercase_ : int) -> Any: """simple docstring""" _UpperCamelCase = jnp.ones((batch_size, length)) / length return scores def __UpperCAmelCase ( self : str) -> Optional[Any]: """simple docstring""" _UpperCamelCase = None _UpperCamelCase = 20 _UpperCamelCase = self._get_uniform_logits(batch_size=2 , length=lowercase_) # tweak scores to not be uniform anymore _UpperCamelCase = scores.at[1, 5].set((1 / length) + 0.1) # peak, 1st batch _UpperCamelCase = scores.at[1, 10].set((1 / length) - 0.4) # valley, 1st batch # compute softmax _UpperCamelCase = jax.nn.softmax(lowercase_ , axis=-1) _UpperCamelCase = FlaxTemperatureLogitsWarper(temperature=0.5) _UpperCamelCase = FlaxTemperatureLogitsWarper(temperature=1.3) _UpperCamelCase = jax.nn.softmax(temp_dist_warper_sharper(lowercase_ , scores.copy() , cur_len=lowercase_) , axis=-1) _UpperCamelCase = jax.nn.softmax(temp_dist_warper_smoother(lowercase_ , scores.copy() , cur_len=lowercase_) , axis=-1) # uniform distribution stays uniform self.assertTrue(jnp.allclose(probs[0, :] , warped_prob_sharp[0, :] , atol=1e-3)) self.assertTrue(jnp.allclose(probs[0, :] , warped_prob_smooth[0, :] , atol=1e-3)) # sharp peaks get higher, valleys get lower self.assertLess(probs[1, :].max() , warped_prob_sharp[1, :].max()) self.assertGreater(probs[1, :].min() , warped_prob_sharp[1, :].min()) # smooth peaks get lower, valleys get higher self.assertGreater(probs[1, :].max() , warped_prob_smooth[1, :].max()) self.assertLess(probs[1, :].min() , warped_prob_smooth[1, :].min()) def __UpperCAmelCase ( self : Tuple) -> Optional[int]: """simple docstring""" _UpperCamelCase = None _UpperCamelCase = 10 _UpperCamelCase = 2 # create ramp distribution _UpperCamelCase = np.broadcast_to(np.arange(lowercase_)[None, :] , (batch_size, vocab_size)).copy() _UpperCamelCase = ramp_logits[1:, : vocab_size // 2] + vocab_size _UpperCamelCase = FlaxTopKLogitsWarper(3) _UpperCamelCase = top_k_warp(lowercase_ , lowercase_ , cur_len=lowercase_) # check that correct tokens are filtered self.assertListEqual(jnp.isinf(scores[0]).tolist() , 7 * [True] + 3 * [False]) self.assertListEqual(jnp.isinf(scores[1]).tolist() , 2 * [True] + 3 * [False] + 5 * [True]) # check special case _UpperCamelCase = 5 _UpperCamelCase = FlaxTopKLogitsWarper(top_k=1 , filter_value=0.0 , min_tokens_to_keep=3) _UpperCamelCase = np.broadcast_to(np.arange(lowercase_)[None, :] , (batch_size, length)).copy() _UpperCamelCase = top_k_warp_safety_check(lowercase_ , lowercase_ , cur_len=lowercase_) # min_tokens overwrites k: 3 tokens are kept => 2 tokens are nullified self.assertListEqual((scores == 0.0).sum(axis=-1).tolist() , [2, 2]) def __UpperCAmelCase ( self : str) -> Tuple: """simple docstring""" _UpperCamelCase = None _UpperCamelCase = 10 _UpperCamelCase = 2 # create distribution and take log (inverse to Softmax as taken in TopPLogitsWarper) _UpperCamelCase = np.log(np.array([[0.3, 0.1, 0.1, 0.5], [0.15, 0.3, 0.3, 0.25]])) _UpperCamelCase = FlaxTopPLogitsWarper(0.8) _UpperCamelCase = np.exp(top_p_warp(lowercase_ , lowercase_ , cur_len=lowercase_)) # dist should be filtered to keep min num values so that sum is >= top_p # exp (-inf) => 0 _UpperCamelCase = np.array([[0.3, 0.0, 0.0, 0.5], [0.0, 0.3, 0.3, 0.25]]) self.assertTrue(np.allclose(lowercase_ , lowercase_ , atol=1e-3)) # check edge cases with negative and extreme logits _UpperCamelCase = np.broadcast_to(np.arange(lowercase_)[None, :] , (batch_size, vocab_size)).copy() - ( vocab_size // 2 ) # make ramp_logits more extreme _UpperCamelCase = ramp_logits[1] * 1_00.0 # make sure at least 2 tokens are kept _UpperCamelCase = FlaxTopPLogitsWarper(0.9 , min_tokens_to_keep=2 , filter_value=0.0) _UpperCamelCase = top_p_warp(lowercase_ , lowercase_ , cur_len=lowercase_) # first batch should keep three tokens, second batch would keep only 1, but due to `min_tokens_to_keep=2` keeps 2. self.assertListEqual((filtered_dist != 0.0).sum(axis=-1).tolist() , [3, 2]) def __UpperCAmelCase ( self : Tuple) -> Tuple: """simple docstring""" _UpperCamelCase = 20 _UpperCamelCase = 4 _UpperCamelCase = 0 _UpperCamelCase = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=lowercase_) # check that min length is applied at length 5 _UpperCamelCase = ids_tensor((batch_size, 20) , vocab_size=20) _UpperCamelCase = 5 _UpperCamelCase = self._get_uniform_logits(lowercase_ , lowercase_) _UpperCamelCase = min_dist_processor(lowercase_ , lowercase_ , cur_len=lowercase_) self.assertListEqual(scores_before_min_length[:, eos_token_id].tolist() , 4 * [-float("inf")]) # check that min length is not applied anymore at length 15 _UpperCamelCase = self._get_uniform_logits(lowercase_ , lowercase_) _UpperCamelCase = 15 _UpperCamelCase = min_dist_processor(lowercase_ , lowercase_ , cur_len=lowercase_) self.assertFalse(jnp.isinf(lowercase_).any()) def __UpperCAmelCase ( self : List[str]) -> List[Any]: """simple docstring""" _UpperCamelCase = 20 _UpperCamelCase = 4 _UpperCamelCase = 0 _UpperCamelCase = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=lowercase_) # check that all scores are -inf except the bos_token_id score _UpperCamelCase = ids_tensor((batch_size, 1) , vocab_size=20) _UpperCamelCase = 1 _UpperCamelCase = self._get_uniform_logits(lowercase_ , lowercase_) _UpperCamelCase = logits_processor(lowercase_ , lowercase_ , cur_len=lowercase_) self.assertTrue(jnp.isneginf(scores[:, bos_token_id + 1 :]).all()) self.assertListEqual(scores[:, bos_token_id].tolist() , 4 * [0]) # score for bos_token_id shold be zero # check that bos_token_id is not forced if current length is greater than 1 _UpperCamelCase = 3 _UpperCamelCase = self._get_uniform_logits(lowercase_ , lowercase_) _UpperCamelCase = logits_processor(lowercase_ , lowercase_ , cur_len=lowercase_) self.assertFalse(jnp.isinf(lowercase_).any()) def __UpperCAmelCase ( self : Tuple) -> Union[str, Any]: """simple docstring""" _UpperCamelCase = 20 _UpperCamelCase = 4 _UpperCamelCase = 0 _UpperCamelCase = 5 _UpperCamelCase = FlaxForcedEOSTokenLogitsProcessor(max_length=lowercase_ , eos_token_id=lowercase_) # check that all scores are -inf except the eos_token_id when max_length is reached _UpperCamelCase = ids_tensor((batch_size, 4) , vocab_size=20) _UpperCamelCase = 4 _UpperCamelCase = self._get_uniform_logits(lowercase_ , lowercase_) _UpperCamelCase = logits_processor(lowercase_ , lowercase_ , cur_len=lowercase_) self.assertTrue(jnp.isneginf(scores[:, eos_token_id + 1 :]).all()) self.assertListEqual(scores[:, eos_token_id].tolist() , 4 * [0]) # score for eos_token_id should be zero # check that eos_token_id is not forced if max_length is not reached _UpperCamelCase = 3 _UpperCamelCase = self._get_uniform_logits(lowercase_ , lowercase_) _UpperCamelCase = logits_processor(lowercase_ , lowercase_ , cur_len=lowercase_) self.assertFalse(jnp.isinf(lowercase_).any()) def __UpperCAmelCase ( self : List[str]) -> Any: """simple docstring""" _UpperCamelCase = 4 _UpperCamelCase = 10 _UpperCamelCase = 15 _UpperCamelCase = 2 _UpperCamelCase = 1 _UpperCamelCase = 15 # dummy input_ids and scores _UpperCamelCase = ids_tensor((batch_size, sequence_length) , lowercase_) _UpperCamelCase = input_ids.copy() _UpperCamelCase = self._get_uniform_logits(lowercase_ , lowercase_) _UpperCamelCase = scores.copy() # instantiate all dist processors _UpperCamelCase = FlaxTemperatureLogitsWarper(temperature=0.5) _UpperCamelCase = FlaxTopKLogitsWarper(3) _UpperCamelCase = FlaxTopPLogitsWarper(0.8) # instantiate all logits processors _UpperCamelCase = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=lowercase_) _UpperCamelCase = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=lowercase_) _UpperCamelCase = FlaxForcedEOSTokenLogitsProcessor(max_length=lowercase_ , eos_token_id=lowercase_) _UpperCamelCase = 10 # no processor list _UpperCamelCase = temp_dist_warp(lowercase_ , lowercase_ , cur_len=lowercase_) _UpperCamelCase = top_k_warp(lowercase_ , lowercase_ , cur_len=lowercase_) _UpperCamelCase = top_p_warp(lowercase_ , lowercase_ , cur_len=lowercase_) _UpperCamelCase = min_dist_proc(lowercase_ , lowercase_ , cur_len=lowercase_) _UpperCamelCase = bos_dist_proc(lowercase_ , lowercase_ , cur_len=lowercase_) _UpperCamelCase = eos_dist_proc(lowercase_ , lowercase_ , cur_len=lowercase_) # with processor list _UpperCamelCase = FlaxLogitsProcessorList( [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc]) _UpperCamelCase = processor(lowercase_ , lowercase_ , cur_len=lowercase_) # scores should be equal self.assertTrue(jnp.allclose(lowercase_ , lowercase_ , atol=1e-3)) # input_ids should never be changed self.assertListEqual(input_ids.tolist() , input_ids_comp.tolist()) def __UpperCAmelCase ( self : List[Any]) -> Optional[Any]: """simple docstring""" _UpperCamelCase = 4 _UpperCamelCase = 10 _UpperCamelCase = 15 _UpperCamelCase = 2 _UpperCamelCase = 1 _UpperCamelCase = 15 # dummy input_ids and scores _UpperCamelCase = ids_tensor((batch_size, sequence_length) , lowercase_) _UpperCamelCase = input_ids.copy() _UpperCamelCase = self._get_uniform_logits(lowercase_ , lowercase_) _UpperCamelCase = scores.copy() # instantiate all dist processors _UpperCamelCase = FlaxTemperatureLogitsWarper(temperature=0.5) _UpperCamelCase = FlaxTopKLogitsWarper(3) _UpperCamelCase = FlaxTopPLogitsWarper(0.8) # instantiate all logits processors _UpperCamelCase = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=lowercase_) _UpperCamelCase = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=lowercase_) _UpperCamelCase = FlaxForcedEOSTokenLogitsProcessor(max_length=lowercase_ , eos_token_id=lowercase_) _UpperCamelCase = 10 # no processor list def run_no_processor_list(lowercase_ : Any , lowercase_ : Any , lowercase_ : int): _UpperCamelCase = temp_dist_warp(lowercase_ , lowercase_ , cur_len=lowercase_) _UpperCamelCase = top_k_warp(lowercase_ , lowercase_ , cur_len=lowercase_) _UpperCamelCase = top_p_warp(lowercase_ , lowercase_ , cur_len=lowercase_) _UpperCamelCase = min_dist_proc(lowercase_ , lowercase_ , cur_len=lowercase_) _UpperCamelCase = bos_dist_proc(lowercase_ , lowercase_ , cur_len=lowercase_) _UpperCamelCase = eos_dist_proc(lowercase_ , lowercase_ , cur_len=lowercase_) return scores # with processor list def run_processor_list(lowercase_ : Any , lowercase_ : int , lowercase_ : Tuple): _UpperCamelCase = FlaxLogitsProcessorList( [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc]) _UpperCamelCase = processor(lowercase_ , lowercase_ , cur_len=lowercase_) return scores _UpperCamelCase = jax.jit(lowercase_) _UpperCamelCase = jax.jit(lowercase_) _UpperCamelCase = jitted_run_no_processor_list(lowercase_ , lowercase_ , lowercase_) _UpperCamelCase = jitted_run_processor_list(lowercase_ , lowercase_ , lowercase_) # scores should be equal self.assertTrue(jnp.allclose(lowercase_ , lowercase_ , atol=1e-3)) # input_ids should never be changed self.assertListEqual(input_ids.tolist() , input_ids_comp.tolist())
82
import unittest import numpy as np import torch from diffusers import KarrasVePipeline, KarrasVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class _UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @property def __UpperCAmelCase ( self : int) -> str: """simple docstring""" torch.manual_seed(0) _UpperCamelCase = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=("DownBlock2D", "AttnDownBlock2D") , up_block_types=("AttnUpBlock2D", "UpBlock2D") , ) return model def __UpperCAmelCase ( self : List[Any]) -> Optional[Any]: """simple docstring""" _UpperCamelCase = self.dummy_uncond_unet _UpperCamelCase = KarrasVeScheduler() _UpperCamelCase = KarrasVePipeline(unet=lowercase_ , scheduler=lowercase_) pipe.to(lowercase_) pipe.set_progress_bar_config(disable=lowercase_) _UpperCamelCase = torch.manual_seed(0) _UpperCamelCase = pipe(num_inference_steps=2 , generator=lowercase_ , output_type="numpy").images _UpperCamelCase = torch.manual_seed(0) _UpperCamelCase = pipe(num_inference_steps=2 , generator=lowercase_ , output_type="numpy" , return_dict=lowercase_)[0] _UpperCamelCase = image[0, -3:, -3:, -1] _UpperCamelCase = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) _UpperCamelCase = np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice).max() < 1e-2 @slow @require_torch class _UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self : int) -> Tuple: """simple docstring""" _UpperCamelCase = "google/ncsnpp-celebahq-256" _UpperCamelCase = UNetaDModel.from_pretrained(lowercase_) _UpperCamelCase = KarrasVeScheduler() _UpperCamelCase = KarrasVePipeline(unet=lowercase_ , scheduler=lowercase_) pipe.to(lowercase_) pipe.set_progress_bar_config(disable=lowercase_) _UpperCamelCase = torch.manual_seed(0) _UpperCamelCase = pipe(num_inference_steps=20 , generator=lowercase_ , output_type="numpy").images _UpperCamelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) _UpperCamelCase = np.array([0.5_78, 0.58_11, 0.59_24, 0.58_09, 0.5_87, 0.58_86, 0.58_61, 0.58_02, 0.5_86]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
82
1
import torch from torch import nn from transformers import CLIPPreTrainedModel, CLIPVisionModel from ...models.attention import BasicTransformerBlock from ...utils import logging UpperCAmelCase_ = logging.get_logger(__name__) # pylint: disable=invalid-name class __UpperCamelCase ( A__ ): def __init__( self , _UpperCamelCase , _UpperCamelCase=768 ): super().__init__(_UpperCamelCase ) _UpperCAmelCase = proj_size _UpperCAmelCase = CLIPVisionModel(_UpperCamelCase ) _UpperCAmelCase = PaintByExampleMapper(_UpperCamelCase ) _UpperCAmelCase = nn.LayerNorm(config.hidden_size ) _UpperCAmelCase = nn.Linear(config.hidden_size , self.proj_size ) # uncondition for scaling _UpperCAmelCase = nn.Parameter(torch.randn((1, 1, self.proj_size) ) ) def UpperCamelCase( self , _UpperCamelCase , _UpperCamelCase=False ): _UpperCAmelCase = self.model(pixel_values=_UpperCamelCase ) _UpperCAmelCase = clip_output.pooler_output _UpperCAmelCase = self.mapper(latent_states[:, None] ) _UpperCAmelCase = self.final_layer_norm(_UpperCamelCase ) _UpperCAmelCase = self.proj_out(_UpperCamelCase ) if return_uncond_vector: return latent_states, self.uncond_vector return latent_states class __UpperCamelCase ( nn.Module ): def __init__( self , _UpperCamelCase ): super().__init__() _UpperCAmelCase = (config.num_hidden_layers + 1) // 5 _UpperCAmelCase = config.hidden_size _UpperCAmelCase = 1 _UpperCAmelCase = nn.ModuleList( [ BasicTransformerBlock(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , activation_fn='''gelu''' , attention_bias=_UpperCamelCase ) for _ in range(_UpperCamelCase ) ] ) def UpperCamelCase( self , _UpperCamelCase ): for block in self.blocks: _UpperCAmelCase = block(_UpperCamelCase ) return hidden_states
32
'''simple docstring''' import argparse from collections import defaultdict import yaml a : List[Any] = 'docs/source/en/_toctree.yml' def __magic_name__ ( __UpperCAmelCase ) -> str: '''simple docstring''' snake_case_ = defaultdict(__UpperCAmelCase ) for doc in model_doc: counts[doc["local"]] += 1 snake_case_ = [key for key, value in counts.items() if value > 1] snake_case_ = [] for duplicate_key in duplicates: snake_case_ = list({doc['''title'''] for doc in model_doc if doc['''local'''] == duplicate_key} ) if len(__UpperCAmelCase ) > 1: raise ValueError( F"{duplicate_key} is present several times in the documentation table of content at " '''`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the ''' '''others.''' ) # Only add this once new_doc.append({'''local''': duplicate_key, '''title''': titles[0]} ) # Add none duplicate-keys new_doc.extend([doc for doc in model_doc if counts[doc['''local''']] == 1] ) # Sort return sorted(__UpperCAmelCase, key=lambda __UpperCAmelCase : s["title"].lower() ) def __magic_name__ ( __UpperCAmelCase=False ) -> List[Any]: '''simple docstring''' with open(__UpperCAmelCase, encoding='''utf-8''' ) as f: snake_case_ = yaml.safe_load(f.read() ) # Get to the API doc snake_case_ = 0 while content[api_idx]["title"] != "API": api_idx += 1 snake_case_ = content[api_idx]['''sections'''] # Then to the model doc snake_case_ = 0 while api_doc[model_idx]["title"] != "Models": model_idx += 1 snake_case_ = api_doc[model_idx]['''sections'''] snake_case_ = [(idx, section) for idx, section in enumerate(__UpperCAmelCase ) if '''sections''' in section] snake_case_ = False for idx, modality_doc in modalities_docs: snake_case_ = modality_doc['''sections'''] snake_case_ = clean_model_doc_toc(__UpperCAmelCase ) if old_modality_doc != new_modality_doc: snake_case_ = True if overwrite: snake_case_ = new_modality_doc if diff: if overwrite: snake_case_ = model_doc snake_case_ = api_doc with open(__UpperCAmelCase, '''w''', encoding='''utf-8''' ) as f: f.write(yaml.dump(__UpperCAmelCase, allow_unicode=__UpperCAmelCase ) ) else: raise ValueError( '''The model doc part of the table of content is not properly sorted, run `make style` to fix this.''' ) if __name__ == "__main__": a : Dict = argparse.ArgumentParser() parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.') a : Union[str, Any] = parser.parse_args() check_model_doc(args.fix_and_overwrite)
640
0
import importlib import math import os from dataclasses import dataclass from enum import Enum from typing import Any, Dict, Optional, Tuple, Union import flax import jax.numpy as jnp from ..utils import BaseOutput lowerCamelCase__ : Optional[Any] = """scheduler_config.json""" class __magic_name__ (snake_case_ ): '''simple docstring''' __lowercase : int = 1 __lowercase : List[Any] = 2 __lowercase : Dict = 3 __lowercase : str = 4 __lowercase : Dict = 5 @dataclass class __magic_name__ (snake_case_ ): '''simple docstring''' __lowercase : jnp.ndarray class __magic_name__ : '''simple docstring''' __lowercase : List[str] = SCHEDULER_CONFIG_NAME __lowercase : Tuple = ['dtype'] __lowercase : str = [] __lowercase : Tuple = True @classmethod def SCREAMING_SNAKE_CASE__ ( cls:List[Any] , _a:Dict[str, Any] = None , _a:Optional[str] = None , _a:str=False , **_a:List[Any] , ): snake_case__ , snake_case__ = cls.load_config( pretrained_model_name_or_path=_a , subfolder=_a , return_unused_kwargs=_a , **_a , ) snake_case__ , snake_case__ = cls.from_config(_a , return_unused_kwargs=_a , **_a ) if hasattr(_a , '''create_state''' ) and getattr(_a , '''has_state''' , _a ): snake_case__ = scheduler.create_state() if return_unused_kwargs: return scheduler, state, unused_kwargs return scheduler, state def SCREAMING_SNAKE_CASE__ ( self:Tuple , _a:Union[str, os.PathLike] , _a:bool = False , **_a:Optional[int] ): self.save_config(save_directory=_a , push_to_hub=_a , **_a ) @property def SCREAMING_SNAKE_CASE__ ( self:str ): return self._get_compatibles() @classmethod def SCREAMING_SNAKE_CASE__ ( cls:Any ): snake_case__ = list(set([cls.__name__] + cls._compatibles ) ) snake_case__ = importlib.import_module(__name__.split('''.''' )[0] ) snake_case__ = [ getattr(_a , _a ) for c in compatible_classes_str if hasattr(_a , _a ) ] return compatible_classes def SCREAMING_SNAKE_CASE ( __lowerCAmelCase , __lowerCAmelCase ) -> jnp.ndarray: assert len(__lowerCAmelCase ) >= x.ndim return jnp.broadcast_to(x.reshape(x.shape + (1,) * (len(__lowerCAmelCase ) - x.ndim) ) , __lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( __lowerCAmelCase , __lowerCAmelCase=0.999 , __lowerCAmelCase=jnp.floataa ) -> jnp.ndarray: def alpha_bar(__lowerCAmelCase ): return math.cos((time_step + 0.008) / 1.008 * math.pi / 2 ) ** 2 snake_case__ = [] for i in range(__lowerCAmelCase ): snake_case__ = i / num_diffusion_timesteps snake_case__ = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar(__lowerCAmelCase ) / alpha_bar(__lowerCAmelCase ) , __lowerCAmelCase ) ) return jnp.array(__lowerCAmelCase , dtype=__lowerCAmelCase ) @flax.struct.dataclass class __magic_name__ : '''simple docstring''' __lowercase : jnp.ndarray __lowercase : jnp.ndarray __lowercase : jnp.ndarray @classmethod def SCREAMING_SNAKE_CASE__ ( cls:Optional[int] , _a:str ): snake_case__ = scheduler.config if config.trained_betas is not None: snake_case__ = jnp.asarray(config.trained_betas , dtype=scheduler.dtype ) elif config.beta_schedule == "linear": snake_case__ = jnp.linspace(config.beta_start , config.beta_end , config.num_train_timesteps , dtype=scheduler.dtype ) elif config.beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. snake_case__ = ( jnp.linspace( config.beta_start**0.5 , config.beta_end**0.5 , config.num_train_timesteps , dtype=scheduler.dtype ) ** 2 ) elif config.beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule snake_case__ = betas_for_alpha_bar(config.num_train_timesteps , dtype=scheduler.dtype ) else: raise NotImplementedError( F"""beta_schedule {config.beta_schedule} is not implemented for scheduler {scheduler.__class__.__name__}""" ) snake_case__ = 1.0 - betas snake_case__ = jnp.cumprod(_a , axis=0 ) return cls( alphas=_a , betas=_a , alphas_cumprod=_a , ) def SCREAMING_SNAKE_CASE ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> str: snake_case__ = state.alphas_cumprod snake_case__ = alphas_cumprod[timesteps] ** 0.5 snake_case__ = sqrt_alpha_prod.flatten() snake_case__ = broadcast_to_shape_from_left(__lowerCAmelCase , original_samples.shape ) snake_case__ = (1 - alphas_cumprod[timesteps]) ** 0.5 snake_case__ = sqrt_one_minus_alpha_prod.flatten() snake_case__ = broadcast_to_shape_from_left(__lowerCAmelCase , original_samples.shape ) return sqrt_alpha_prod, sqrt_one_minus_alpha_prod def SCREAMING_SNAKE_CASE ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Optional[int]: snake_case__ , snake_case__ = get_sqrt_alpha_prod(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) snake_case__ = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise return noisy_samples def SCREAMING_SNAKE_CASE ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Any: snake_case__ , snake_case__ = get_sqrt_alpha_prod(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) snake_case__ = sqrt_alpha_prod * noise - sqrt_one_minus_alpha_prod * sample return velocity
701
def SCREAMING_SNAKE_CASE ( __lowerCAmelCase ) -> int: snake_case__ = abs(__lowerCAmelCase ) snake_case__ = 0 while n > 0: res += n % 10 n //= 10 return res def SCREAMING_SNAKE_CASE ( __lowerCAmelCase ) -> int: snake_case__ = abs(__lowerCAmelCase ) return n if n < 10 else n % 10 + sum_of_digits(n // 10 ) def SCREAMING_SNAKE_CASE ( __lowerCAmelCase ) -> int: return sum(int(__lowerCAmelCase ) for c in str(abs(__lowerCAmelCase ) ) ) def SCREAMING_SNAKE_CASE ( ) -> None: from collections.abc import Callable from timeit import timeit def benchmark_a_function(__lowerCAmelCase , __lowerCAmelCase ) -> None: snake_case__ = F"""{func.__name__}({value})""" snake_case__ = timeit(F"""__main__.{call}""" , setup='''import __main__''' ) print(F"""{call:56} = {func(__lowerCAmelCase )} -- {timing:.4f} seconds""" ) for value in (26_2144, 1125_8999_0684_2624, 126_7650_6002_2822_9401_4967_0320_5376): for func in (sum_of_digits, sum_of_digits_recursion, sum_of_digits_compact): benchmark_a_function(__lowerCAmelCase , __lowerCAmelCase ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
208
0
def snake_case (UpperCAmelCase__ ) -> int: if n == 1 or not isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): return 0 elif n == 2: return 1 else: UpperCamelCase_: Union[str, Any] = [0, 1] for i in range(2 , n + 1 ): sequence.append(sequence[i - 1] + sequence[i - 2] ) return sequence[n] def snake_case (UpperCAmelCase__ ) -> int: UpperCamelCase_: List[Any] = 0 UpperCamelCase_: List[str] = 2 while digits < n: index += 1 UpperCamelCase_: Union[str, Any] = len(str(fibonacci(UpperCAmelCase__ ) ) ) return index def snake_case (UpperCAmelCase__ = 1_0_0_0 ) -> int: return fibonacci_digits_index(UpperCAmelCase__ ) if __name__ == "__main__": print(solution(int(str(input()).strip())))
57
'''simple docstring''' # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import os from ...utils.constants import SAGEMAKER_PARALLEL_EC2_INSTANCES, TORCH_DYNAMO_MODES from ...utils.dataclasses import ComputeEnvironment, SageMakerDistributedType from ...utils.imports import is_botoa_available from .config_args import SageMakerConfig from .config_utils import ( DYNAMO_BACKENDS, _ask_field, _ask_options, _convert_dynamo_backend, _convert_mixed_precision, _convert_sagemaker_distributed_mode, _convert_yes_no_to_bool, ) if is_botoa_available(): import botoa # noqa: F401 def __lowercase (_lowercase ) -> str: """simple docstring""" __lowerCamelCase : Tuple = botoa.client("""iam""" ) __lowerCamelCase : Any = { """Version""": """2012-10-17""", """Statement""": [ {"""Effect""": """Allow""", """Principal""": {"""Service""": """sagemaker.amazonaws.com"""}, """Action""": """sts:AssumeRole"""} ], } try: # create the role, associated with the chosen trust policy iam_client.create_role( RoleName=_lowercase, AssumeRolePolicyDocument=json.dumps(_lowercase, indent=2 ) ) __lowerCamelCase : List[Any] = { """Version""": """2012-10-17""", """Statement""": [ { """Effect""": """Allow""", """Action""": [ """sagemaker:*""", """ecr:GetDownloadUrlForLayer""", """ecr:BatchGetImage""", """ecr:BatchCheckLayerAvailability""", """ecr:GetAuthorizationToken""", """cloudwatch:PutMetricData""", """cloudwatch:GetMetricData""", """cloudwatch:GetMetricStatistics""", """cloudwatch:ListMetrics""", """logs:CreateLogGroup""", """logs:CreateLogStream""", """logs:DescribeLogStreams""", """logs:PutLogEvents""", """logs:GetLogEvents""", """s3:CreateBucket""", """s3:ListBucket""", """s3:GetBucketLocation""", """s3:GetObject""", """s3:PutObject""", ], """Resource""": """*""", } ], } # attach policy to role iam_client.put_role_policy( RoleName=_lowercase, PolicyName=f"{role_name}_policy_permission", PolicyDocument=json.dumps(_lowercase, indent=2 ), ) except iam_client.exceptions.EntityAlreadyExistsException: print(f"role {role_name} already exists. Using existing one" ) def __lowercase (_lowercase ) -> Any: """simple docstring""" __lowerCamelCase : List[Any] = botoa.client("""iam""" ) return iam_client.get_role(RoleName=_lowercase )["Role"]["Arn"] def __lowercase () -> int: """simple docstring""" __lowerCamelCase : Tuple = _ask_options( """How do you want to authorize?""", ["""AWS Profile""", """Credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) """], _lowercase, ) __lowerCamelCase : List[str] = None if credentials_configuration == 0: __lowerCamelCase : Optional[Any] = _ask_field("""Enter your AWS Profile name: [default] """, default="""default""" ) __lowerCamelCase : Optional[Any] = aws_profile else: print( """Note you will need to provide AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY when you launch you training script with,""" """`accelerate launch --aws_access_key_id XXX --aws_secret_access_key YYY`""" ) __lowerCamelCase : List[Any] = _ask_field("""AWS Access Key ID: """ ) __lowerCamelCase : Union[str, Any] = aws_access_key_id __lowerCamelCase : int = _ask_field("""AWS Secret Access Key: """ ) __lowerCamelCase : Optional[Any] = aws_secret_access_key __lowerCamelCase : Tuple = _ask_field("""Enter your AWS Region: [us-east-1]""", default="""us-east-1""" ) __lowerCamelCase : Any = aws_region __lowerCamelCase : int = _ask_options( """Do you already have an IAM Role for executing Amazon SageMaker Training Jobs?""", ["""Provide IAM Role name""", """Create new IAM role using credentials"""], _lowercase, ) if role_management == 0: __lowerCamelCase : Tuple = _ask_field("""Enter your IAM role name: """ ) else: __lowerCamelCase : int = """accelerate_sagemaker_execution_role""" print(f"Accelerate will create an iam role \"{iam_role_name}\" using the provided credentials" ) _create_iam_role_for_sagemaker(_lowercase ) __lowerCamelCase : List[Any] = _ask_field( """Do you want to use custom Docker image? [yes/NO]: """, _convert_yes_no_to_bool, default=_lowercase, error_message="""Please enter yes or no.""", ) __lowerCamelCase : Union[str, Any] = None if is_custom_docker_image: __lowerCamelCase : Optional[int] = _ask_field("""Enter your Docker image: """, lambda _lowercase : str(_lowercase ).lower() ) __lowerCamelCase : str = _ask_field( """Do you want to provide SageMaker input channels with data locations? [yes/NO]: """, _convert_yes_no_to_bool, default=_lowercase, error_message="""Please enter yes or no.""", ) __lowerCamelCase : Any = None if is_sagemaker_inputs_enabled: __lowerCamelCase : Optional[Any] = _ask_field( """Enter the path to the SageMaker inputs TSV file with columns (channel_name, data_location): """, lambda _lowercase : str(_lowercase ).lower(), ) __lowerCamelCase : Optional[Any] = _ask_field( """Do you want to enable SageMaker metrics? [yes/NO]: """, _convert_yes_no_to_bool, default=_lowercase, error_message="""Please enter yes or no.""", ) __lowerCamelCase : Union[str, Any] = None if is_sagemaker_metrics_enabled: __lowerCamelCase : Optional[int] = _ask_field( """Enter the path to the SageMaker metrics TSV file with columns (metric_name, metric_regex): """, lambda _lowercase : str(_lowercase ).lower(), ) __lowerCamelCase : Any = _ask_options( """What is the distributed mode?""", ["""No distributed training""", """Data parallelism"""], _convert_sagemaker_distributed_mode, ) __lowerCamelCase : List[str] = {} __lowerCamelCase : Union[str, Any] = _ask_field( """Do you wish to optimize your script with torch dynamo?[yes/NO]:""", _convert_yes_no_to_bool, default=_lowercase, error_message="""Please enter yes or no.""", ) if use_dynamo: __lowerCamelCase : Union[str, Any] = """dynamo_""" __lowerCamelCase : Optional[Any] = _ask_options( """Which dynamo backend would you like to use?""", [x.lower() for x in DYNAMO_BACKENDS], _convert_dynamo_backend, default=2, ) __lowerCamelCase : Optional[int] = _ask_field( """Do you want to customize the defaults sent to torch.compile? [yes/NO]: """, _convert_yes_no_to_bool, default=_lowercase, error_message="""Please enter yes or no.""", ) if use_custom_options: __lowerCamelCase : Tuple = _ask_options( """Which mode do you want to use?""", _lowercase, lambda _lowercase : TORCH_DYNAMO_MODES[int(_lowercase )], default="""default""", ) __lowerCamelCase : Dict = _ask_field( """Do you want the fullgraph mode or it is ok to break model into several subgraphs? [yes/NO]: """, _convert_yes_no_to_bool, default=_lowercase, error_message="""Please enter yes or no.""", ) __lowerCamelCase : int = _ask_field( """Do you want to enable dynamic shape tracing? [yes/NO]: """, _convert_yes_no_to_bool, default=_lowercase, error_message="""Please enter yes or no.""", ) __lowerCamelCase : Dict = """Which EC2 instance type you want to use for your training?""" if distributed_type != SageMakerDistributedType.NO: __lowerCamelCase : Any = _ask_options( _lowercase, _lowercase, lambda _lowercase : SAGEMAKER_PARALLEL_EC2_INSTANCES[int(_lowercase )] ) else: eca_instance_query += "? [ml.p3.2xlarge]:" __lowerCamelCase : List[Any] = _ask_field(_lowercase, lambda _lowercase : str(_lowercase ).lower(), default="""ml.p3.2xlarge""" ) __lowerCamelCase : int = 1 if distributed_type in (SageMakerDistributedType.DATA_PARALLEL, SageMakerDistributedType.MODEL_PARALLEL): __lowerCamelCase : Any = _ask_field( """How many machines do you want use? [1]: """, _lowercase, default=1, ) __lowerCamelCase : Union[str, Any] = _ask_options( """Do you wish to use FP16 or BF16 (mixed precision)?""", ["""no""", """fp16""", """bf16""", """fp8"""], _convert_mixed_precision, ) if use_dynamo and mixed_precision == "no": print( """Torch dynamo used without mixed precision requires TF32 to be efficient. Accelerate will enable it by default when launching your scripts.""" ) return SageMakerConfig( image_uri=_lowercase, compute_environment=ComputeEnvironment.AMAZON_SAGEMAKER, distributed_type=_lowercase, use_cpu=_lowercase, dynamo_config=_lowercase, eca_instance_type=_lowercase, profile=_lowercase, region=_lowercase, iam_role_name=_lowercase, mixed_precision=_lowercase, num_machines=_lowercase, sagemaker_inputs_file=_lowercase, sagemaker_metrics_file=_lowercase, )
150
0
import unittest from transformers import RoFormerTokenizer, RoFormerTokenizerFast from transformers.testing_utils import require_rjieba, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_rjieba @require_tokenizers class lowercase ( a , unittest.TestCase ): lowercase__ : List[str] = RoFormerTokenizer lowercase__ : Any = RoFormerTokenizerFast lowercase__ : str = True lowercase__ : List[str] = True def __snake_case( self : List[Any] ) -> Optional[int]: '''simple docstring''' super().setUp() def __snake_case( self : List[Any] , **_UpperCamelCase : str ) -> Tuple: '''simple docstring''' return self.tokenizer_class.from_pretrained("junnyu/roformer_chinese_base" , **_UpperCamelCase ) def __snake_case( self : Union[str, Any] , **_UpperCamelCase : Any ) -> Tuple: '''simple docstring''' return self.rust_tokenizer_class.from_pretrained("junnyu/roformer_chinese_base" , **_UpperCamelCase ) def __snake_case( self : List[Any] ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = "永和服装饰品有限公司,今天天气非常好" SCREAMING_SNAKE_CASE = "永和 服装 饰品 有限公司 , 今 天 天 气 非常 好" return input_text, output_text def __snake_case( self : str ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.get_chinese_input_output_texts() SCREAMING_SNAKE_CASE = tokenizer.tokenize(_UpperCamelCase ) self.assertListEqual(_UpperCamelCase , output_text.split() ) SCREAMING_SNAKE_CASE = tokens + [tokenizer.unk_token] SCREAMING_SNAKE_CASE = [22_943, 21_332, 34_431, 45_904, 117, 306, 1_231, 1_231, 2_653, 33_994, 1_266, 100] self.assertListEqual(tokenizer.convert_tokens_to_ids(_UpperCamelCase ) , _UpperCamelCase ) def __snake_case( self : Dict ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.get_chinese_input_output_texts() SCREAMING_SNAKE_CASE = tokenizer.tokenize(_UpperCamelCase ) self.assertListEqual(_UpperCamelCase , output_text.split() ) SCREAMING_SNAKE_CASE = tokens + [tokenizer.unk_token] SCREAMING_SNAKE_CASE = [22_943, 21_332, 34_431, 45_904, 117, 306, 1_231, 1_231, 2_653, 33_994, 1_266, 100] self.assertListEqual(tokenizer.convert_tokens_to_ids(_UpperCamelCase ) , _UpperCamelCase ) def __snake_case( self : Optional[int] ) -> Any: '''simple docstring''' pass def __snake_case( self : List[Any] ) -> Optional[Any]: '''simple docstring''' pass def __snake_case( self : Tuple ) -> Optional[int]: '''simple docstring''' pass
647
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) _lowerCamelCase : Optional[int] = logging.getLogger(__name__) _lowerCamelCase : Optional[int] = '''Hello world! cécé herlolip''' _lowerCamelCase : List[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 __lowerCamelCase (UpperCAmelCase__ : str , UpperCAmelCase__ : Optional[int] ): SCREAMING_SNAKE_CASE = BertAbsConfig( temp_dir="." , finetune_bert=UpperCAmelCase__ , large=UpperCAmelCase__ , share_emb=UpperCAmelCase__ , use_bert_emb=UpperCAmelCase__ , encoder="bert" , max_pos=5_1_2 , enc_layers=6 , enc_hidden_size=5_1_2 , enc_heads=8 , enc_ff_size=5_1_2 , enc_dropout=0.2 , dec_layers=6 , dec_hidden_size=7_6_8 , dec_heads=8 , dec_ff_size=2_0_4_8 , dec_dropout=0.2 , ) SCREAMING_SNAKE_CASE = torch.load(UpperCAmelCase__ , lambda UpperCAmelCase__ , UpperCAmelCase__ : storage ) SCREAMING_SNAKE_CASE = AbsSummarizer(UpperCAmelCase__ , torch.device("cpu" ) , UpperCAmelCase__ ) original.eval() SCREAMING_SNAKE_CASE = BertAbsSummarizer(UpperCAmelCase__ , 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 = BertTokenizer.from_pretrained("bert-base-uncased" ) # prepare the model inputs SCREAMING_SNAKE_CASE = tokenizer.encode("This is sample éàalj'-." ) encoder_input_ids.extend([tokenizer.pad_token_id] * (5_1_2 - len(UpperCAmelCase__ )) ) SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ ).unsqueeze(0 ) SCREAMING_SNAKE_CASE = tokenizer.encode("This is sample 3 éàalj'-." ) decoder_input_ids.extend([tokenizer.pad_token_id] * (5_1_2 - len(UpperCAmelCase__ )) ) SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ ).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 = encoder_input_ids SCREAMING_SNAKE_CASE = decoder_input_ids SCREAMING_SNAKE_CASE = SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = 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 = original(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ )[0] SCREAMING_SNAKE_CASE = original.generator(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE = new_model( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ )[0] SCREAMING_SNAKE_CASE = new_model.generator(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE = torch.max(torch.abs(output_converted_model - output_original_model ) ).item() print("Maximum absolute difference beween weights: {:.2f}".format(UpperCAmelCase__ ) ) SCREAMING_SNAKE_CASE = torch.max(torch.abs(output_converted_generator - output_original_generator ) ).item() print("Maximum absolute difference beween weights: {:.2f}".format(UpperCAmelCase__ ) ) SCREAMING_SNAKE_CASE = torch.allclose(UpperCAmelCase__ , UpperCAmelCase__ , 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__": _lowerCamelCase : Union[str, Any] = 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.''', ) _lowerCamelCase : Any = parser.parse_args() convert_bertabs_checkpoints( args.bertabs_checkpoint_path, args.pytorch_dump_folder_path, )
647
1
'''simple docstring''' def _a (lowercase__ : str ) -> list: """simple docstring""" return [ txt[:a] + txt[a].upper() + txt[a + 1 :] for a in range(len(lowercase__ ) ) if txt[a].isalpha() ] if __name__ == "__main__": __import__("doctest").testmod()
56
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging _a : List[str] = logging.get_logger(__name__) _a : Dict = { "facebook/timesformer": "https://huggingface.co/facebook/timesformer/resolve/main/config.json", } class _lowercase ( __lowercase ): _SCREAMING_SNAKE_CASE : int = "timesformer" def __init__( self : Dict , SCREAMING_SNAKE_CASE_ : List[str]=224 , SCREAMING_SNAKE_CASE_ : List[str]=16 , SCREAMING_SNAKE_CASE_ : Any=3 , SCREAMING_SNAKE_CASE_ : int=8 , SCREAMING_SNAKE_CASE_ : Tuple=768 , SCREAMING_SNAKE_CASE_ : int=12 , SCREAMING_SNAKE_CASE_ : Optional[int]=12 , SCREAMING_SNAKE_CASE_ : Optional[int]=3072 , SCREAMING_SNAKE_CASE_ : Tuple="gelu" , SCREAMING_SNAKE_CASE_ : Optional[Any]=0.0 , SCREAMING_SNAKE_CASE_ : List[Any]=0.0 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=0.0_2 , SCREAMING_SNAKE_CASE_ : Any=1e-6 , SCREAMING_SNAKE_CASE_ : str=True , SCREAMING_SNAKE_CASE_ : List[str]="divided_space_time" , SCREAMING_SNAKE_CASE_ : int=0 , **SCREAMING_SNAKE_CASE_ : Optional[int] , ) -> List[str]: super().__init__(**SCREAMING_SNAKE_CASE_ ) __snake_case = image_size __snake_case = patch_size __snake_case = num_channels __snake_case = num_frames __snake_case = hidden_size __snake_case = num_hidden_layers __snake_case = num_attention_heads __snake_case = intermediate_size __snake_case = hidden_act __snake_case = hidden_dropout_prob __snake_case = attention_probs_dropout_prob __snake_case = initializer_range __snake_case = layer_norm_eps __snake_case = qkv_bias __snake_case = attention_type __snake_case = drop_path_rate
56
1
"""simple docstring""" import argparse from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_controlnet_from_original_ckpt if __name__ == "__main__": A__ : Optional[int]= argparse.ArgumentParser() parser.add_argument( """--checkpoint_path""", default=None, type=str, required=True, help="""Path to the checkpoint to convert.""" ) parser.add_argument( """--original_config_file""", type=str, required=True, help="""The YAML config file corresponding to the original architecture.""", ) parser.add_argument( """--num_in_channels""", default=None, type=int, help="""The number of input channels. If `None` number of input channels will be automatically inferred.""", ) parser.add_argument( """--image_size""", default=5_12, type=int, help=( """The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2""" """ Base. Use 768 for Stable Diffusion v2.""" ), ) parser.add_argument( """--extract_ema""", action="""store_true""", help=( """Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights""" """ or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield""" """ higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning.""" ), ) parser.add_argument( """--upcast_attention""", action="""store_true""", help=( """Whether the attention computation should always be upcasted. This is necessary when running stable""" """ diffusion 2.1.""" ), ) parser.add_argument( """--from_safetensors""", action="""store_true""", help="""If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.""", ) parser.add_argument( """--to_safetensors""", action="""store_true""", help="""Whether to store pipeline in safetensors format or not.""", ) parser.add_argument("""--dump_path""", default=None, type=str, required=True, help="""Path to the output model.""") parser.add_argument("""--device""", type=str, help="""Device to use (e.g. cpu, cuda:0, cuda:1, etc.)""") def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" if string == "True": return True elif string == "False": return False else: raise ValueError(F'could not parse string as bool {string}' ) parser.add_argument( """--use_linear_projection""", help="""Override for use linear projection""", required=False, type=parse_bool ) parser.add_argument("""--cross_attention_dim""", help="""Override for cross attention_dim""", required=False, type=int) A__ : Tuple= parser.parse_args() A__ : Optional[Any]= download_controlnet_from_original_ckpt( checkpoint_path=args.checkpoint_path, original_config_file=args.original_config_file, image_size=args.image_size, extract_ema=args.extract_ema, num_in_channels=args.num_in_channels, upcast_attention=args.upcast_attention, from_safetensors=args.from_safetensors, device=args.device, use_linear_projection=args.use_linear_projection, cross_attention_dim=args.cross_attention_dim, ) controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
20
"""simple docstring""" import argparse import json import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinConfig, SwinForImageClassification def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" UpperCamelCase__ = SwinConfig() UpperCamelCase__ = swin_name.split('_' ) UpperCamelCase__ = name_split[1] UpperCamelCase__ = int(name_split[4] ) UpperCamelCase__ = int(name_split[3][-1] ) if model_size == "tiny": UpperCamelCase__ = 96 UpperCamelCase__ = (2, 2, 6, 2) UpperCamelCase__ = (3, 6, 12, 24) elif model_size == "small": UpperCamelCase__ = 96 UpperCamelCase__ = (2, 2, 18, 2) UpperCamelCase__ = (3, 6, 12, 24) elif model_size == "base": UpperCamelCase__ = 1_28 UpperCamelCase__ = (2, 2, 18, 2) UpperCamelCase__ = (4, 8, 16, 32) else: UpperCamelCase__ = 1_92 UpperCamelCase__ = (2, 2, 18, 2) UpperCamelCase__ = (6, 12, 24, 48) if "in22k" in swin_name: UpperCamelCase__ = 2_18_41 else: UpperCamelCase__ = 10_00 UpperCamelCase__ = 'huggingface/label-files' UpperCamelCase__ = 'imagenet-1k-id2label.json' UpperCamelCase__ = json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , repo_type='dataset' ) , 'r' ) ) UpperCamelCase__ = {int(SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()} UpperCamelCase__ = idalabel UpperCamelCase__ = {v: k for k, v in idalabel.items()} UpperCamelCase__ = img_size UpperCamelCase__ = num_classes UpperCamelCase__ = embed_dim UpperCamelCase__ = depths UpperCamelCase__ = num_heads UpperCamelCase__ = window_size return config def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" if "patch_embed.proj" in name: UpperCamelCase__ = name.replace('patch_embed.proj' , 'embeddings.patch_embeddings.projection' ) if "patch_embed.norm" in name: UpperCamelCase__ = name.replace('patch_embed.norm' , 'embeddings.norm' ) if "layers" in name: UpperCamelCase__ = 'encoder.' + name if "attn.proj" in name: UpperCamelCase__ = name.replace('attn.proj' , 'attention.output.dense' ) if "attn" in name: UpperCamelCase__ = name.replace('attn' , 'attention.self' ) if "norm1" in name: UpperCamelCase__ = name.replace('norm1' , 'layernorm_before' ) if "norm2" in name: UpperCamelCase__ = name.replace('norm2' , 'layernorm_after' ) if "mlp.fc1" in name: UpperCamelCase__ = name.replace('mlp.fc1' , 'intermediate.dense' ) if "mlp.fc2" in name: UpperCamelCase__ = name.replace('mlp.fc2' , 'output.dense' ) if name == "norm.weight": UpperCamelCase__ = 'layernorm.weight' if name == "norm.bias": UpperCamelCase__ = 'layernorm.bias' if "head" in name: UpperCamelCase__ = name.replace('head' , 'classifier' ) else: UpperCamelCase__ = 'swin.' + name return name def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" for key in orig_state_dict.copy().keys(): UpperCamelCase__ = orig_state_dict.pop(SCREAMING_SNAKE_CASE ) if "mask" in key: continue elif "qkv" in key: UpperCamelCase__ = key.split('.' ) UpperCamelCase__ = int(key_split[1] ) UpperCamelCase__ = int(key_split[3] ) UpperCamelCase__ = model.swin.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: UpperCamelCase__ = val[:dim, :] UpperCamelCase__ = val[ dim : dim * 2, : ] UpperCamelCase__ = val[-dim:, :] else: UpperCamelCase__ = val[ :dim ] UpperCamelCase__ = val[ dim : dim * 2 ] UpperCamelCase__ = val[ -dim: ] else: UpperCamelCase__ = val return orig_state_dict def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" UpperCamelCase__ = timm.create_model(SCREAMING_SNAKE_CASE , pretrained=SCREAMING_SNAKE_CASE ) timm_model.eval() UpperCamelCase__ = get_swin_config(SCREAMING_SNAKE_CASE ) UpperCamelCase__ = SwinForImageClassification(SCREAMING_SNAKE_CASE ) model.eval() UpperCamelCase__ = convert_state_dict(timm_model.state_dict() , SCREAMING_SNAKE_CASE ) model.load_state_dict(SCREAMING_SNAKE_CASE ) UpperCamelCase__ = 'http://images.cocodataset.org/val2017/000000039769.jpg' UpperCamelCase__ = AutoImageProcessor.from_pretrained('microsoft/{}'.format(swin_name.replace('_' , '-' ) ) ) UpperCamelCase__ = Image.open(requests.get(SCREAMING_SNAKE_CASE , stream=SCREAMING_SNAKE_CASE ).raw ) UpperCamelCase__ = image_processor(images=SCREAMING_SNAKE_CASE , return_tensors='pt' ) UpperCamelCase__ = timm_model(inputs['pixel_values'] ) UpperCamelCase__ = model(**SCREAMING_SNAKE_CASE ).logits assert torch.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=1E-3 ) print(F'Saving model {swin_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(SCREAMING_SNAKE_CASE ) print(F'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(SCREAMING_SNAKE_CASE ) if __name__ == "__main__": A__ : Optional[Any]= argparse.ArgumentParser() # Required parameters parser.add_argument( """--swin_name""", default="""swin_tiny_patch4_window7_224""", type=str, help="""Name of the Swin 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.""" ) A__ : Tuple= parser.parse_args() convert_swin_checkpoint(args.swin_name, args.pytorch_dump_folder_path)
20
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) SCREAMING_SNAKE_CASE__ : int = { "configuration_albert": ["ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "AlbertConfig", "AlbertOnnxConfig"], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Dict = ["AlbertTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Tuple = ["AlbertTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ "ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "AlbertForMaskedLM", "AlbertForMultipleChoice", "AlbertForPreTraining", "AlbertForQuestionAnswering", "AlbertForSequenceClassification", "AlbertForTokenClassification", "AlbertModel", "AlbertPreTrainedModel", "load_tf_weights_in_albert", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Dict = [ "TF_ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFAlbertForMaskedLM", "TFAlbertForMultipleChoice", "TFAlbertForPreTraining", "TFAlbertForQuestionAnswering", "TFAlbertForSequenceClassification", "TFAlbertForTokenClassification", "TFAlbertMainLayer", "TFAlbertModel", "TFAlbertPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[Any] = [ "FlaxAlbertForMaskedLM", "FlaxAlbertForMultipleChoice", "FlaxAlbertForPreTraining", "FlaxAlbertForQuestionAnswering", "FlaxAlbertForSequenceClassification", "FlaxAlbertForTokenClassification", "FlaxAlbertModel", "FlaxAlbertPreTrainedModel", ] if TYPE_CHECKING: from .configuration_albert import ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, AlbertConfig, AlbertOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_albert import AlbertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_albert_fast import AlbertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_albert import ( ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST, AlbertForMaskedLM, AlbertForMultipleChoice, AlbertForPreTraining, AlbertForQuestionAnswering, AlbertForSequenceClassification, AlbertForTokenClassification, AlbertModel, AlbertPreTrainedModel, load_tf_weights_in_albert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_albert import ( TF_ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFAlbertForMaskedLM, TFAlbertForMultipleChoice, TFAlbertForPreTraining, TFAlbertForQuestionAnswering, TFAlbertForSequenceClassification, TFAlbertForTokenClassification, TFAlbertMainLayer, TFAlbertModel, TFAlbertPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_albert import ( FlaxAlbertForMaskedLM, FlaxAlbertForMultipleChoice, FlaxAlbertForPreTraining, FlaxAlbertForQuestionAnswering, FlaxAlbertForSequenceClassification, FlaxAlbertForTokenClassification, FlaxAlbertModel, FlaxAlbertPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
import unittest from knapsack import knapsack as k class UpperCAmelCase( unittest.TestCase ): """simple docstring""" def __a ( self ) -> Any: """simple docstring""" lowercase__ : Optional[int] = 0 lowercase__ : str = [0] lowercase__ : List[Any] = [0] lowercase__ : Optional[Any] = len(lowerCamelCase ) self.assertEqual(k.knapsack(lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ) , 0 ) lowercase__ : List[Any] = [60] lowercase__ : Optional[Any] = [10] lowercase__ : Optional[Any] = len(lowerCamelCase ) self.assertEqual(k.knapsack(lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ) , 0 ) def __a ( self ) -> Optional[Any]: """simple docstring""" lowercase__ : Optional[Any] = 3 lowercase__ : str = [1, 2, 3] lowercase__ : int = [3, 2, 1] lowercase__ : List[str] = len(lowerCamelCase ) self.assertEqual(k.knapsack(lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ) , 5 ) def __a ( self ) -> str: """simple docstring""" lowercase__ : Any = 50 lowercase__ : Optional[Any] = [60, 100, 120] lowercase__ : Optional[int] = [10, 20, 30] lowercase__ : List[str] = len(lowerCamelCase ) self.assertEqual(k.knapsack(lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ) , 220 ) if __name__ == "__main__": unittest.main()
397
0
"""simple docstring""" from __future__ import annotations import csv import requests from bsa import BeautifulSoup def lowercase ( __snake_case : str = "" ): lowercase_ : List[Any] = url or '''https://www.imdb.com/chart/top/?ref_=nv_mv_250''' lowercase_ : List[Any] = BeautifulSoup(requests.get(__snake_case ).text , '''html.parser''' ) lowercase_ : Optional[Any] = soup.find_all('''td''' , attrs='''titleColumn''' ) lowercase_ : str = soup.find_all('''td''' , class_='''ratingColumn imdbRating''' ) return { title.a.text: float(rating.strong.text ) for title, rating in zip(__snake_case , __snake_case ) } def lowercase ( __snake_case : str = "IMDb_Top_250_Movies.csv" ): lowercase_ : Dict = get_imdb_top_aaa_movies() with open(__snake_case , '''w''' , newline='''''' ) as out_file: lowercase_ : List[Any] = csv.writer(__snake_case ) writer.writerow(['''Movie title''', '''IMDb rating'''] ) for title, rating in movies.items(): writer.writerow([title, rating] ) if __name__ == "__main__": write_movies()
700
"""simple docstring""" from unittest import TestCase from datasets import Dataset from minhash_deduplication import deduplicate_dataset, make_duplicate_clusters def lowercase ( ): lowercase_ : Union[str, Any] = { '''repo_name''': ['''test_repo1''', '''test_repo2''', '''test_repo3'''], '''path''': ['''test_1.py''', '''test_2.py''', '''unit_test.py'''], '''content''': ['''a ''' * 2_0, '''a ''' * 3_0, '''b ''' * 7], } lowercase_ : Any = Dataset.from_dict(__snake_case ) return dataset class _UpperCAmelCase ( _A ): def A ( self : str ) -> str: lowercase_ : Tuple = get_dataset() lowercase_ : Any = make_duplicate_clusters(A , 0.85 ) self.assertEqual(len(duplicate_clusters[0] ) , 2 ) def A ( self : List[str] ) -> Union[str, Any]: lowercase_ : Any = get_dataset() lowercase_ , lowercase_ : str = deduplicate_dataset(A ) self.assertEqual(len(A ) , 2 ) print(A ) self.assertEqual(duplicate_clusters[0][0]['''copies'''] , 2 ) self.assertEqual(duplicate_clusters[0][0]['''is_extreme'''] , A )
141
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCAmelCase : List[str] = logging.get_logger(__name__) _lowerCAmelCase : List[str] = { '''google/vivit-b-16x2-kinetics400''': ( '''https://huggingface.co/google/vivit-b-16x2-kinetics400/resolve/main/config.json''' ), # See all Vivit models at https://huggingface.co/models?filter=vivit } class A_ ( _a ): lowerCAmelCase__ = 'vivit' def __init__( self: List[Any] ,__lowerCAmelCase: int=224 ,__lowerCAmelCase: Any=32 ,__lowerCAmelCase: str=[2, 16, 16] ,__lowerCAmelCase: Optional[Any]=3 ,__lowerCAmelCase: List[str]=768 ,__lowerCAmelCase: List[Any]=12 ,__lowerCAmelCase: Optional[int]=12 ,__lowerCAmelCase: Optional[Any]=3_072 ,__lowerCAmelCase: Any="gelu_fast" ,__lowerCAmelCase: Tuple=0.0 ,__lowerCAmelCase: Any=0.0 ,__lowerCAmelCase: Union[str, Any]=0.02 ,__lowerCAmelCase: List[str]=1e-06 ,__lowerCAmelCase: Optional[Any]=True ,**__lowerCAmelCase: Optional[int] ,): '''simple docstring''' _lowerCamelCase : Any = hidden_size _lowerCamelCase : List[str] = num_hidden_layers _lowerCamelCase : Union[str, Any] = num_attention_heads _lowerCamelCase : Any = intermediate_size _lowerCamelCase : Tuple = hidden_act _lowerCamelCase : Tuple = hidden_dropout_prob _lowerCamelCase : Optional[Any] = attention_probs_dropout_prob _lowerCamelCase : List[Any] = initializer_range _lowerCamelCase : int = layer_norm_eps _lowerCamelCase : Tuple = image_size _lowerCamelCase : Dict = num_frames _lowerCamelCase : Optional[int] = tubelet_size _lowerCamelCase : int = num_channels _lowerCamelCase : List[str] = qkv_bias super().__init__(**__lowerCAmelCase )
46
SCREAMING_SNAKE_CASE__ : Tuple = { """a""": """AAAAA""", """b""": """AAAAB""", """c""": """AAABA""", """d""": """AAABB""", """e""": """AABAA""", """f""": """AABAB""", """g""": """AABBA""", """h""": """AABBB""", """i""": """ABAAA""", """j""": """BBBAA""", """k""": """ABAAB""", """l""": """ABABA""", """m""": """ABABB""", """n""": """ABBAA""", """o""": """ABBAB""", """p""": """ABBBA""", """q""": """ABBBB""", """r""": """BAAAA""", """s""": """BAAAB""", """t""": """BAABA""", """u""": """BAABB""", """v""": """BBBAB""", """w""": """BABAA""", """x""": """BABAB""", """y""": """BABBA""", """z""": """BABBB""", """ """: """ """, } SCREAMING_SNAKE_CASE__ : Union[str, Any] = {value: key for key, value in encode_dict.items()} def __lowercase ( snake_case ): """simple docstring""" __magic_name__ :Tuple = '''''' for letter in word.lower(): if letter.isalpha() or letter == " ": encoded += encode_dict[letter] else: raise Exception('''encode() accepts only letters of the alphabet and spaces''' ) return encoded def __lowercase ( snake_case ): """simple docstring""" if set(snake_case ) - {"A", "B", " "} != set(): raise Exception('''decode() accepts only \'A\', \'B\' and spaces''' ) __magic_name__ :Dict = '''''' for word in coded.split(): while len(snake_case ) != 0: decoded += decode_dict[word[:5]] __magic_name__ :int = word[5:] decoded += " " return decoded.strip() if __name__ == "__main__": from doctest import testmod testmod()
0
0
import argparse import collections import os import re import tempfile import pandas as pd from datasets import Dataset from huggingface_hub import hf_hub_download, upload_folder from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/update_metadata.py __A : Any = """src/transformers""" # This is to make sure the transformers module imported is the one in the repo. __A : Any = direct_transformers_import(TRANSFORMERS_PATH) # Regexes that match TF/Flax/PT model names. __A : Tuple = re.compile(r"""TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""") __A : Optional[Any] = re.compile(r"""Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""") # Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes. __A : Optional[int] = re.compile(r"""(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""") # Fill this with tuples (pipeline_tag, model_mapping, auto_model) __A : str = [ ("""pretraining""", """MODEL_FOR_PRETRAINING_MAPPING_NAMES""", """AutoModelForPreTraining"""), ("""feature-extraction""", """MODEL_MAPPING_NAMES""", """AutoModel"""), ("""audio-classification""", """MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES""", """AutoModelForAudioClassification"""), ("""text-generation""", """MODEL_FOR_CAUSAL_LM_MAPPING_NAMES""", """AutoModelForCausalLM"""), ("""automatic-speech-recognition""", """MODEL_FOR_CTC_MAPPING_NAMES""", """AutoModelForCTC"""), ("""image-classification""", """MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES""", """AutoModelForImageClassification"""), ("""image-segmentation""", """MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES""", """AutoModelForImageSegmentation"""), ("""fill-mask""", """MODEL_FOR_MASKED_LM_MAPPING_NAMES""", """AutoModelForMaskedLM"""), ("""object-detection""", """MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES""", """AutoModelForObjectDetection"""), ( """zero-shot-object-detection""", """MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES""", """AutoModelForZeroShotObjectDetection""", ), ("""question-answering""", """MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES""", """AutoModelForQuestionAnswering"""), ("""text2text-generation""", """MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES""", """AutoModelForSeq2SeqLM"""), ("""text-classification""", """MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES""", """AutoModelForSequenceClassification"""), ("""automatic-speech-recognition""", """MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES""", """AutoModelForSpeechSeq2Seq"""), ( """table-question-answering""", """MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES""", """AutoModelForTableQuestionAnswering""", ), ("""token-classification""", """MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES""", """AutoModelForTokenClassification"""), ("""multiple-choice""", """MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES""", """AutoModelForMultipleChoice"""), ( """next-sentence-prediction""", """MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES""", """AutoModelForNextSentencePrediction""", ), ( """audio-frame-classification""", """MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES""", """AutoModelForAudioFrameClassification""", ), ("""audio-xvector""", """MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES""", """AutoModelForAudioXVector"""), ( """document-question-answering""", """MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES""", """AutoModelForDocumentQuestionAnswering""", ), ( """visual-question-answering""", """MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING_NAMES""", """AutoModelForVisualQuestionAnswering""", ), ("""image-to-text""", """MODEL_FOR_FOR_VISION_2_SEQ_MAPPING_NAMES""", """AutoModelForVision2Seq"""), ( """zero-shot-image-classification""", """MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES""", """AutoModelForZeroShotImageClassification""", ), ("""depth-estimation""", """MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES""", """AutoModelForDepthEstimation"""), ("""video-classification""", """MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES""", """AutoModelForVideoClassification"""), ("""mask-generation""", """MODEL_FOR_MASK_GENERATION_MAPPING_NAMES""", """AutoModelForMaskGeneration"""), ] def lowerCamelCase_ ( SCREAMING_SNAKE_CASE ): '''simple docstring''' SCREAMING_SNAKE_CASE = re.finditer(""".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)""" , __lowercase ) return [m.group(0 ) for m in matches] def lowerCamelCase_ ( ): '''simple docstring''' SCREAMING_SNAKE_CASE = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES SCREAMING_SNAKE_CASE = { config.replace("""Config""" , """""" ): model_type for model_type, config in config_maping_names.items() } # Dictionaries flagging if each model prefix has a backend in PT/TF/Flax. SCREAMING_SNAKE_CASE = collections.defaultdict(__lowercase ) SCREAMING_SNAKE_CASE = collections.defaultdict(__lowercase ) SCREAMING_SNAKE_CASE = collections.defaultdict(__lowercase ) # Let's lookup through all transformers object (once) and find if models are supported by a given backend. for attr_name in dir(__lowercase ): SCREAMING_SNAKE_CASE = None if _re_tf_models.match(__lowercase ) is not None: SCREAMING_SNAKE_CASE = tf_models SCREAMING_SNAKE_CASE = _re_tf_models.match(__lowercase ).groups()[0] elif _re_flax_models.match(__lowercase ) is not None: SCREAMING_SNAKE_CASE = flax_models SCREAMING_SNAKE_CASE = _re_flax_models.match(__lowercase ).groups()[0] elif _re_pt_models.match(__lowercase ) is not None: SCREAMING_SNAKE_CASE = pt_models SCREAMING_SNAKE_CASE = _re_pt_models.match(__lowercase ).groups()[0] if lookup_dict is not None: while len(__lowercase ) > 0: if attr_name in model_prefix_to_model_type: SCREAMING_SNAKE_CASE = True break # Try again after removing the last word in the name SCREAMING_SNAKE_CASE = ''.join(camel_case_split(__lowercase )[:-1] ) SCREAMING_SNAKE_CASE = set(list(pt_models.keys() ) + list(tf_models.keys() ) + list(flax_models.keys() ) ) SCREAMING_SNAKE_CASE = list(__lowercase ) all_models.sort() SCREAMING_SNAKE_CASE = {'model_type': all_models} SCREAMING_SNAKE_CASE = [pt_models[t] for t in all_models] SCREAMING_SNAKE_CASE = [tf_models[t] for t in all_models] SCREAMING_SNAKE_CASE = [flax_models[t] for t in all_models] # Now let's use the auto-mapping names to make sure SCREAMING_SNAKE_CASE = {} for t in all_models: if t in transformers_module.models.auto.processing_auto.PROCESSOR_MAPPING_NAMES: SCREAMING_SNAKE_CASE = 'AutoProcessor' elif t in transformers_module.models.auto.tokenization_auto.TOKENIZER_MAPPING_NAMES: SCREAMING_SNAKE_CASE = 'AutoTokenizer' elif t in transformers_module.models.auto.feature_extraction_auto.FEATURE_EXTRACTOR_MAPPING_NAMES: SCREAMING_SNAKE_CASE = 'AutoFeatureExtractor' else: # Default to AutoTokenizer if a model has nothing, for backward compatibility. SCREAMING_SNAKE_CASE = 'AutoTokenizer' SCREAMING_SNAKE_CASE = [processors[t] for t in all_models] return pd.DataFrame(__lowercase ) def lowerCamelCase_ ( SCREAMING_SNAKE_CASE ): '''simple docstring''' SCREAMING_SNAKE_CASE = [ transformers_module.models.auto.modeling_auto, transformers_module.models.auto.modeling_tf_auto, transformers_module.models.auto.modeling_flax_auto, ] for pipeline_tag, model_mapping, auto_class in PIPELINE_TAGS_AND_AUTO_MODELS: SCREAMING_SNAKE_CASE = [model_mapping, f"""TF_{model_mapping}""", f"""FLAX_{model_mapping}"""] SCREAMING_SNAKE_CASE = [auto_class, f"""TF_{auto_class}""", f"""Flax_{auto_class}"""] # Loop through all three frameworks for module, cls, mapping in zip(__lowercase , __lowercase , __lowercase ): # The type of pipeline may not exist in this framework if not hasattr(__lowercase , __lowercase ): continue # First extract all model_names SCREAMING_SNAKE_CASE = [] for name in getattr(__lowercase , __lowercase ).values(): if isinstance(__lowercase , __lowercase ): model_names.append(__lowercase ) else: model_names.extend(list(__lowercase ) ) # Add pipeline tag and auto model class for those models table.update({model_name: (pipeline_tag, cls) for model_name in model_names} ) return table def lowerCamelCase_ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): '''simple docstring''' SCREAMING_SNAKE_CASE = get_frameworks_table() SCREAMING_SNAKE_CASE = Dataset.from_pandas(__lowercase ) SCREAMING_SNAKE_CASE = hf_hub_download( """huggingface/transformers-metadata""" , """pipeline_tags.json""" , repo_type="""dataset""" , token=__lowercase ) SCREAMING_SNAKE_CASE = Dataset.from_json(__lowercase ) SCREAMING_SNAKE_CASE = { tags_dataset[i]['model_class']: (tags_dataset[i]['pipeline_tag'], tags_dataset[i]['auto_class']) for i in range(len(__lowercase ) ) } SCREAMING_SNAKE_CASE = update_pipeline_and_auto_class_table(__lowercase ) # Sort the model classes to avoid some nondeterministic updates to create false update commits. SCREAMING_SNAKE_CASE = sorted(table.keys() ) SCREAMING_SNAKE_CASE = pd.DataFrame( { """model_class""": model_classes, """pipeline_tag""": [table[m][0] for m in model_classes], """auto_class""": [table[m][1] for m in model_classes], } ) SCREAMING_SNAKE_CASE = Dataset.from_pandas(__lowercase ) with tempfile.TemporaryDirectory() as tmp_dir: frameworks_dataset.to_json(os.path.join(__lowercase , """frameworks.json""" ) ) tags_dataset.to_json(os.path.join(__lowercase , """pipeline_tags.json""" ) ) if commit_sha is not None: SCREAMING_SNAKE_CASE = ( f"""Update with commit {commit_sha}\n\nSee: """ f"""https://github.com/huggingface/transformers/commit/{commit_sha}""" ) else: SCREAMING_SNAKE_CASE = 'Update' upload_folder( repo_id="""huggingface/transformers-metadata""" , folder_path=__lowercase , repo_type="""dataset""" , token=__lowercase , commit_message=__lowercase , ) def lowerCamelCase_ ( ): '''simple docstring''' SCREAMING_SNAKE_CASE = {tag: cls for tag, _, cls in PIPELINE_TAGS_AND_AUTO_MODELS} SCREAMING_SNAKE_CASE = transformers_module.pipelines.SUPPORTED_TASKS SCREAMING_SNAKE_CASE = [] for key in pipeline_tasks: if key not in in_table: SCREAMING_SNAKE_CASE = pipeline_tasks[key]['pt'] if isinstance(__lowercase , (list, tuple) ): SCREAMING_SNAKE_CASE = model[0] SCREAMING_SNAKE_CASE = model.__name__ if model not in in_table.values(): missing.append(__lowercase ) if len(__lowercase ) > 0: SCREAMING_SNAKE_CASE = ', '.join(__lowercase ) raise ValueError( """The following pipeline tags are not present in the `PIPELINE_TAGS_AND_AUTO_MODELS` constant inside """ f"""`utils/update_metadata.py`: {msg}. Please add them!""" ) if __name__ == "__main__": __A : Optional[Any] = argparse.ArgumentParser() parser.add_argument("""--token""", type=str, help="""The token to use to push to the transformers-metadata dataset.""") parser.add_argument("""--commit_sha""", type=str, help="""The sha of the commit going with this update.""") parser.add_argument("""--check-only""", action="""store_true""", help="""Activate to just check all pipelines are present.""") __A : List[str] = parser.parse_args() if args.check_only: check_pipeline_tags() else: update_metadata(args.token, args.commit_sha)
704
import os from shutil import copyfile from typing import List, Optional, Tuple from tokenizers import processors from ...tokenization_utils import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_mbart import MBartTokenizer else: __A : Tuple = None __A : Any = logging.get_logger(__name__) __A : Union[str, Any] = {"""vocab_file""": """sentencepiece.bpe.model""", """tokenizer_file""": """tokenizer.json"""} __A : List[Any] = { """vocab_file""": { """facebook/mbart-large-en-ro""": ( """https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/sentencepiece.bpe.model""" ), """facebook/mbart-large-cc25""": ( """https://huggingface.co/facebook/mbart-large-cc25/resolve/main/sentencepiece.bpe.model""" ), }, """tokenizer_file""": { """facebook/mbart-large-en-ro""": """https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/tokenizer.json""", """facebook/mbart-large-cc25""": """https://huggingface.co/facebook/mbart-large-cc25/resolve/main/tokenizer.json""", }, } __A : int = { """facebook/mbart-large-en-ro""": 1_0_2_4, """facebook/mbart-large-cc25""": 1_0_2_4, } # fmt: off __A : List[Any] = ["""ar_AR""", """cs_CZ""", """de_DE""", """en_XX""", """es_XX""", """et_EE""", """fi_FI""", """fr_XX""", """gu_IN""", """hi_IN""", """it_IT""", """ja_XX""", """kk_KZ""", """ko_KR""", """lt_LT""", """lv_LV""", """my_MM""", """ne_NP""", """nl_XX""", """ro_RO""", """ru_RU""", """si_LK""", """tr_TR""", """vi_VN""", """zh_CN"""] class UpperCAmelCase_ ( A ): '''simple docstring''' a__ = VOCAB_FILES_NAMES a__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a__ = PRETRAINED_VOCAB_FILES_MAP a__ = ['''input_ids''', '''attention_mask'''] a__ = MBartTokenizer a__ = [] a__ = [] def __init__( self : str , a : List[Any]=None , a : Optional[int]=None , a : str="<s>" , a : Tuple="</s>" , a : Optional[int]="</s>" , a : int="<s>" , a : List[str]="<unk>" , a : Tuple="<pad>" , a : Dict="<mask>" , a : Optional[Any]=None , a : List[Any]=None , a : Any=None , **a : Optional[Any] , ) -> Any: # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE = AddedToken(a , lstrip=a , rstrip=a ) if isinstance(a , a ) else mask_token super().__init__( vocab_file=a , tokenizer_file=a , bos_token=a , eos_token=a , sep_token=a , cls_token=a , unk_token=a , pad_token=a , mask_token=a , src_lang=a , tgt_lang=a , additional_special_tokens=a , **a , ) SCREAMING_SNAKE_CASE = vocab_file SCREAMING_SNAKE_CASE = False if not self.vocab_file else True SCREAMING_SNAKE_CASE = FAIRSEQ_LANGUAGE_CODES.copy() if additional_special_tokens is not None: # Only add those special tokens if they are not already there. _additional_special_tokens.extend( [t for t in additional_special_tokens if t not in _additional_special_tokens] ) self.add_special_tokens({"""additional_special_tokens""": _additional_special_tokens} ) SCREAMING_SNAKE_CASE = { lang_code: self.convert_tokens_to_ids(a ) for lang_code in FAIRSEQ_LANGUAGE_CODES } SCREAMING_SNAKE_CASE = src_lang if src_lang is not None else """en_XX""" SCREAMING_SNAKE_CASE = self.convert_tokens_to_ids(self._src_lang ) SCREAMING_SNAKE_CASE = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) @property def _UpperCAmelCase ( self : int ) -> str: return self._src_lang @src_lang.setter def _UpperCAmelCase ( self : List[Any] , a : str ) -> None: SCREAMING_SNAKE_CASE = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def _UpperCAmelCase ( self : Dict , a : List[int] , a : Optional[List[int]] = None ) -> List[int]: if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def _UpperCAmelCase ( self : Tuple , a : List[int] , a : Optional[List[int]] = None ) -> List[int]: SCREAMING_SNAKE_CASE = [self.sep_token_id] SCREAMING_SNAKE_CASE = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def _UpperCAmelCase ( self : Optional[Any] , a : Optional[int] , a : str , a : Optional[str] , a : Optional[str] , **a : Optional[Any] ) -> Optional[Any]: if src_lang is None or tgt_lang is None: raise ValueError("""Translation requires a `src_lang` and a `tgt_lang` for this model""" ) SCREAMING_SNAKE_CASE = src_lang SCREAMING_SNAKE_CASE = self(a , add_special_tokens=a , return_tensors=a , **a ) SCREAMING_SNAKE_CASE = self.convert_tokens_to_ids(a ) SCREAMING_SNAKE_CASE = tgt_lang_id return inputs def _UpperCAmelCase ( self : str , a : List[str] , a : str = "en_XX" , a : Optional[List[str]] = None , a : str = "ro_RO" , **a : List[str] , ) -> BatchEncoding: SCREAMING_SNAKE_CASE = src_lang SCREAMING_SNAKE_CASE = tgt_lang return super().prepare_seqaseq_batch(a , a , **a ) def _UpperCAmelCase ( self : Optional[Any] ) -> str: return self.set_src_lang_special_tokens(self.src_lang ) def _UpperCAmelCase ( self : str ) -> List[str]: return self.set_tgt_lang_special_tokens(self.tgt_lang ) def _UpperCAmelCase ( self : Dict , a : List[str] ) -> None: SCREAMING_SNAKE_CASE = self.convert_tokens_to_ids(a ) SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = [self.eos_token_id, self.cur_lang_code] SCREAMING_SNAKE_CASE = self.convert_ids_to_tokens(self.prefix_tokens ) SCREAMING_SNAKE_CASE = self.convert_ids_to_tokens(self.suffix_tokens ) SCREAMING_SNAKE_CASE = processors.TemplateProcessing( single=prefix_tokens_str + ["""$A"""] + suffix_tokens_str , pair=prefix_tokens_str + ["""$A""", """$B"""] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def _UpperCAmelCase ( self : Dict , a : str ) -> None: SCREAMING_SNAKE_CASE = self.convert_tokens_to_ids(a ) SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = [self.eos_token_id, self.cur_lang_code] SCREAMING_SNAKE_CASE = self.convert_ids_to_tokens(self.prefix_tokens ) SCREAMING_SNAKE_CASE = self.convert_ids_to_tokens(self.suffix_tokens ) SCREAMING_SNAKE_CASE = processors.TemplateProcessing( single=prefix_tokens_str + ["""$A"""] + suffix_tokens_str , pair=prefix_tokens_str + ["""$A""", """$B"""] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def _UpperCAmelCase ( self : Dict , a : str , a : Optional[str] = None ) -> Tuple[str]: if not self.can_save_slow_tokenizer: raise ValueError( """Your fast tokenizer does not have the necessary information to save the vocabulary for a slow """ """tokenizer.""" ) if not os.path.isdir(a ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory.""" ) return SCREAMING_SNAKE_CASE = os.path.join( a , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(a ): copyfile(self.vocab_file , a ) return (out_vocab_file,)
450
0
def _a ( __lowercase ) -> list: """simple docstring""" if len(__lowercase ) <= 1: return [tuple(__lowercase )] __UpperCamelCase = [] def generate(__lowercase , __lowercase ): if k == 1: res.append(tuple(arr[:] ) ) return generate(k - 1 , __lowercase ) for i in range(k - 1 ): if k % 2 == 0: # k is even __UpperCamelCase , __UpperCamelCase = arr[k - 1], arr[i] else: # k is odd __UpperCamelCase , __UpperCamelCase = arr[k - 1], arr[0] generate(k - 1 , __lowercase ) generate(len(__lowercase ) , __lowercase ) return res if __name__ == "__main__": _snake_case = input('Enter numbers separated by a comma:\n').strip() _snake_case = [int(item) for item in user_input.split(',')] print(heaps(arr))
383
from __future__ import annotations from collections import Counter from random import random class lowerCAmelCase_ : """simple docstring""" def __init__( self ) -> List[str]: __UpperCamelCase = {} def __lowercase( self , _SCREAMING_SNAKE_CASE ) -> None: __UpperCamelCase = {} def __lowercase( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> None: if nodea not in self.connections: self.add_node(_SCREAMING_SNAKE_CASE ) if nodea not in self.connections: self.add_node(_SCREAMING_SNAKE_CASE ) __UpperCamelCase = probability def __lowercase( self ) -> list[str]: return list(self.connections ) def __lowercase( self , _SCREAMING_SNAKE_CASE ) -> str: __UpperCamelCase = 0 __UpperCamelCase = random() for dest in self.connections[node]: current_probability += self.connections[node][dest] if current_probability > random_value: return dest return "" def _a ( __lowercase , __lowercase , __lowercase ) -> dict[str, int]: """simple docstring""" __UpperCamelCase = MarkovChainGraphUndirectedUnweighted() for nodea, nodea, probability in transitions: graph.add_transition_probability(__lowercase , __lowercase , __lowercase ) __UpperCamelCase = Counter(graph.get_nodes() ) __UpperCamelCase = start for _ in range(__lowercase ): __UpperCamelCase = graph.transition(__lowercase ) visited[node] += 1 return visited if __name__ == "__main__": import doctest doctest.testmod()
383
1
"""simple docstring""" import argparse import torch from transformers import ( WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaForAudioFrameClassification, WavaVecaForSequenceClassification, WavaVecaForXVector, logging, ) logging.set_verbosity_info() lowercase__ : List[Any] = logging.get_logger(__name__) def __lowercase ( _a , _a , _a ): snake_case_ : List[str] = WavaVecaForSequenceClassification.from_pretrained(_a , config=_a ) snake_case_ : List[str] = downstream_dict['''projector.weight'''] snake_case_ : int = downstream_dict['''projector.bias'''] snake_case_ : Union[str, Any] = downstream_dict['''model.post_net.linear.weight'''] snake_case_ : int = downstream_dict['''model.post_net.linear.bias'''] return model def __lowercase ( _a , _a , _a ): snake_case_ : Any = WavaVecaForAudioFrameClassification.from_pretrained(_a , config=_a ) snake_case_ : Optional[int] = downstream_dict['''model.linear.weight'''] snake_case_ : Dict = downstream_dict['''model.linear.bias'''] return model def __lowercase ( _a , _a , _a ): snake_case_ : Optional[Any] = WavaVecaForXVector.from_pretrained(_a , config=_a ) snake_case_ : List[Any] = downstream_dict['''connector.weight'''] snake_case_ : Tuple = downstream_dict['''connector.bias'''] for i, kernel_size in enumerate(hf_config.tdnn_kernel ): snake_case_ : List[Any] = downstream_dict[ f"model.framelevel_feature_extractor.module.{i}.kernel.weight" ] snake_case_ : Dict = downstream_dict[f"model.framelevel_feature_extractor.module.{i}.kernel.bias"] snake_case_ : Tuple = downstream_dict['''model.utterancelevel_feature_extractor.linear1.weight'''] snake_case_ : List[str] = downstream_dict['''model.utterancelevel_feature_extractor.linear1.bias'''] snake_case_ : Tuple = downstream_dict['''model.utterancelevel_feature_extractor.linear2.weight'''] snake_case_ : Optional[int] = downstream_dict['''model.utterancelevel_feature_extractor.linear2.bias'''] snake_case_ : int = downstream_dict['''objective.W'''] return model @torch.no_grad() def __lowercase ( _a , _a , _a , _a ): snake_case_ : Any = torch.load(_a , map_location='''cpu''' ) snake_case_ : Tuple = checkpoint['''Downstream'''] snake_case_ : int = WavaVecaConfig.from_pretrained(_a ) snake_case_ : List[str] = WavaVecaFeatureExtractor.from_pretrained( _a , return_attention_mask=_a , do_normalize=_a ) snake_case_ : Tuple = hf_config.architectures[0] if arch.endswith('''ForSequenceClassification''' ): snake_case_ : Tuple = convert_classification(_a , _a , _a ) elif arch.endswith('''ForAudioFrameClassification''' ): snake_case_ : Optional[int] = convert_diarization(_a , _a , _a ) elif arch.endswith('''ForXVector''' ): snake_case_ : Union[str, Any] = convert_xvector(_a , _a , _a ) else: raise NotImplementedError(f"S3PRL weights conversion is not supported for {arch}" ) if hf_config.use_weighted_layer_sum: snake_case_ : Optional[int] = checkpoint['''Featurizer''']['''weights'''] hf_feature_extractor.save_pretrained(_a ) hf_model.save_pretrained(_a ) if __name__ == "__main__": lowercase__ : Optional[int] = argparse.ArgumentParser() parser.add_argument( '''--base_model_name''', default=None, type=str, help='''Name of the huggingface pretrained base model.''' ) parser.add_argument('''--config_path''', default=None, type=str, help='''Path to the huggingface classifier config.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to the s3prl checkpoint.''') parser.add_argument('''--model_dump_path''', default=None, type=str, help='''Path to the final converted model.''') lowercase__ : Optional[int] = parser.parse_args() convert_saprl_checkpoint(args.base_model_name, args.config_path, args.checkpoint_path, args.model_dump_path)
708
"""simple docstring""" import numpy as np from numpy import ndarray from scipy.optimize import Bounds, LinearConstraint, minimize def __lowercase ( _a ): return np.dot(_a , _a ) class _UpperCAmelCase : def __init__( self : int , *, lowercase_ : float = np.inf , lowercase_ : str = "linear" , lowercase_ : float = 0.0 , ): snake_case_ : Optional[Any] = regularization snake_case_ : Tuple = gamma if kernel == "linear": snake_case_ : int = self.__linear elif kernel == "rbf": if self.gamma == 0: raise ValueError('''rbf kernel requires gamma''' ) if not isinstance(self.gamma , (float, int) ): raise ValueError('''gamma must be float or int''' ) if not self.gamma > 0: raise ValueError('''gamma must be > 0''' ) snake_case_ : int = self.__rbf # in the future, there could be a default value like in sklearn # sklear: def_gamma = 1/(n_features * X.var()) (wiki) # previously it was 1/(n_features) else: snake_case_ : List[Any] = f"Unknown kernel: {kernel}" raise ValueError(lowercase_ ) def _snake_case ( self : int , lowercase_ : ndarray , lowercase_ : ndarray ): return np.dot(lowercase_ , lowercase_ ) def _snake_case ( self : int , lowercase_ : ndarray , lowercase_ : ndarray ): return np.exp(-(self.gamma * norm_squared(vectora - vectora )) ) def _snake_case ( self : Any , lowercase_ : list[ndarray] , lowercase_ : ndarray ): snake_case_ : Union[str, Any] = observations snake_case_ : int = classes # using Wolfe's Dual to calculate w. # Primal problem: minimize 1/2*norm_squared(w) # constraint: yn(w . xn + b) >= 1 # # With l a vector # Dual problem: maximize sum_n(ln) - # 1/2 * sum_n(sum_m(ln*lm*yn*ym*xn . xm)) # constraint: self.C >= ln >= 0 # and sum_n(ln*yn) = 0 # Then we get w using w = sum_n(ln*yn*xn) # At the end we can get b ~= mean(yn - w . xn) # # Since we use kernels, we only need l_star to calculate b # and to classify observations ((snake_case_), ) : List[str] = np.shape(lowercase_ ) def to_minimize(lowercase_ : ndarray ) -> float: snake_case_ : Tuple = 0 ((snake_case_), ) : Optional[Any] = np.shape(lowercase_ ) for i in range(lowercase_ ): for j in range(lowercase_ ): s += ( candidate[i] * candidate[j] * classes[i] * classes[j] * self.kernel(observations[i] , observations[j] ) ) return 1 / 2 * s - sum(lowercase_ ) snake_case_ : Optional[Any] = LinearConstraint(lowercase_ , 0 , 0 ) snake_case_ : str = Bounds(0 , self.regularization ) snake_case_ : int = minimize( lowercase_ , np.ones(lowercase_ ) , bounds=lowercase_ , constraints=[ly_contraint] ).x snake_case_ : Optional[Any] = l_star # calculating mean offset of separation plane to points snake_case_ : List[Any] = 0 for i in range(lowercase_ ): for j in range(lowercase_ ): s += classes[i] - classes[i] * self.optimum[i] * self.kernel( observations[i] , observations[j] ) snake_case_ : Union[str, Any] = s / n def _snake_case ( self : List[str] , lowercase_ : ndarray ): snake_case_ : int = sum( self.optimum[n] * self.classes[n] * self.kernel(self.observations[n] , lowercase_ ) for n in range(len(self.classes ) ) ) return 1 if s + self.offset >= 0 else -1 if __name__ == "__main__": import doctest doctest.testmod()
485
0
import glob import os import random from string import ascii_lowercase, digits import cva import numpy as np # Parrameters __snake_case = (7_2_0, 1_2_8_0) # Height, Width __snake_case = (0.4, 0.6) # if height or width lower than this scale, drop it. __snake_case = 1 / 1_0_0 __snake_case = '''''' __snake_case = '''''' __snake_case = '''''' __snake_case = 2_5_0 def _A ( ) -> None: """simple docstring""" __UpperCamelCase, __UpperCamelCase = get_dataset(_lowercase , _lowercase ) for index in range(_lowercase ): __UpperCamelCase = random.sample(range(len(_lowercase ) ) , 4 ) __UpperCamelCase, __UpperCamelCase, __UpperCamelCase = update_image_and_anno( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , filter_scale=_lowercase , ) # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' __UpperCamelCase = random_chars(32 ) __UpperCamelCase = path.split(os.sep )[-1].rsplit('.' , 1 )[0] __UpperCamelCase = f'''{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}''' cva.imwrite(f'''{file_root}.jpg''' , _lowercase , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(f'''Succeeded {index+1}/{NUMBER_IMAGES} with {file_name}''' ) __UpperCamelCase = [] for anno in new_annos: __UpperCamelCase = anno[3] - anno[1] __UpperCamelCase = anno[4] - anno[2] __UpperCamelCase = anno[1] + width / 2 __UpperCamelCase = anno[2] + height / 2 __UpperCamelCase = f'''{anno[0]} {x_center} {y_center} {width} {height}''' annos_list.append(_lowercase ) with open(f'''{file_root}.txt''' , 'w' ) as outfile: outfile.write('\n'.join(line for line in annos_list ) ) def _A ( _lowercase , _lowercase ) -> tuple[list, list]: """simple docstring""" __UpperCamelCase = [] __UpperCamelCase = [] for label_file in glob.glob(os.path.join(_lowercase , '*.txt' ) ): __UpperCamelCase = label_file.split(os.sep )[-1].rsplit('.' , 1 )[0] with open(_lowercase ) as in_file: __UpperCamelCase = in_file.readlines() __UpperCamelCase = os.path.join(_lowercase , f'''{label_name}.jpg''' ) __UpperCamelCase = [] for obj_list in obj_lists: __UpperCamelCase = obj_list.rstrip('\n' ).split(' ' ) __UpperCamelCase = float(obj[1] ) - float(obj[3] ) / 2 __UpperCamelCase = float(obj[2] ) - float(obj[4] ) / 2 __UpperCamelCase = float(obj[1] ) + float(obj[3] ) / 2 __UpperCamelCase = float(obj[2] ) + float(obj[4] ) / 2 boxes.append([int(obj[0] ), xmin, ymin, xmax, ymax] ) if not boxes: continue img_paths.append(_lowercase ) labels.append(_lowercase ) return img_paths, labels def _A ( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase = 0.0 , ) -> tuple[list, list, str]: """simple docstring""" __UpperCamelCase = np.zeros([output_size[0], output_size[1], 3] , dtype=np.uinta ) __UpperCamelCase = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) __UpperCamelCase = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) __UpperCamelCase = int(scale_x * output_size[1] ) __UpperCamelCase = int(scale_y * output_size[0] ) __UpperCamelCase = [] __UpperCamelCase = [] for i, index in enumerate(_lowercase ): __UpperCamelCase = all_img_list[index] path_list.append(_lowercase ) __UpperCamelCase = all_annos[index] __UpperCamelCase = cva.imread(_lowercase ) if i == 0: # top-left __UpperCamelCase = cva.resize(_lowercase , (divid_point_x, divid_point_y) ) __UpperCamelCase = img for bbox in img_annos: __UpperCamelCase = bbox[1] * scale_x __UpperCamelCase = bbox[2] * scale_y __UpperCamelCase = bbox[3] * scale_x __UpperCamelCase = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 1: # top-right __UpperCamelCase = cva.resize(_lowercase , (output_size[1] - divid_point_x, divid_point_y) ) __UpperCamelCase = img for bbox in img_annos: __UpperCamelCase = scale_x + bbox[1] * (1 - scale_x) __UpperCamelCase = bbox[2] * scale_y __UpperCamelCase = scale_x + bbox[3] * (1 - scale_x) __UpperCamelCase = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 2: # bottom-left __UpperCamelCase = cva.resize(_lowercase , (divid_point_x, output_size[0] - divid_point_y) ) __UpperCamelCase = img for bbox in img_annos: __UpperCamelCase = bbox[1] * scale_x __UpperCamelCase = scale_y + bbox[2] * (1 - scale_y) __UpperCamelCase = bbox[3] * scale_x __UpperCamelCase = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) else: # bottom-right __UpperCamelCase = cva.resize( _lowercase , (output_size[1] - divid_point_x, output_size[0] - divid_point_y) ) __UpperCamelCase = img for bbox in img_annos: __UpperCamelCase = scale_x + bbox[1] * (1 - scale_x) __UpperCamelCase = scale_y + bbox[2] * (1 - scale_y) __UpperCamelCase = scale_x + bbox[3] * (1 - scale_x) __UpperCamelCase = 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: __UpperCamelCase = [ 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 ) -> str: """simple docstring""" assert number_char > 1, "The number of character should greater than 1" __UpperCamelCase = ascii_lowercase + digits return "".join(random.choice(_lowercase ) for _ in range(_lowercase ) ) if __name__ == "__main__": main() print('''DONE ✅''')
1
"""simple docstring""" import re from flax.core.frozen_dict import freeze from flax.traverse_util import flatten_dict, unflatten_dict from jax.experimental import PartitionSpec as P # Sentinels __A = object() # For specifying empty leaf dict `{}` __A = object() def a__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> Dict: __lowerCAmelCase: Dict = tuple((re.compile(x + "$" ) for x in qs) ) for i in range(len(__SCREAMING_SNAKE_CASE ) - len(__SCREAMING_SNAKE_CASE ) + 1 ): __lowerCAmelCase: Tuple = [x.match(__SCREAMING_SNAKE_CASE ) for x, y in zip(__SCREAMING_SNAKE_CASE , ks[i:] )] if matches and all(__SCREAMING_SNAKE_CASE ): return True return False def a__ ( __SCREAMING_SNAKE_CASE ) -> List[Any]: def replace(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): for rule, replacement in rules: if _match(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): return replacement return val return replace def a__ ( ) -> str: return [ # embeddings (("transformer", "wpe", "embedding"), P("mp" , __SCREAMING_SNAKE_CASE )), (("transformer", "wte", "embedding"), P("mp" , __SCREAMING_SNAKE_CASE )), # atention (("attention", "(q_proj|k_proj|v_proj)", "kernel"), P(__SCREAMING_SNAKE_CASE , "mp" )), (("attention", "out_proj", "kernel"), P("mp" , __SCREAMING_SNAKE_CASE )), (("attention", "out_proj", "bias"), None), # mlp (("mlp", "c_fc", "kernel"), P(__SCREAMING_SNAKE_CASE , "mp" )), (("mlp", "c_fc", "bias"), P("mp" )), (("mlp", "c_proj", "kernel"), P("mp" , __SCREAMING_SNAKE_CASE )), (("mlp", "c_proj", "bias"), None), # layer norms ((r"ln_\d+", "bias"), None), ((r"\d+", r"ln_\d+", "scale"), None), (("ln_f", "bias"), None), (("ln_f", "scale"), None), ] def a__ ( __SCREAMING_SNAKE_CASE ) -> List[str]: __lowerCAmelCase: Any = _get_partition_rules() __lowerCAmelCase: List[Any] = _replacement_rules(__SCREAMING_SNAKE_CASE ) __lowerCAmelCase: Tuple = {k: _unmatched for k in flatten_dict(__SCREAMING_SNAKE_CASE )} __lowerCAmelCase: Any = {k: replace(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) for k, v in initd.items()} assert _unmatched not in result.values(), "Incomplete partition spec." return freeze(unflatten_dict(__SCREAMING_SNAKE_CASE ) )
346
0
'''simple docstring''' import torch from diffusers import DiffusionPipeline class _a ( __UpperCAmelCase ): """simple docstring""" def __init__( self ,__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ): super().__init__() self.register_modules(unet=_lowerCamelCase ,scheduler=_lowerCamelCase ) def __call__( self ): SCREAMING_SNAKE_CASE : Dict = torch.randn( (1, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) ,) SCREAMING_SNAKE_CASE : Optional[int] = 1 SCREAMING_SNAKE_CASE : List[Any] = self.unet(_lowerCamelCase ,_lowerCamelCase ).sample SCREAMING_SNAKE_CASE : Union[str, Any] = self.scheduler.step(_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ).prev_sample SCREAMING_SNAKE_CASE : List[str] = scheduler_output - scheduler_output + torch.ones_like(_lowerCamelCase ) return result
701
'''simple docstring''' import argparse from pathlib import Path import fairseq import torch from fairseq.models.xmod import XMODModel as FairseqXmodModel from packaging import version from transformers import XmodConfig, XmodForMaskedLM, XmodForSequenceClassification from transformers.utils import logging if version.parse(fairseq.__version__) < version.parse('0.12.2'): raise Exception('requires fairseq >= 0.12.2') if version.parse(fairseq.__version__) > version.parse('2'): raise Exception('requires fairseq < v2') logging.set_verbosity_info() __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = 'Hello, World!' __UpperCAmelCase = 'en_XX' def SCREAMING_SNAKE_CASE_ ( snake_case_ : str , snake_case_ : str , snake_case_ : bool ) -> Union[str, Any]: SCREAMING_SNAKE_CASE : List[Any] = Path('data_bin' ) SCREAMING_SNAKE_CASE : List[Any] = FairseqXmodModel.from_pretrained( model_name_or_path=str(Path(snake_case_ ).parent ) , checkpoint_file=Path(snake_case_ ).name , _name='xmod_base' , arch='xmod_base' , task='multilingual_masked_lm' , data_name_or_path=str(snake_case_ ) , bpe='sentencepiece' , sentencepiece_model=str(Path(snake_case_ ).parent / 'sentencepiece.bpe.model' ) , src_dict=str(data_dir / 'dict.txt' ) , ) xmod.eval() # disable dropout print(snake_case_ ) SCREAMING_SNAKE_CASE : Any = xmod.model.encoder.sentence_encoder SCREAMING_SNAKE_CASE : Optional[int] = XmodConfig( vocab_size=xmod_sent_encoder.embed_tokens.num_embeddings , hidden_size=xmod.cfg.model.encoder_embed_dim , num_hidden_layers=xmod.cfg.model.encoder_layers , num_attention_heads=xmod.cfg.model.encoder_attention_heads , intermediate_size=xmod.cfg.model.encoder_ffn_embed_dim , max_position_embeddings=514 , type_vocab_size=1 , layer_norm_eps=1e-5 , pre_norm=xmod.cfg.model.encoder_normalize_before , adapter_reduction_factor=getattr(xmod.cfg.model , 'bottleneck' , 2 ) , adapter_layer_norm=xmod.cfg.model.adapter_layer_norm , adapter_reuse_layer_norm=xmod.cfg.model.adapter_reuse_layer_norm , ln_before_adapter=xmod.cfg.model.ln_before_adapter , languages=xmod.cfg.model.languages , ) if classification_head: SCREAMING_SNAKE_CASE : List[Any] = xmod.model.classification_heads['mnli'].out_proj.weight.shape[0] print('Our X-MOD config:' , snake_case_ ) SCREAMING_SNAKE_CASE : int = XmodForSequenceClassification(snake_case_ ) if classification_head else XmodForMaskedLM(snake_case_ ) model.eval() # Now let's copy all the weights. # Embeddings SCREAMING_SNAKE_CASE : Tuple = xmod_sent_encoder.embed_tokens.weight SCREAMING_SNAKE_CASE : str = xmod_sent_encoder.embed_positions.weight SCREAMING_SNAKE_CASE : List[Any] = torch.zeros_like( model.roberta.embeddings.token_type_embeddings.weight ) # just zero them out b/c xmod doesn't use them. SCREAMING_SNAKE_CASE : Optional[int] = xmod_sent_encoder.layernorm_embedding.weight SCREAMING_SNAKE_CASE : Any = xmod_sent_encoder.layernorm_embedding.bias for i in range(config.num_hidden_layers ): # Encoder: start of layer SCREAMING_SNAKE_CASE : List[str] = model.roberta.encoder.layer[i] SCREAMING_SNAKE_CASE : List[Any] = xmod_sent_encoder.layers[i] # self attention SCREAMING_SNAKE_CASE : Dict = layer.attention.self if not ( xmod_layer.self_attn.k_proj.weight.data.shape == xmod_layer.self_attn.q_proj.weight.data.shape == xmod_layer.self_attn.v_proj.weight.data.shape == torch.Size((config.hidden_size, config.hidden_size) ) ): raise AssertionError('Dimensions of self-attention weights do not match.' ) SCREAMING_SNAKE_CASE : List[Any] = xmod_layer.self_attn.q_proj.weight SCREAMING_SNAKE_CASE : Union[str, Any] = xmod_layer.self_attn.q_proj.bias SCREAMING_SNAKE_CASE : List[Any] = xmod_layer.self_attn.k_proj.weight SCREAMING_SNAKE_CASE : int = xmod_layer.self_attn.k_proj.bias SCREAMING_SNAKE_CASE : int = xmod_layer.self_attn.v_proj.weight SCREAMING_SNAKE_CASE : Optional[Any] = xmod_layer.self_attn.v_proj.bias # self-attention output SCREAMING_SNAKE_CASE : List[Any] = layer.attention.output if self_output.dense.weight.shape != xmod_layer.self_attn.out_proj.weight.shape: raise AssertionError('Dimensions of self-attention output weights do not match.' ) SCREAMING_SNAKE_CASE : int = xmod_layer.self_attn.out_proj.weight SCREAMING_SNAKE_CASE : Optional[int] = xmod_layer.self_attn.out_proj.bias SCREAMING_SNAKE_CASE : Union[str, Any] = xmod_layer.self_attn_layer_norm.weight SCREAMING_SNAKE_CASE : str = xmod_layer.self_attn_layer_norm.bias # intermediate SCREAMING_SNAKE_CASE : Union[str, Any] = layer.intermediate if intermediate.dense.weight.shape != xmod_layer.fca.weight.shape: raise AssertionError('Dimensions of intermediate weights do not match.' ) SCREAMING_SNAKE_CASE : int = xmod_layer.fca.weight SCREAMING_SNAKE_CASE : List[str] = xmod_layer.fca.bias # output SCREAMING_SNAKE_CASE : Dict = layer.output if bert_output.dense.weight.shape != xmod_layer.fca.weight.shape: raise AssertionError('Dimensions of feed-forward weights do not match.' ) SCREAMING_SNAKE_CASE : int = xmod_layer.fca.weight SCREAMING_SNAKE_CASE : Optional[Any] = xmod_layer.fca.bias SCREAMING_SNAKE_CASE : Tuple = xmod_layer.final_layer_norm.weight SCREAMING_SNAKE_CASE : Dict = xmod_layer.final_layer_norm.bias if bert_output.adapter_layer_norm is not None: SCREAMING_SNAKE_CASE : Tuple = xmod_layer.adapter_layer_norm.weight SCREAMING_SNAKE_CASE : str = xmod_layer.adapter_layer_norm.bias if sorted(bert_output.adapter_modules.keys() ) != sorted(xmod_layer.adapter_modules.keys() ): raise AssertionError('Lists of language adapters do not match.' ) for lang_code, adapter in xmod_layer.adapter_modules.items(): SCREAMING_SNAKE_CASE : int = bert_output.adapter_modules[lang_code] SCREAMING_SNAKE_CASE : Optional[int] = xmod_layer.adapter_modules[lang_code] SCREAMING_SNAKE_CASE : Optional[int] = from_adapter.fca.weight SCREAMING_SNAKE_CASE : Optional[int] = from_adapter.fca.bias SCREAMING_SNAKE_CASE : Optional[int] = from_adapter.fca.weight SCREAMING_SNAKE_CASE : Any = from_adapter.fca.bias # end of layer if xmod_sent_encoder.layer_norm is not None: SCREAMING_SNAKE_CASE : Any = xmod_sent_encoder.layer_norm.weight SCREAMING_SNAKE_CASE : List[Any] = xmod_sent_encoder.layer_norm.bias if classification_head: SCREAMING_SNAKE_CASE : int = xmod.model.classification_heads['mnli'].dense.weight SCREAMING_SNAKE_CASE : List[Any] = xmod.model.classification_heads['mnli'].dense.bias SCREAMING_SNAKE_CASE : str = xmod.model.classification_heads['mnli'].out_proj.weight SCREAMING_SNAKE_CASE : int = xmod.model.classification_heads['mnli'].out_proj.bias else: # LM Head SCREAMING_SNAKE_CASE : Optional[Any] = xmod.model.encoder.lm_head.dense.weight SCREAMING_SNAKE_CASE : Tuple = xmod.model.encoder.lm_head.dense.bias SCREAMING_SNAKE_CASE : Optional[int] = xmod.model.encoder.lm_head.layer_norm.weight SCREAMING_SNAKE_CASE : Optional[int] = xmod.model.encoder.lm_head.layer_norm.bias SCREAMING_SNAKE_CASE : Optional[int] = xmod.model.encoder.lm_head.weight SCREAMING_SNAKE_CASE : Tuple = xmod.model.encoder.lm_head.bias # Let's check that we get the same results. SCREAMING_SNAKE_CASE : Union[str, Any] = xmod.encode(snake_case_ ).unsqueeze(0 ) # batch of size 1 model.roberta.set_default_language(snake_case_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = model(snake_case_ )[0] if classification_head: SCREAMING_SNAKE_CASE : List[str] = xmod.model.classification_heads['mnli'](xmod.extract_features(snake_case_ ) ) else: SCREAMING_SNAKE_CASE : Any = xmod.model(snake_case_ , lang_id=[SAMPLE_LANGUAGE] )[0] print(our_output.shape , their_output.shape ) SCREAMING_SNAKE_CASE : List[str] = torch.max(torch.abs(our_output - their_output ) ).item() print(f"""max_absolute_diff = {max_absolute_diff}""" ) # ~ 1e-7 SCREAMING_SNAKE_CASE : Dict = torch.allclose(snake_case_ , snake_case_ , atol=1e-3 ) print('Do both models output the same tensors?' , '🔥' if success else '💩' ) if not success: raise Exception('Something went wRoNg' ) Path(snake_case_ ).mkdir(parents=snake_case_ , exist_ok=snake_case_ ) print(f"""Saving model to {pytorch_dump_folder_path}""" ) model.save_pretrained(snake_case_ ) if __name__ == "__main__": __UpperCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '--xmod_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.' ) parser.add_argument( '--classification_head', action='store_true', help='Whether to convert a final classification head.' ) __UpperCAmelCase = parser.parse_args() convert_xmod_checkpoint_to_pytorch( args.xmod_checkpoint_path, args.pytorch_dump_folder_path, args.classification_head )
220
0
'''simple docstring''' from collections.abc import Callable class __UpperCamelCase : def __init__( self :Optional[int] ,_UpperCamelCase :Callable | None = None ): # Stores actual heap items. snake_case_ : list = [] # Stores indexes of each item for supporting updates and deletion. snake_case_ : dict = {} # Stores current size of heap. snake_case_ : str = 0 # Stores function used to evaluate the score of an item on which basis ordering # will be done. snake_case_ : Optional[Any] = key or (lambda _UpperCamelCase : x) def a__ ( self :Optional[Any] ,_UpperCamelCase :int ): return int((i - 1) / 2 ) if i > 0 else None def a__ ( self :Dict ,_UpperCamelCase :int ): snake_case_ : int = int(2 * i + 1 ) return left if 0 < left < self.size else None def a__ ( self :List[str] ,_UpperCamelCase :int ): snake_case_ : Dict = int(2 * i + 2 ) return right if 0 < right < self.size else None def a__ ( self :Tuple ,_UpperCamelCase :int ,_UpperCamelCase :int ): snake_case_ , snake_case_ : List[Any] = ( self.pos_map[self.arr[j][0]], self.pos_map[self.arr[i][0]], ) # Then swap the items in the list. snake_case_ , snake_case_ : Tuple = self.arr[j], self.arr[i] def a__ ( self :Union[str, Any] ,_UpperCamelCase :int ,_UpperCamelCase :int ): return self.arr[i][1] < self.arr[j][1] def a__ ( self :Tuple ,_UpperCamelCase :int ): snake_case_ : List[str] = self._left(_UpperCamelCase ) snake_case_ : Optional[Any] = self._right(_UpperCamelCase ) snake_case_ : Optional[int] = i if left is not None and not self._cmp(_UpperCamelCase ,_UpperCamelCase ): snake_case_ : List[str] = left if right is not None and not self._cmp(_UpperCamelCase ,_UpperCamelCase ): snake_case_ : Optional[Any] = right return valid_parent def a__ ( self :Any ,_UpperCamelCase :int ): snake_case_ : Optional[int] = self._parent(_UpperCamelCase ) while parent is not None and not self._cmp(_UpperCamelCase ,_UpperCamelCase ): self._swap(_UpperCamelCase ,_UpperCamelCase ) snake_case_ , snake_case_ : Optional[Any] = parent, self._parent(_UpperCamelCase ) def a__ ( self :Any ,_UpperCamelCase :int ): snake_case_ : Optional[int] = self._get_valid_parent(_UpperCamelCase ) while valid_parent != index: self._swap(_UpperCamelCase ,_UpperCamelCase ) snake_case_ , snake_case_ : Optional[Any] = valid_parent, self._get_valid_parent(_UpperCamelCase ) def a__ ( self :Any ,_UpperCamelCase :int ,_UpperCamelCase :int ): if item not in self.pos_map: return snake_case_ : List[Any] = self.pos_map[item] snake_case_ : Optional[Any] = [item, self.key(_UpperCamelCase )] # Make sure heap is right in both up and down direction. # Ideally only one of them will make any change. self._heapify_up(_UpperCamelCase ) self._heapify_down(_UpperCamelCase ) def a__ ( self :List[str] ,_UpperCamelCase :int ): if item not in self.pos_map: return snake_case_ : List[Any] = self.pos_map[item] del self.pos_map[item] snake_case_ : Optional[Any] = self.arr[self.size - 1] snake_case_ : str = index self.size -= 1 # Make sure heap is right in both up and down direction. Ideally only one # of them will make any change- so no performance loss in calling both. if self.size > index: self._heapify_up(_UpperCamelCase ) self._heapify_down(_UpperCamelCase ) def a__ ( self :Tuple ,_UpperCamelCase :int ,_UpperCamelCase :int ): snake_case_ : Dict = len(self.arr ) if arr_len == self.size: self.arr.append([item, self.key(_UpperCamelCase )] ) else: snake_case_ : Any = [item, self.key(_UpperCamelCase )] snake_case_ : List[Any] = self.size self.size += 1 self._heapify_up(self.size - 1 ) def a__ ( self :List[Any] ): return self.arr[0] if self.size else None def a__ ( self :Union[str, Any] ): snake_case_ : Optional[Any] = self.get_top() if top_item_tuple: self.delete_item(top_item_tuple[0] ) return top_item_tuple def UpperCAmelCase ( ): '''simple docstring''' if __name__ == "__main__": import doctest doctest.testmod()
334
'''simple docstring''' 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. __A : Dict = {'LayoutLMv2Config', 'LayoutLMv3Config'} @is_pipeline_test class __UpperCamelCase ( unittest.TestCase ): lowercase : Optional[int] = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING lowercase : Tuple = TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if model_mapping is not None: lowercase : int = {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP} if tf_model_mapping is not None: lowercase : Any = { config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP } def a__ ( self :int ,_UpperCamelCase :Optional[Any] ,_UpperCamelCase :str ,_UpperCamelCase :List[Any] ): snake_case_ : Optional[Any] = ZeroShotClassificationPipeline( model=_UpperCamelCase ,tokenizer=_UpperCamelCase ,candidate_labels=["""polics""", """health"""] ) return classifier, ["Who are you voting for in 2020?", "My stomach hurts."] def a__ ( self :Dict ,_UpperCamelCase :Any ,_UpperCamelCase :int ): snake_case_ : int = classifier("""Who are you voting for in 2020?""" ,candidate_labels="""politics""" ) self.assertEqual(_UpperCamelCase ,{"""sequence""": ANY(_UpperCamelCase ), """labels""": [ANY(_UpperCamelCase )], """scores""": [ANY(_UpperCamelCase )]} ) # No kwarg snake_case_ : List[str] = classifier("""Who are you voting for in 2020?""" ,["""politics"""] ) self.assertEqual(_UpperCamelCase ,{"""sequence""": ANY(_UpperCamelCase ), """labels""": [ANY(_UpperCamelCase )], """scores""": [ANY(_UpperCamelCase )]} ) snake_case_ : Union[str, Any] = classifier("""Who are you voting for in 2020?""" ,candidate_labels=["""politics"""] ) self.assertEqual(_UpperCamelCase ,{"""sequence""": ANY(_UpperCamelCase ), """labels""": [ANY(_UpperCamelCase )], """scores""": [ANY(_UpperCamelCase )]} ) snake_case_ : int = classifier("""Who are you voting for in 2020?""" ,candidate_labels="""politics, public health""" ) self.assertEqual( _UpperCamelCase ,{"""sequence""": ANY(_UpperCamelCase ), """labels""": [ANY(_UpperCamelCase ), ANY(_UpperCamelCase )], """scores""": [ANY(_UpperCamelCase ), ANY(_UpperCamelCase )]} ) self.assertAlmostEqual(sum(nested_simplify(outputs["""scores"""] ) ) ,1.0 ) snake_case_ : Any = classifier("""Who are you voting for in 2020?""" ,candidate_labels=["""politics""", """public health"""] ) self.assertEqual( _UpperCamelCase ,{"""sequence""": ANY(_UpperCamelCase ), """labels""": [ANY(_UpperCamelCase ), ANY(_UpperCamelCase )], """scores""": [ANY(_UpperCamelCase ), ANY(_UpperCamelCase )]} ) self.assertAlmostEqual(sum(nested_simplify(outputs["""scores"""] ) ) ,1.0 ) snake_case_ : List[Any] = classifier( """Who are you voting for in 2020?""" ,candidate_labels="""politics""" ,hypothesis_template="""This text is about {}""" ) self.assertEqual(_UpperCamelCase ,{"""sequence""": ANY(_UpperCamelCase ), """labels""": [ANY(_UpperCamelCase )], """scores""": [ANY(_UpperCamelCase )]} ) # https://github.com/huggingface/transformers/issues/13846 snake_case_ : Union[str, Any] = classifier(["""I am happy"""] ,["""positive""", """negative"""] ) self.assertEqual( _UpperCamelCase ,[ {"""sequence""": ANY(_UpperCamelCase ), """labels""": [ANY(_UpperCamelCase ), ANY(_UpperCamelCase )], """scores""": [ANY(_UpperCamelCase ), ANY(_UpperCamelCase )]} for i in range(1 ) ] ,) snake_case_ : Union[str, Any] = classifier(["""I am happy""", """I am sad"""] ,["""positive""", """negative"""] ) self.assertEqual( _UpperCamelCase ,[ {"""sequence""": ANY(_UpperCamelCase ), """labels""": [ANY(_UpperCamelCase ), ANY(_UpperCamelCase )], """scores""": [ANY(_UpperCamelCase ), ANY(_UpperCamelCase )]} for i in range(2 ) ] ,) with self.assertRaises(_UpperCamelCase ): classifier("""""" ,candidate_labels="""politics""" ) with self.assertRaises(_UpperCamelCase ): classifier(_UpperCamelCase ,candidate_labels="""politics""" ) with self.assertRaises(_UpperCamelCase ): classifier("""Who are you voting for in 2020?""" ,candidate_labels="""""" ) with self.assertRaises(_UpperCamelCase ): classifier("""Who are you voting for in 2020?""" ,candidate_labels=_UpperCamelCase ) with self.assertRaises(_UpperCamelCase ): classifier( """Who are you voting for in 2020?""" ,candidate_labels="""politics""" ,hypothesis_template="""Not formatting template""" ,) with self.assertRaises(_UpperCamelCase ): classifier( """Who are you voting for in 2020?""" ,candidate_labels="""politics""" ,hypothesis_template=_UpperCamelCase ,) self.run_entailment_id(_UpperCamelCase ) def a__ ( self :Tuple ,_UpperCamelCase :Pipeline ): snake_case_ : int = zero_shot_classifier.model.config snake_case_ : Union[str, Any] = config.labelaid snake_case_ : Optional[Any] = zero_shot_classifier.entailment_id snake_case_ : List[Any] = {"""LABEL_0""": 0, """LABEL_1""": 1, """LABEL_2""": 2} self.assertEqual(zero_shot_classifier.entailment_id ,-1 ) snake_case_ : Optional[Any] = {"""entailment""": 0, """neutral""": 1, """contradiction""": 2} self.assertEqual(zero_shot_classifier.entailment_id ,0 ) snake_case_ : int = {"""ENTAIL""": 0, """NON-ENTAIL""": 1} self.assertEqual(zero_shot_classifier.entailment_id ,0 ) snake_case_ : Tuple = {"""ENTAIL""": 2, """NEUTRAL""": 1, """CONTR""": 0} self.assertEqual(zero_shot_classifier.entailment_id ,2 ) snake_case_ : Optional[Any] = original_labelaid self.assertEqual(_UpperCamelCase ,zero_shot_classifier.entailment_id ) @require_torch def a__ ( self :Any ): snake_case_ : Dict = 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?""" * 1_0_0 ,candidate_labels=["""politics""", """public health""", """science"""] ) @require_torch def a__ ( self :Dict ): snake_case_ : Union[str, Any] = pipeline( """zero-shot-classification""" ,model="""sshleifer/tiny-distilbert-base-cased-distilled-squad""" ,framework="""pt""" ,) snake_case_ : Union[str, Any] = zero_shot_classifier( """Who are you voting for in 2020?""" ,candidate_labels=["""politics""", """public health""", """science"""] ) self.assertEqual( nested_simplify(_UpperCamelCase ) ,{ """sequence""": """Who are you voting for in 2020?""", """labels""": ["""science""", """public health""", """politics"""], """scores""": [0.3_33, 0.3_33, 0.3_33], } ,) @require_tf def a__ ( self :Tuple ): snake_case_ : Union[str, Any] = pipeline( """zero-shot-classification""" ,model="""sshleifer/tiny-distilbert-base-cased-distilled-squad""" ,framework="""tf""" ,) snake_case_ : Union[str, Any] = zero_shot_classifier( """Who are you voting for in 2020?""" ,candidate_labels=["""politics""", """public health""", """science"""] ) self.assertEqual( nested_simplify(_UpperCamelCase ) ,{ """sequence""": """Who are you voting for in 2020?""", """labels""": ["""science""", """public health""", """politics"""], """scores""": [0.3_33, 0.3_33, 0.3_33], } ,) @slow @require_torch def a__ ( self :Optional[int] ): snake_case_ : Dict = pipeline("""zero-shot-classification""" ,model="""roberta-large-mnli""" ,framework="""pt""" ) snake_case_ : str = zero_shot_classifier( """Who are you voting for in 2020?""" ,candidate_labels=["""politics""", """public health""", """science"""] ) self.assertEqual( nested_simplify(_UpperCamelCase ) ,{ """sequence""": """Who are you voting for in 2020?""", """labels""": ["""politics""", """public health""", """science"""], """scores""": [0.9_76, 0.0_15, 0.0_09], } ,) snake_case_ : int = 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=_UpperCamelCase ,) self.assertEqual( nested_simplify(_UpperCamelCase ) ,{ """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.8_17, 0.7_13, 0.0_18, 0.0_18], } ,) @slow @require_tf def a__ ( self :Optional[int] ): snake_case_ : List[str] = pipeline("""zero-shot-classification""" ,model="""roberta-large-mnli""" ,framework="""tf""" ) snake_case_ : str = zero_shot_classifier( """Who are you voting for in 2020?""" ,candidate_labels=["""politics""", """public health""", """science"""] ) self.assertEqual( nested_simplify(_UpperCamelCase ) ,{ """sequence""": """Who are you voting for in 2020?""", """labels""": ["""politics""", """public health""", """science"""], """scores""": [0.9_76, 0.0_15, 0.0_09], } ,) snake_case_ : Optional[int] = 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=_UpperCamelCase ,) self.assertEqual( nested_simplify(_UpperCamelCase ) ,{ """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.8_17, 0.7_13, 0.0_18, 0.0_18], } ,)
334
1
'''simple docstring''' import os import time import numpy as np import onnxruntime as ort __UpperCAmelCase = "1" __UpperCAmelCase = "0" __UpperCAmelCase = "1" __UpperCAmelCase = ort.SessionOptions() __UpperCAmelCase = ort.GraphOptimizationLevel.ORT_DISABLE_ALL print("Create inference session...") __UpperCAmelCase = ["TensorrtExecutionProvider", "CUDAExecutionProvider"] __UpperCAmelCase = ort.InferenceSession("model.onnx", sess_options=sess_opt, providers=execution_provider) __UpperCAmelCase = ort.RunOptions() __UpperCAmelCase = 128 __UpperCAmelCase = 1 __UpperCAmelCase = np.ones((batch, sequence), dtype=np.intaa) __UpperCAmelCase = np.ones((batch, sequence), dtype=np.intaa) __UpperCAmelCase = np.ones((batch, sequence), dtype=np.intaa) print("Warm up phase...") sess.run( None, { sess.get_inputs()[0].name: input_ids, sess.get_inputs()[1].name: attention_mask, sess.get_inputs()[2].name: token_type_ids, }, run_options=run_opt, ) print("Start inference...") __UpperCAmelCase = time.time() __UpperCAmelCase = 2_000 __UpperCAmelCase = {} for iter in range(max_iters): __UpperCAmelCase = sess.run( None, { sess.get_inputs()[0].name: input_ids, sess.get_inputs()[1].name: attention_mask, sess.get_inputs()[2].name: token_type_ids, }, run_options=run_opt, ) print("Average Inference Time = {:.3f} ms".format((time.time() - start_time) * 1_000 / max_iters))
692
'''simple docstring''' import json import os import re import shutil import tempfile import unittest from typing import Tuple from transformers import AddedToken, BatchEncoding, ByTaTokenizer from transformers.utils import cached_property, is_tf_available, is_torch_available from ...test_tokenization_common import TokenizerTesterMixin if is_torch_available(): __UpperCAmelCase = "pt" elif is_tf_available(): __UpperCAmelCase = "tf" else: __UpperCAmelCase = "jax" class SCREAMING_SNAKE_CASE ( snake_case , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = ByTaTokenizer __UpperCamelCase = False def _UpperCamelCase ( self ): '''simple docstring''' super().setUp() snake_case: int = ByTaTokenizer() tokenizer.save_pretrained(self.tmpdirname ) @cached_property def _UpperCamelCase ( self ): '''simple docstring''' return ByTaTokenizer.from_pretrained('google/byt5-small' ) def _UpperCamelCase ( self , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return self.tokenizer_class.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=20 , SCREAMING_SNAKE_CASE__=5 ): '''simple docstring''' snake_case: Optional[Any] = [] for i in range(len(SCREAMING_SNAKE_CASE__ ) ): try: snake_case: Optional[Any] = tokenizer.decode([i] , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE__ ) except UnicodeDecodeError: pass toks.append((i, tok) ) snake_case: List[str] = list(filter(lambda SCREAMING_SNAKE_CASE__ : re.match(r'^[ a-zA-Z]+$' , t[1] ) , SCREAMING_SNAKE_CASE__ ) ) snake_case: str = list(filter(lambda SCREAMING_SNAKE_CASE__ : [t[0]] == tokenizer.encode(t[1] , add_special_tokens=SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) ) if max_length is not None and len(SCREAMING_SNAKE_CASE__ ) > max_length: snake_case: Union[str, Any] = toks[:max_length] if min_length is not None and len(SCREAMING_SNAKE_CASE__ ) < min_length and len(SCREAMING_SNAKE_CASE__ ) > 0: while len(SCREAMING_SNAKE_CASE__ ) < min_length: snake_case: Tuple = toks + toks # toks_str = [t[1] for t in toks] snake_case: Dict = [t[0] for t in toks] # Ensure consistency snake_case: int = tokenizer.decode(SCREAMING_SNAKE_CASE__ , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE__ ) if " " not in output_txt and len(SCREAMING_SNAKE_CASE__ ) > 1: snake_case: str = ( tokenizer.decode([toks_ids[0]] , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE__ ) + ' ' + tokenizer.decode(toks_ids[1:] , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE__ ) ) if with_prefix_space: snake_case: Tuple = ' ' + output_txt snake_case: Optional[int] = tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) return output_txt, output_ids def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = self.ta_base_tokenizer snake_case: str = tokenizer(['hi</s>', 'I went to the gym</s>', '</s>'] ) snake_case: List[Any] = tokenizer(['hi', 'I went to the gym', ''] ) self.assertListEqual(batch_with_eos_added['input_ids'] , batch_without_eos_added['input_ids'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = self.ta_base_tokenizer snake_case: Union[str, Any] = 'Unicode €.' snake_case: str = tokenizer(SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = [88, 1_13, 1_08, 1_02, 1_14, 1_03, 1_04, 35, 2_29, 1_33, 1_75, 49, 1] self.assertEqual(encoded['input_ids'] , SCREAMING_SNAKE_CASE__ ) # decoding snake_case: List[str] = tokenizer.decode(SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , 'Unicode €.</s>' ) snake_case: List[Any] = tokenizer('e è é ê ë' ) snake_case: Optional[Any] = [1_04, 35, 1_98, 1_71, 35, 1_98, 1_72, 35, 1_98, 1_73, 35, 1_98, 1_74, 1] self.assertEqual(encoded['input_ids'] , SCREAMING_SNAKE_CASE__ ) # decoding snake_case: List[Any] = tokenizer.decode(SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , 'e è é ê ë</s>' ) # encode/decode, but with `encode` instead of `__call__` self.assertEqual(tokenizer.decode(tokenizer.encode('e è é ê ë' ) ) , 'e è é ê ë</s>' ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = self.ta_base_tokenizer snake_case: Optional[Any] = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] # fmt: off snake_case: Optional[int] = [68, 35, 1_11, 1_14, 1_13, 1_06, 35, 1_15, 1_00, 1_17, 1_00, 1_06, 1_17, 1_00, 1_15, 1_07, 35, 1_05, 1_14, 1_17, 35, 1_18, 1_20, 1_12, 1_12, 1_00, 1_17, 1_08, 1_25, 1_00, 1_19, 1_08, 1_14, 1_13, 49, 1, 0] # fmt: on snake_case: str = tokenizer(SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if FRAMEWORK != "jax": snake_case: Optional[Any] = list(batch.input_ids.numpy()[0] ) else: snake_case: Dict = list(batch.input_ids.tolist()[0] ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertEqual((2, 37) , batch.input_ids.shape ) self.assertEqual((2, 37) , batch.attention_mask.shape ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = self.ta_base_tokenizer snake_case: List[str] = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] snake_case: Union[str, Any] = tokenizer(SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ ) # check if input_ids are returned and no decoder_input_ids self.assertIn('input_ids' , SCREAMING_SNAKE_CASE__ ) self.assertIn('attention_mask' , SCREAMING_SNAKE_CASE__ ) self.assertNotIn('decoder_input_ids' , SCREAMING_SNAKE_CASE__ ) self.assertNotIn('decoder_attention_mask' , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[str] = self.ta_base_tokenizer snake_case: str = [ 'Summary of the text.', 'Another summary.', ] snake_case: Dict = tokenizer( text_target=SCREAMING_SNAKE_CASE__ , max_length=32 , padding='max_length' , truncation=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ ) self.assertEqual(32 , targets['input_ids'].shape[1] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Union[str, Any] = self.ta_base_tokenizer snake_case: Optional[int] = ['A long paragraph for summarization. </s>'] snake_case: str = ['Summary of the text. </s>'] # fmt: off snake_case: str = [68, 35, 1_11, 1_14, 1_13, 1_06, 35, 1_15, 1_00, 1_17, 1_00, 1_06, 1_17, 1_00, 1_15, 1_07, 35, 1_05, 1_14, 1_17, 35, 1_18, 1_20, 1_12, 1_12, 1_00, 1_17, 1_08, 1_25, 1_00, 1_19, 1_08, 1_14, 1_13, 49, 35, 1] snake_case: Optional[int] = [86, 1_20, 1_12, 1_12, 1_00, 1_17, 1_24, 35, 1_14, 1_05, 35, 1_19, 1_07, 1_04, 35, 1_19, 1_04, 1_23, 1_19, 49, 35, 1] # fmt: on snake_case: List[Any] = tokenizer(SCREAMING_SNAKE_CASE__ , text_target=SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , batch['input_ids'][0] ) self.assertEqual(SCREAMING_SNAKE_CASE__ , batch['labels'][0] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = 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 snake_case: Optional[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 snake_case: Union[str, Any] = tempfile.mkdtemp() snake_case: Dict = ' He is very happy, UNwant\u00E9d,running' snake_case: Optional[int] = tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = tokenizer.__class__.from_pretrained(SCREAMING_SNAKE_CASE__ ) snake_case: Any = after_tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) snake_case: Any = 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 snake_case: List[str] = tempfile.mkdtemp() snake_case: str = ' He is very happy, UNwant\u00E9d,running' tokenizer.add_tokens(['bim', 'bambam'] ) snake_case: List[str] = tokenizer.additional_special_tokens additional_special_tokens.append('new_additional_special_token' ) tokenizer.add_special_tokens({'additional_special_tokens': additional_special_tokens} ) snake_case: int = tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = tokenizer.__class__.from_pretrained(SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = after_tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertIn('new_additional_special_token' , after_tokenizer.additional_special_tokens ) self.assertEqual(after_tokenizer.model_max_length , 42 ) snake_case: Union[str, Any] = tokenizer.__class__.from_pretrained(SCREAMING_SNAKE_CASE__ , model_max_length=43 ) self.assertEqual(tokenizer.model_max_length , 43 ) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Union[str, 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(SCREAMING_SNAKE_CASE__ ) with open(os.path.join(SCREAMING_SNAKE_CASE__ , 'special_tokens_map.json' ) , encoding='utf-8' ) as json_file: snake_case: Any = json.load(SCREAMING_SNAKE_CASE__ ) with open(os.path.join(SCREAMING_SNAKE_CASE__ , 'tokenizer_config.json' ) , encoding='utf-8' ) as json_file: snake_case: str = json.load(SCREAMING_SNAKE_CASE__ ) snake_case: int = [F"""<extra_id_{i}>""" for i in range(1_25 )] snake_case: Optional[int] = added_tokens_extra_ids + [ 'an_additional_special_token' ] snake_case: str = added_tokens_extra_ids + [ 'an_additional_special_token' ] with open(os.path.join(SCREAMING_SNAKE_CASE__ , 'special_tokens_map.json' ) , 'w' , encoding='utf-8' ) as outfile: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) with open(os.path.join(SCREAMING_SNAKE_CASE__ , 'tokenizer_config.json' ) , 'w' , encoding='utf-8' ) as outfile: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # 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 snake_case: Dict = tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE__ , ) self.assertIn( 'an_additional_special_token' , 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( ['an_additional_special_token'] , tokenizer_without_change_in_init.convert_ids_to_tokens( tokenizer_without_change_in_init.convert_tokens_to_ids(['an_additional_special_token'] ) ) , ) # Now we test that we can change the value of additional_special_tokens in the from_pretrained snake_case: Union[str, Any] = added_tokens_extra_ids + [AddedToken('a_new_additional_special_token' , lstrip=SCREAMING_SNAKE_CASE__ )] snake_case: Union[str, Any] = tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE__ , additional_special_tokens=SCREAMING_SNAKE_CASE__ , ) self.assertIn('a_new_additional_special_token' , tokenizer.additional_special_tokens ) self.assertEqual( ['a_new_additional_special_token'] , tokenizer.convert_ids_to_tokens( tokenizer.convert_tokens_to_ids(['a_new_additional_special_token'] ) ) , ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[str] = [] 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(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[Any] = tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertTrue(tokenizer.decode([2_55] ) == '' ) def _UpperCamelCase ( self ): '''simple docstring''' pass def _UpperCamelCase ( self ): '''simple docstring''' pass def _UpperCamelCase ( self ): '''simple docstring''' pass def _UpperCamelCase ( self ): '''simple docstring''' pass def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = self.get_tokenizers(fast=SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ ) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): snake_case: Union[str, Any] = ['t', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 'x', 't', '</s>'] snake_case: List[str] = tokenizer.convert_tokens_to_string(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): snake_case: Optional[Any] = [ 'bos_token', 'eos_token', 'unk_token', 'sep_token', 'pad_token', 'cls_token', 'mask_token', ] snake_case: Dict = 0 snake_case: List[Any] = tokenizer.convert_ids_to_tokens( SCREAMING_SNAKE_CASE__ , skip_special_tokens=SCREAMING_SNAKE_CASE__ ) for attr in attributes_list: setattr(SCREAMING_SNAKE_CASE__ , attr + '_id' , SCREAMING_SNAKE_CASE__ ) self.assertEqual(getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) self.assertEqual(getattr(SCREAMING_SNAKE_CASE__ , attr + '_id' ) , SCREAMING_SNAKE_CASE__ ) setattr(SCREAMING_SNAKE_CASE__ , attr + '_id' , SCREAMING_SNAKE_CASE__ ) self.assertEqual(getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) self.assertEqual(getattr(SCREAMING_SNAKE_CASE__ , attr + '_id' ) , SCREAMING_SNAKE_CASE__ ) setattr(SCREAMING_SNAKE_CASE__ , 'additional_special_tokens_ids' , [] ) self.assertListEqual(getattr(SCREAMING_SNAKE_CASE__ , 'additional_special_tokens' ) , [] ) self.assertListEqual(getattr(SCREAMING_SNAKE_CASE__ , 'additional_special_tokens_ids' ) , [] ) setattr(SCREAMING_SNAKE_CASE__ , 'additional_special_tokens_ids' , [token_id_to_test_setters] ) self.assertListEqual(getattr(SCREAMING_SNAKE_CASE__ , 'additional_special_tokens' ) , [token_to_test_setters] ) self.assertListEqual(getattr(SCREAMING_SNAKE_CASE__ , 'additional_special_tokens_ids' ) , [token_id_to_test_setters] )
692
1
'''simple docstring''' from __future__ import annotations from collections.abc import Iterator from typing import Any class __SCREAMING_SNAKE_CASE : def __init__( self : Optional[int] , UpperCAmelCase__ : Any ): '''simple docstring''' lowercase : Any =data lowercase : Node | None =None class __SCREAMING_SNAKE_CASE : def __init__( self : List[str] ): '''simple docstring''' lowercase : List[str] =None lowercase : str =None def __iter__( self : Optional[int] ): '''simple docstring''' lowercase : List[Any] =self.head while self.head: yield node.data lowercase : Dict =node.next if node == self.head: break def __len__( self : List[Any] ): '''simple docstring''' return sum(1 for _ in self ) def __repr__( self : Optional[Any] ): '''simple docstring''' return "->".join(str(UpperCAmelCase__ ) for item in iter(self ) ) def lowerCamelCase_ ( self : List[str] , UpperCAmelCase__ : Any ): '''simple docstring''' self.insert_nth(len(self ) , UpperCAmelCase__ ) def lowerCamelCase_ ( self : Optional[int] , UpperCAmelCase__ : Any ): '''simple docstring''' self.insert_nth(0 , UpperCAmelCase__ ) def lowerCamelCase_ ( self : List[str] , UpperCAmelCase__ : int , UpperCAmelCase__ : Any ): '''simple docstring''' if index < 0 or index > len(self ): raise IndexError('''list index out of range.''' ) lowercase : List[Any] =Node(UpperCAmelCase__ ) if self.head is None: lowercase : Optional[int] =new_node # first node points itself lowercase : Union[str, Any] =new_node elif index == 0: # insert at head lowercase : int =self.head lowercase : List[str] =new_node else: lowercase : List[str] =self.head for _ in range(index - 1 ): lowercase : Optional[int] =temp.next lowercase : str =temp.next lowercase : List[Any] =new_node if index == len(self ) - 1: # insert at tail lowercase : str =new_node def lowerCamelCase_ ( self : Dict ): '''simple docstring''' return self.delete_nth(0 ) def lowerCamelCase_ ( self : Any ): '''simple docstring''' return self.delete_nth(len(self ) - 1 ) def lowerCamelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : int = 0 ): '''simple docstring''' if not 0 <= index < len(self ): raise IndexError('''list index out of range.''' ) lowercase : int =self.head if self.head == self.tail: # just one node lowercase : str =None elif index == 0: # delete head node lowercase : List[Any] =self.tail.next.next lowercase : Tuple =self.head.next else: lowercase : Tuple =self.head for _ in range(index - 1 ): lowercase : List[str] =temp.next lowercase : str =temp.next lowercase : Tuple =temp.next.next if index == len(self ) - 1: # delete at tail lowercase : int =temp return delete_node.data def lowerCamelCase_ ( self : Any ): '''simple docstring''' return len(self ) == 0 def _lowerCAmelCase ( ) -> None: lowercase : Optional[int] =CircularLinkedList() assert len(__magic_name__ ) == 0 assert circular_linked_list.is_empty() is True assert str(__magic_name__ ) == "" try: circular_linked_list.delete_front() raise AssertionError # This should not happen except IndexError: assert True # This should happen try: circular_linked_list.delete_tail() raise AssertionError # This should not happen except IndexError: assert True # This should happen try: circular_linked_list.delete_nth(-1 ) raise AssertionError except IndexError: assert True try: circular_linked_list.delete_nth(0 ) raise AssertionError except IndexError: assert True assert circular_linked_list.is_empty() is True for i in range(5 ): assert len(__magic_name__ ) == i circular_linked_list.insert_nth(__magic_name__ , i + 1 ) assert str(__magic_name__ ) == "->".join(str(__magic_name__ ) for i in range(1 , 6 ) ) circular_linked_list.insert_tail(6 ) assert str(__magic_name__ ) == "->".join(str(__magic_name__ ) for i in range(1 , 7 ) ) circular_linked_list.insert_head(0 ) assert str(__magic_name__ ) == "->".join(str(__magic_name__ ) for i in range(0 , 7 ) ) assert circular_linked_list.delete_front() == 0 assert circular_linked_list.delete_tail() == 6 assert str(__magic_name__ ) == "->".join(str(__magic_name__ ) for i in range(1 , 6 ) ) assert circular_linked_list.delete_nth(2 ) == 3 circular_linked_list.insert_nth(2 , 3 ) assert str(__magic_name__ ) == "->".join(str(__magic_name__ ) for i in range(1 , 6 ) ) assert circular_linked_list.is_empty() is False if __name__ == "__main__": import doctest doctest.testmod()
92
from __future__ import annotations from math import pi # Define the Reduced Planck Constant ℏ (H bar), speed of light C, value of # Pi and the function __magic_name__ = 1.054_571_817E-34 # unit of ℏ : J * s __magic_name__ = 3E8 # unit of c : m * s^-1 def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_): '''simple docstring''' if (force, area, distance).count(0) != 1: raise ValueError("One and only one argument must be 0") if force < 0: raise ValueError("Magnitude of force can not be negative") if distance < 0: raise ValueError("Distance can not be negative") if area < 0: raise ValueError("Area can not be negative") if force == 0: lowerCamelCase_ : Dict = (REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 * area) / ( 240 * (distance) ** 4 ) return {"force": force} elif area == 0: lowerCamelCase_ : List[str] = (240 * force * (distance) ** 4) / ( REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 ) return {"area": area} elif distance == 0: lowerCamelCase_ : Any = ( (REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 * area) / (240 * force) ) ** (1 / 4) return {"distance": distance} raise ValueError("One and only one argument must be 0") # Run doctest if __name__ == "__main__": import doctest doctest.testmod()
250
0
'''simple docstring''' def SCREAMING_SNAKE_CASE_ ( ) -> int: return 1 def SCREAMING_SNAKE_CASE_ ( snake_case_ : int ) -> int: return 0 if x < 0 else two_pence(x - 2 ) + one_pence() def SCREAMING_SNAKE_CASE_ ( snake_case_ : int ) -> int: return 0 if x < 0 else five_pence(x - 5 ) + two_pence(snake_case_ ) def SCREAMING_SNAKE_CASE_ ( snake_case_ : int ) -> int: return 0 if x < 0 else ten_pence(x - 10 ) + five_pence(snake_case_ ) def SCREAMING_SNAKE_CASE_ ( snake_case_ : int ) -> int: return 0 if x < 0 else twenty_pence(x - 20 ) + ten_pence(snake_case_ ) def SCREAMING_SNAKE_CASE_ ( snake_case_ : int ) -> int: return 0 if x < 0 else fifty_pence(x - 50 ) + twenty_pence(snake_case_ ) def SCREAMING_SNAKE_CASE_ ( snake_case_ : int ) -> int: return 0 if x < 0 else one_pound(x - 100 ) + fifty_pence(snake_case_ ) def SCREAMING_SNAKE_CASE_ ( snake_case_ : int ) -> int: return 0 if x < 0 else two_pound(x - 200 ) + one_pound(snake_case_ ) def SCREAMING_SNAKE_CASE_ ( snake_case_ : int = 200 ) -> int: return two_pound(snake_case_ ) if __name__ == "__main__": print(solution(int(input().strip())))
220
'''simple docstring''' import logging import os import random import sys from dataclasses import dataclass, field from typing import Optional import datasets import evaluate import numpy as np from datasets import load_dataset import transformers from transformers import ( AutoConfig, AutoModelForSequenceClassification, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, default_data_collator, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version('4.31.0') require_version('datasets>=1.8.0', 'To fix: pip install -r examples/pytorch/text-classification/requirements.txt') __UpperCAmelCase = logging.getLogger(__name__) @dataclass class _a : """simple docstring""" A = field( default=1_28 , metadata={ 'help': ( 'The maximum total input sequence length after tokenization. Sequences longer ' 'than this will be truncated, sequences shorter will be padded.' ) } , ) A = field( default=SCREAMING_SNAKE_CASE , metadata={'help': 'Overwrite the cached preprocessed datasets or not.'} ) A = field( default=SCREAMING_SNAKE_CASE , metadata={ 'help': ( 'Whether to pad all samples to `max_seq_length`. ' 'If False, will pad the samples dynamically when batching to the maximum length in the batch.' ) } , ) A = field( default=SCREAMING_SNAKE_CASE , metadata={ 'help': ( 'For debugging purposes or quicker training, truncate the number of training examples to this ' 'value if set.' ) } , ) A = field( default=SCREAMING_SNAKE_CASE , metadata={ 'help': ( 'For debugging purposes or quicker training, truncate the number of evaluation examples to this ' 'value if set.' ) } , ) A = field( default=SCREAMING_SNAKE_CASE , metadata={ 'help': ( 'For debugging purposes or quicker training, truncate the number of prediction examples to this ' 'value if set.' ) } , ) @dataclass class _a : """simple docstring""" A = field( default=SCREAMING_SNAKE_CASE , metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'} ) A = field( default=SCREAMING_SNAKE_CASE , metadata={'help': 'Evaluation language. Also train language if `train_language` is set to None.'} ) A = field( default=SCREAMING_SNAKE_CASE , metadata={'help': 'Train language if it is different from the evaluation language.'} ) A = field( default=SCREAMING_SNAKE_CASE , metadata={'help': 'Pretrained config name or path if not the same as model_name'} ) A = field( default=SCREAMING_SNAKE_CASE , metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'} ) A = field( default=SCREAMING_SNAKE_CASE , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'} , ) A = field( default=SCREAMING_SNAKE_CASE , metadata={'help': 'arg to indicate if tokenizer should do lower case in AutoTokenizer.from_pretrained()'} , ) A = field( default=SCREAMING_SNAKE_CASE , metadata={'help': 'Whether to use one of the fast tokenizer (backed by the tokenizers library) or not.'} , ) A = field( default='main' , metadata={'help': 'The specific model version to use (can be a branch name, tag name or commit id).'} , ) A = field( default=SCREAMING_SNAKE_CASE , metadata={ 'help': ( 'Will use the token generated when running `huggingface-cli login` (necessary to use this script ' 'with private models).' ) } , ) A = field( default=SCREAMING_SNAKE_CASE , metadata={'help': 'Will enable to load a pretrained model whose head dimensions are different.'} , ) def SCREAMING_SNAKE_CASE_ ( ) -> Union[str, Any]: # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. SCREAMING_SNAKE_CASE : List[Any] = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry('run_xnli' , snake_case_ ) # Setup logging logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() SCREAMING_SNAKE_CASE : Optional[int] = training_args.get_process_log_level() logger.setLevel(snake_case_ ) datasets.utils.logging.set_verbosity(snake_case_ ) transformers.utils.logging.set_verbosity(snake_case_ ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}""" + f"""distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}""" ) logger.info(f"""Training/evaluation parameters {training_args}""" ) # Detecting last checkpoint. SCREAMING_SNAKE_CASE : int = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: SCREAMING_SNAKE_CASE : Tuple = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f"""Output directory ({training_args.output_dir}) already exists and is not empty. """ 'Use --overwrite_output_dir to overcome.' ) elif last_checkpoint is not None: logger.info( f"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """ 'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.' ) # Set seed before initializing model. set_seed(training_args.seed ) # In distributed training, the load_dataset function guarantees that only one local process can concurrently # download the dataset. # Downloading and loading xnli dataset from the hub. if training_args.do_train: if model_args.train_language is None: SCREAMING_SNAKE_CASE : Tuple = load_dataset( 'xnli' , model_args.language , split='train' , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) else: SCREAMING_SNAKE_CASE : Optional[Any] = load_dataset( 'xnli' , model_args.train_language , split='train' , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) SCREAMING_SNAKE_CASE : List[str] = train_dataset.features['label'].names if training_args.do_eval: SCREAMING_SNAKE_CASE : List[str] = load_dataset( 'xnli' , model_args.language , split='validation' , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) SCREAMING_SNAKE_CASE : str = eval_dataset.features['label'].names if training_args.do_predict: SCREAMING_SNAKE_CASE : List[Any] = load_dataset( 'xnli' , model_args.language , split='test' , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) SCREAMING_SNAKE_CASE : List[Any] = predict_dataset.features['label'].names # Labels SCREAMING_SNAKE_CASE : List[str] = len(snake_case_ ) # Load pretrained model and tokenizer # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. SCREAMING_SNAKE_CASE : List[Any] = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=snake_case_ , idalabel={str(snake_case_ ): label for i, label in enumerate(snake_case_ )} , labelaid={label: i for i, label in enumerate(snake_case_ )} , finetuning_task='xnli' , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) SCREAMING_SNAKE_CASE : Dict = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , do_lower_case=model_args.do_lower_case , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast_tokenizer , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) SCREAMING_SNAKE_CASE : Dict = AutoModelForSequenceClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool('.ckpt' in model_args.model_name_or_path ) , config=snake_case_ , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ignore_mismatched_sizes=model_args.ignore_mismatched_sizes , ) # Preprocessing the datasets # Padding strategy if data_args.pad_to_max_length: SCREAMING_SNAKE_CASE : Dict = 'max_length' else: # We will pad later, dynamically at batch creation, to the max sequence length in each batch SCREAMING_SNAKE_CASE : Tuple = False def preprocess_function(snake_case_ : Optional[Any] ): # Tokenize the texts return tokenizer( examples['premise'] , examples['hypothesis'] , padding=snake_case_ , max_length=data_args.max_seq_length , truncation=snake_case_ , ) if training_args.do_train: if data_args.max_train_samples is not None: SCREAMING_SNAKE_CASE : List[Any] = min(len(snake_case_ ) , data_args.max_train_samples ) SCREAMING_SNAKE_CASE : List[Any] = train_dataset.select(range(snake_case_ ) ) with training_args.main_process_first(desc='train dataset map pre-processing' ): SCREAMING_SNAKE_CASE : int = train_dataset.map( snake_case_ , batched=snake_case_ , load_from_cache_file=not data_args.overwrite_cache , desc='Running tokenizer on train dataset' , ) # Log a few random samples from the training set: for index in random.sample(range(len(snake_case_ ) ) , 3 ): logger.info(f"""Sample {index} of the training set: {train_dataset[index]}.""" ) if training_args.do_eval: if data_args.max_eval_samples is not None: SCREAMING_SNAKE_CASE : str = min(len(snake_case_ ) , data_args.max_eval_samples ) SCREAMING_SNAKE_CASE : List[str] = eval_dataset.select(range(snake_case_ ) ) with training_args.main_process_first(desc='validation dataset map pre-processing' ): SCREAMING_SNAKE_CASE : Optional[Any] = eval_dataset.map( snake_case_ , batched=snake_case_ , load_from_cache_file=not data_args.overwrite_cache , desc='Running tokenizer on validation dataset' , ) if training_args.do_predict: if data_args.max_predict_samples is not None: SCREAMING_SNAKE_CASE : Tuple = min(len(snake_case_ ) , data_args.max_predict_samples ) SCREAMING_SNAKE_CASE : Optional[Any] = predict_dataset.select(range(snake_case_ ) ) with training_args.main_process_first(desc='prediction dataset map pre-processing' ): SCREAMING_SNAKE_CASE : Any = predict_dataset.map( snake_case_ , batched=snake_case_ , load_from_cache_file=not data_args.overwrite_cache , desc='Running tokenizer on prediction dataset' , ) # Get the metric function SCREAMING_SNAKE_CASE : List[str] = evaluate.load('xnli' ) # You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a # predictions and label_ids field) and has to return a dictionary string to float. def compute_metrics(snake_case_ : EvalPrediction ): SCREAMING_SNAKE_CASE : Optional[int] = p.predictions[0] if isinstance(p.predictions , snake_case_ ) else p.predictions SCREAMING_SNAKE_CASE : Optional[Any] = np.argmax(snake_case_ , axis=1 ) return metric.compute(predictions=snake_case_ , references=p.label_ids ) # Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding. if data_args.pad_to_max_length: SCREAMING_SNAKE_CASE : List[str] = default_data_collator elif training_args.fpaa: SCREAMING_SNAKE_CASE : int = DataCollatorWithPadding(snake_case_ , pad_to_multiple_of=8 ) else: SCREAMING_SNAKE_CASE : str = None # Initialize our Trainer SCREAMING_SNAKE_CASE : Optional[int] = Trainer( model=snake_case_ , args=snake_case_ , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , compute_metrics=snake_case_ , tokenizer=snake_case_ , data_collator=snake_case_ , ) # Training if training_args.do_train: SCREAMING_SNAKE_CASE : Optional[int] = None if training_args.resume_from_checkpoint is not None: SCREAMING_SNAKE_CASE : Dict = training_args.resume_from_checkpoint elif last_checkpoint is not None: SCREAMING_SNAKE_CASE : Optional[int] = last_checkpoint SCREAMING_SNAKE_CASE : Union[str, Any] = trainer.train(resume_from_checkpoint=snake_case_ ) SCREAMING_SNAKE_CASE : Any = train_result.metrics SCREAMING_SNAKE_CASE : int = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(snake_case_ ) ) SCREAMING_SNAKE_CASE : Tuple = min(snake_case_ , len(snake_case_ ) ) trainer.save_model() # Saves the tokenizer too for easy upload trainer.log_metrics('train' , snake_case_ ) trainer.save_metrics('train' , snake_case_ ) trainer.save_state() # Evaluation if training_args.do_eval: logger.info('*** Evaluate ***' ) SCREAMING_SNAKE_CASE : int = trainer.evaluate(eval_dataset=snake_case_ ) SCREAMING_SNAKE_CASE : Optional[Any] = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(snake_case_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = min(snake_case_ , len(snake_case_ ) ) trainer.log_metrics('eval' , snake_case_ ) trainer.save_metrics('eval' , snake_case_ ) # Prediction if training_args.do_predict: logger.info('*** Predict ***' ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[Any] = trainer.predict(snake_case_ , metric_key_prefix='predict' ) SCREAMING_SNAKE_CASE : Optional[int] = ( data_args.max_predict_samples if data_args.max_predict_samples is not None else len(snake_case_ ) ) SCREAMING_SNAKE_CASE : Optional[Any] = min(snake_case_ , len(snake_case_ ) ) trainer.log_metrics('predict' , snake_case_ ) trainer.save_metrics('predict' , snake_case_ ) SCREAMING_SNAKE_CASE : int = np.argmax(snake_case_ , axis=1 ) SCREAMING_SNAKE_CASE : Optional[int] = os.path.join(training_args.output_dir , 'predictions.txt' ) if trainer.is_world_process_zero(): with open(snake_case_ , 'w' ) as writer: writer.write('index\tprediction\n' ) for index, item in enumerate(snake_case_ ): SCREAMING_SNAKE_CASE : str = label_list[item] writer.write(f"""{index}\t{item}\n""" ) if __name__ == "__main__": main()
220
1
"""simple docstring""" import argparse import os import re import torch from flax.traverse_util import flatten_dict from tax import checkpoints from transformers import ( AutoTokenizer, PixaStructConfig, PixaStructForConditionalGeneration, PixaStructImageProcessor, PixaStructProcessor, PixaStructTextConfig, PixaStructVisionConfig, ) def UpperCAmelCase ( A : List[Any] ): '''simple docstring''' _UpperCAmelCase = checkpoints.load_tax_checkpoint(lowercase__ ) _UpperCAmelCase = flatten_dict(lowercase__ ) return flax_params def UpperCAmelCase ( A : str ): '''simple docstring''' _UpperCAmelCase = {} _UpperCAmelCase = { 'token_embedder': 'embeddings', 'encoder_norm': 'layernorm', 'kernel': 'weight', '.out': '.output', 'scale': 'weight', 'embedders_0.pos_embedding': 'row_embedder.weight', 'embedders_1.pos_embedding': 'column_embedder.weight', } _UpperCAmelCase = { 'query': 'attention.query', 'key': 'attention.key', 'value': 'attention.value', 'output.dense': 'output', 'encoder_decoder_attention.o': 'encoder_decoder_attention.attention.o', 'pre_self_attention_layer_norm': 'self_attention.layer_norm', 'pre_cross_attention_layer_norm': 'encoder_decoder_attention.layer_norm', 'mlp.': 'mlp.DenseReluDense.', 'pre_mlp_layer_norm': 'mlp.layer_norm', 'self_attention.o': 'self_attention.attention.o', 'decoder.embeddings.embedding': 'decoder.embed_tokens.weight', 'decoder.relpos_bias.rel_embedding': 'decoder.layer.0.self_attention.attention.relative_attention_bias.weight', 'decoder.decoder_norm.weight': 'decoder.final_layer_norm.weight', 'decoder.logits_dense.weight': 'decoder.lm_head.weight', } for key in flax_dict.keys(): if "target" in key: # remove the first prefix from the key _UpperCAmelCase = '.'.join(key[1:] ) # rename the key for old, new in CONVERSION_MAPPING.items(): _UpperCAmelCase = new_key.replace(lowercase__ , lowercase__ ) if "decoder" in new_key: for old, new in DECODER_CONVERSION_MAPPING.items(): _UpperCAmelCase = new_key.replace(lowercase__ , lowercase__ ) if "layers" in new_key and "decoder" not in new_key: # use regex to replace the layer number _UpperCAmelCase = re.sub(r'layers_(\d+)' , r'layer.\1' , lowercase__ ) _UpperCAmelCase = new_key.replace('encoder' , 'encoder.encoder' ) elif "layers" in new_key and "decoder" in new_key: # use regex to replace the layer number _UpperCAmelCase = re.sub(r'layers_(\d+)' , r'layer.\1' , lowercase__ ) _UpperCAmelCase = flax_dict[key] _UpperCAmelCase = {} # convert converted_dict into torch format for key in converted_dict.keys(): if ("embed_tokens" not in key) and ("embedder" not in key): _UpperCAmelCase = torch.from_numpy(converted_dict[key].T ) else: _UpperCAmelCase = torch.from_numpy(converted_dict[key] ) return converted_torch_dict def UpperCAmelCase ( A : Optional[int] , A : Union[str, Any] , A : Optional[Any]=False , A : Any=False ): '''simple docstring''' _UpperCAmelCase = get_flax_param(lowercase__ ) if not use_large: _UpperCAmelCase = PixaStructVisionConfig() _UpperCAmelCase = PixaStructTextConfig() else: _UpperCAmelCase = PixaStructVisionConfig( hidden_size=1536 , d_ff=3968 , num_attention_heads=24 , num_hidden_layers=18 ) _UpperCAmelCase = PixaStructTextConfig(hidden_size=1536 , d_ff=3968 , num_heads=24 , num_layers=18 ) _UpperCAmelCase = PixaStructConfig( vision_config=encoder_config.to_dict() , text_config=decoder_config.to_dict() , is_vqa=lowercase__ ) _UpperCAmelCase = PixaStructForConditionalGeneration(lowercase__ ) _UpperCAmelCase = rename_and_convert_flax_params(lowercase__ ) model.load_state_dict(lowercase__ ) _UpperCAmelCase = AutoTokenizer.from_pretrained('ybelkada/test-pix2struct-tokenizer' ) _UpperCAmelCase = PixaStructImageProcessor() _UpperCAmelCase = PixaStructProcessor(image_processor=lowercase__ , tokenizer=lowercase__ ) if use_large: _UpperCAmelCase = 4096 _UpperCAmelCase = True # mkdir if needed os.makedirs(lowercase__ , exist_ok=lowercase__ ) model.save_pretrained(lowercase__ ) processor.save_pretrained(lowercase__ ) print('Model saved in {}'.format(lowercase__ ) ) if __name__ == "__main__": lowercase = argparse.ArgumentParser() parser.add_argument('''--t5x_checkpoint_path''', default=None, type=str, help='''Path to the original T5x checkpoint.''') parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--use_large''', action='''store_true''', help='''Use large model.''') parser.add_argument('''--is_vqa''', action='''store_true''', help='''Use large model.''') lowercase = parser.parse_args() convert_pixastruct_original_pytorch_checkpoint_to_hf( args.tax_checkpoint_path, args.pytorch_dump_folder_path, args.use_large )
573
class SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self , __UpperCamelCase ): """simple docstring""" snake_case_ = val snake_case_ = None snake_case_ = None def __lowerCAmelCase ( self , __UpperCamelCase ): """simple docstring""" if self.val: if val < self.val: if self.left is None: snake_case_ = Node(__UpperCamelCase ) else: self.left.insert(__UpperCamelCase ) elif val > self.val: if self.right is None: snake_case_ = Node(__UpperCamelCase ) else: self.right.insert(__UpperCamelCase ) else: snake_case_ = val def a(lowercase__ , lowercase__ ): '''simple docstring''' # Recursive traversal if root: inorder(root.left , lowercase__ ) res.append(root.val ) inorder(root.right , lowercase__ ) def a(lowercase__ ): '''simple docstring''' # Build BST if len(lowercase__ ) == 0: return arr snake_case_ = Node(arr[0] ) for i in range(1 , len(lowercase__ ) ): root.insert(arr[i] ) # Traverse BST in order. snake_case_ = [] inorder(lowercase__ , lowercase__ ) return res if __name__ == "__main__": print(tree_sort([10, 1, 3, 2, 9, 14, 13]))
187
0
from math import isclose, sqrt def UpperCAmelCase_ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase = point_y / 4 / point_x lowercase = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) lowercase = (1 - normal_gradient * normal_gradient) / ( 1 + normal_gradient * normal_gradient ) lowercase = (sa - ca * incoming_gradient) / (ca + sa * incoming_gradient) # to find the next point, solve the simultaeneous equations: # y^2 + 4x^2 = 100 # y - b = m * (x - a) # ==> A x^2 + B x + C = 0 lowercase = outgoing_gradient**2 + 4 lowercase = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) lowercase = (point_y - outgoing_gradient * point_x) ** 2 - 100 lowercase = ( -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) lowercase = ( -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) # two solutions, one of which is our input point lowercase = x_minus if isclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else x_plus lowercase = point_y + outgoing_gradient * (next_x - point_x) return next_x, next_y, outgoing_gradient def UpperCAmelCase_ ( __SCREAMING_SNAKE_CASE = 1.4 , __SCREAMING_SNAKE_CASE = -9.6 ): lowercase = 0 lowercase = first_x_coord lowercase = first_y_coord lowercase = (10.1 - point_y) / (0.0 - point_x) while not (-0.01 <= point_x <= 0.01 and point_y > 0): lowercase , lowercase , lowercase = next_point(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) num_reflections += 1 return num_reflections if __name__ == "__main__": print(F"""{solution() = }""")
701
from abc import ABC, abstractmethod from typing import List, Optional class A_ ( __lowerCamelCase ): '''simple docstring''' def __init__( self ): # test for the above condition self.test() def SCREAMING_SNAKE_CASE__ ( self ): lowercase = 0 lowercase = False while not completed: if counter == 1: self.reset() lowercase = self.advance() if not self.does_advance(snake_case ): raise Exception( 'Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true.' ) lowercase , lowercase , lowercase = self.update(snake_case ) counter += 1 if counter > 1_0000: raise Exception('update() does not fulfill the constraint.' ) if self.remaining() != 0: raise Exception('Custom Constraint is not defined correctly.' ) @abstractmethod def SCREAMING_SNAKE_CASE__ ( self ): raise NotImplementedError( F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) @abstractmethod def SCREAMING_SNAKE_CASE__ ( self , snake_case ): raise NotImplementedError( F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) @abstractmethod def SCREAMING_SNAKE_CASE__ ( self , snake_case ): raise NotImplementedError( F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) @abstractmethod def SCREAMING_SNAKE_CASE__ ( self ): raise NotImplementedError( F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) @abstractmethod def SCREAMING_SNAKE_CASE__ ( self ): raise NotImplementedError( F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) @abstractmethod def SCREAMING_SNAKE_CASE__ ( self , snake_case=False ): raise NotImplementedError( F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) class A_ ( __lowerCamelCase ): '''simple docstring''' def __init__( self , snake_case ): super(snake_case , self ).__init__() if not isinstance(snake_case , snake_case ) or len(snake_case ) == 0: raise ValueError(F'''`token_ids` has to be a non-empty list, but is {token_ids}.''' ) if any((not isinstance(snake_case , snake_case ) or token_id < 0) for token_id in token_ids ): raise ValueError(F'''Each list in `token_ids` has to be a list of positive integers, but is {token_ids}.''' ) lowercase = token_ids lowercase = len(self.token_ids ) lowercase = -1 # the index of the currently fulfilled step lowercase = False def SCREAMING_SNAKE_CASE__ ( self ): if self.completed: return None return self.token_ids[self.fulfilled_idx + 1] def SCREAMING_SNAKE_CASE__ ( self , snake_case ): if not isinstance(snake_case , snake_case ): raise ValueError(F'''`token_id` has to be an `int`, but is {token_id} of type {type(snake_case )}''' ) if self.completed: return False return token_id == self.token_ids[self.fulfilled_idx + 1] def SCREAMING_SNAKE_CASE__ ( self , snake_case ): if not isinstance(snake_case , snake_case ): raise ValueError(F'''`token_id` has to be an `int`, but is {token_id} of type {type(snake_case )}''' ) lowercase = False lowercase = False lowercase = False if self.does_advance(snake_case ): self.fulfilled_idx += 1 lowercase = True if self.fulfilled_idx == (self.seqlen - 1): lowercase = True lowercase = completed else: # failed to make progress. lowercase = True self.reset() return stepped, completed, reset def SCREAMING_SNAKE_CASE__ ( self ): lowercase = False lowercase = 0 def SCREAMING_SNAKE_CASE__ ( self ): return self.seqlen - (self.fulfilled_idx + 1) def SCREAMING_SNAKE_CASE__ ( self , snake_case=False ): lowercase = PhrasalConstraint(self.token_ids ) if stateful: lowercase = self.seqlen lowercase = self.fulfilled_idx lowercase = self.completed return new_constraint class A_ : '''simple docstring''' def __init__( self , snake_case , snake_case=True ): lowercase = max([len(snake_case ) for one in nested_token_ids] ) lowercase = {} for token_ids in nested_token_ids: lowercase = root for tidx, token_id in enumerate(snake_case ): if token_id not in level: lowercase = {} lowercase = level[token_id] if no_subsets and self.has_subsets(snake_case , snake_case ): raise ValueError( 'Each list in `nested_token_ids` can\'t be a complete subset of another list, but is' F''' {nested_token_ids}.''' ) lowercase = root def SCREAMING_SNAKE_CASE__ ( self , snake_case ): lowercase = self.trie for current_token in current_seq: lowercase = start[current_token] lowercase = list(start.keys() ) return next_tokens def SCREAMING_SNAKE_CASE__ ( self , snake_case ): lowercase = self.next_tokens(snake_case ) return len(snake_case ) == 0 def SCREAMING_SNAKE_CASE__ ( self , snake_case ): lowercase = list(root.values() ) if len(snake_case ) == 0: return 1 else: return sum([self.count_leaves(snake_case ) for nn in next_nodes] ) def SCREAMING_SNAKE_CASE__ ( self , snake_case , snake_case ): lowercase = self.count_leaves(snake_case ) return len(snake_case ) != leaf_count class A_ ( __lowerCamelCase ): '''simple docstring''' def __init__( self , snake_case ): super(snake_case , self ).__init__() if not isinstance(snake_case , snake_case ) or len(snake_case ) == 0: raise ValueError(F'''`nested_token_ids` has to be a non-empty list, but is {nested_token_ids}.''' ) if any(not isinstance(snake_case , snake_case ) for token_ids in nested_token_ids ): raise ValueError(F'''`nested_token_ids` has to be a list of lists, but is {nested_token_ids}.''' ) if any( any((not isinstance(snake_case , snake_case ) or token_id < 0) for token_id in token_ids ) for token_ids in nested_token_ids ): raise ValueError( F'''Each list in `nested_token_ids` has to be a list of positive integers, but is {nested_token_ids}.''' ) lowercase = DisjunctiveTrie(snake_case ) lowercase = nested_token_ids lowercase = self.trie.max_height lowercase = [] lowercase = False def SCREAMING_SNAKE_CASE__ ( self ): lowercase = self.trie.next_tokens(self.current_seq ) if len(snake_case ) == 0: return None else: return token_list def SCREAMING_SNAKE_CASE__ ( self , snake_case ): if not isinstance(snake_case , snake_case ): raise ValueError(F'''`token_id` is supposed to be type `int`, but is {token_id} of type {type(snake_case )}''' ) lowercase = self.trie.next_tokens(self.current_seq ) return token_id in next_tokens def SCREAMING_SNAKE_CASE__ ( self , snake_case ): if not isinstance(snake_case , snake_case ): raise ValueError(F'''`token_id` is supposed to be type `int`, but is {token_id} of type {type(snake_case )}''' ) lowercase = False lowercase = False lowercase = False if self.does_advance(snake_case ): self.current_seq.append(snake_case ) lowercase = True else: lowercase = True self.reset() lowercase = self.trie.reached_leaf(self.current_seq ) lowercase = completed return stepped, completed, reset def SCREAMING_SNAKE_CASE__ ( self ): lowercase = False lowercase = [] def SCREAMING_SNAKE_CASE__ ( self ): if self.completed: # since this can be completed without reaching max height return 0 else: return self.seqlen - len(self.current_seq ) def SCREAMING_SNAKE_CASE__ ( self , snake_case=False ): lowercase = DisjunctiveConstraint(self.token_ids ) if stateful: lowercase = self.seqlen lowercase = self.current_seq lowercase = self.completed return new_constraint class A_ : '''simple docstring''' def __init__( self , snake_case ): lowercase = constraints # max # of steps required to fulfill a given constraint lowercase = max([c.seqlen for c in constraints] ) lowercase = len(snake_case ) lowercase = False self.init_state() def SCREAMING_SNAKE_CASE__ ( self ): lowercase = [] lowercase = None lowercase = [constraint.copy(stateful=snake_case ) for constraint in self.constraints] def SCREAMING_SNAKE_CASE__ ( self ): lowercase = 0 if self.inprogress_constraint: # extra points for having a constraint mid-fulfilled add += self.max_seqlen - self.inprogress_constraint.remaining() return (len(self.complete_constraints ) * self.max_seqlen) + add def SCREAMING_SNAKE_CASE__ ( self ): lowercase = [] if self.inprogress_constraint is None: for constraint in self.pending_constraints: # "pending" == "unfulfilled yet" lowercase = constraint.advance() if isinstance(snake_case , snake_case ): token_list.append(snake_case ) elif isinstance(snake_case , snake_case ): token_list.extend(snake_case ) else: lowercase = self.inprogress_constraint.advance() if isinstance(snake_case , snake_case ): token_list.append(snake_case ) elif isinstance(snake_case , snake_case ): token_list.extend(snake_case ) if len(snake_case ) == 0: return None else: return token_list def SCREAMING_SNAKE_CASE__ ( self , snake_case ): self.init_state() if token_ids is not None: for token in token_ids: # completes or steps **one** constraint lowercase , lowercase = self.add(snake_case ) # the entire list of constraints are fulfilled if self.completed: break def SCREAMING_SNAKE_CASE__ ( self , snake_case ): if not isinstance(snake_case , snake_case ): raise ValueError(F'''`token_id` should be an `int`, but is `{token_id}`.''' ) lowercase , lowercase = False, False if self.completed: lowercase = True lowercase = False return complete, stepped if self.inprogress_constraint is not None: # In the middle of fulfilling a constraint. If the `token_id` *does* makes an incremental progress to current # job, simply update the state lowercase , lowercase , lowercase = self.inprogress_constraint.update(snake_case ) if reset: # 1. If the next token breaks the progress, then we must restart. # e.g. constraint = "I love pies" and sequence so far is "I love" but `token_id` == "books". # But that doesn't mean we self.init_state(), since we only reset the state for this particular # constraint, not the full list of constraints. self.pending_constraints.append(self.inprogress_constraint.copy(stateful=snake_case ) ) lowercase = None if complete: # 2. If the next token completes the constraint, move it to completed list, set # inprogress to None. If there are no pending constraints either, then this full list of constraints # is complete. self.complete_constraints.append(self.inprogress_constraint ) lowercase = None if len(self.pending_constraints ) == 0: # we're done! lowercase = True else: # Not in the middle of fulfilling a constraint. So does this `token_id` helps us step towards any of our list # of constraints? for cidx, pending_constraint in enumerate(self.pending_constraints ): if pending_constraint.does_advance(snake_case ): lowercase , lowercase , lowercase = pending_constraint.update(snake_case ) if not stepped: raise Exception( '`constraint.update(token_id)` is not yielding incremental progress, ' 'even though `constraint.does_advance(token_id)` is true.' ) if complete: self.complete_constraints.append(snake_case ) lowercase = None if not complete and stepped: lowercase = pending_constraint if complete or stepped: # If we made any progress at all, then it's at least not a "pending constraint". lowercase = ( self.pending_constraints[:cidx] + self.pending_constraints[cidx + 1 :] ) if len(self.pending_constraints ) == 0 and self.inprogress_constraint is None: # If there's no longer any pending after this and no inprogress either, then we must be # complete. lowercase = True break # prevent accidentally stepping through multiple constraints with just one token. return complete, stepped def SCREAMING_SNAKE_CASE__ ( self , snake_case=True ): lowercase = ConstraintListState(self.constraints ) # we actually never though self.constraints objects # throughout this process. So it's at initialization state. if stateful: lowercase = [ constraint.copy(stateful=snake_case ) for constraint in self.complete_constraints ] if self.inprogress_constraint is not None: lowercase = self.inprogress_constraint.copy(stateful=snake_case ) lowercase = [constraint.copy() for constraint in self.pending_constraints] return new_state
565
0
from typing import TYPE_CHECKING from ...utils import _LazyModule UpperCamelCase_ = {'tokenization_bertweet': ['BertweetTokenizer']} if TYPE_CHECKING: from .tokenization_bertweet import BertweetTokenizer else: import sys UpperCamelCase_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
625
import inspect import unittest from transformers import DPTConfig from transformers.file_utils import is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import MODEL_MAPPING, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel from transformers.models.dpt.modeling_dpt import DPT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DPTImageProcessor class snake_case_ : '''simple docstring''' def __init__( self, A_, A_=2, A_=32, A_=16, A_=3, A_=True, A_=True, A_=32, A_=4, A_=[0, 1, 2, 3], A_=4, A_=37, A_="gelu", A_=0.1, A_=0.1, A_=0.02, A_=3, A_=[1, 384, 24, 24], A_=True, A_=None, ) -> Optional[int]: UpperCAmelCase__ =parent UpperCAmelCase__ =batch_size UpperCAmelCase__ =image_size UpperCAmelCase__ =patch_size UpperCAmelCase__ =num_channels UpperCAmelCase__ =is_training UpperCAmelCase__ =use_labels UpperCAmelCase__ =hidden_size UpperCAmelCase__ =num_hidden_layers UpperCAmelCase__ =backbone_out_indices UpperCAmelCase__ =num_attention_heads UpperCAmelCase__ =intermediate_size UpperCAmelCase__ =hidden_act UpperCAmelCase__ =hidden_dropout_prob UpperCAmelCase__ =attention_probs_dropout_prob UpperCAmelCase__ =initializer_range UpperCAmelCase__ =num_labels UpperCAmelCase__ =backbone_featmap_shape UpperCAmelCase__ =scope UpperCAmelCase__ =is_hybrid # sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token) UpperCAmelCase__ =(image_size // patch_size) ** 2 UpperCAmelCase__ =num_patches + 1 def __UpperCAmelCase ( self ) -> str: UpperCAmelCase__ =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCAmelCase__ =None if self.use_labels: UpperCAmelCase__ =ids_tensor([self.batch_size, self.image_size, self.image_size], self.num_labels ) UpperCAmelCase__ =self.get_config() return config, pixel_values, labels def __UpperCAmelCase ( self ) -> Dict: UpperCAmelCase__ ={ "global_padding": "same", "layer_type": "bottleneck", "depths": [3, 4, 9], "out_features": ["stage1", "stage2", "stage3"], "embedding_dynamic_padding": True, "hidden_sizes": [96, 192, 384, 768], "num_groups": 2, } return DPTConfig( image_size=self.image_size, patch_size=self.patch_size, num_channels=self.num_channels, hidden_size=self.hidden_size, num_hidden_layers=self.num_hidden_layers, backbone_out_indices=self.backbone_out_indices, num_attention_heads=self.num_attention_heads, intermediate_size=self.intermediate_size, hidden_act=self.hidden_act, hidden_dropout_prob=self.hidden_dropout_prob, attention_probs_dropout_prob=self.attention_probs_dropout_prob, is_decoder=A_, initializer_range=self.initializer_range, is_hybrid=self.is_hybrid, backbone_config=A_, backbone_featmap_shape=self.backbone_featmap_shape, ) def __UpperCAmelCase ( self, A_, A_, A_ ) -> Optional[Any]: UpperCAmelCase__ =DPTModel(config=A_ ) model.to(A_ ) model.eval() UpperCAmelCase__ =model(A_ ) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self, A_, A_, A_ ) -> Union[str, Any]: UpperCAmelCase__ =self.num_labels UpperCAmelCase__ =DPTForDepthEstimation(A_ ) model.to(A_ ) model.eval() UpperCAmelCase__ =model(A_ ) self.parent.assertEqual(result.predicted_depth.shape, (self.batch_size, self.image_size, self.image_size) ) def __UpperCAmelCase ( self, A_, A_, A_ ) -> Optional[Any]: UpperCAmelCase__ =self.num_labels UpperCAmelCase__ =DPTForSemanticSegmentation(A_ ) model.to(A_ ) model.eval() UpperCAmelCase__ =model(A_, labels=A_ ) self.parent.assertEqual( result.logits.shape, (self.batch_size, self.num_labels, self.image_size, self.image_size) ) def __UpperCAmelCase ( self ) -> int: UpperCAmelCase__ =self.prepare_config_and_inputs() UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ =config_and_inputs UpperCAmelCase__ ={"pixel_values": pixel_values} return config, inputs_dict @require_torch class snake_case_ ( a, a, unittest.TestCase ): '''simple docstring''' __UpperCamelCase = (DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else () __UpperCamelCase = ( { 'depth-estimation': DPTForDepthEstimation, 'feature-extraction': DPTModel, 'image-segmentation': DPTForSemanticSegmentation, } if is_torch_available() else {} ) __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False def __UpperCAmelCase ( self ) -> int: UpperCAmelCase__ =DPTModelTester(self ) UpperCAmelCase__ =ConfigTester(self, config_class=A_, has_text_modality=A_, hidden_size=37 ) def __UpperCAmelCase ( self ) -> Optional[Any]: self.config_tester.run_common_tests() @unittest.skip(reason="DPT does not use inputs_embeds" ) def __UpperCAmelCase ( self ) -> List[Any]: pass def __UpperCAmelCase ( self ) -> str: UpperCAmelCase__ , UpperCAmelCase__ =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase__ =model_class(A_ ) self.assertIsInstance(model.get_input_embeddings(), (nn.Module) ) UpperCAmelCase__ =model.get_output_embeddings() self.assertTrue(x is None or isinstance(A_, nn.Linear ) ) def __UpperCAmelCase ( self ) -> Optional[int]: UpperCAmelCase__ , UpperCAmelCase__ =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase__ =model_class(A_ ) UpperCAmelCase__ =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCAmelCase__ =[*signature.parameters.keys()] UpperCAmelCase__ =["pixel_values"] self.assertListEqual(arg_names[:1], A_ ) def __UpperCAmelCase ( self ) -> List[Any]: UpperCAmelCase__ =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A_ ) def __UpperCAmelCase ( self ) -> str: UpperCAmelCase__ =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_depth_estimation(*A_ ) def __UpperCAmelCase ( self ) -> List[Any]: UpperCAmelCase__ =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*A_ ) def __UpperCAmelCase ( self ) -> Any: for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue UpperCAmelCase__ , UpperCAmelCase__ =self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase__ =True if model_class in get_values(A_ ): continue UpperCAmelCase__ =model_class(A_ ) model.to(A_ ) model.train() UpperCAmelCase__ =self._prepare_for_class(A_, A_, return_labels=A_ ) UpperCAmelCase__ =model(**A_ ).loss loss.backward() def __UpperCAmelCase ( self ) -> List[Any]: for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue UpperCAmelCase__ , UpperCAmelCase__ =self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase__ =False UpperCAmelCase__ =True if model_class in get_values(A_ ) or not model_class.supports_gradient_checkpointing: continue UpperCAmelCase__ =model_class(A_ ) model.to(A_ ) model.gradient_checkpointing_enable() model.train() UpperCAmelCase__ =self._prepare_for_class(A_, A_, return_labels=A_ ) UpperCAmelCase__ =model(**A_ ).loss loss.backward() def __UpperCAmelCase ( self ) -> int: UpperCAmelCase__ , UpperCAmelCase__ =self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase__ =_config_zero_init(A_ ) for model_class in self.all_model_classes: UpperCAmelCase__ =model_class(config=A_ ) # Skip the check for the backbone UpperCAmelCase__ =[] for name, module in model.named_modules(): if module.__class__.__name__ == "DPTViTHybridEmbeddings": UpperCAmelCase__ =[f"""{name}.{key}""" for key in module.state_dict().keys()] break for name, param in model.named_parameters(): if param.requires_grad: if name in backbone_params: continue self.assertIn( ((param.data.mean() * 1E9).round() / 1E9).item(), [0.0, 1.0], msg=f"""Parameter {name} of model {model_class} seems not properly initialized""", ) @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." ) def __UpperCAmelCase ( self ) -> List[Any]: pass @slow def __UpperCAmelCase ( self ) -> Optional[int]: for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]: UpperCAmelCase__ =DPTModel.from_pretrained(A_ ) self.assertIsNotNone(A_ ) def __UpperCAmelCase ( self ) -> Any: # We do this test only for DPTForDepthEstimation since it is the only model that uses readout_type UpperCAmelCase__ , UpperCAmelCase__ =self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase__ ="add" with self.assertRaises(A_ ): UpperCAmelCase__ =DPTForDepthEstimation(A_ ) def _UpperCAmelCase ( ): '''simple docstring''' UpperCAmelCase__ =Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision @slow class snake_case_ ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ) -> Union[str, Any]: UpperCAmelCase__ =DPTImageProcessor.from_pretrained("Intel/dpt-hybrid-midas" ) UpperCAmelCase__ =DPTForDepthEstimation.from_pretrained("Intel/dpt-hybrid-midas" ).to(A_ ) UpperCAmelCase__ =prepare_img() UpperCAmelCase__ =image_processor(images=A_, return_tensors="pt" ).to(A_ ) # forward pass with torch.no_grad(): UpperCAmelCase__ =model(**A_ ) UpperCAmelCase__ =outputs.predicted_depth # verify the predicted depth UpperCAmelCase__ =torch.Size((1, 384, 384) ) self.assertEqual(predicted_depth.shape, A_ ) UpperCAmelCase__ =torch.tensor( [[[5.64_37, 5.61_46, 5.65_11], [5.43_71, 5.56_49, 5.59_58], [5.52_15, 5.51_84, 5.52_93]]] ).to(A_ ) self.assertTrue(torch.allclose(outputs.predicted_depth[:3, :3, :3] / 100, A_, atol=1E-4 ) )
625
1
import itertools import random import unittest import numpy as np from transformers import is_speech_available from transformers.testing_utils import require_torch, require_torchaudio from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import SpeechaTextFeatureExtractor UpperCAmelCase_ = random.Random() def lowerCAmelCase_ ( __UpperCAmelCase: Dict , __UpperCAmelCase: Optional[Any]=1.0 , __UpperCAmelCase: Tuple=None , __UpperCAmelCase: str=None ) -> List[Any]: if rng is None: UpperCamelCase__ : Optional[Any] = global_rng UpperCamelCase__ : str = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch @require_torchaudio class lowercase__ ( unittest.TestCase ): '''simple docstring''' def __init__( self, __magic_name__, __magic_name__=7, __magic_name__=400, __magic_name__=2000, __magic_name__=24, __magic_name__=24, __magic_name__=0.0, __magic_name__=16000, __magic_name__=True, __magic_name__=True, ) -> int: """simple docstring""" UpperCamelCase__ : int = parent UpperCamelCase__ : Dict = batch_size UpperCamelCase__ : Optional[Any] = min_seq_length UpperCamelCase__ : str = max_seq_length UpperCamelCase__ : Optional[int] = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) UpperCamelCase__ : Any = feature_size UpperCamelCase__ : Dict = num_mel_bins UpperCamelCase__ : Union[str, Any] = padding_value UpperCamelCase__ : str = sampling_rate UpperCamelCase__ : List[str] = return_attention_mask UpperCamelCase__ : Dict = do_normalize def UpperCamelCase__ ( self ) -> Optional[Any]: """simple docstring""" return { "feature_size": self.feature_size, "num_mel_bins": self.num_mel_bins, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def UpperCamelCase__ ( self, __magic_name__=False, __magic_name__=False ) -> Optional[int]: """simple docstring""" def _flatten(__magic_name__ ): return list(itertools.chain(*A_ ) ) if equal_length: UpperCamelCase__ : Optional[int] = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size UpperCamelCase__ : Dict = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length, self.max_seq_length, self.seq_length_diff ) ] if numpify: UpperCamelCase__ : Union[str, Any] = [np.asarray(A_ ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class lowercase__ ( _SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' a : Optional[int] = SpeechaTextFeatureExtractor if is_speech_available() else None def UpperCamelCase__ ( self ) -> int: """simple docstring""" UpperCamelCase__ : Optional[int] = SpeechaTextFeatureExtractionTester(self ) def UpperCamelCase__ ( self, __magic_name__ ) -> Optional[Any]: """simple docstring""" self.assertTrue(np.all(np.mean(A_, axis=0 ) < 1E-3 ) ) self.assertTrue(np.all(np.abs(np.var(A_, axis=0 ) - 1 ) < 1E-3 ) ) def UpperCamelCase__ ( self ) -> Tuple: """simple docstring""" UpperCamelCase__ : Union[str, Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 UpperCamelCase__ : Union[str, Any] = [floats_list((1, x) )[0] for x in range(800, 1400, 200 )] UpperCamelCase__ : List[Any] = [np.asarray(A_ ) for speech_input in speech_inputs] # Test feature size UpperCamelCase__ : Dict = feature_extractor(A_, padding=A_, return_tensors='''np''' ).input_features self.assertTrue(input_features.ndim == 3 ) self.assertTrue(input_features.shape[-1] == feature_extractor.feature_size ) # Test not batched input UpperCamelCase__ : List[str] = feature_extractor(speech_inputs[0], return_tensors='''np''' ).input_features UpperCamelCase__ : List[str] = feature_extractor(np_speech_inputs[0], return_tensors='''np''' ).input_features self.assertTrue(np.allclose(A_, A_, atol=1E-3 ) ) # Test batched UpperCamelCase__ : List[str] = feature_extractor(A_, return_tensors='''np''' ).input_features UpperCamelCase__ : Tuple = feature_extractor(A_, return_tensors='''np''' ).input_features for enc_seq_a, enc_seq_a in zip(A_, A_ ): self.assertTrue(np.allclose(A_, A_, atol=1E-3 ) ) # Test 2-D numpy arrays are batched. UpperCamelCase__ : Any = [floats_list((1, x) )[0] for x in (800, 800, 800)] UpperCamelCase__ : str = np.asarray(A_ ) UpperCamelCase__ : str = feature_extractor(A_, return_tensors='''np''' ).input_features UpperCamelCase__ : Dict = feature_extractor(A_, return_tensors='''np''' ).input_features for enc_seq_a, enc_seq_a in zip(A_, A_ ): self.assertTrue(np.allclose(A_, A_, atol=1E-3 ) ) def UpperCamelCase__ ( self ) -> List[Any]: """simple docstring""" UpperCamelCase__ : Tuple = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCamelCase__ : int = [floats_list((1, x) )[0] for x in range(800, 1400, 200 )] UpperCamelCase__ : Union[str, Any] = ['''longest''', '''max_length''', '''do_not_pad'''] UpperCamelCase__ : List[Any] = [None, 16, None] for max_length, padding in zip(A_, A_ ): UpperCamelCase__ : Optional[int] = feature_extractor( A_, padding=A_, max_length=A_, return_attention_mask=A_ ) UpperCamelCase__ : List[str] = inputs.input_features UpperCamelCase__ : List[str] = inputs.attention_mask UpperCamelCase__ : str = [np.sum(A_ ) for x in attention_mask] self._check_zero_mean_unit_variance(input_features[0][: fbank_feat_lengths[0]] ) self._check_zero_mean_unit_variance(input_features[1][: fbank_feat_lengths[1]] ) self._check_zero_mean_unit_variance(input_features[2][: fbank_feat_lengths[2]] ) def UpperCamelCase__ ( self ) -> Dict: """simple docstring""" UpperCamelCase__ : Dict = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCamelCase__ : List[Any] = [floats_list((1, x) )[0] for x in range(800, 1400, 200 )] UpperCamelCase__ : Union[str, Any] = ['''longest''', '''max_length''', '''do_not_pad'''] UpperCamelCase__ : List[str] = [None, 16, None] for max_length, padding in zip(A_, A_ ): UpperCamelCase__ : List[Any] = feature_extractor( A_, max_length=A_, padding=A_, return_tensors='''np''', return_attention_mask=A_ ) UpperCamelCase__ : str = inputs.input_features UpperCamelCase__ : Tuple = inputs.attention_mask UpperCamelCase__ : str = [np.sum(A_ ) for x in attention_mask] self._check_zero_mean_unit_variance(input_features[0][: fbank_feat_lengths[0]] ) self.assertTrue(input_features[0][fbank_feat_lengths[0] :].sum() < 1E-6 ) self._check_zero_mean_unit_variance(input_features[1][: fbank_feat_lengths[1]] ) self.assertTrue(input_features[0][fbank_feat_lengths[1] :].sum() < 1E-6 ) self._check_zero_mean_unit_variance(input_features[2][: fbank_feat_lengths[2]] ) def UpperCamelCase__ ( self ) -> Dict: """simple docstring""" UpperCamelCase__ : List[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCamelCase__ : Optional[Any] = [floats_list((1, x) )[0] for x in range(800, 1400, 200 )] UpperCamelCase__ : List[Any] = feature_extractor( A_, padding='''max_length''', max_length=4, truncation=A_, return_tensors='''np''', return_attention_mask=A_, ) UpperCamelCase__ : Union[str, Any] = inputs.input_features UpperCamelCase__ : Dict = inputs.attention_mask UpperCamelCase__ : Tuple = np.sum(attention_mask == 1, axis=1 ) self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]] ) self._check_zero_mean_unit_variance(input_features[1] ) self._check_zero_mean_unit_variance(input_features[2] ) def UpperCamelCase__ ( self ) -> Optional[int]: """simple docstring""" UpperCamelCase__ : List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCamelCase__ : Any = [floats_list((1, x) )[0] for x in range(800, 1400, 200 )] UpperCamelCase__ : Any = feature_extractor( A_, padding='''longest''', max_length=4, truncation=A_, return_tensors='''np''', return_attention_mask=A_, ) UpperCamelCase__ : List[Any] = inputs.input_features UpperCamelCase__ : Dict = inputs.attention_mask UpperCamelCase__ : str = np.sum(attention_mask == 1, axis=1 ) self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]] ) self._check_zero_mean_unit_variance(input_features[1, : fbank_feat_lengths[1]] ) self._check_zero_mean_unit_variance(input_features[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertEqual(input_features.shape, (3, 4, 24) ) UpperCamelCase__ : List[Any] = [floats_list((1, x) )[0] for x in range(800, 1400, 200 )] UpperCamelCase__ : List[Any] = feature_extractor( A_, padding='''longest''', max_length=16, truncation=A_, return_tensors='''np''', return_attention_mask=A_, ) UpperCamelCase__ : str = inputs.input_features UpperCamelCase__ : str = inputs.attention_mask UpperCamelCase__ : Optional[Any] = np.sum(attention_mask == 1, axis=1 ) self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]] ) self._check_zero_mean_unit_variance(input_features[1, : fbank_feat_lengths[1]] ) self._check_zero_mean_unit_variance(input_features[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertEqual(input_features.shape, (3, 6, 24) ) def UpperCamelCase__ ( self ) -> Dict: """simple docstring""" import torch UpperCamelCase__ : Dict = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCamelCase__ : Tuple = np.random.rand(100, 32 ).astype(np.floataa ) UpperCamelCase__ : Any = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: UpperCamelCase__ : str = feature_extractor.pad([{'''input_features''': inputs}], return_tensors='''np''' ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) UpperCamelCase__ : List[str] = feature_extractor.pad([{'''input_features''': inputs}], return_tensors='''pt''' ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def UpperCamelCase__ ( self, __magic_name__ ) -> Optional[Any]: """simple docstring""" from datasets import load_dataset UpperCamelCase__ : int = load_dataset('''hf-internal-testing/librispeech_asr_dummy''', '''clean''', split='''validation''' ) # automatic decoding with librispeech UpperCamelCase__ : Union[str, Any] = ds.sort('''id''' ).select(range(A_ ) )[:num_samples]['''audio'''] return [x["array"] for x in speech_samples] def UpperCamelCase__ ( self ) -> int: """simple docstring""" UpperCamelCase__ : Tuple = np.array([ -1.5745, -1.7713, -1.7020, -1.6069, -1.2250, -1.1105, -0.9072, -0.8241, -1.2310, -0.8098, -0.3320, -0.4101, -0.7985, -0.4996, -0.8213, -0.9128, -1.0420, -1.1286, -1.0440, -0.7999, -0.8405, -1.2275, -1.5443, -1.4625, ] ) # fmt: on UpperCamelCase__ : Union[str, Any] = self._load_datasamples(1 ) UpperCamelCase__ : Any = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCamelCase__ : Optional[Any] = feature_extractor(A_, return_tensors='''pt''' ).input_features self.assertEquals(input_features.shape, (1, 584, 24) ) self.assertTrue(np.allclose(input_features[0, 0, :30], A_, atol=1E-4 ) )
703
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 YolosConfig, YolosForObjectDetection, YolosImageProcessor from transformers.utils import logging logging.set_verbosity_info() UpperCAmelCase_ = logging.get_logger(__name__) def lowerCAmelCase_ ( __UpperCAmelCase: str ) -> YolosConfig: UpperCamelCase__ : str = YolosConfig() # size of the architecture if "yolos_ti" in yolos_name: UpperCamelCase__ : Dict = 192 UpperCamelCase__ : Dict = 768 UpperCamelCase__ : Optional[Any] = 12 UpperCamelCase__ : List[Any] = 3 UpperCamelCase__ : Optional[int] = [800, 1333] UpperCamelCase__ : Tuple = False elif yolos_name == "yolos_s_dWr": UpperCamelCase__ : int = 330 UpperCamelCase__ : Tuple = 14 UpperCamelCase__ : str = 6 UpperCamelCase__ : Optional[int] = 1320 elif "yolos_s" in yolos_name: UpperCamelCase__ : Optional[int] = 384 UpperCamelCase__ : Any = 1536 UpperCamelCase__ : Union[str, Any] = 12 UpperCamelCase__ : int = 6 elif "yolos_b" in yolos_name: UpperCamelCase__ : Dict = [800, 1344] UpperCamelCase__ : List[Any] = 91 UpperCamelCase__ : str = '''huggingface/label-files''' UpperCamelCase__ : Dict = '''coco-detection-id2label.json''' UpperCamelCase__ : List[str] = json.load(open(hf_hub_download(__UpperCAmelCase , __UpperCAmelCase , repo_type='''dataset''' ) , '''r''' ) ) UpperCamelCase__ : str = {int(__UpperCAmelCase ): v for k, v in idalabel.items()} UpperCamelCase__ : str = idalabel UpperCamelCase__ : Optional[int] = {v: k for k, v in idalabel.items()} return config def lowerCAmelCase_ ( __UpperCAmelCase: dict , __UpperCAmelCase: YolosConfig , __UpperCAmelCase: bool = False ) -> str: for i in range(config.num_hidden_layers ): # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) UpperCamelCase__ : str = state_dict.pop(f"blocks.{i}.attn.qkv.weight" ) UpperCamelCase__ : Dict = state_dict.pop(f"blocks.{i}.attn.qkv.bias" ) # next, add query, keys and values (in that order) to the state dict UpperCamelCase__ : List[str] = in_proj_weight[: config.hidden_size, :] UpperCamelCase__ : Any = in_proj_bias[: config.hidden_size] UpperCamelCase__ : Tuple = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] UpperCamelCase__ : List[str] = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] UpperCamelCase__ : Optional[int] = in_proj_weight[-config.hidden_size :, :] UpperCamelCase__ : Optional[int] = in_proj_bias[-config.hidden_size :] def lowerCAmelCase_ ( __UpperCAmelCase: str ) -> str: if "backbone" in name: UpperCamelCase__ : str = name.replace('''backbone''' , '''vit''' ) if "cls_token" in name: UpperCamelCase__ : str = name.replace('''cls_token''' , '''embeddings.cls_token''' ) if "det_token" in name: UpperCamelCase__ : str = name.replace('''det_token''' , '''embeddings.detection_tokens''' ) if "mid_pos_embed" in name: UpperCamelCase__ : List[str] = name.replace('''mid_pos_embed''' , '''encoder.mid_position_embeddings''' ) if "pos_embed" in name: UpperCamelCase__ : List[Any] = name.replace('''pos_embed''' , '''embeddings.position_embeddings''' ) if "patch_embed.proj" in name: UpperCamelCase__ : Any = name.replace('''patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' ) if "blocks" in name: UpperCamelCase__ : Union[str, Any] = name.replace('''blocks''' , '''encoder.layer''' ) if "attn.proj" in name: UpperCamelCase__ : Dict = name.replace('''attn.proj''' , '''attention.output.dense''' ) if "attn" in name: UpperCamelCase__ : Optional[int] = name.replace('''attn''' , '''attention.self''' ) if "norm1" in name: UpperCamelCase__ : int = name.replace('''norm1''' , '''layernorm_before''' ) if "norm2" in name: UpperCamelCase__ : str = name.replace('''norm2''' , '''layernorm_after''' ) if "mlp.fc1" in name: UpperCamelCase__ : Optional[Any] = name.replace('''mlp.fc1''' , '''intermediate.dense''' ) if "mlp.fc2" in name: UpperCamelCase__ : List[str] = name.replace('''mlp.fc2''' , '''output.dense''' ) if "class_embed" in name: UpperCamelCase__ : List[Any] = name.replace('''class_embed''' , '''class_labels_classifier''' ) if "bbox_embed" in name: UpperCamelCase__ : Optional[int] = name.replace('''bbox_embed''' , '''bbox_predictor''' ) if "vit.norm" in name: UpperCamelCase__ : Tuple = name.replace('''vit.norm''' , '''vit.layernorm''' ) return name def lowerCAmelCase_ ( __UpperCAmelCase: dict , __UpperCAmelCase: YolosForObjectDetection ) -> dict: for key in orig_state_dict.copy().keys(): UpperCamelCase__ : Union[str, Any] = orig_state_dict.pop(__UpperCAmelCase ) if "qkv" in key: UpperCamelCase__ : Optional[int] = key.split('''.''' ) UpperCamelCase__ : Union[str, Any] = int(key_split[2] ) UpperCamelCase__ : Tuple = model.vit.encoder.layer[layer_num].attention.attention.all_head_size if "weight" in key: UpperCamelCase__ : Dict = val[:dim, :] UpperCamelCase__ : int = val[ dim : dim * 2, : ] UpperCamelCase__ : Dict = val[-dim:, :] else: UpperCamelCase__ : List[Any] = val[:dim] UpperCamelCase__ : List[str] = val[dim : dim * 2] UpperCamelCase__ : int = val[-dim:] else: UpperCamelCase__ : Union[str, Any] = val return orig_state_dict def lowerCAmelCase_ ( ) -> torch.Tensor: UpperCamelCase__ : str = '''http://images.cocodataset.org/val2017/000000039769.jpg''' UpperCamelCase__ : Dict = Image.open(requests.get(__UpperCAmelCase , stream=__UpperCAmelCase ).raw ) return im @torch.no_grad() def lowerCAmelCase_ ( __UpperCAmelCase: str , __UpperCAmelCase: str , __UpperCAmelCase: str , __UpperCAmelCase: bool = False ) -> Optional[int]: UpperCamelCase__ : List[str] = get_yolos_config(__UpperCAmelCase ) # load original state_dict UpperCamelCase__ : List[Any] = torch.load(__UpperCAmelCase , map_location='''cpu''' )['''model'''] # load 🤗 model UpperCamelCase__ : List[Any] = YolosForObjectDetection(__UpperCAmelCase ) model.eval() UpperCamelCase__ : Dict = convert_state_dict(__UpperCAmelCase , __UpperCAmelCase ) model.load_state_dict(__UpperCAmelCase ) # Check outputs on an image, prepared by YolosImageProcessor UpperCamelCase__ : List[Any] = 800 if yolos_name != '''yolos_ti''' else 512 UpperCamelCase__ : int = YolosImageProcessor(format='''coco_detection''' , size=__UpperCAmelCase ) UpperCamelCase__ : Union[str, Any] = image_processor(images=prepare_img() , return_tensors='''pt''' ) UpperCamelCase__ : Dict = model(**__UpperCAmelCase ) UpperCamelCase__ ,UpperCamelCase__ : Optional[Any] = outputs.logits, outputs.pred_boxes UpperCamelCase__ ,UpperCamelCase__ : int = None, None if yolos_name == "yolos_ti": UpperCamelCase__ : List[str] = torch.tensor( [[-39.5022, -11.9820, -17.6888], [-29.9574, -9.9769, -17.7691], [-42.3281, -20.7200, -30.6294]] ) UpperCamelCase__ : Dict = torch.tensor( [[0.4021, 0.0836, 0.7979], [0.0184, 0.2609, 0.0364], [0.1781, 0.2004, 0.2095]] ) elif yolos_name == "yolos_s_200_pre": UpperCamelCase__ : Optional[int] = torch.tensor( [[-24.0248, -10.3024, -14.8290], [-42.0392, -16.8200, -27.4334], [-27.2743, -11.8154, -18.7148]] ) UpperCamelCase__ : Union[str, Any] = torch.tensor( [[0.2559, 0.5455, 0.4706], [0.2989, 0.7279, 0.1875], [0.7732, 0.4017, 0.4462]] ) elif yolos_name == "yolos_s_300_pre": UpperCamelCase__ : Optional[Any] = torch.tensor( [[-36.2220, -14.4385, -23.5457], [-35.6970, -14.7583, -21.3935], [-31.5939, -13.6042, -16.8049]] ) UpperCamelCase__ : List[Any] = torch.tensor( [[0.7614, 0.2316, 0.4728], [0.7168, 0.4495, 0.3855], [0.4996, 0.1466, 0.9996]] ) elif yolos_name == "yolos_s_dWr": UpperCamelCase__ : Any = torch.tensor( [[-42.8668, -24.1049, -41.1690], [-34.7456, -14.1274, -24.9194], [-33.7898, -12.1946, -25.6495]] ) UpperCamelCase__ : List[Any] = torch.tensor( [[0.5587, 0.2773, 0.0605], [0.5004, 0.3014, 0.9994], [0.4999, 0.1548, 0.9994]] ) elif yolos_name == "yolos_base": UpperCamelCase__ : Optional[Any] = torch.tensor( [[-40.6064, -24.3084, -32.6447], [-55.1990, -30.7719, -35.5877], [-51.4311, -33.3507, -35.6462]] ) UpperCamelCase__ : List[Any] = torch.tensor( [[0.5555, 0.2794, 0.0655], [0.9049, 0.2664, 0.1894], [0.9183, 0.1984, 0.1635]] ) else: raise ValueError(f"Unknown yolos_name: {yolos_name}" ) assert torch.allclose(logits[0, :3, :3] , __UpperCAmelCase , atol=1e-4 ) assert torch.allclose(pred_boxes[0, :3, :3] , __UpperCAmelCase , atol=1e-4 ) Path(__UpperCAmelCase ).mkdir(exist_ok=__UpperCAmelCase ) print(f"Saving model {yolos_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: UpperCamelCase__ : Any = { '''yolos_ti''': '''yolos-tiny''', '''yolos_s_200_pre''': '''yolos-small''', '''yolos_s_300_pre''': '''yolos-small-300''', '''yolos_s_dWr''': '''yolos-small-dwr''', '''yolos_base''': '''yolos-base''', } print('''Pushing to the hub...''' ) UpperCamelCase__ : Optional[int] = model_mapping[yolos_name] image_processor.push_to_hub(__UpperCAmelCase , organization='''hustvl''' ) model.push_to_hub(__UpperCAmelCase , organization='''hustvl''' ) if __name__ == "__main__": UpperCAmelCase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--yolos_name', default='yolos_s_200_pre', type=str, help=( 'Name of the YOLOS model you\'d like to convert. Should be one of \'yolos_ti\', \'yolos_s_200_pre\',' ' \'yolos_s_300_pre\', \'yolos_s_dWr\', \'yolos_base\'.' ), ) parser.add_argument( '--checkpoint_path', default=None, type=str, help='Path to the original state dict (.pth file).' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.' ) UpperCAmelCase_ = parser.parse_args() convert_yolos_checkpoint(args.yolos_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub)
369
0
import gc import random import unittest import numpy as np import torch from PIL import Image from diffusers import ( DDIMScheduler, KandinskyVaaControlnetImgaImgPipeline, KandinskyVaaPriorEmbaEmbPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class snake_case_ ( __A , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = KandinskyVaaControlnetImgaImgPipeline SCREAMING_SNAKE_CASE : int = ["image_embeds", "negative_image_embeds", "image", "hint"] SCREAMING_SNAKE_CASE : List[str] = ["image_embeds", "negative_image_embeds", "image", "hint"] SCREAMING_SNAKE_CASE : Any = [ "generator", "height", "width", "strength", "guidance_scale", "num_inference_steps", "return_dict", "guidance_scale", "num_images_per_prompt", "output_type", "return_dict", ] SCREAMING_SNAKE_CASE : Tuple = False @property def snake_case__( self : Optional[Any] ) ->Tuple: return 3_2 @property def snake_case__( self : Dict ) ->Tuple: return 3_2 @property def snake_case__( self : List[str] ) ->Dict: return self.time_input_dim @property def snake_case__( self : Optional[Any] ) ->List[str]: return self.time_input_dim * 4 @property def snake_case__( self : Any ) ->Optional[Any]: return 1_0_0 @property def snake_case__( self : Union[str, Any] ) ->str: torch.manual_seed(0 ) snake_case_ = { '''in_channels''': 8, # Out channels is double in channels because predicts mean and variance '''out_channels''': 8, '''addition_embed_type''': '''image_hint''', '''down_block_types''': ('''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D'''), '''up_block_types''': ('''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''), '''mid_block_type''': '''UNetMidBlock2DSimpleCrossAttn''', '''block_out_channels''': (self.block_out_channels_a, self.block_out_channels_a * 2), '''layers_per_block''': 1, '''encoder_hid_dim''': self.text_embedder_hidden_size, '''encoder_hid_dim_type''': '''image_proj''', '''cross_attention_dim''': self.cross_attention_dim, '''attention_head_dim''': 4, '''resnet_time_scale_shift''': '''scale_shift''', '''class_embed_type''': None, } snake_case_ = UNetaDConditionModel(**_UpperCamelCase ) return model @property def snake_case__( self : Any ) ->Optional[int]: return { "block_out_channels": [3_2, 3_2, 6_4, 6_4], "down_block_types": [ "DownEncoderBlock2D", "DownEncoderBlock2D", "DownEncoderBlock2D", "AttnDownEncoderBlock2D", ], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 1_2, "out_channels": 3, "up_block_types": ["AttnUpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"], "vq_embed_dim": 4, } @property def snake_case__( self : int ) ->int: torch.manual_seed(0 ) snake_case_ = VQModel(**self.dummy_movq_kwargs ) return model def snake_case__( self : Optional[Any] ) ->Union[str, Any]: snake_case_ = self.dummy_unet snake_case_ = self.dummy_movq snake_case_ = { '''num_train_timesteps''': 1_0_0_0, '''beta_schedule''': '''linear''', '''beta_start''': 0.00085, '''beta_end''': 0.012, '''clip_sample''': False, '''set_alpha_to_one''': False, '''steps_offset''': 0, '''prediction_type''': '''epsilon''', '''thresholding''': False, } snake_case_ = DDIMScheduler(**_UpperCamelCase ) snake_case_ = { '''unet''': unet, '''scheduler''': scheduler, '''movq''': movq, } return components def snake_case__( self : Dict , _UpperCamelCase : Union[str, Any] , _UpperCamelCase : Union[str, Any]=0 ) ->List[str]: snake_case_ = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(_UpperCamelCase ) ).to(_UpperCamelCase ) snake_case_ = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( _UpperCamelCase ) # create init_image snake_case_ = floats_tensor((1, 3, 6_4, 6_4) , rng=random.Random(_UpperCamelCase ) ).to(_UpperCamelCase ) snake_case_ = image.cpu().permute(0 , 2 , 3 , 1 )[0] snake_case_ = Image.fromarray(np.uinta(_UpperCamelCase ) ).convert('''RGB''' ).resize((2_5_6, 2_5_6) ) # create hint snake_case_ = floats_tensor((1, 3, 6_4, 6_4) , rng=random.Random(_UpperCamelCase ) ).to(_UpperCamelCase ) if str(_UpperCamelCase ).startswith('''mps''' ): snake_case_ = torch.manual_seed(_UpperCamelCase ) else: snake_case_ = torch.Generator(device=_UpperCamelCase ).manual_seed(_UpperCamelCase ) snake_case_ = { '''image''': init_image, '''image_embeds''': image_embeds, '''negative_image_embeds''': negative_image_embeds, '''hint''': hint, '''generator''': generator, '''height''': 6_4, '''width''': 6_4, '''num_inference_steps''': 1_0, '''guidance_scale''': 7.0, '''strength''': 0.2, '''output_type''': '''np''', } return inputs def snake_case__( self : Tuple ) ->Optional[Any]: snake_case_ = '''cpu''' snake_case_ = self.get_dummy_components() snake_case_ = self.pipeline_class(**_UpperCamelCase ) snake_case_ = pipe.to(_UpperCamelCase ) pipe.set_progress_bar_config(disable=_UpperCamelCase ) snake_case_ = pipe(**self.get_dummy_inputs(_UpperCamelCase ) ) snake_case_ = output.images snake_case_ = pipe( **self.get_dummy_inputs(_UpperCamelCase ) , return_dict=_UpperCamelCase , )[0] snake_case_ = image[0, -3:, -3:, -1] snake_case_ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 6_4, 6_4, 3) snake_case_ = np.array( [0.54985034, 0.55509365, 0.52561504, 0.5570494, 0.5593818, 0.5263979, 0.50285643, 0.5069846, 0.51196736] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), f''' expected_slice {expected_slice}, but got {image_slice.flatten()}''' assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), f''' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}''' @slow @require_torch_gpu class snake_case_ ( unittest.TestCase ): '''simple docstring''' def snake_case__( self : Tuple ) ->List[Any]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def snake_case__( self : Tuple ) ->Union[str, Any]: snake_case_ = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinskyv22/kandinskyv22_controlnet_img2img_robotcat_fp16.npy''' ) snake_case_ = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinsky/cat.png''' ) snake_case_ = init_image.resize((5_1_2, 5_1_2) ) snake_case_ = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinskyv22/hint_image_cat.png''' ) snake_case_ = torch.from_numpy(np.array(_UpperCamelCase ) ).float() / 255.0 snake_case_ = hint.permute(2 , 0 , 1 ).unsqueeze(0 ) snake_case_ = '''A robot, 4k photo''' snake_case_ = KandinskyVaaPriorEmbaEmbPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-prior''' , torch_dtype=torch.floataa ) pipe_prior.to(_UpperCamelCase ) snake_case_ = KandinskyVaaControlnetImgaImgPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-controlnet-depth''' , torch_dtype=torch.floataa ) snake_case_ = pipeline.to(_UpperCamelCase ) pipeline.set_progress_bar_config(disable=_UpperCamelCase ) snake_case_ = torch.Generator(device='''cpu''' ).manual_seed(0 ) snake_case_, snake_case_ = pipe_prior( _UpperCamelCase , image=_UpperCamelCase , strength=0.85 , generator=_UpperCamelCase , negative_prompt='''''' , ).to_tuple() snake_case_ = pipeline( image=_UpperCamelCase , image_embeds=_UpperCamelCase , negative_image_embeds=_UpperCamelCase , hint=_UpperCamelCase , generator=_UpperCamelCase , num_inference_steps=1_0_0 , height=5_1_2 , width=5_1_2 , strength=0.5 , output_type='''np''' , ) snake_case_ = output.images[0] assert image.shape == (5_1_2, 5_1_2, 3) assert_mean_pixel_difference(_UpperCamelCase , _UpperCamelCase )
39
'''simple docstring''' def lowercase__ ( __UpperCamelCase )-> bool: UpperCamelCase = (1 + 24 * n) ** 0.5 return ((1 + root) / 6) % 1 == 0 def lowercase__ ( __UpperCamelCase = 5000 )-> int: UpperCamelCase = [(i * (3 * i - 1)) // 2 for i in range(1 , __UpperCamelCase )] for i, pentagonal_i in enumerate(__UpperCamelCase ): for j in range(__UpperCamelCase , len(__UpperCamelCase ) ): UpperCamelCase = pentagonal_nums[j] UpperCamelCase = pentagonal_i + pentagonal_j UpperCamelCase = pentagonal_j - pentagonal_i if is_pentagonal(__UpperCamelCase ) and is_pentagonal(__UpperCamelCase ): return b return -1 if __name__ == "__main__": print(f'{solution() = }')
301
0
"""simple docstring""" def lowerCamelCase__ ( ): '''simple docstring''' _lowerCAmelCase : Tuple = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] _lowerCAmelCase : str = 6 _lowerCAmelCase : Any = 1 _lowerCAmelCase : int = 1901 _lowerCAmelCase : Union[str, Any] = 0 while year < 2001: day += 7 if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0): if day > days_per_month[month - 1] and month != 2: month += 1 _lowerCAmelCase : List[str] = day - days_per_month[month - 2] elif day > 29 and month == 2: month += 1 _lowerCAmelCase : Dict = day - 29 else: if day > days_per_month[month - 1]: month += 1 _lowerCAmelCase : Any = day - days_per_month[month - 2] if month > 12: year += 1 _lowerCAmelCase : str = 1 if year < 2001 and day == 1: sundays += 1 return sundays if __name__ == "__main__": print(solution())
16
"""simple docstring""" from __future__ import annotations import json import requests from bsa import BeautifulSoup from fake_useragent import UserAgent _lowerCAmelCase = {"""UserAgent""": UserAgent().random} def lowerCamelCase__ ( _lowerCamelCase ): '''simple docstring''' _lowerCAmelCase : Any = script.contents[0] _lowerCAmelCase : Union[str, Any] = json.loads(data[data.find('{"config"' ) : -1] ) return info["entry_data"]["ProfilePage"][0]["graphql"]["user"] class __UpperCamelCase : def __init__( self ,_A ): '''simple docstring''' _lowerCAmelCase : Optional[Any] = F"""https://www.instagram.com/{username}/""" _lowerCAmelCase : str = self.get_json() def __lowerCamelCase ( self ): '''simple docstring''' _lowerCAmelCase : str = requests.get(self.url ,headers=_A ).text _lowerCAmelCase : Optional[Any] = BeautifulSoup(_A ,'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 ): '''simple docstring''' return F"""{self.__class__.__name__}('{self.username}')""" def __str__( self ): '''simple docstring''' return F"""{self.fullname} ({self.username}) is {self.biography}""" @property def __lowerCamelCase ( self ): '''simple docstring''' return self.user_data["username"] @property def __lowerCamelCase ( self ): '''simple docstring''' return self.user_data["full_name"] @property def __lowerCamelCase ( self ): '''simple docstring''' return self.user_data["biography"] @property def __lowerCamelCase ( self ): '''simple docstring''' return self.user_data["business_email"] @property def __lowerCamelCase ( self ): '''simple docstring''' return self.user_data["external_url"] @property def __lowerCamelCase ( self ): '''simple docstring''' return self.user_data["edge_followed_by"]["count"] @property def __lowerCamelCase ( self ): '''simple docstring''' return self.user_data["edge_follow"]["count"] @property def __lowerCamelCase ( self ): '''simple docstring''' return self.user_data["edge_owner_to_timeline_media"]["count"] @property def __lowerCamelCase ( self ): '''simple docstring''' return self.user_data["profile_pic_url_hd"] @property def __lowerCamelCase ( self ): '''simple docstring''' return self.user_data["is_verified"] @property def __lowerCamelCase ( self ): '''simple docstring''' return self.user_data["is_private"] def lowerCamelCase__ ( _lowerCamelCase = "github" ): '''simple docstring''' import os if os.environ.get('CI' ): return # test failing on GitHub Actions _lowerCAmelCase : Tuple = InstagramUser(_lowerCamelCase ) assert instagram_user.user_data assert isinstance(instagram_user.user_data , _lowerCamelCase ) 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 > 120000 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() _lowerCAmelCase = 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 = }''')
16
1
def __lowerCAmelCase ( _UpperCamelCase : int = 10 , _UpperCamelCase : int = 10_00 , _UpperCamelCase : bool = True ) -> int: '''simple docstring''' assert ( isinstance(_UpperCamelCase , _UpperCamelCase ) and isinstance(_UpperCamelCase , _UpperCamelCase ) and isinstance(_UpperCamelCase , _UpperCamelCase ) ), "Invalid type of value(s) specified to function!" if min_val > max_val: raise ValueError('Invalid value for min_val or max_val (min_value < max_value)' ) return min_val if option else max_val def __lowerCAmelCase ( _UpperCamelCase : int , _UpperCamelCase : int ) -> int: '''simple docstring''' return int((number_a + number_a) / 2 ) def __lowerCAmelCase ( _UpperCamelCase : int , _UpperCamelCase : int , _UpperCamelCase : int ) -> None: '''simple docstring''' assert ( isinstance(_UpperCamelCase , _UpperCamelCase ) and isinstance(_UpperCamelCase , _UpperCamelCase ) and isinstance(_UpperCamelCase , _UpperCamelCase ) ), 'argument values must be type of "int"' if lower > higher: raise ValueError('argument value for lower and higher must be(lower > higher)' ) if not lower < to_guess < higher: raise ValueError( 'guess value must be within the range of lower and higher value' ) def answer(_UpperCamelCase : int ) -> str: if number > to_guess: return "high" elif number < to_guess: return "low" else: return "same" print('started...' ) SCREAMING_SNAKE_CASE = lower SCREAMING_SNAKE_CASE = higher SCREAMING_SNAKE_CASE = [] while True: SCREAMING_SNAKE_CASE = get_avg(_UpperCamelCase , _UpperCamelCase ) last_numbers.append(_UpperCamelCase ) if answer(_UpperCamelCase ) == "low": SCREAMING_SNAKE_CASE = number elif answer(_UpperCamelCase ) == "high": SCREAMING_SNAKE_CASE = number else: break print(f"""guess the number : {last_numbers[-1]}""" ) print(f"""details : {last_numbers!s}""" ) def __lowerCAmelCase ( ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE = int(input('Enter lower value : ' ).strip() ) SCREAMING_SNAKE_CASE = int(input('Enter high value : ' ).strip() ) SCREAMING_SNAKE_CASE = int(input('Enter value to guess : ' ).strip() ) guess_the_number(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) if __name__ == "__main__": main()
439
import argparse from transformers import BigBirdConfig, BigBirdForPreTraining, BigBirdForQuestionAnswering, load_tf_weights_in_big_bird from transformers.utils import logging logging.set_verbosity_info() def __lowerCAmelCase ( _UpperCamelCase : str , _UpperCamelCase : Union[str, Any] , _UpperCamelCase : Tuple , _UpperCamelCase : Tuple ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE = BigBirdConfig.from_json_file(_UpperCamelCase ) print(f"""Building PyTorch model from configuration: {config}""" ) if is_trivia_qa: SCREAMING_SNAKE_CASE = BigBirdForQuestionAnswering(_UpperCamelCase ) else: SCREAMING_SNAKE_CASE = BigBirdForPreTraining(_UpperCamelCase ) # Load weights from tf checkpoint load_tf_weights_in_big_bird(_UpperCamelCase , _UpperCamelCase , is_trivia_qa=_UpperCamelCase ) # Save pytorch-model print(f"""Save PyTorch model to {pytorch_dump_path}""" ) model.save_pretrained(_UpperCamelCase ) if __name__ == "__main__": a_ : int = argparse.ArgumentParser() # Required parameters parser.add_argument( "--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path." ) parser.add_argument( "--big_bird_config_file", default=None, type=str, required=True, help=( "The config json file corresponding to the pre-trained BERT model. \n" "This specifies the model architecture." ), ) parser.add_argument( "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) parser.add_argument( "--is_trivia_qa", action="store_true", help="Whether to convert a model with a trivia_qa head." ) a_ : Any = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.tf_checkpoint_path, args.big_bird_config_file, args.pytorch_dump_path, args.is_trivia_qa )
439
1
'''simple docstring''' def lowercase ( lowerCAmelCase : Any): """simple docstring""" if n == 1 or not isinstance(a__ , a__): return 0 elif n == 2: return 1 else: _A : List[str] = [0, 1] for i in range(2 , n + 1): sequence.append(sequence[i - 1] + sequence[i - 2]) return sequence[n] def lowercase ( lowerCAmelCase : Optional[Any]): """simple docstring""" _A : Optional[Any] = 0 _A : Dict = 2 while digits < n: index += 1 _A : Any = len(str(fibonacci(a__))) return index def lowercase ( lowerCAmelCase : int = 1000): """simple docstring""" return fibonacci_digits_index(a__) if __name__ == "__main__": print(solution(int(str(input()).strip())))
714
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_mvp import MvpTokenizer __UpperCamelCase : str = logging.get_logger(__name__) __UpperCamelCase : Dict = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} # See all MVP models at https://huggingface.co/models?filter=mvp __UpperCamelCase : Optional[Any] = { '''vocab_file''': { '''RUCAIBox/mvp''': '''https://huggingface.co/RUCAIBox/mvp/resolve/main/vocab.json''', }, '''added_tokens.json''': { '''RUCAIBox/mvp''': '''https://huggingface.co/RUCAIBox/mvp/resolve/main/added_tokens.json''', }, '''merges_file''': { '''RUCAIBox/mvp''': '''https://huggingface.co/RUCAIBox/mvp/resolve/main/merges.txt''', }, '''tokenizer_file''': { '''RUCAIBox/mvp''': '''https://huggingface.co/RUCAIBox/mvp/resolve/main/tokenizer.json''', }, } __UpperCamelCase : Tuple = { '''RUCAIBox/mvp''': 1024, } class lowerCamelCase__ ( snake_case_ ): """simple docstring""" __magic_name__ = VOCAB_FILES_NAMES __magic_name__ = PRETRAINED_VOCAB_FILES_MAP __magic_name__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __magic_name__ = ["""input_ids""", """attention_mask"""] __magic_name__ = MvpTokenizer def __init__( self , UpperCAmelCase__=None , UpperCAmelCase__=None , UpperCAmelCase__=None , UpperCAmelCase__="replace" , UpperCAmelCase__="<s>" , UpperCAmelCase__="</s>" , UpperCAmelCase__="</s>" , UpperCAmelCase__="<s>" , UpperCAmelCase__="<unk>" , UpperCAmelCase__="<pad>" , UpperCAmelCase__="<mask>" , UpperCAmelCase__=False , UpperCAmelCase__=True , **UpperCAmelCase__ , ) -> List[Any]: super().__init__( UpperCAmelCase__ , UpperCAmelCase__ , tokenizer_file=UpperCAmelCase__ , errors=UpperCAmelCase__ , bos_token=UpperCAmelCase__ , eos_token=UpperCAmelCase__ , sep_token=UpperCAmelCase__ , cls_token=UpperCAmelCase__ , unk_token=UpperCAmelCase__ , pad_token=UpperCAmelCase__ , mask_token=UpperCAmelCase__ , add_prefix_space=UpperCAmelCase__ , trim_offsets=UpperCAmelCase__ , **UpperCAmelCase__ , ) _A : Any = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get('''add_prefix_space''' , UpperCAmelCase__ ) != add_prefix_space: _A : Dict = getattr(UpperCAmelCase__ , pre_tok_state.pop('''type''' ) ) _A : List[Any] = add_prefix_space _A : Tuple = pre_tok_class(**UpperCAmelCase__ ) _A : List[Any] = add_prefix_space # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__` _A : Any = '''post_processor''' _A : Union[str, Any] = getattr(self.backend_tokenizer , UpperCAmelCase__ , UpperCAmelCase__ ) if tokenizer_component_instance: _A : Optional[int] = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: _A : int = tuple(state['''sep'''] ) if "cls" in state: _A : Union[str, Any] = tuple(state['''cls'''] ) _A : int = False if state.get('''add_prefix_space''' , UpperCAmelCase__ ) != add_prefix_space: _A : Optional[int] = add_prefix_space _A : Union[str, Any] = True if state.get('''trim_offsets''' , UpperCAmelCase__ ) != trim_offsets: _A : List[str] = trim_offsets _A : int = True if changes_to_apply: _A : Optional[int] = getattr(UpperCAmelCase__ , state.pop('''type''' ) ) _A : str = component_class(**UpperCAmelCase__ ) setattr(self.backend_tokenizer , UpperCAmelCase__ , UpperCAmelCase__ ) @property def _lowerCamelCase ( self ) -> str: if self._mask_token is None: if self.verbose: logger.error('''Using mask_token, but it is not set yet.''' ) return None return str(self._mask_token ) @mask_token.setter def _lowerCamelCase ( self , UpperCAmelCase__ ) -> Tuple: _A : Any = AddedToken(UpperCAmelCase__ , lstrip=UpperCAmelCase__ , rstrip=UpperCAmelCase__ ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) else value _A : Any = value def _lowerCamelCase ( self , *UpperCAmelCase__ , **UpperCAmelCase__ ) -> BatchEncoding: _A : Optional[int] = kwargs.get('''is_split_into_words''' , UpperCAmelCase__ ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ '''to use it with pretokenized inputs.''' ) return super()._batch_encode_plus(*UpperCAmelCase__ , **UpperCAmelCase__ ) def _lowerCamelCase ( self , *UpperCAmelCase__ , **UpperCAmelCase__ ) -> BatchEncoding: _A : int = kwargs.get('''is_split_into_words''' , UpperCAmelCase__ ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ '''to use it with pretokenized inputs.''' ) return super()._encode_plus(*UpperCAmelCase__ , **UpperCAmelCase__ ) def _lowerCamelCase ( self , UpperCAmelCase__ , UpperCAmelCase__ = None ) -> Tuple[str]: _A : List[Any] = self._tokenizer.model.save(UpperCAmelCase__ , name=UpperCAmelCase__ ) return tuple(UpperCAmelCase__ ) def _lowerCamelCase ( self , UpperCAmelCase__ , UpperCAmelCase__=None ) -> Tuple: _A : Dict = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def _lowerCamelCase ( self , UpperCAmelCase__ , UpperCAmelCase__ = None ) -> List[int]: _A : str = [self.sep_token_id] _A : Tuple = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
417
0
import unittest import numpy as np from transformers import DistilBertConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.distilbert.modeling_flax_distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, ) class __A ( unittest.TestCase ): """simple docstring""" def __init__( self , a__ , a__=13 , a__=7 , a__=True , a__=True , a__=True , a__=True , a__=99 , a__=32 , a__=5 , a__=4 , a__=37 , a__="gelu" , a__=0.1 , a__=0.1 , a__=512 , a__=16 , a__=2 , a__=0.02 , a__=4 , ): """simple docstring""" _lowerCamelCase : Tuple = parent _lowerCamelCase : Dict = batch_size _lowerCamelCase : str = seq_length _lowerCamelCase : int = is_training _lowerCamelCase : Dict = use_attention_mask _lowerCamelCase : List[str] = use_token_type_ids _lowerCamelCase : Union[str, Any] = use_labels _lowerCamelCase : Any = vocab_size _lowerCamelCase : Tuple = hidden_size _lowerCamelCase : Tuple = num_hidden_layers _lowerCamelCase : Dict = num_attention_heads _lowerCamelCase : str = intermediate_size _lowerCamelCase : int = hidden_act _lowerCamelCase : Dict = hidden_dropout_prob _lowerCamelCase : Tuple = attention_probs_dropout_prob _lowerCamelCase : Tuple = max_position_embeddings _lowerCamelCase : str = type_vocab_size _lowerCamelCase : str = type_sequence_label_size _lowerCamelCase : str = initializer_range _lowerCamelCase : str = num_choices def __snake_case ( self): """simple docstring""" _lowerCamelCase : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) _lowerCamelCase : Any = None if self.use_attention_mask: _lowerCamelCase : str = random_attention_mask([self.batch_size, self.seq_length]) _lowerCamelCase : Tuple = DistilBertConfig( vocab_size=self.vocab_size , dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , hidden_dim=self.intermediate_size , hidden_act=self.hidden_act , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , tie_weights_=a__ , ) return config, input_ids, attention_mask def __snake_case ( self): """simple docstring""" _lowerCamelCase : Tuple = self.prepare_config_and_inputs() _lowerCamelCase : Tuple = config_and_inputs _lowerCamelCase : Optional[Any] = {"""input_ids""": input_ids, """attention_mask""": attention_mask} return config, inputs_dict @require_flax class __A ( UpperCAmelCase__ ,unittest.TestCase ): """simple docstring""" UpperCAmelCase__ = ( ( FlaxDistilBertModel, FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertForQuestionAnswering, ) if is_flax_available() else () ) def __snake_case ( self): """simple docstring""" _lowerCamelCase : Dict = FlaxDistilBertModelTester(self) @slow def __snake_case ( self): """simple docstring""" for model_class_name in self.all_model_classes: _lowerCamelCase : str = model_class_name.from_pretrained('''distilbert-base-uncased''') _lowerCamelCase : List[str] = model(np.ones((1, 1))) self.assertIsNotNone(a__) @require_flax class __A ( unittest.TestCase ): """simple docstring""" @slow def __snake_case ( self): """simple docstring""" _lowerCamelCase : Union[str, Any] = FlaxDistilBertModel.from_pretrained('''distilbert-base-uncased''') _lowerCamelCase : Tuple = np.array([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]]) _lowerCamelCase : Any = np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]) _lowerCamelCase : Union[str, Any] = model(a__ , attention_mask=a__)[0] _lowerCamelCase : Union[str, Any] = (1, 11, 768) self.assertEqual(output.shape , a__) _lowerCamelCase : int = np.array([[[-0.1639, 0.3299, 0.1648], [-0.1746, 0.3289, 0.1710], [-0.1884, 0.3357, 0.1810]]]) self.assertTrue(jnp.allclose(output[:, 1:4, 1:4] , a__ , atol=1e-4))
114
"""simple docstring""" import warnings 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 _UpperCAmelCase = logging.get_logger(__name__) _UpperCAmelCase = { """nvidia/segformer-b0-finetuned-ade-512-512""": ( """https://huggingface.co/nvidia/segformer-b0-finetuned-ade-512-512/resolve/main/config.json""" ), # See all SegFormer models at https://huggingface.co/models?filter=segformer } class a ( UpperCAmelCase__ ): UpperCamelCase : str = 'segformer' def __init__( self : Tuple , lowerCAmelCase : str=3 , lowerCAmelCase : List[str]=4 , lowerCAmelCase : List[str]=[2, 2, 2, 2] , lowerCAmelCase : Optional[Any]=[8, 4, 2, 1] , lowerCAmelCase : Optional[int]=[32, 64, 160, 256] , lowerCAmelCase : int=[7, 3, 3, 3] , lowerCAmelCase : str=[4, 2, 2, 2] , lowerCAmelCase : str=[1, 2, 5, 8] , lowerCAmelCase : Union[str, Any]=[4, 4, 4, 4] , lowerCAmelCase : Union[str, Any]="gelu" , lowerCAmelCase : Optional[int]=0.0 , lowerCAmelCase : List[str]=0.0 , lowerCAmelCase : Optional[Any]=0.1 , lowerCAmelCase : str=0.0_2 , lowerCAmelCase : int=0.1 , lowerCAmelCase : Union[str, Any]=1E-6 , lowerCAmelCase : List[Any]=256 , lowerCAmelCase : Tuple=255 , **lowerCAmelCase : Tuple , ) -> Tuple: '''simple docstring''' super().__init__(**lowerCAmelCase ) if "reshape_last_stage" in kwargs and kwargs["reshape_last_stage"] is False: warnings.warn( """Reshape_last_stage is set to False in this config. This argument is deprecated and will soon be""" """ removed, as the behaviour will default to that of reshape_last_stage = True.""" , lowerCAmelCase , ) SCREAMING_SNAKE_CASE_: int =num_channels SCREAMING_SNAKE_CASE_: int =num_encoder_blocks SCREAMING_SNAKE_CASE_: List[str] =depths SCREAMING_SNAKE_CASE_: Tuple =sr_ratios SCREAMING_SNAKE_CASE_: Any =hidden_sizes SCREAMING_SNAKE_CASE_: List[str] =patch_sizes SCREAMING_SNAKE_CASE_: Dict =strides SCREAMING_SNAKE_CASE_: Optional[int] =mlp_ratios SCREAMING_SNAKE_CASE_: List[str] =num_attention_heads SCREAMING_SNAKE_CASE_: int =hidden_act SCREAMING_SNAKE_CASE_: Union[str, Any] =hidden_dropout_prob SCREAMING_SNAKE_CASE_: str =attention_probs_dropout_prob SCREAMING_SNAKE_CASE_: int =classifier_dropout_prob SCREAMING_SNAKE_CASE_: Dict =initializer_range SCREAMING_SNAKE_CASE_: Any =drop_path_rate SCREAMING_SNAKE_CASE_: Union[str, Any] =layer_norm_eps SCREAMING_SNAKE_CASE_: Dict =decoder_hidden_size SCREAMING_SNAKE_CASE_: Optional[Any] =kwargs.get("""reshape_last_stage""" , lowerCAmelCase ) SCREAMING_SNAKE_CASE_: int =semantic_loss_ignore_index class a ( UpperCAmelCase__ ): UpperCamelCase : List[str] = version.parse('1.11' ) @property def lowerCamelCase__ ( self : str ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def lowerCamelCase__ ( self : List[Any] ) -> float: '''simple docstring''' return 1E-4 @property def lowerCamelCase__ ( self : List[Any] ) -> int: '''simple docstring''' return 12
409
0
"""simple docstring""" import math import random from typing import Any from .hill_climbing import SearchProblem def _SCREAMING_SNAKE_CASE (__lowerCAmelCase , __lowerCAmelCase = True , __lowerCAmelCase = math.inf , __lowerCAmelCase = -math.inf , __lowerCAmelCase = math.inf , __lowerCAmelCase = -math.inf , __lowerCAmelCase = False , __lowerCAmelCase = 1_00 , __lowerCAmelCase = 0.01 , __lowerCAmelCase = 1 , ) -> Any: '''simple docstring''' lowercase_ = False lowercase_ = search_prob lowercase_ = start_temperate lowercase_ = [] lowercase_ = 0 lowercase_ = None while not search_end: lowercase_ = current_state.score() if best_state is None or current_score > best_state.score(): lowercase_ = current_state scores.append(_lowercase ) iterations += 1 lowercase_ = None lowercase_ = current_state.get_neighbors() while ( next_state is None and neighbors ): # till we do not find a neighbor that we can move to lowercase_ = random.randint(0 , len(_lowercase ) - 1 ) # picking a random neighbor lowercase_ = neighbors.pop(_lowercase ) lowercase_ = picked_neighbor.score() - current_score if ( picked_neighbor.x > max_x or picked_neighbor.x < min_x or picked_neighbor.y > max_y or picked_neighbor.y < min_y ): continue # neighbor outside our bounds if not find_max: lowercase_ = change * -1 # in case we are finding minimum if change > 0: # improves the solution lowercase_ = picked_neighbor else: lowercase_ = (math.e) ** ( change / current_temp ) # probability generation function if random.random() < probability: # random number within probability lowercase_ = picked_neighbor lowercase_ = current_temp - (current_temp * rate_of_decrease) if current_temp < threshold_temp or next_state is None: # temperature below threshold, or could not find a suitable neighbor lowercase_ = True else: lowercase_ = next_state if visualization: from matplotlib import pyplot as plt plt.plot(range(_lowercase ) , _lowercase ) plt.xlabel("""Iterations""" ) plt.ylabel("""Function values""" ) plt.show() return best_state if __name__ == "__main__": def _SCREAMING_SNAKE_CASE (__lowerCAmelCase , __lowerCAmelCase ) -> Dict: '''simple docstring''' return (x**2) + (y**2) # starting the problem with initial coordinates (12, 47) UpperCAmelCase : Dict = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_fa) UpperCAmelCase : Optional[Any] = simulated_annealing( prob, find_max=False, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True ) print( "The minimum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 " F"and 50 > y > - 5 found via hill climbing: {local_min.score()}" ) # starting the problem with initial coordinates (12, 47) UpperCAmelCase : Union[str, Any] = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_fa) UpperCAmelCase : Optional[Any] = simulated_annealing( prob, find_max=True, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True ) print( "The maximum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 " F"and 50 > y > - 5 found via hill climbing: {local_min.score()}" ) def _SCREAMING_SNAKE_CASE (__lowerCAmelCase , __lowerCAmelCase ) -> List[str]: '''simple docstring''' return (3 * x**2) - (6 * y) UpperCAmelCase : Any = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa) UpperCAmelCase : Union[str, Any] = simulated_annealing(prob, find_max=False, visualization=True) print( "The minimum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: " F"{local_min.score()}" ) UpperCAmelCase : List[str] = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa) UpperCAmelCase : Any = simulated_annealing(prob, find_max=True, visualization=True) print( "The maximum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: " F"{local_min.score()}" )
704
"""simple docstring""" from typing import List import datasets from datasets.tasks import AudioClassification from ..folder_based_builder import folder_based_builder UpperCAmelCase : Union[str, Any] = datasets.utils.logging.get_logger(__name__) class SCREAMING_SNAKE_CASE__ ( folder_based_builder.FolderBasedBuilderConfig ): lowercase__ = None lowercase__ = None class SCREAMING_SNAKE_CASE__ ( folder_based_builder.FolderBasedBuilder ): lowercase__ = datasets.Audio() lowercase__ = "audio" lowercase__ = AudioFolderConfig lowercase__ = 42 # definition at the bottom of the script lowercase__ = AudioClassification(audio_column="audio" , label_column="label" ) UpperCAmelCase : Tuple = [ ".aiff", ".au", ".avr", ".caf", ".flac", ".htk", ".svx", ".mat4", ".mat5", ".mpc2k", ".ogg", ".paf", ".pvf", ".raw", ".rf64", ".sd2", ".sds", ".ircam", ".voc", ".w64", ".wav", ".nist", ".wavex", ".wve", ".xi", ".mp3", ".opus", ] UpperCAmelCase : Any = AUDIO_EXTENSIONS
100
0
'''simple docstring''' import os import tempfile import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from torch import nn from transformers import ( Adafactor, AdamW, get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_inverse_sqrt_schedule, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) def snake_case_ (UpperCamelCase : Dict , UpperCamelCase : Optional[Any]=10 ): '''simple docstring''' _a = [] for _ in range(UpperCamelCase ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() return lrs def snake_case_ (UpperCamelCase : Optional[Any] , UpperCamelCase : Tuple=10 ): '''simple docstring''' _a = [] for step in range(UpperCamelCase ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() if step == num_steps // 2: with tempfile.TemporaryDirectory() as tmpdirname: _a = os.path.join(UpperCamelCase , '''schedule.bin''' ) torch.save(scheduler.state_dict() , UpperCamelCase ) _a = torch.load(UpperCamelCase ) scheduler.load_state_dict(UpperCamelCase ) return lrs @require_torch class A ( unittest.TestCase ): def __lowerCAmelCase ( self : Tuple , lowerCAmelCase_ : List[str] , lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : List[Any] ) -> int: """simple docstring""" self.assertEqual(len(lowerCAmelCase_ ) , len(lowerCAmelCase_ ) ) for a, b in zip(lowerCAmelCase_ , lowerCAmelCase_ ): self.assertAlmostEqual(lowerCAmelCase_ , lowerCAmelCase_ , delta=lowerCAmelCase_ ) def __lowerCAmelCase ( self : List[str] ) -> Any: """simple docstring""" _a = torch.tensor([0.1, -0.2, -0.1] , requires_grad=lowerCAmelCase_ ) _a = torch.tensor([0.4, 0.2, -0.5] ) _a = nn.MSELoss() # No warmup, constant schedule, no gradient clipping _a = AdamW(params=[w] , lr=2e-1 , weight_decay=0.0 ) for _ in range(1_00 ): _a = criterion(lowerCAmelCase_ , lowerCAmelCase_ ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1e-2 ) def __lowerCAmelCase ( self : Union[str, Any] ) -> Optional[int]: """simple docstring""" _a = torch.tensor([0.1, -0.2, -0.1] , requires_grad=lowerCAmelCase_ ) _a = torch.tensor([0.4, 0.2, -0.5] ) _a = nn.MSELoss() # No warmup, constant schedule, no gradient clipping _a = Adafactor( params=[w] , lr=1e-2 , eps=(1e-30, 1e-3) , clip_threshold=1.0 , decay_rate=-0.8 , betaa=lowerCAmelCase_ , weight_decay=0.0 , relative_step=lowerCAmelCase_ , scale_parameter=lowerCAmelCase_ , warmup_init=lowerCAmelCase_ , ) for _ in range(10_00 ): _a = criterion(lowerCAmelCase_ , lowerCAmelCase_ ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1e-2 ) @require_torch class A ( unittest.TestCase ): lowercase_ = nn.Linear(50 ,50 ) if is_torch_available() else None lowercase_ = AdamW(m.parameters() ,lr=10.0 ) if is_torch_available() else None lowercase_ = 10 def __lowerCAmelCase ( self : Optional[Any] , lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : List[str] , lowerCAmelCase_ : str , lowerCAmelCase_ : Optional[int]=None ) -> Optional[int]: """simple docstring""" self.assertEqual(len(lowerCAmelCase_ ) , len(lowerCAmelCase_ ) ) for a, b in zip(lowerCAmelCase_ , lowerCAmelCase_ ): self.assertAlmostEqual(lowerCAmelCase_ , lowerCAmelCase_ , delta=lowerCAmelCase_ , msg=lowerCAmelCase_ ) def __lowerCAmelCase ( self : Tuple ) -> List[Any]: """simple docstring""" _a = {'''num_warmup_steps''': 2, '''num_training_steps''': 10} # schedulers doct format # function: (sched_args_dict, expected_learning_rates) _a = { get_constant_schedule: ({}, [1_0.0] * self.num_steps), get_constant_schedule_with_warmup: ( {'''num_warmup_steps''': 4}, [0.0, 2.5, 5.0, 7.5, 1_0.0, 1_0.0, 1_0.0, 1_0.0, 1_0.0, 1_0.0], ), get_linear_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 1_0.0, 8.7_5, 7.5, 6.2_5, 5.0, 3.7_5, 2.5, 1.2_5], ), get_cosine_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 1_0.0, 9.6_1, 8.5_3, 6.9_1, 5.0, 3.0_8, 1.4_6, 0.3_8], ), get_cosine_with_hard_restarts_schedule_with_warmup: ( {**common_kwargs, '''num_cycles''': 2}, [0.0, 5.0, 1_0.0, 8.5_3, 5.0, 1.4_6, 1_0.0, 8.5_3, 5.0, 1.4_6], ), get_polynomial_decay_schedule_with_warmup: ( {**common_kwargs, '''power''': 2.0, '''lr_end''': 1e-7}, [0.0, 5.0, 1_0.0, 7.6_5_6, 5.6_2_5, 3.9_0_6, 2.5, 1.4_0_6, 0.6_2_5, 0.1_5_6], ), get_inverse_sqrt_schedule: ( {'''num_warmup_steps''': 2}, [0.0, 5.0, 1_0.0, 8.1_6_5, 7.0_7_1, 6.3_2_5, 5.7_7_4, 5.3_4_5, 5.0, 4.7_1_4], ), } for scheduler_func, data in scheds.items(): _a , _a = data _a = scheduler_func(self.optimizer , **lowerCAmelCase_ ) self.assertEqual(len([scheduler.get_lr()[0]] ) , 1 ) _a = unwrap_schedule(lowerCAmelCase_ , self.num_steps ) self.assertListAlmostEqual( lowerCAmelCase_ , lowerCAmelCase_ , tol=1e-2 , msg=F'failed for {scheduler_func} in normal scheduler' , ) _a = scheduler_func(self.optimizer , **lowerCAmelCase_ ) if scheduler_func.__name__ != "get_constant_schedule": LambdaScheduleWrapper.wrap_scheduler(lowerCAmelCase_ ) # wrap to test picklability of the schedule _a = unwrap_and_save_reload_schedule(lowerCAmelCase_ , self.num_steps ) self.assertListEqual(lowerCAmelCase_ , lowerCAmelCase_ , msg=F'failed for {scheduler_func} in save and reload' ) class A : def __init__( self : Optional[Any] , lowerCAmelCase_ : Tuple ) -> Optional[int]: """simple docstring""" _a = fn def __call__( self : List[str] , *lowerCAmelCase_ : Optional[int] , **lowerCAmelCase_ : Dict ) -> Optional[Any]: """simple docstring""" return self.fn(*lowerCAmelCase_ , **lowerCAmelCase_ ) @classmethod def __lowerCAmelCase ( self : List[str] , lowerCAmelCase_ : List[str] ) -> Tuple: """simple docstring""" _a = list(map(self , scheduler.lr_lambdas ) )
22
'''simple docstring''' from typing import Optional, Tuple, Union import torch from einops import rearrange, reduce from diffusers import DDIMScheduler, DDPMScheduler, DiffusionPipeline, ImagePipelineOutput, UNetaDConditionModel from diffusers.schedulers.scheduling_ddim import DDIMSchedulerOutput from diffusers.schedulers.scheduling_ddpm import DDPMSchedulerOutput _snake_case : Optional[Any] = 8 def snake_case_ (UpperCamelCase : List[Any] , UpperCamelCase : Dict=BITS ): '''simple docstring''' _a = x.device _a = (x * 255).int().clamp(0 , 255 ) _a = 2 ** torch.arange(bits - 1 , -1 , -1 , device=UpperCamelCase ) _a = rearrange(UpperCamelCase , '''d -> d 1 1''' ) _a = rearrange(UpperCamelCase , '''b c h w -> b c 1 h w''' ) _a = ((x & mask) != 0).float() _a = rearrange(UpperCamelCase , '''b c d h w -> b (c d) h w''' ) _a = bits * 2 - 1 return bits def snake_case_ (UpperCamelCase : List[Any] , UpperCamelCase : Any=BITS ): '''simple docstring''' _a = x.device _a = (x > 0).int() _a = 2 ** torch.arange(bits - 1 , -1 , -1 , device=UpperCamelCase , dtype=torch.intaa ) _a = rearrange(UpperCamelCase , '''d -> d 1 1''' ) _a = rearrange(UpperCamelCase , '''b (c d) h w -> b c d h w''' , d=8 ) _a = reduce(x * mask , '''b c d h w -> b c h w''' , '''sum''' ) return (dec / 255).clamp(0.0 , 1.0 ) def snake_case_ (self : Union[str, Any] , UpperCamelCase : torch.FloatTensor , UpperCamelCase : int , UpperCamelCase : torch.FloatTensor , UpperCamelCase : float = 0.0 , UpperCamelCase : bool = True , UpperCamelCase : Any=None , 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''' ) # See formulas (12) and (16) of DDIM paper https://arxiv.org/pdf/2010.02502.pdf # Ideally, read DDIM paper in-detail understanding # Notation (<variable name> -> <name in paper> # - pred_noise_t -> e_theta(x_t, t) # - pred_original_sample -> f_theta(x_t, t) or x_0 # - std_dev_t -> sigma_t # - eta -> η # - pred_sample_direction -> "direction pointing to x_t" # - pred_prev_sample -> "x_t-1" # 1. get previous step value (=t-1) _a = timestep - self.config.num_train_timesteps // self.num_inference_steps # 2. compute alphas, betas _a = self.alphas_cumprod[timestep] _a = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod _a = 1 - alpha_prod_t # 3. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf _a = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 # 4. Clip "predicted x_0" _a = self.bit_scale if self.config.clip_sample: _a = torch.clamp(UpperCamelCase , -scale , UpperCamelCase ) # 5. compute variance: "sigma_t(η)" -> see formula (16) # σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1) _a = self._get_variance(UpperCamelCase , UpperCamelCase ) _a = eta * variance ** 0.5 if use_clipped_model_output: # the model_output is always re-derived from the clipped x_0 in Glide _a = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5 # 6. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf _a = (1 - alpha_prod_t_prev - std_dev_t**2) ** 0.5 * model_output # 7. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf _a = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction if eta > 0: # randn_like does not support generator https://github.com/pytorch/pytorch/issues/27072 _a = model_output.device if torch.is_tensor(UpperCamelCase ) else '''cpu''' _a = torch.randn(model_output.shape , dtype=model_output.dtype , generator=UpperCamelCase ).to(UpperCamelCase ) _a = self._get_variance(UpperCamelCase , UpperCamelCase ) ** 0.5 * eta * noise _a = prev_sample + variance if not return_dict: return (prev_sample,) return DDIMSchedulerOutput(prev_sample=UpperCamelCase , pred_original_sample=UpperCamelCase ) def snake_case_ (self : Any , UpperCamelCase : torch.FloatTensor , UpperCamelCase : int , UpperCamelCase : torch.FloatTensor , UpperCamelCase : str="epsilon" , UpperCamelCase : Dict=None , UpperCamelCase : bool = True , ): '''simple docstring''' _a = timestep if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type in ["learned", "learned_range"]: _a , _a = torch.split(UpperCamelCase , sample.shape[1] , dim=1 ) else: _a = None # 1. compute alphas, betas _a = self.alphas_cumprod[t] _a = self.alphas_cumprod[t - 1] if t > 0 else self.one _a = 1 - alpha_prod_t _a = 1 - alpha_prod_t_prev # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if prediction_type == "epsilon": _a = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif prediction_type == "sample": _a = model_output else: raise ValueError(f'Unsupported prediction_type {prediction_type}.' ) # 3. Clip "predicted x_0" _a = self.bit_scale if self.config.clip_sample: _a = torch.clamp(UpperCamelCase , -scale , UpperCamelCase ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf _a = (alpha_prod_t_prev ** 0.5 * self.betas[t]) / beta_prod_t _a = self.alphas[t] ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf _a = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise _a = 0 if t > 0: _a = torch.randn( model_output.size() , dtype=model_output.dtype , layout=model_output.layout , generator=UpperCamelCase ).to(model_output.device ) _a = (self._get_variance(UpperCamelCase , predicted_variance=UpperCamelCase ) ** 0.5) * noise _a = pred_prev_sample + variance if not return_dict: return (pred_prev_sample,) return DDPMSchedulerOutput(prev_sample=UpperCamelCase , pred_original_sample=UpperCamelCase ) class A ( _a ): def __init__( self : Any , lowerCAmelCase_ : UNetaDConditionModel , lowerCAmelCase_ : Union[DDIMScheduler, DDPMScheduler] , lowerCAmelCase_ : Optional[float] = 1.0 , ) -> int: """simple docstring""" super().__init__() _a = bit_scale _a = ( ddim_bit_scheduler_step if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) else ddpm_bit_scheduler_step ) self.register_modules(unet=lowerCAmelCase_ , scheduler=lowerCAmelCase_ ) @torch.no_grad() def __call__( self : List[Any] , lowerCAmelCase_ : Optional[int] = 2_56 , lowerCAmelCase_ : Optional[int] = 2_56 , lowerCAmelCase_ : Optional[int] = 50 , lowerCAmelCase_ : Optional[torch.Generator] = None , lowerCAmelCase_ : Optional[int] = 1 , lowerCAmelCase_ : Optional[str] = "pil" , lowerCAmelCase_ : bool = True , **lowerCAmelCase_ : Any , ) -> Union[Tuple, ImagePipelineOutput]: """simple docstring""" _a = torch.randn( (batch_size, self.unet.config.in_channels, height, width) , generator=lowerCAmelCase_ , ) _a = decimal_to_bits(lowerCAmelCase_ ) * self.bit_scale _a = latents.to(self.device ) self.scheduler.set_timesteps(lowerCAmelCase_ ) for t in self.progress_bar(self.scheduler.timesteps ): # predict the noise residual _a = self.unet(lowerCAmelCase_ , lowerCAmelCase_ ).sample # compute the previous noisy sample x_t -> x_t-1 _a = self.scheduler.step(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ).prev_sample _a = bits_to_decimal(lowerCAmelCase_ ) if output_type == "pil": _a = self.numpy_to_pil(lowerCAmelCase_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=lowerCAmelCase_ )
22
1
"""simple docstring""" from __future__ import annotations def lowerCamelCase_ ( __lowerCAmelCase , __lowerCAmelCase = None ) -> list[list[str]]: '''simple docstring''' lowerCamelCase__ =word_bank or [] # create a table lowerCamelCase__ =len(__lowerCAmelCase ) + 1 lowerCamelCase__ =[] for _ in range(__lowerCAmelCase ): table.append([] ) # seed value lowerCamelCase__ =[[]] # because empty string has empty combination # iterate through the indices for i in range(__lowerCAmelCase ): # condition if table[i] != []: for word in word_bank: # slice condition if target[i : i + len(__lowerCAmelCase )] == word: lowerCamelCase__ =[ [word, *way] for way in table[i] ] # adds the word to every combination the current position holds # now,push that combination to the table[i+len(word)] table[i + len(__lowerCAmelCase )] += new_combinations # combinations are in reverse order so reverse for better output for combination in table[len(__lowerCAmelCase )]: combination.reverse() return table[len(__lowerCAmelCase )] if __name__ == "__main__": print(all_construct('jwajalapa', ['jwa', 'j', 'w', 'a', 'la', 'lapa'])) print(all_construct('rajamati', ['s', 'raj', 'amat', 'raja', 'ma', 'i', 't'])) print( all_construct( 'hexagonosaurus', ['h', 'ex', 'hex', 'ag', 'ago', 'ru', 'auru', 'rus', 'go', 'no', 'o', 's'], ) )
132
"""simple docstring""" import random import unittest import numpy as np from diffusers import ( DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionImgaImgPipeline, PNDMScheduler, ) from diffusers.utils import floats_tensor from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class __UpperCAmelCase ( __lowerCAmelCase , unittest.TestCase ): A__ : Union[str, Any] = '''hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline''' def _a ( self , _lowerCamelCase=0 ): lowerCamelCase__ =floats_tensor((1, 3, 128, 128) , rng=random.Random(_lowerCamelCase ) ) lowerCamelCase__ =np.random.RandomState(_lowerCamelCase ) lowerCamelCase__ ={ "prompt": "A painting of a squirrel eating a burger", "image": image, "generator": generator, "num_inference_steps": 3, "strength": 0.7_5, "guidance_scale": 7.5, "output_type": "numpy", } return inputs def _a ( self ): lowerCamelCase__ =OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) lowerCamelCase__ =self.get_dummy_inputs() lowerCamelCase__ =pipe(**_lowerCamelCase ).images lowerCamelCase__ =image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 128, 128, 3) lowerCamelCase__ =np.array([0.6_9_6_4_3, 0.5_8_4_8_4, 0.5_0_3_1_4, 0.5_8_7_6_0, 0.5_5_3_6_8, 0.5_9_6_4_3, 0.5_1_5_2_9, 0.4_1_2_1_7, 0.4_9_0_8_7] ) assert np.abs(image_slice - expected_slice ).max() < 1E-1 def _a ( self ): lowerCamelCase__ =OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" ) lowerCamelCase__ =PNDMScheduler.from_config(pipe.scheduler.config , skip_prk_steps=_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) lowerCamelCase__ =self.get_dummy_inputs() lowerCamelCase__ =pipe(**_lowerCamelCase ).images lowerCamelCase__ =image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) lowerCamelCase__ =np.array([0.6_1_7_3_7, 0.5_4_6_4_2, 0.5_3_1_8_3, 0.5_4_4_6_5, 0.5_2_7_4_2, 0.6_0_5_2_5, 0.4_9_9_6_9, 0.4_0_6_5_5, 0.4_8_1_5_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 def _a ( self ): lowerCamelCase__ =OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" ) lowerCamelCase__ =LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) # warmup pass to apply optimizations lowerCamelCase__ =pipe(**self.get_dummy_inputs() ) lowerCamelCase__ =self.get_dummy_inputs() lowerCamelCase__ =pipe(**_lowerCamelCase ).images lowerCamelCase__ =image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) lowerCamelCase__ =np.array([0.5_2_7_6_1, 0.5_9_9_7_7, 0.4_9_0_3_3, 0.4_9_6_1_9, 0.5_4_2_8_2, 0.5_0_3_1_1, 0.4_7_6_0_0, 0.4_0_9_1_8, 0.4_5_2_0_3] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 def _a ( self ): lowerCamelCase__ =OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" ) lowerCamelCase__ =EulerDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) lowerCamelCase__ =self.get_dummy_inputs() lowerCamelCase__ =pipe(**_lowerCamelCase ).images lowerCamelCase__ =image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) lowerCamelCase__ =np.array([0.5_2_9_1_1, 0.6_0_0_0_4, 0.4_9_2_2_9, 0.4_9_8_0_5, 0.5_4_5_0_2, 0.5_0_6_8_0, 0.4_7_7_7_7, 0.4_1_0_2_8, 0.4_5_3_0_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 def _a ( self ): lowerCamelCase__ =OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" ) lowerCamelCase__ =EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) lowerCamelCase__ =self.get_dummy_inputs() lowerCamelCase__ =pipe(**_lowerCamelCase ).images lowerCamelCase__ =image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) lowerCamelCase__ =np.array([0.5_2_9_1_1, 0.6_0_0_0_4, 0.4_9_2_2_9, 0.4_9_8_0_5, 0.5_4_5_0_2, 0.5_0_6_8_0, 0.4_7_7_7_7, 0.4_1_0_2_8, 0.4_5_3_0_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 def _a ( self ): lowerCamelCase__ =OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" ) lowerCamelCase__ =DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) lowerCamelCase__ =self.get_dummy_inputs() lowerCamelCase__ =pipe(**_lowerCamelCase ).images lowerCamelCase__ =image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) lowerCamelCase__ =np.array([0.6_5_3_3_1, 0.5_8_2_7_7, 0.4_8_2_0_4, 0.5_6_0_5_9, 0.5_3_6_6_5, 0.5_6_2_3_5, 0.5_0_9_6_9, 0.4_0_0_0_9, 0.4_6_5_5_2] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 @nightly @require_onnxruntime @require_torch_gpu class __UpperCAmelCase ( unittest.TestCase ): @property def _a ( self ): return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def _a ( self ): lowerCamelCase__ =ort.SessionOptions() lowerCamelCase__ =False return options def _a ( self ): lowerCamelCase__ =load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/img2img/sketch-mountains-input.jpg" ) lowerCamelCase__ =init_image.resize((768, 512) ) # using the PNDM scheduler by default lowerCamelCase__ =OnnxStableDiffusionImgaImgPipeline.from_pretrained( "CompVis/stable-diffusion-v1-4" , revision="onnx" , safety_checker=_lowerCamelCase , feature_extractor=_lowerCamelCase , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) lowerCamelCase__ ="A fantasy landscape, trending on artstation" lowerCamelCase__ =np.random.RandomState(0 ) lowerCamelCase__ =pipe( prompt=_lowerCamelCase , image=_lowerCamelCase , strength=0.7_5 , guidance_scale=7.5 , num_inference_steps=10 , generator=_lowerCamelCase , output_type="np" , ) lowerCamelCase__ =output.images lowerCamelCase__ =images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 768, 3) lowerCamelCase__ =np.array([0.4_9_0_9, 0.5_0_5_9, 0.5_3_7_2, 0.4_6_2_3, 0.4_8_7_6, 0.5_0_4_9, 0.4_8_2_0, 0.4_9_5_6, 0.5_0_1_9] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2E-2 def _a ( self ): lowerCamelCase__ =load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/img2img/sketch-mountains-input.jpg" ) lowerCamelCase__ =init_image.resize((768, 512) ) lowerCamelCase__ =LMSDiscreteScheduler.from_pretrained( "runwayml/stable-diffusion-v1-5" , subfolder="scheduler" , revision="onnx" ) lowerCamelCase__ =OnnxStableDiffusionImgaImgPipeline.from_pretrained( "runwayml/stable-diffusion-v1-5" , revision="onnx" , scheduler=_lowerCamelCase , safety_checker=_lowerCamelCase , feature_extractor=_lowerCamelCase , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) lowerCamelCase__ ="A fantasy landscape, trending on artstation" lowerCamelCase__ =np.random.RandomState(0 ) lowerCamelCase__ =pipe( prompt=_lowerCamelCase , image=_lowerCamelCase , strength=0.7_5 , guidance_scale=7.5 , num_inference_steps=20 , generator=_lowerCamelCase , output_type="np" , ) lowerCamelCase__ =output.images lowerCamelCase__ =images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 768, 3) lowerCamelCase__ =np.array([0.8_0_4_3, 0.9_2_6, 0.9_5_8_1, 0.8_1_1_9, 0.8_9_5_4, 0.9_1_3, 0.7_2_0_9, 0.7_4_6_3, 0.7_4_3_1] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2E-2
132
1
import os import sys import unittest _lowerCamelCase : Optional[int] = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, """utils""")) import get_test_info # noqa: E402 from get_test_info import ( # noqa: E402 get_model_to_test_mapping, get_model_to_tester_mapping, get_test_to_tester_mapping, ) _lowerCamelCase : List[Any] = os.path.join("""tests""", """models""", """bert""", """test_modeling_bert.py""") _lowerCamelCase : Dict = os.path.join("""tests""", """models""", """blip""", """test_modeling_blip.py""") class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE ( self : str) ->List[str]: '''simple docstring''' A__ = get_test_to_tester_mapping(lowerCAmelCase_) A__ = get_test_to_tester_mapping(lowerCAmelCase_) A__ = {'BertModelTest': 'BertModelTester'} A__ = { 'BlipModelTest': 'BlipModelTester', 'BlipTextImageModelTest': 'BlipTextImageModelsModelTester', 'BlipTextModelTest': 'BlipTextModelTester', 'BlipTextRetrievalModelTest': 'BlipTextRetrievalModelTester', 'BlipVQAModelTest': 'BlipVQAModelTester', 'BlipVisionModelTest': 'BlipVisionModelTester', } self.assertEqual(get_test_info.to_json(lowerCAmelCase_) , lowerCAmelCase_) self.assertEqual(get_test_info.to_json(lowerCAmelCase_) , lowerCAmelCase_) def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->Tuple: '''simple docstring''' A__ = get_model_to_test_mapping(lowerCAmelCase_) A__ = get_model_to_test_mapping(lowerCAmelCase_) A__ = { 'BertForMaskedLM': ['BertModelTest'], 'BertForMultipleChoice': ['BertModelTest'], 'BertForNextSentencePrediction': ['BertModelTest'], 'BertForPreTraining': ['BertModelTest'], 'BertForQuestionAnswering': ['BertModelTest'], 'BertForSequenceClassification': ['BertModelTest'], 'BertForTokenClassification': ['BertModelTest'], 'BertLMHeadModel': ['BertModelTest'], 'BertModel': ['BertModelTest'], } A__ = { 'BlipForConditionalGeneration': ['BlipTextImageModelTest'], 'BlipForImageTextRetrieval': ['BlipTextRetrievalModelTest'], 'BlipForQuestionAnswering': ['BlipVQAModelTest'], 'BlipModel': ['BlipModelTest'], 'BlipTextModel': ['BlipTextModelTest'], 'BlipVisionModel': ['BlipVisionModelTest'], } self.assertEqual(get_test_info.to_json(lowerCAmelCase_) , lowerCAmelCase_) self.assertEqual(get_test_info.to_json(lowerCAmelCase_) , lowerCAmelCase_) def SCREAMING_SNAKE_CASE ( self : List[str]) ->str: '''simple docstring''' A__ = get_model_to_tester_mapping(lowerCAmelCase_) A__ = get_model_to_tester_mapping(lowerCAmelCase_) A__ = { 'BertForMaskedLM': ['BertModelTester'], 'BertForMultipleChoice': ['BertModelTester'], 'BertForNextSentencePrediction': ['BertModelTester'], 'BertForPreTraining': ['BertModelTester'], 'BertForQuestionAnswering': ['BertModelTester'], 'BertForSequenceClassification': ['BertModelTester'], 'BertForTokenClassification': ['BertModelTester'], 'BertLMHeadModel': ['BertModelTester'], 'BertModel': ['BertModelTester'], } A__ = { 'BlipForConditionalGeneration': ['BlipTextImageModelsModelTester'], 'BlipForImageTextRetrieval': ['BlipTextRetrievalModelTester'], 'BlipForQuestionAnswering': ['BlipVQAModelTester'], 'BlipModel': ['BlipModelTester'], 'BlipTextModel': ['BlipTextModelTester'], 'BlipVisionModel': ['BlipVisionModelTester'], } self.assertEqual(get_test_info.to_json(lowerCAmelCase_) , lowerCAmelCase_) self.assertEqual(get_test_info.to_json(lowerCAmelCase_) , lowerCAmelCase_)
87
"""simple docstring""" import platform from argparse import ArgumentParser import huggingface_hub from .. import __version__ as version from ..utils import is_accelerate_available, is_torch_available, is_transformers_available, is_xformers_available from . import BaseDiffusersCLICommand def lowercase__ ( lowerCamelCase ): return EnvironmentCommand() class _lowerCAmelCase ( __UpperCAmelCase ): @staticmethod def A ( lowerCAmelCase_ ) -> List[Any]: _SCREAMING_SNAKE_CASE : int = parser.add_parser('env' ) download_parser.set_defaults(func=lowerCAmelCase_ ) def A ( self ) -> Any: _SCREAMING_SNAKE_CASE : int = huggingface_hub.__version__ _SCREAMING_SNAKE_CASE : Optional[Any] = 'not installed' _SCREAMING_SNAKE_CASE : Union[str, Any] = 'NA' if is_torch_available(): import torch _SCREAMING_SNAKE_CASE : Union[str, Any] = torch.__version__ _SCREAMING_SNAKE_CASE : Union[str, Any] = torch.cuda.is_available() _SCREAMING_SNAKE_CASE : Union[str, Any] = 'not installed' if is_transformers_available(): import transformers _SCREAMING_SNAKE_CASE : Tuple = transformers.__version__ _SCREAMING_SNAKE_CASE : Optional[int] = 'not installed' if is_accelerate_available(): import accelerate _SCREAMING_SNAKE_CASE : str = accelerate.__version__ _SCREAMING_SNAKE_CASE : str = 'not installed' if is_xformers_available(): import xformers _SCREAMING_SNAKE_CASE : Optional[int] = xformers.__version__ _SCREAMING_SNAKE_CASE : Any = { '`diffusers` version': version, 'Platform': platform.platform(), 'Python version': platform.python_version(), 'PyTorch version (GPU?)': F"""{pt_version} ({pt_cuda_available})""", 'Huggingface_hub version': hub_version, 'Transformers version': transformers_version, 'Accelerate version': accelerate_version, 'xFormers version': xformers_version, 'Using GPU in script?': '<fill in>', 'Using distributed or parallel set-up in script?': '<fill in>', } print('\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n' ) print(self.format_dict(lowerCAmelCase_ ) ) return info @staticmethod def A ( lowerCAmelCase_ ) -> int: return "\n".join([F"""- {prop}: {val}""" for prop, val in d.items()] ) + "\n"
621
0
from __future__ import annotations from random import random from typing import Generic, TypeVar lowerCamelCase__ : Optional[Any] = TypeVar("""KT""") lowerCamelCase__ : str = TypeVar("""VT""") class _snake_case ( Generic[KT, VT] ): def __init__( self , SCREAMING_SNAKE_CASE_ = "root" , SCREAMING_SNAKE_CASE_ = None): '''simple docstring''' lowercase__ : Union[str, Any] = key lowercase__ : List[Any] = value lowercase__ : list[Node[KT, VT]] = [] def __repr__( self): '''simple docstring''' return f'Node({self.key}: {self.value})' @property def lowercase__ ( self): '''simple docstring''' return len(self.forward) class _snake_case ( Generic[KT, VT] ): def __init__( self , SCREAMING_SNAKE_CASE_ = 0.5 , SCREAMING_SNAKE_CASE_ = 16): '''simple docstring''' lowercase__ : Node[KT, VT] = Node[KT, VT]() lowercase__ : List[Any] = 0 lowercase__ : str = p lowercase__ : Dict = max_level def __str__( self): '''simple docstring''' lowercase__ : Union[str, Any] = list(self) if len(SCREAMING_SNAKE_CASE_) == 0: return f'SkipList(level={self.level})' lowercase__ : Any = max((len(str(SCREAMING_SNAKE_CASE_)) for item in items) , default=4) lowercase__ : int = max(SCREAMING_SNAKE_CASE_ , 4) + 4 lowercase__ : int = self.head lowercase__ : str = [] lowercase__ : Union[str, Any] = node.forward.copy() lines.append(f'[{node.key}]'.ljust(SCREAMING_SNAKE_CASE_ , """-""") + """* """ * len(SCREAMING_SNAKE_CASE_)) lines.append(""" """ * label_size + """| """ * len(SCREAMING_SNAKE_CASE_)) while len(node.forward) != 0: lowercase__ : Optional[int] = node.forward[0] lines.append( f'[{node.key}]'.ljust(SCREAMING_SNAKE_CASE_ , """-""") + """ """.join(str(n.key) if n.key == node.key else """|""" for n in forwards)) lines.append(""" """ * label_size + """| """ * len(SCREAMING_SNAKE_CASE_)) lowercase__ : Optional[int] = node.forward lines.append("""None""".ljust(SCREAMING_SNAKE_CASE_) + """* """ * len(SCREAMING_SNAKE_CASE_)) return f'SkipList(level={self.level})\n' + "\n".join(SCREAMING_SNAKE_CASE_) def __iter__( self): '''simple docstring''' lowercase__ : Optional[int] = self.head while len(node.forward) != 0: yield node.forward[0].key lowercase__ : Union[str, Any] = node.forward[0] def lowercase__ ( self): '''simple docstring''' lowercase__ : Union[str, Any] = 1 while random() < self.p and level < self.max_level: level += 1 return level def lowercase__ ( self , SCREAMING_SNAKE_CASE_): '''simple docstring''' lowercase__ : Union[str, Any] = [] lowercase__ : Dict = self.head for i in reversed(range(self.level)): # i < node.level - When node level is lesser than `i` decrement `i`. # node.forward[i].key < key - Jumping to node with key value higher # or equal to searched key would result # in skipping searched key. while i < node.level and node.forward[i].key < key: lowercase__ : List[str] = node.forward[i] # Each leftmost node (relative to searched node) will potentially have to # be updated. update_vector.append(SCREAMING_SNAKE_CASE_) update_vector.reverse() # Note that we were inserting values in reverse order. # len(node.forward) != 0 - If current node doesn't contain any further # references then searched key is not present. # node.forward[0].key == key - Next node key should be equal to search key # if key is present. if len(node.forward) != 0 and node.forward[0].key == key: return node.forward[0], update_vector else: return None, update_vector def lowercase__ ( self , SCREAMING_SNAKE_CASE_): '''simple docstring''' lowercase__ , lowercase__ : Optional[int] = self._locate_node(SCREAMING_SNAKE_CASE_) if node is not None: for i, update_node in enumerate(SCREAMING_SNAKE_CASE_): # Remove or replace all references to removed node. if update_node.level > i and update_node.forward[i].key == key: if node.level > i: lowercase__ : int = node.forward[i] else: lowercase__ : List[Any] = update_node.forward[:i] def lowercase__ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_): '''simple docstring''' lowercase__ , lowercase__ : Union[str, Any] = self._locate_node(SCREAMING_SNAKE_CASE_) if node is not None: lowercase__ : str = value else: lowercase__ : Union[str, Any] = self.random_level() if level > self.level: # After level increase we have to add additional nodes to head. for _ in range(self.level - 1 , SCREAMING_SNAKE_CASE_): update_vector.append(self.head) lowercase__ : int = level lowercase__ : Optional[int] = Node(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_) for i, update_node in enumerate(update_vector[:level]): # Change references to pass through new node. if update_node.level > i: new_node.forward.append(update_node.forward[i]) if update_node.level < i + 1: update_node.forward.append(SCREAMING_SNAKE_CASE_) else: lowercase__ : int = new_node def lowercase__ ( self , SCREAMING_SNAKE_CASE_): '''simple docstring''' lowercase__ , lowercase__ : str = self._locate_node(SCREAMING_SNAKE_CASE_) if node is not None: return node.value return None def UpperCamelCase ( ) -> List[str]: '''simple docstring''' lowercase__ : int = SkipList() skip_list.insert("""Key1""" , 3 ) skip_list.insert("""Key2""" , 12 ) skip_list.insert("""Key3""" , 41 ) skip_list.insert("""Key4""" , -19 ) lowercase__ : List[str] = skip_list.head lowercase__ : Union[str, Any] = {} while node.level != 0: lowercase__ : Optional[int] = node.forward[0] lowercase__ : Union[str, Any] = node.value assert len(lowercase_ ) == 4 assert all_values["Key1"] == 3 assert all_values["Key2"] == 12 assert all_values["Key3"] == 41 assert all_values["Key4"] == -19 def UpperCamelCase ( ) -> Optional[Any]: '''simple docstring''' lowercase__ : Dict = SkipList() skip_list.insert("""Key1""" , 10 ) skip_list.insert("""Key1""" , 12 ) skip_list.insert("""Key5""" , 7 ) skip_list.insert("""Key7""" , 10 ) skip_list.insert("""Key10""" , 5 ) skip_list.insert("""Key7""" , 7 ) skip_list.insert("""Key5""" , 5 ) skip_list.insert("""Key10""" , 10 ) lowercase__ : Optional[int] = skip_list.head lowercase__ : Optional[int] = {} while node.level != 0: lowercase__ : int = node.forward[0] lowercase__ : str = node.value if len(lowercase_ ) != 4: print() assert len(lowercase_ ) == 4 assert all_values["Key1"] == 12 assert all_values["Key7"] == 7 assert all_values["Key5"] == 5 assert all_values["Key10"] == 10 def UpperCamelCase ( ) -> Optional[int]: '''simple docstring''' lowercase__ : Optional[Any] = SkipList() assert skip_list.find("""Some key""" ) is None def UpperCamelCase ( ) -> int: '''simple docstring''' lowercase__ : List[Any] = SkipList() skip_list.insert("""Key2""" , 20 ) assert skip_list.find("""Key2""" ) == 20 skip_list.insert("""Some Key""" , 10 ) skip_list.insert("""Key2""" , 8 ) skip_list.insert("""V""" , 13 ) assert skip_list.find("""Y""" ) is None assert skip_list.find("""Key2""" ) == 8 assert skip_list.find("""Some Key""" ) == 10 assert skip_list.find("""V""" ) == 13 def UpperCamelCase ( ) -> str: '''simple docstring''' lowercase__ : int = SkipList() skip_list.delete("""Some key""" ) assert len(skip_list.head.forward ) == 0 def UpperCamelCase ( ) -> List[str]: '''simple docstring''' lowercase__ : Any = SkipList() skip_list.insert("""Key1""" , 12 ) skip_list.insert("""V""" , 13 ) skip_list.insert("""X""" , 14 ) skip_list.insert("""Key2""" , 15 ) skip_list.delete("""V""" ) skip_list.delete("""Key2""" ) assert skip_list.find("""V""" ) is None assert skip_list.find("""Key2""" ) is None def UpperCamelCase ( ) -> Optional[int]: '''simple docstring''' lowercase__ : Optional[Any] = SkipList() skip_list.insert("""Key1""" , 12 ) skip_list.insert("""V""" , 13 ) skip_list.insert("""X""" , 14 ) skip_list.insert("""Key2""" , 15 ) skip_list.delete("""V""" ) assert skip_list.find("""V""" ) is None assert skip_list.find("""X""" ) == 14 assert skip_list.find("""Key1""" ) == 12 assert skip_list.find("""Key2""" ) == 15 skip_list.delete("""X""" ) assert skip_list.find("""V""" ) is None assert skip_list.find("""X""" ) is None assert skip_list.find("""Key1""" ) == 12 assert skip_list.find("""Key2""" ) == 15 skip_list.delete("""Key1""" ) assert skip_list.find("""V""" ) is None assert skip_list.find("""X""" ) is None assert skip_list.find("""Key1""" ) is None assert skip_list.find("""Key2""" ) == 15 skip_list.delete("""Key2""" ) assert skip_list.find("""V""" ) is None assert skip_list.find("""X""" ) is None assert skip_list.find("""Key1""" ) is None assert skip_list.find("""Key2""" ) is None def UpperCamelCase ( ) -> Dict: '''simple docstring''' lowercase__ : Dict = SkipList() skip_list.insert("""Key1""" , 12 ) skip_list.insert("""V""" , 13 ) skip_list.insert("""X""" , 1_42 ) skip_list.insert("""Key2""" , 15 ) skip_list.delete("""X""" ) def traverse_keys(lowercase_ ): yield node.key for forward_node in node.forward: yield from traverse_keys(lowercase_ ) assert len(set(traverse_keys(skip_list.head ) ) ) == 4 def UpperCamelCase ( ) -> Union[str, Any]: '''simple docstring''' def is_sorted(lowercase_ ): return all(next_item >= item for item, next_item in zip(lowercase_ , lst[1:] ) ) lowercase__ : List[str] = SkipList() for i in range(10 ): skip_list.insert(lowercase_ , lowercase_ ) assert is_sorted(list(lowercase_ ) ) skip_list.delete(5 ) skip_list.delete(8 ) skip_list.delete(2 ) assert is_sorted(list(lowercase_ ) ) skip_list.insert(-12 , -12 ) skip_list.insert(77 , 77 ) assert is_sorted(list(lowercase_ ) ) def UpperCamelCase ( ) -> List[str]: '''simple docstring''' for _ in range(1_00 ): # Repeat test 100 times due to the probabilistic nature of skip list # random values == random bugs test_insert() test_insert_overrides_existing_value() test_searching_empty_list_returns_none() test_search() test_deleting_item_from_empty_list_do_nothing() test_deleted_items_are_not_founded_by_find_method() test_delete_removes_only_given_key() test_delete_doesnt_leave_dead_nodes() test_iter_always_yields_sorted_values() def UpperCamelCase ( ) -> Tuple: '''simple docstring''' lowercase__ : Optional[Any] = SkipList() skip_list.insert(2 , """2""" ) skip_list.insert(4 , """4""" ) skip_list.insert(6 , """4""" ) skip_list.insert(4 , """5""" ) skip_list.insert(8 , """4""" ) skip_list.insert(9 , """4""" ) skip_list.delete(4 ) print(lowercase_ ) if __name__ == "__main__": import doctest doctest.testmod() main()
495
import argparse import os import re lowerCamelCase__ : List[Any] = """src/transformers""" # Pattern that looks at the indentation in a line. lowerCamelCase__ : Union[str, Any] = re.compile(R"""^(\s*)\S""") # Pattern that matches `"key":" and puts `key` in group 0. lowerCamelCase__ : Any = re.compile(R"""^\s*\"([^\"]+)\":""") # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. lowerCamelCase__ : int = re.compile(R"""^\s*_import_structure\[\"([^\"]+)\"\]""") # Pattern that matches `"key",` and puts `key` in group 0. lowerCamelCase__ : List[Any] = re.compile(R"""^\s*\"([^\"]+)\",\s*$""") # Pattern that matches any `[stuff]` and puts `stuff` in group 0. lowerCamelCase__ : str = re.compile(R"""\[([^\]]+)\]""") def UpperCamelCase ( lowercase_ ) -> Union[str, Any]: '''simple docstring''' lowercase__ : Optional[Any] = _re_indent.search(lowercase_ ) return "" if search is None else search.groups()[0] def UpperCamelCase ( lowercase_ , lowercase_="" , lowercase_=None , lowercase_=None ) -> Dict: '''simple docstring''' lowercase__ : List[str] = 0 lowercase__ : List[Any] = code.split("""\n""" ) if start_prompt is not None: while not lines[index].startswith(lowercase_ ): index += 1 lowercase__ : List[str] = ["""\n""".join(lines[:index] )] else: lowercase__ : Optional[Any] = [] # We split into blocks until we get to the `end_prompt` (or the end of the block). lowercase__ : List[Any] = [lines[index]] index += 1 while index < len(lowercase_ ) and (end_prompt is None or not lines[index].startswith(lowercase_ )): if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level: if len(lowercase_ ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + """ """ ): current_block.append(lines[index] ) blocks.append("""\n""".join(lowercase_ ) ) if index < len(lowercase_ ) - 1: lowercase__ : str = [lines[index + 1]] index += 1 else: lowercase__ : Union[str, Any] = [] else: blocks.append("""\n""".join(lowercase_ ) ) lowercase__ : Tuple = [lines[index]] else: current_block.append(lines[index] ) index += 1 # Adds current block if it's nonempty. if len(lowercase_ ) > 0: blocks.append("""\n""".join(lowercase_ ) ) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(lowercase_ ): blocks.append("""\n""".join(lines[index:] ) ) return blocks def UpperCamelCase ( lowercase_ ) -> List[Any]: '''simple docstring''' def _inner(lowercase_ ): return key(lowercase_ ).lower().replace("""_""" , """""" ) return _inner def UpperCamelCase ( lowercase_ , lowercase_=None ) -> Optional[Any]: '''simple docstring''' def noop(lowercase_ ): return x if key is None: lowercase__ : Dict = noop # Constants are all uppercase, they go first. lowercase__ : Dict = [obj for obj in objects if key(lowercase_ ).isupper()] # Classes are not all uppercase but start with a capital, they go second. lowercase__ : Any = [obj for obj in objects if key(lowercase_ )[0].isupper() and not key(lowercase_ ).isupper()] # Functions begin with a lowercase, they go last. lowercase__ : Optional[int] = [obj for obj in objects if not key(lowercase_ )[0].isupper()] lowercase__ : Tuple = ignore_underscore(lowercase_ ) return sorted(lowercase_ , key=lowercase_ ) + sorted(lowercase_ , key=lowercase_ ) + sorted(lowercase_ , key=lowercase_ ) def UpperCamelCase ( lowercase_ ) -> Tuple: '''simple docstring''' def _replace(lowercase_ ): lowercase__ : int = match.groups()[0] if "," not in imports: return F'[{imports}]' lowercase__ : Union[str, Any] = [part.strip().replace("""\"""" , """""" ) for part in imports.split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: lowercase__ : int = keys[:-1] return "[" + ", ".join([F'"{k}"' for k in sort_objects(lowercase_ )] ) + "]" lowercase__ : Any = import_statement.split("""\n""" ) if len(lowercase_ ) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. lowercase__ : Tuple = 2 if lines[1].strip() == """[""" else 1 lowercase__ : Optional[int] = [(i, _re_strip_line.search(lowercase_ ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] lowercase__ : Optional[Any] = sort_objects(lowercase_ , key=lambda lowercase_ : x[1] ) lowercase__ : Union[str, Any] = [lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] ) elif len(lowercase_ ) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1] ) is not None: lowercase__ : List[str] = _re_bracket_content.sub(_replace , lines[1] ) else: lowercase__ : Optional[int] = [part.strip().replace("""\"""" , """""" ) for part in lines[1].split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: lowercase__ : Optional[int] = keys[:-1] lowercase__ : int = get_indent(lines[1] ) + """, """.join([F'"{k}"' for k in sort_objects(lowercase_ )] ) return "\n".join(lowercase_ ) else: # Finally we have to deal with imports fitting on one line lowercase__ : Any = _re_bracket_content.sub(_replace , lowercase_ ) return import_statement def UpperCamelCase ( lowercase_ , lowercase_=True ) -> Optional[int]: '''simple docstring''' with open(lowercase_ , encoding="""utf-8""" ) as f: lowercase__ : str = f.read() if "_import_structure" not in code: return # Blocks of indent level 0 lowercase__ : Any = split_code_in_indented_blocks( lowercase_ , start_prompt="""_import_structure = {""" , end_prompt="""if TYPE_CHECKING:""" ) # We ignore block 0 (everything untils start_prompt) and the last block (everything after end_prompt). for block_idx in range(1 , len(lowercase_ ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. lowercase__ : List[str] = main_blocks[block_idx] lowercase__ : str = block.split("""\n""" ) # Get to the start of the imports. lowercase__ : Optional[Any] = 0 while line_idx < len(lowercase_ ) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: lowercase__ : int = len(lowercase_ ) else: line_idx += 1 if line_idx >= len(lowercase_ ): continue # Ignore beginning and last line: they don't contain anything. lowercase__ : List[str] = """\n""".join(block_lines[line_idx:-1] ) lowercase__ : Dict = get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. lowercase__ : List[str] = split_code_in_indented_blocks(lowercase_ , indent_level=lowercase_ ) # We have two categories of import key: list or _import_structure[key].append/extend lowercase__ : Optional[int] = _re_direct_key if """_import_structure = {""" in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or just comments. lowercase__ : Optional[Any] = [(pattern.search(lowercase_ ).groups()[0] if pattern.search(lowercase_ ) is not None else None) for b in internal_blocks] # We only sort the lines with a key. lowercase__ : List[Any] = [(i, key) for i, key in enumerate(lowercase_ ) if key is not None] lowercase__ : Optional[int] = [x[0] for x in sorted(lowercase_ , key=lambda lowercase_ : x[1] )] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. lowercase__ : Any = 0 lowercase__ : Optional[Any] = [] for i in range(len(lowercase_ ) ): if keys[i] is None: reorderded_blocks.append(internal_blocks[i] ) else: lowercase__ : Optional[Any] = sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reorderded_blocks.append(lowercase_ ) count += 1 # And we put our main block back together with its first and last line. lowercase__ : Union[str, Any] = """\n""".join(block_lines[:line_idx] + reorderded_blocks + [block_lines[-1]] ) if code != "\n".join(lowercase_ ): if check_only: return True else: print(F'Overwriting {file}.' ) with open(lowercase_ , """w""" , encoding="""utf-8""" ) as f: f.write("""\n""".join(lowercase_ ) ) def UpperCamelCase ( lowercase_=True ) -> Optional[int]: '''simple docstring''' lowercase__ : int = [] for root, _, files in os.walk(lowercase_ ): if "__init__.py" in files: lowercase__ : Dict = sort_imports(os.path.join(lowercase_ , """__init__.py""" ) , check_only=lowercase_ ) if result: lowercase__ : List[str] = [os.path.join(lowercase_ , """__init__.py""" )] if len(lowercase_ ) > 0: raise ValueError(F'Would overwrite {len(lowercase_ )} files, run `make style`.' ) if __name__ == "__main__": lowerCamelCase__ : int = argparse.ArgumentParser() parser.add_argument("""--check_only""", action="""store_true""", help="""Whether to only check or fix style.""") lowerCamelCase__ : List[Any] = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
495
1
'''simple docstring''' import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin from .feature_extraction_wavaveca import WavaVecaFeatureExtractor from .tokenization_wavaveca import WavaVecaCTCTokenizer class snake_case ( lowercase_ ): """simple docstring""" _a = """Wav2Vec2FeatureExtractor""" _a = """AutoTokenizer""" def __init__( self, _lowercase, _lowercase ) -> Dict: super().__init__(snake_case_, snake_case_ ) SCREAMING_SNAKE_CASE_ = self.feature_extractor SCREAMING_SNAKE_CASE_ = False @classmethod def a__ ( cls, _lowercase, **_lowercase ) -> str: try: return super().from_pretrained(snake_case_, **snake_case_ ) except OSError: warnings.warn( f"""Loading a tokenizer inside {cls.__name__} from a config that does not""" ' include a `tokenizer_class` attribute is deprecated and will be ' 'removed in v5. Please add `\'tokenizer_class\': \'Wav2Vec2CTCTokenizer\'`' ' attribute to either your `config.json` or `tokenizer_config.json` ' 'file to suppress this warning: ', snake_case_, ) SCREAMING_SNAKE_CASE_ = WavaVecaFeatureExtractor.from_pretrained(snake_case_, **snake_case_ ) SCREAMING_SNAKE_CASE_ = WavaVecaCTCTokenizer.from_pretrained(snake_case_, **snake_case_ ) return cls(feature_extractor=snake_case_, tokenizer=snake_case_ ) def __call__( self, *_lowercase, **_lowercase ) -> Optional[int]: # For backward compatibility if self._in_target_context_manager: return self.current_processor(*snake_case_, **snake_case_ ) if "raw_speech" in kwargs: warnings.warn('Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.' ) SCREAMING_SNAKE_CASE_ = kwargs.pop('raw_speech' ) else: SCREAMING_SNAKE_CASE_ = kwargs.pop('audio', snake_case_ ) SCREAMING_SNAKE_CASE_ = kwargs.pop('sampling_rate', snake_case_ ) SCREAMING_SNAKE_CASE_ = kwargs.pop('text', snake_case_ ) if len(snake_case_ ) > 0: SCREAMING_SNAKE_CASE_ = args[0] SCREAMING_SNAKE_CASE_ = args[1:] if audio is None and text is None: raise ValueError('You need to specify either an `audio` or `text` input to process.' ) if audio is not None: SCREAMING_SNAKE_CASE_ = self.feature_extractor(snake_case_, *snake_case_, sampling_rate=snake_case_, **snake_case_ ) if text is not None: SCREAMING_SNAKE_CASE_ = self.tokenizer(snake_case_, **snake_case_ ) if text is None: return inputs elif audio is None: return encodings else: SCREAMING_SNAKE_CASE_ = encodings['input_ids'] return inputs def a__ ( self, *_lowercase, **_lowercase ) -> Tuple: # For backward compatibility if self._in_target_context_manager: return self.current_processor.pad(*snake_case_, **snake_case_ ) SCREAMING_SNAKE_CASE_ = kwargs.pop('input_features', snake_case_ ) SCREAMING_SNAKE_CASE_ = kwargs.pop('labels', snake_case_ ) if len(snake_case_ ) > 0: SCREAMING_SNAKE_CASE_ = args[0] SCREAMING_SNAKE_CASE_ = args[1:] if input_features is not None: SCREAMING_SNAKE_CASE_ = self.feature_extractor.pad(snake_case_, *snake_case_, **snake_case_ ) if labels is not None: SCREAMING_SNAKE_CASE_ = self.tokenizer.pad(snake_case_, **snake_case_ ) if labels is None: return input_features elif input_features is None: return labels else: SCREAMING_SNAKE_CASE_ = labels['input_ids'] return input_features def a__ ( self, *_lowercase, **_lowercase ) -> Any: return self.tokenizer.batch_decode(*snake_case_, **snake_case_ ) def a__ ( self, *_lowercase, **_lowercase ) -> Optional[int]: return self.tokenizer.decode(*snake_case_, **snake_case_ ) @contextmanager def a__ ( self ) -> Union[str, Any]: warnings.warn( '`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your ' 'labels by using the argument `text` of the regular `__call__` method (either in the same call as ' 'your audio inputs, or in a separate call.' ) SCREAMING_SNAKE_CASE_ = True SCREAMING_SNAKE_CASE_ = self.tokenizer yield SCREAMING_SNAKE_CASE_ = self.feature_extractor SCREAMING_SNAKE_CASE_ = False
294
def __lowerCAmelCase ( __lowerCamelCase : int , __lowerCamelCase : int ) -> bool: return numa ^ numa < 0 if __name__ == "__main__": import doctest doctest.testmod()
354
0
import timeit import numpy as np import datasets from datasets.arrow_writer import ArrowWriter from datasets.features.features import _ArrayXD def _SCREAMING_SNAKE_CASE ( snake_case_ : int ): def wrapper(*snake_case_ : int , **snake_case_ : Optional[Any] ): __magic_name__ = timeit.default_timer() __magic_name__ = func(*snake_case_ , **snake_case_ ) __magic_name__ = timeit.default_timer() - starttime return delta __magic_name__ = func.__name__ return wrapper def _SCREAMING_SNAKE_CASE ( snake_case_ : dict , snake_case_ : Any=100 , snake_case_ : int=None ): __magic_name__ = [] __magic_name__ = seq_shapes or {} for i in range(snake_case_ ): __magic_name__ = {} for col_id, (k, v) in enumerate(features.items() ): if isinstance(snake_case_ , _ArrayXD ): __magic_name__ = np.random.rand(*v.shape ).astype(v.dtype ) elif isinstance(snake_case_ , datasets.Value ): if v.dtype == "string": __magic_name__ = '''The small grey turtle was surprisingly fast when challenged.''' else: __magic_name__ = np.random.randint(10 , size=1 ).astype(v.dtype ).item() elif isinstance(snake_case_ , datasets.Sequence ): while isinstance(snake_case_ , datasets.Sequence ): __magic_name__ = v.feature __magic_name__ = seq_shapes[k] __magic_name__ = np.random.rand(*snake_case_ ).astype(v.dtype ) __magic_name__ = data dummy_data.append((i, example) ) return dummy_data def _SCREAMING_SNAKE_CASE ( snake_case_ : Union[str, Any] , snake_case_ : List[Any] , snake_case_ : Optional[Any]=100 , snake_case_ : Dict=None ): __magic_name__ = generate_examples(snake_case_ , num_examples=snake_case_ , seq_shapes=snake_case_ ) with ArrowWriter(features=snake_case_ , path=snake_case_ ) as writer: for key, record in dummy_data: __magic_name__ = features.encode_example(snake_case_ ) writer.write(snake_case_ ) __magic_name__ , __magic_name__ = writer.finalize() if not num_final_examples == num_examples: raise ValueError( f'Error writing the dataset, wrote {num_final_examples} examples but should have written {num_examples}.' ) __magic_name__ = datasets.Dataset.from_file(filename=snake_case_ , info=datasets.DatasetInfo(features=snake_case_ ) ) return dataset
703
from __future__ import annotations import collections import pprint from pathlib import Path def _SCREAMING_SNAKE_CASE ( snake_case_ : str ): return "".join(sorted(snake_case_ ) ) def _SCREAMING_SNAKE_CASE ( snake_case_ : str ): return word_by_signature[signature(snake_case_ )] a_ : str = Path(__file__).parent.joinpath('words.txt').read_text(encoding='utf-8') a_ : Optional[Any] = sorted({word.strip().lower() for word in data.splitlines()}) a_ : List[Any] = collections.defaultdict(list) for word in word_list: word_by_signature[signature(word)].append(word) if __name__ == "__main__": a_ : Optional[Any] = {word: anagram(word) for word in word_list if len(anagram(word)) > 1} with open('anagrams.txt', 'w') as file: file.write('all_anagrams = \n ') file.write(pprint.pformat(all_anagrams))
678
0
import requests lowercase : List[Any] = """https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=""" def UpperCAmelCase_ ( _UpperCAmelCase ): # fetching a list of articles in json format lowerCamelCase_: Any = requests.get(_NEWS_API + bbc_news_api_key ).json() # each article in the list is a dict for i, article in enumerate(bbc_news_page["""articles"""] , 1 ): print(f"""{i}.) {article['title']}""" ) if __name__ == "__main__": fetch_bbc_news(bbc_news_api_key="""<Your BBC News API key goes here>""")
423
"""simple docstring""" def lowerCAmelCase__ ( __magic_name__ ) ->int: if not isinstance(__magic_name__ , __magic_name__ ): raise ValueError("multiplicative_persistence() only accepts integral values" ) if num < 0: raise ValueError("multiplicative_persistence() does not accept negative values" ) __lowercase = 0 __lowercase = str(__magic_name__ ) while len(__magic_name__ ) != 1: __lowercase = [int(__magic_name__ ) for i in num_string] __lowercase = 1 for i in range(0 , len(__magic_name__ ) ): total *= numbers[i] __lowercase = str(__magic_name__ ) steps += 1 return steps def lowerCAmelCase__ ( __magic_name__ ) ->int: if not isinstance(__magic_name__ , __magic_name__ ): raise ValueError("additive_persistence() only accepts integral values" ) if num < 0: raise ValueError("additive_persistence() does not accept negative values" ) __lowercase = 0 __lowercase = str(__magic_name__ ) while len(__magic_name__ ) != 1: __lowercase = [int(__magic_name__ ) for i in num_string] __lowercase = 0 for i in range(0 , len(__magic_name__ ) ): total += numbers[i] __lowercase = str(__magic_name__ ) steps += 1 return steps if __name__ == "__main__": import doctest doctest.testmod()
118
0
def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> int: return int(input_a == input_a == 0 ) def A_ ( ) -> None: print("Truth Table of NOR Gate:" ) print("| Input 1 | Input 2 | Output |" ) print(F"""| 0 | 0 | {nor_gate(0 , 0 )} |""" ) print(F"""| 0 | 1 | {nor_gate(0 , 1 )} |""" ) print(F"""| 1 | 0 | {nor_gate(1 , 0 )} |""" ) print(F"""| 1 | 1 | {nor_gate(1 , 1 )} |""" ) if __name__ == "__main__": import doctest doctest.testmod() main()
38
from __future__ import annotations import os import tempfile import unittest from transformers import ConvBertConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFConvBertForMaskedLM, TFConvBertForMultipleChoice, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertModel, ) class A__ : def __init__( self , A_ , A_=13 , A_=7 , A_=True , A_=True , A_=True , A_=True , A_=99 , A_=32 , A_=2 , A_=4 , A_=37 , A_="gelu" , A_=0.1 , A_=0.1 , A_=512 , A_=16 , A_=2 , A_=0.02 , A_=3 , A_=4 , A_=None , ): '''simple docstring''' UpperCamelCase : Dict = parent UpperCamelCase : str = 13 UpperCamelCase : int = 7 UpperCamelCase : str = True UpperCamelCase : Dict = True UpperCamelCase : str = True UpperCamelCase : Tuple = True UpperCamelCase : List[str] = 99 UpperCamelCase : Optional[Any] = 384 UpperCamelCase : Tuple = 2 UpperCamelCase : Union[str, Any] = 4 UpperCamelCase : Dict = 37 UpperCamelCase : Any = "gelu" UpperCamelCase : List[Any] = 0.1 UpperCamelCase : int = 0.1 UpperCamelCase : Tuple = 512 UpperCamelCase : List[Any] = 16 UpperCamelCase : int = 2 UpperCamelCase : Dict = 0.02 UpperCamelCase : Optional[Any] = 3 UpperCamelCase : List[Any] = 4 UpperCamelCase : Dict = 128 UpperCamelCase : Optional[Any] = 2 UpperCamelCase : Optional[int] = 9 UpperCamelCase : Optional[int] = 1 UpperCamelCase : Union[str, Any] = None def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : int = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase : str = None if self.use_input_mask: UpperCamelCase : List[Any] = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase : Tuple = None if self.use_token_type_ids: UpperCamelCase : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCamelCase : Optional[int] = None UpperCamelCase : Optional[int] = None UpperCamelCase : List[Any] = None if self.use_labels: UpperCamelCase : int = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase : Optional[Any] = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase : Any = ConvBertConfig( 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 , return_dict=A_ , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ): '''simple docstring''' UpperCamelCase : str = TFConvBertModel(config=A_ ) UpperCamelCase : Optional[Any] = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} UpperCamelCase : Optional[int] = [input_ids, input_mask] UpperCamelCase : Any = model(A_ ) UpperCamelCase : int = model(A_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ): '''simple docstring''' UpperCamelCase : Tuple = TFConvBertForMaskedLM(config=A_ ) UpperCamelCase : int = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } UpperCamelCase : Dict = model(A_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ): '''simple docstring''' UpperCamelCase : Dict = self.num_labels UpperCamelCase : int = TFConvBertForSequenceClassification(config=A_ ) UpperCamelCase : List[Any] = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } UpperCamelCase : Optional[Any] = model(A_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ): '''simple docstring''' UpperCamelCase : List[str] = self.num_choices UpperCamelCase : str = TFConvBertForMultipleChoice(config=A_ ) UpperCamelCase : List[Any] = tf.tile(tf.expand_dims(A_ , 1 ) , (1, self.num_choices, 1) ) UpperCamelCase : Dict = tf.tile(tf.expand_dims(A_ , 1 ) , (1, self.num_choices, 1) ) UpperCamelCase : Any = tf.tile(tf.expand_dims(A_ , 1 ) , (1, self.num_choices, 1) ) UpperCamelCase : List[str] = { "input_ids": multiple_choice_inputs_ids, "attention_mask": multiple_choice_input_mask, "token_type_ids": multiple_choice_token_type_ids, } UpperCamelCase : Optional[Any] = model(A_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ): '''simple docstring''' UpperCamelCase : Dict = self.num_labels UpperCamelCase : str = TFConvBertForTokenClassification(config=A_ ) UpperCamelCase : List[Any] = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } UpperCamelCase : str = model(A_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ): '''simple docstring''' UpperCamelCase : List[str] = TFConvBertForQuestionAnswering(config=A_ ) UpperCamelCase : Union[str, Any] = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } UpperCamelCase : Union[str, Any] = model(A_ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Optional[int] = self.prepare_config_and_inputs() ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) : Optional[Any] = config_and_inputs UpperCamelCase : int = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_tf class A__ ( __snake_case , __snake_case , unittest.TestCase ): _UpperCAmelCase :Dict = ( ( TFConvBertModel, TFConvBertForMaskedLM, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertForMultipleChoice, ) if is_tf_available() else () ) _UpperCAmelCase :Optional[Any] = ( { 'feature-extraction': TFConvBertModel, 'fill-mask': TFConvBertForMaskedLM, 'question-answering': TFConvBertForQuestionAnswering, 'text-classification': TFConvBertForSequenceClassification, 'token-classification': TFConvBertForTokenClassification, 'zero-shot': TFConvBertForSequenceClassification, } if is_tf_available() else {} ) _UpperCAmelCase :Any = False _UpperCAmelCase :int = False _UpperCAmelCase :str = False def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Dict = TFConvBertModelTester(self ) UpperCamelCase : Dict = ConfigTester(self , config_class=A_ , hidden_size=37 ) def __UpperCamelCase( self ): '''simple docstring''' self.config_tester.run_common_tests() def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*A_ ) @slow def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase , UpperCamelCase : Dict = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase : Optional[Any] = True UpperCamelCase : Any = True if hasattr(A_ , "use_cache" ): UpperCamelCase : List[str] = True UpperCamelCase : List[Any] = getattr(self.model_tester , "encoder_seq_length" , self.model_tester.seq_length ) UpperCamelCase : Any = getattr(self.model_tester , "key_length" , A_ ) for model_class in self.all_model_classes: UpperCamelCase : List[Any] = self._prepare_for_class(A_ , A_ ) UpperCamelCase : Dict = model_class(A_ ) UpperCamelCase : Optional[int] = len(model(A_ ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(A_ , saved_model=A_ ) UpperCamelCase : Union[str, Any] = os.path.join(A_ , "saved_model" , "1" ) UpperCamelCase : Dict = tf.keras.models.load_model(A_ ) UpperCamelCase : str = model(A_ ) if self.is_encoder_decoder: UpperCamelCase : Union[str, Any] = outputs["encoder_hidden_states"] UpperCamelCase : Any = outputs["encoder_attentions"] else: UpperCamelCase : Any = outputs["hidden_states"] UpperCamelCase : List[str] = outputs["attentions"] self.assertEqual(len(A_ ) , A_ ) UpperCamelCase : int = getattr( self.model_tester , "expected_num_hidden_layers" , self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(A_ ) , A_ ) self.assertListEqual( list(output_hidden_states[0].shape[-2:] ) , [self.model_tester.seq_length, self.model_tester.hidden_size] , ) self.assertEqual(len(A_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(output_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , ) @slow def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Union[str, Any] = TFConvBertModel.from_pretrained("YituTech/conv-bert-base" ) self.assertIsNotNone(A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase , UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase : Dict = True UpperCamelCase : int = getattr(self.model_tester , "decoder_seq_length" , self.model_tester.seq_length ) UpperCamelCase : Optional[int] = getattr(self.model_tester , "encoder_seq_length" , self.model_tester.seq_length ) UpperCamelCase : Optional[int] = getattr(self.model_tester , "key_length" , A_ ) UpperCamelCase : Optional[Any] = getattr(self.model_tester , "key_length" , A_ ) def check_decoder_attentions_output(A_ ): UpperCamelCase : Optional[Any] = len(A_ ) self.assertEqual(out_len % 2 , 0 ) UpperCamelCase : Any = outputs.decoder_attentions self.assertEqual(len(A_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, decoder_seq_length, decoder_key_length] , ) def check_encoder_attentions_output(A_ ): UpperCamelCase : Dict = [ t.numpy() for t in (outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions) ] self.assertEqual(len(A_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , ) for model_class in self.all_model_classes: UpperCamelCase : Union[str, Any] = True UpperCamelCase : List[Any] = False UpperCamelCase : Dict = model_class(A_ ) UpperCamelCase : Dict = model(self._prepare_for_class(A_ , A_ ) ) UpperCamelCase : List[str] = len(A_ ) self.assertEqual(config.output_hidden_states , A_ ) check_encoder_attentions_output(A_ ) if self.is_encoder_decoder: UpperCamelCase : int = model_class(A_ ) UpperCamelCase : Tuple = model(self._prepare_for_class(A_ , A_ ) ) self.assertEqual(config.output_hidden_states , A_ ) check_decoder_attentions_output(A_ ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] UpperCamelCase : Tuple = True UpperCamelCase : int = model_class(A_ ) UpperCamelCase : Dict = model(self._prepare_for_class(A_ , A_ ) ) self.assertEqual(config.output_hidden_states , A_ ) check_encoder_attentions_output(A_ ) # Check attention is always last and order is fine UpperCamelCase : Optional[int] = True UpperCamelCase : List[str] = True UpperCamelCase : Optional[int] = model_class(A_ ) UpperCamelCase : Optional[Any] = model(self._prepare_for_class(A_ , A_ ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(A_ ) ) self.assertEqual(model.config.output_hidden_states , A_ ) check_encoder_attentions_output(A_ ) @require_tf class A__ ( unittest.TestCase ): @slow def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : str = TFConvBertModel.from_pretrained("YituTech/conv-bert-base" ) UpperCamelCase : str = tf.constant([[0, 1, 2, 3, 4, 5]] ) UpperCamelCase : List[str] = model(A_ )[0] UpperCamelCase : int = [1, 6, 768] self.assertEqual(output.shape , A_ ) UpperCamelCase : List[str] = tf.constant( [ [ [-0.03_47_54_93, -0.4_68_60_34, -0.30_63_88_32], [0.22_63_72_48, -0.26_98_86_46, -0.7_42_34_24], [0.10_32_48_68, -0.45_01_35_08, -0.58_28_07_84], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , A_ , atol=1e-4 )
38
1
"""simple docstring""" import csv import tweepy # Twitter API credentials _A = '' _A = '' _A = '' _A = '' def SCREAMING_SNAKE_CASE ( __UpperCAmelCase ) -> None: SCREAMING_SNAKE_CASE__ = tweepy.OAuthHandler(__UpperCAmelCase , __UpperCAmelCase ) auth.set_access_token(__UpperCAmelCase , __UpperCAmelCase ) SCREAMING_SNAKE_CASE__ = tweepy.API(__UpperCAmelCase ) # initialize a list to hold all the tweepy Tweets SCREAMING_SNAKE_CASE__ = [] # make initial request for most recent tweets (200 is the maximum allowed count) SCREAMING_SNAKE_CASE__ = api.user_timeline(screen_name=__UpperCAmelCase , count=200 ) # save most recent tweets alltweets.extend(__UpperCAmelCase ) # save the id of the oldest tweet less one SCREAMING_SNAKE_CASE__ = alltweets[-1].id - 1 # keep grabbing tweets until there are no tweets left to grab while len(__UpperCAmelCase ) > 0: print(F"""getting tweets before {oldest}""" ) # all subsequent requests use the max_id param to prevent duplicates SCREAMING_SNAKE_CASE__ = api.user_timeline( screen_name=__UpperCAmelCase , count=200 , max_id=__UpperCAmelCase ) # save most recent tweets alltweets.extend(__UpperCAmelCase ) # update the id of the oldest tweet less one SCREAMING_SNAKE_CASE__ = alltweets[-1].id - 1 print(F"""...{len(__UpperCAmelCase )} tweets downloaded so far""" ) # transform the tweepy tweets into a 2D array that will populate the csv SCREAMING_SNAKE_CASE__ = [[tweet.id_str, tweet.created_at, tweet.text] for tweet in alltweets] # write the csv with open(F"""new_{screen_name}_tweets.csv""" , "w" ) as f: SCREAMING_SNAKE_CASE__ = csv.writer(__UpperCAmelCase ) writer.writerow(["id", "created_at", "text"] ) writer.writerows(__UpperCAmelCase ) if __name__ == "__main__": # pass in the username of the account you want to download get_all_tweets('FirePing32')
159
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 lowerCAmelCase_ : def __init__( self : Dict , __A : Optional[int] , __A : int=2 , __A : str=True , __A : List[Any]=False , __A : List[str]=10 , __A : Union[str, Any]=3 , __A : Dict=32 * 8 , __A : str=32 * 8 , __A : int=4 , __A : List[str]=64 , ) ->Tuple: """simple docstring""" a__ :Optional[Any] = parent a__ :Dict = batch_size a__ :str = is_training a__ :Optional[int] = use_auxiliary_loss a__ :str = num_queries a__ :int = num_channels a__ :Optional[int] = min_size a__ :Optional[Any] = max_size a__ :Dict = num_labels a__ :Union[str, Any] = hidden_dim a__ :Any = hidden_dim def _snake_case ( self : Tuple ) ->List[str]: """simple docstring""" a__ :Optional[int] = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( __A ) a__ :Optional[int] = torch.ones([self.batch_size, self.min_size, self.max_size] , device=__A ) a__ :Optional[int] = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=__A ) > 0.5 ).float() a__ :List[str] = (torch.rand((self.batch_size, self.num_labels) , device=__A ) > 0.5).long() a__ :Tuple = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def _snake_case ( self : Tuple ) ->Union[str, Any]: """simple docstring""" a__ :List[str] = MaskaFormerConfig( hidden_size=self.hidden_dim , ) a__ :List[str] = self.num_queries a__ :Optional[int] = self.num_labels a__ :Tuple = [1, 1, 1, 1] a__ :Dict = self.num_channels a__ :Optional[Any] = 64 a__ :Union[str, Any] = 128 a__ :Optional[Any] = self.hidden_dim a__ :int = self.hidden_dim a__ :List[str] = self.hidden_dim return config def _snake_case ( self : Any ) ->Dict: """simple docstring""" a__ , a__ , a__ , a__ , a__ :int = self.prepare_config_and_inputs() a__ :Optional[int] = {"pixel_values": pixel_values, "pixel_mask": pixel_mask} return config, inputs_dict def _snake_case ( self : int , __A : Union[str, Any] , __A : Tuple ) ->List[Any]: """simple docstring""" a__ :Tuple = output.encoder_hidden_states a__ :List[Any] = output.pixel_decoder_hidden_states a__ :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 _snake_case ( self : Dict , __A : List[str] , __A : Tuple , __A : Union[str, Any] , __A : Dict=False ) ->Any: """simple docstring""" with torch.no_grad(): a__ :Dict = MaskaFormerModel(config=__A ) model.to(__A ) model.eval() a__ :Tuple = model(pixel_values=__A , pixel_mask=__A ) a__ :Dict = 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 _snake_case ( self : Optional[int] , __A : int , __A : str , __A : Tuple , __A : List[Any] , __A : List[str] ) ->Any: """simple docstring""" a__ :Dict = MaskaFormerForUniversalSegmentation(config=__A ) model.to(__A ) model.eval() def comm_check_on_output(__A : Tuple ): # 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(): a__ :Union[str, Any] = model(pixel_values=__A , pixel_mask=__A ) a__ :List[Any] = model(__A ) comm_check_on_output(__A ) a__ :str = 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 lowerCAmelCase_ ( _a ,_a ,unittest.TestCase): lowerCamelCase_ = (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else () lowerCamelCase_ = {'feature-extraction': MaskaFormerModel} if is_torch_available() else {} lowerCamelCase_ = False lowerCamelCase_ = False lowerCamelCase_ = False lowerCamelCase_ = False def _snake_case ( self : Tuple ) ->Dict: """simple docstring""" a__ :List[str] = MaskaFormerModelTester(self ) a__ :List[str] = ConfigTester(self , config_class=__A , has_text_modality=__A ) def _snake_case ( self : Tuple ) ->str: """simple docstring""" self.config_tester.run_common_tests() def _snake_case ( self : str ) ->Tuple: """simple docstring""" a__ , a__ :str = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(__A , **__A , output_hidden_states=__A ) def _snake_case ( self : Union[str, Any] ) ->int: """simple docstring""" a__ :Optional[Any] = 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 _snake_case ( self : List[str] ) ->Optional[Any]: """simple docstring""" pass @unittest.skip(reason="Mask2Former does not have a get_input_embeddings method" ) def _snake_case ( self : int ) ->Dict: """simple docstring""" pass @unittest.skip(reason="Mask2Former is not a generative model" ) def _snake_case ( self : Any ) ->List[str]: """simple docstring""" pass @unittest.skip(reason="Mask2Former does not use token embeddings" ) def _snake_case ( self : Union[str, Any] ) ->Union[str, Any]: """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 _snake_case ( self : str ) ->str: """simple docstring""" pass @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." ) def _snake_case ( self : Optional[int] ) ->Any: """simple docstring""" pass def _snake_case ( self : Any ) ->Union[str, Any]: """simple docstring""" a__ , a__ :Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a__ :Any = model_class(__A ) a__ :Union[str, Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic a__ :Optional[Any] = [*signature.parameters.keys()] a__ :str = ["pixel_values"] self.assertListEqual(arg_names[:1] , __A ) @slow def _snake_case ( self : Dict ) ->str: """simple docstring""" for model_name in ["facebook/mask2former-swin-small-coco-instance"]: a__ :Any = MaskaFormerModel.from_pretrained(__A ) self.assertIsNotNone(__A ) def _snake_case ( self : List[str] ) ->List[Any]: """simple docstring""" a__ :Tuple = (self.model_tester.min_size,) * 2 a__ :Optional[int] = { "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(), } a__ :Dict = self.model_tester.get_config() a__ :str = MaskaFormerForUniversalSegmentation(__A ).to(__A ) a__ :int = model(**__A ) self.assertTrue(outputs.loss is not None ) def _snake_case ( self : List[str] ) ->Any: """simple docstring""" a__ , a__ :Optional[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 _snake_case ( self : Tuple ) ->Tuple: """simple docstring""" a__ , a__ :Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a__ :Union[str, Any] = model_class(__A ).to(__A ) a__ :int = model(**__A , output_attentions=__A ) self.assertTrue(outputs.attentions is not None ) def _snake_case ( self : Any ) ->Any: """simple docstring""" if not self.model_tester.is_training: return a__ :str = self.all_model_classes[1] a__ , a__ , a__ , a__ , a__ :Any = self.model_tester.prepare_config_and_inputs() a__ :Optional[Any] = model_class(__A ) model.to(__A ) model.train() a__ :Any = model(__A , mask_labels=__A , class_labels=__A ).loss loss.backward() def _snake_case ( self : Tuple ) ->Optional[Any]: """simple docstring""" a__ :List[str] = self.all_model_classes[1] a__ , a__ , a__ , a__ , a__ :int = self.model_tester.prepare_config_and_inputs() a__ :Optional[Any] = True a__ :Optional[int] = True a__ :List[Any] = model_class(__A ).to(__A ) model.train() a__ :Optional[Any] = model(__A , mask_labels=__A , class_labels=__A ) a__ :int = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() a__ :List[str] = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() a__ :List[Any] = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() a__ :Optional[int] = 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 ) snake_case__ = 1e-4 def lowerCamelCase__ ( ) -> Optional[int]: """simple docstring""" a__ :Dict = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_vision @slow class lowerCAmelCase_ ( unittest.TestCase): @cached_property def _snake_case ( self : int ) ->Optional[int]: """simple docstring""" return "facebook/mask2former-swin-small-coco-instance" @cached_property def _snake_case ( self : int ) ->Dict: """simple docstring""" return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints ) if is_vision_available() else None def _snake_case ( self : str ) ->int: """simple docstring""" a__ :Tuple = MaskaFormerModel.from_pretrained(self.model_checkpoints ).to(__A ) a__ :List[Any] = self.default_image_processor a__ :str = prepare_img() a__ :Union[str, Any] = image_processor(__A , return_tensors="pt" ).to(__A ) a__ :Union[str, 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(): a__ :Optional[int] = model(**__A ) a__ :str = torch.tensor( [[-0.2_790, -1.0_717, -1.1_668], [-0.5_128, -0.3_128, -0.4_987], [-0.5_832, 0.1_971, -0.0_197]] ).to(__A ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , __A , atol=__A ) ) a__ :Dict = torch.tensor( [[0.8_973, 1.1_847, 1.1_776], [1.1_934, 1.5_040, 1.5_128], [1.1_153, 1.4_486, 1.4_951]] ).to(__A ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , __A , atol=__A ) ) a__ :Union[str, Any] = torch.tensor( [[2.1_152, 1.7_000, -0.8_603], [1.5_808, 1.8_004, -0.9_353], [1.6_043, 1.7_495, -0.5_999]] ).to(__A ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , __A , atol=__A ) ) def _snake_case ( self : Any ) ->Dict: """simple docstring""" a__ :Dict = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(__A ).eval() a__ :Tuple = self.default_image_processor a__ :Any = prepare_img() a__ :str = image_processor(__A , return_tensors="pt" ).to(__A ) a__ :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(): a__ :int = model(**__A ) # masks_queries_logits a__ :Optional[Any] = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) ) a__ :Dict = [ [-8.7_839, -9.0_056, -8.8_121], [-7.4_104, -7.0_313, -6.5_401], [-6.6_105, -6.3_427, -6.4_675], ] a__ :Any = torch.tensor(__A ).to(__A ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , __A , atol=__A ) ) # class_queries_logits a__ :Tuple = outputs.class_queries_logits self.assertEqual(class_queries_logits.shape , (1, model.config.num_queries, model.config.num_labels + 1) ) a__ :Optional[int] = torch.tensor( [ [1.8_324, -8.0_835, -4.1_922], [0.8_450, -9.0_050, -3.6_053], [0.3_045, -7.7_293, -3.0_275], ] ).to(__A ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , __A , atol=__A ) ) def _snake_case ( self : List[str] ) ->List[Any]: """simple docstring""" a__ :List[str] = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(__A ).eval() a__ :Tuple = self.default_image_processor a__ :str = 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" , ) a__ :Tuple = inputs["pixel_values"].to(__A ) a__ :List[Any] = [el.to(__A ) for el in inputs["mask_labels"]] a__ :List[str] = [el.to(__A ) for el in inputs["class_labels"]] with torch.no_grad(): a__ :List[str] = model(**__A ) self.assertTrue(outputs.loss is not None )
395
0
"""simple docstring""" from __future__ import annotations def UpperCamelCase_ ( SCREAMING_SNAKE_CASE_ ): '''simple docstring''' if not nums: return 0 SCREAMING_SNAKE_CASE = nums[0] SCREAMING_SNAKE_CASE = 0 for num in nums[1:]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = ( max_excluding + num, max(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ), ) return max(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": import doctest doctest.testmod()
706
"""simple docstring""" import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import YolosConfig, YolosForObjectDetection, YolosImageProcessor from transformers.utils import logging logging.set_verbosity_info() snake_case = logging.get_logger(__name__) def UpperCamelCase_ ( SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE = YolosConfig() # size of the architecture if "yolos_ti" in yolos_name: SCREAMING_SNAKE_CASE = 1_9_2 SCREAMING_SNAKE_CASE = 7_6_8 SCREAMING_SNAKE_CASE = 1_2 SCREAMING_SNAKE_CASE = 3 SCREAMING_SNAKE_CASE = [8_0_0, 1_3_3_3] SCREAMING_SNAKE_CASE = False elif yolos_name == "yolos_s_dWr": SCREAMING_SNAKE_CASE = 3_3_0 SCREAMING_SNAKE_CASE = 1_4 SCREAMING_SNAKE_CASE = 6 SCREAMING_SNAKE_CASE = 1_3_2_0 elif "yolos_s" in yolos_name: SCREAMING_SNAKE_CASE = 3_8_4 SCREAMING_SNAKE_CASE = 1_5_3_6 SCREAMING_SNAKE_CASE = 1_2 SCREAMING_SNAKE_CASE = 6 elif "yolos_b" in yolos_name: SCREAMING_SNAKE_CASE = [8_0_0, 1_3_4_4] SCREAMING_SNAKE_CASE = 9_1 SCREAMING_SNAKE_CASE = 'huggingface/label-files' SCREAMING_SNAKE_CASE = 'coco-detection-id2label.json' SCREAMING_SNAKE_CASE = json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, repo_type='dataset' ), 'r' ) ) SCREAMING_SNAKE_CASE = {int(SCREAMING_SNAKE_CASE_ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE = idalabel SCREAMING_SNAKE_CASE = {v: k for k, v in idalabel.items()} return config def UpperCamelCase_ ( SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ = False ): for i in range(config.num_hidden_layers ): # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) SCREAMING_SNAKE_CASE = state_dict.pop(f'''blocks.{i}.attn.qkv.weight''' ) SCREAMING_SNAKE_CASE = 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 = in_proj_weight[: config.hidden_size, :] SCREAMING_SNAKE_CASE = in_proj_bias[: config.hidden_size] SCREAMING_SNAKE_CASE = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] SCREAMING_SNAKE_CASE = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] SCREAMING_SNAKE_CASE = in_proj_weight[-config.hidden_size :, :] SCREAMING_SNAKE_CASE = in_proj_bias[-config.hidden_size :] def UpperCamelCase_ ( SCREAMING_SNAKE_CASE_ ): if "backbone" in name: SCREAMING_SNAKE_CASE = name.replace('backbone', 'vit' ) if "cls_token" in name: SCREAMING_SNAKE_CASE = name.replace('cls_token', 'embeddings.cls_token' ) if "det_token" in name: SCREAMING_SNAKE_CASE = name.replace('det_token', 'embeddings.detection_tokens' ) if "mid_pos_embed" in name: SCREAMING_SNAKE_CASE = name.replace('mid_pos_embed', 'encoder.mid_position_embeddings' ) if "pos_embed" in name: SCREAMING_SNAKE_CASE = name.replace('pos_embed', 'embeddings.position_embeddings' ) if "patch_embed.proj" in name: SCREAMING_SNAKE_CASE = name.replace('patch_embed.proj', 'embeddings.patch_embeddings.projection' ) if "blocks" in name: SCREAMING_SNAKE_CASE = name.replace('blocks', 'encoder.layer' ) if "attn.proj" in name: SCREAMING_SNAKE_CASE = name.replace('attn.proj', 'attention.output.dense' ) if "attn" in name: SCREAMING_SNAKE_CASE = name.replace('attn', 'attention.self' ) if "norm1" in name: SCREAMING_SNAKE_CASE = name.replace('norm1', 'layernorm_before' ) if "norm2" in name: SCREAMING_SNAKE_CASE = name.replace('norm2', 'layernorm_after' ) if "mlp.fc1" in name: SCREAMING_SNAKE_CASE = name.replace('mlp.fc1', 'intermediate.dense' ) if "mlp.fc2" in name: SCREAMING_SNAKE_CASE = name.replace('mlp.fc2', 'output.dense' ) if "class_embed" in name: SCREAMING_SNAKE_CASE = name.replace('class_embed', 'class_labels_classifier' ) if "bbox_embed" in name: SCREAMING_SNAKE_CASE = name.replace('bbox_embed', 'bbox_predictor' ) if "vit.norm" in name: SCREAMING_SNAKE_CASE = name.replace('vit.norm', 'vit.layernorm' ) return name def UpperCamelCase_ ( SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ): for key in orig_state_dict.copy().keys(): SCREAMING_SNAKE_CASE = orig_state_dict.pop(SCREAMING_SNAKE_CASE_ ) if "qkv" in key: SCREAMING_SNAKE_CASE = key.split('.' ) SCREAMING_SNAKE_CASE = int(key_split[2] ) SCREAMING_SNAKE_CASE = model.vit.encoder.layer[layer_num].attention.attention.all_head_size if "weight" in key: SCREAMING_SNAKE_CASE = val[:dim, :] SCREAMING_SNAKE_CASE = val[ dim : dim * 2, : ] SCREAMING_SNAKE_CASE = val[-dim:, :] else: SCREAMING_SNAKE_CASE = val[:dim] SCREAMING_SNAKE_CASE = val[dim : dim * 2] SCREAMING_SNAKE_CASE = val[-dim:] else: SCREAMING_SNAKE_CASE = val return orig_state_dict def UpperCamelCase_ ( ): SCREAMING_SNAKE_CASE = 'http://images.cocodataset.org/val2017/000000039769.jpg' SCREAMING_SNAKE_CASE = Image.open(requests.get(SCREAMING_SNAKE_CASE_, stream=SCREAMING_SNAKE_CASE_ ).raw ) return im @torch.no_grad() def UpperCamelCase_ ( SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ = False ): SCREAMING_SNAKE_CASE = get_yolos_config(SCREAMING_SNAKE_CASE_ ) # load original state_dict SCREAMING_SNAKE_CASE = torch.load(SCREAMING_SNAKE_CASE_, map_location='cpu' )['model'] # load 🤗 model SCREAMING_SNAKE_CASE = YolosForObjectDetection(SCREAMING_SNAKE_CASE_ ) model.eval() SCREAMING_SNAKE_CASE = convert_state_dict(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) model.load_state_dict(SCREAMING_SNAKE_CASE_ ) # Check outputs on an image, prepared by YolosImageProcessor SCREAMING_SNAKE_CASE = 8_0_0 if yolos_name != 'yolos_ti' else 5_1_2 SCREAMING_SNAKE_CASE = YolosImageProcessor(format='coco_detection', size=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE = image_processor(images=prepare_img(), return_tensors='pt' ) SCREAMING_SNAKE_CASE = model(**SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = outputs.logits, outputs.pred_boxes SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = None, None if yolos_name == "yolos_ti": SCREAMING_SNAKE_CASE = torch.tensor( [[-39.5_022, -11.9_820, -17.6_888], [-29.9_574, -9.9_769, -17.7_691], [-42.3_281, -20.7_200, -30.6_294]] ) SCREAMING_SNAKE_CASE = torch.tensor( [[0.4_021, 0.0_836, 0.7_979], [0.0_184, 0.2_609, 0.0_364], [0.1_781, 0.2_004, 0.2_095]] ) elif yolos_name == "yolos_s_200_pre": SCREAMING_SNAKE_CASE = torch.tensor( [[-24.0_248, -10.3_024, -14.8_290], [-42.0_392, -16.8_200, -27.4_334], [-27.2_743, -11.8_154, -18.7_148]] ) SCREAMING_SNAKE_CASE = torch.tensor( [[0.2_559, 0.5_455, 0.4_706], [0.2_989, 0.7_279, 0.1_875], [0.7_732, 0.4_017, 0.4_462]] ) elif yolos_name == "yolos_s_300_pre": SCREAMING_SNAKE_CASE = torch.tensor( [[-36.2_220, -14.4_385, -23.5_457], [-35.6_970, -14.7_583, -21.3_935], [-31.5_939, -13.6_042, -16.8_049]] ) SCREAMING_SNAKE_CASE = torch.tensor( [[0.7_614, 0.2_316, 0.4_728], [0.7_168, 0.4_495, 0.3_855], [0.4_996, 0.1_466, 0.9_996]] ) elif yolos_name == "yolos_s_dWr": SCREAMING_SNAKE_CASE = torch.tensor( [[-42.8_668, -24.1_049, -41.1_690], [-34.7_456, -14.1_274, -24.9_194], [-33.7_898, -12.1_946, -25.6_495]] ) SCREAMING_SNAKE_CASE = torch.tensor( [[0.5_587, 0.2_773, 0.0_605], [0.5_004, 0.3_014, 0.9_994], [0.4_999, 0.1_548, 0.9_994]] ) elif yolos_name == "yolos_base": SCREAMING_SNAKE_CASE = torch.tensor( [[-40.6_064, -24.3_084, -32.6_447], [-55.1_990, -30.7_719, -35.5_877], [-51.4_311, -33.3_507, -35.6_462]] ) SCREAMING_SNAKE_CASE = torch.tensor( [[0.5_555, 0.2_794, 0.0_655], [0.9_049, 0.2_664, 0.1_894], [0.9_183, 0.1_984, 0.1_635]] ) else: raise ValueError(f'''Unknown yolos_name: {yolos_name}''' ) assert torch.allclose(logits[0, :3, :3], SCREAMING_SNAKE_CASE_, atol=1E-4 ) assert torch.allclose(pred_boxes[0, :3, :3], SCREAMING_SNAKE_CASE_, atol=1E-4 ) Path(SCREAMING_SNAKE_CASE_ ).mkdir(exist_ok=SCREAMING_SNAKE_CASE_ ) print(f'''Saving model {yolos_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(SCREAMING_SNAKE_CASE_ ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(SCREAMING_SNAKE_CASE_ ) if push_to_hub: SCREAMING_SNAKE_CASE = { 'yolos_ti': 'yolos-tiny', 'yolos_s_200_pre': 'yolos-small', 'yolos_s_300_pre': 'yolos-small-300', 'yolos_s_dWr': 'yolos-small-dwr', 'yolos_base': 'yolos-base', } print('Pushing to the hub...' ) SCREAMING_SNAKE_CASE = model_mapping[yolos_name] image_processor.push_to_hub(SCREAMING_SNAKE_CASE_, organization='hustvl' ) model.push_to_hub(SCREAMING_SNAKE_CASE_, organization='hustvl' ) if __name__ == "__main__": snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument( '--yolos_name', default='yolos_s_200_pre', type=str, help=( 'Name of the YOLOS model you\'d like to convert. Should be one of \'yolos_ti\', \'yolos_s_200_pre\',' ' \'yolos_s_300_pre\', \'yolos_s_dWr\', \'yolos_base\'.' ), ) parser.add_argument( '--checkpoint_path', default=None, type=str, help='Path to the original state dict (.pth file).' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.' ) snake_case = parser.parse_args() convert_yolos_checkpoint(args.yolos_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub)
406
0
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.utils import ComputeEnvironment from .cluster import get_cluster_input from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401 from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401 from .sagemaker import get_sagemaker_input lowercase : Optional[int] = "Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine" def UpperCAmelCase_ (): __UpperCamelCase : Dict = _ask_options( "In which compute environment are you running?" , ["This machine", "AWS (Amazon SageMaker)"] , _convert_compute_environment , ) if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: __UpperCamelCase : Dict = get_sagemaker_input() else: __UpperCamelCase : List[Any] = get_cluster_input() return config def UpperCAmelCase_ (_lowerCAmelCase : int=None ): if subparsers is not None: __UpperCamelCase : Dict = subparsers.add_parser("config" , description=_lowerCAmelCase ) else: __UpperCamelCase : Optional[int] = argparse.ArgumentParser("Accelerate config command" , description=_lowerCAmelCase ) parser.add_argument( "--config_file" , default=_lowerCAmelCase , help=( "The path to use to store the config file. Will default to a file named default_config.yaml in the cache " "location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have " "such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed " "with 'huggingface'." ) , ) if subparsers is not None: parser.set_defaults(func=_lowerCAmelCase ) return parser def UpperCAmelCase_ (_lowerCAmelCase : List[Any] ): __UpperCamelCase : int = get_user_input() if args.config_file is not None: __UpperCamelCase : Optional[int] = args.config_file else: if not os.path.isdir(_lowerCAmelCase ): os.makedirs(_lowerCAmelCase ) __UpperCamelCase : Optional[int] = default_yaml_config_file if config_file.endswith(".json" ): config.to_json_file(_lowerCAmelCase ) else: config.to_yaml_file(_lowerCAmelCase ) print(F'''accelerate configuration saved at {config_file}''' ) def UpperCAmelCase_ (): __UpperCamelCase : List[Any] = config_command_parser() __UpperCamelCase : Dict = parser.parse_args() config_command(_lowerCAmelCase ) if __name__ == "__main__": main()
327
# 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. from argparse import ArgumentParser from accelerate.commands.config import get_config_parser from accelerate.commands.env import env_command_parser from accelerate.commands.launch import launch_command_parser from accelerate.commands.test import test_command_parser from accelerate.commands.tpu import tpu_command_parser def UpperCAmelCase_ (): __UpperCamelCase : Any = ArgumentParser("Accelerate CLI tool" , usage="accelerate <command> [<args>]" , allow_abbrev=_lowerCAmelCase ) __UpperCamelCase : Optional[Any] = parser.add_subparsers(help="accelerate command helpers" ) # Register commands get_config_parser(subparsers=_lowerCAmelCase ) env_command_parser(subparsers=_lowerCAmelCase ) launch_command_parser(subparsers=_lowerCAmelCase ) tpu_command_parser(subparsers=_lowerCAmelCase ) test_command_parser(subparsers=_lowerCAmelCase ) # Let's go __UpperCamelCase : int = parser.parse_args() if not hasattr(_lowerCAmelCase , "func" ): parser.print_help() exit(1 ) # Run args.func(_lowerCAmelCase ) if __name__ == "__main__": main()
327
1
import argparse import requests import torch from PIL import Image from transformers import CLIPProcessor, GroupViTConfig, GroupViTModel def _lowerCAmelCase ( _lowerCAmelCase ): '''simple docstring''' if "img_encoder.pos_embed" in name: A_ : Tuple = name.replace("""img_encoder.pos_embed""" ,"""vision_model.embeddings.position_embeddings""" ) if "img_encoder.patch_embed.proj" in name: A_ : Optional[Any] = name.replace("""img_encoder.patch_embed.proj""" ,"""vision_model.embeddings.patch_embeddings.projection""" ) if "img_encoder.patch_embed.norm" in name: A_ : List[Any] = name.replace("""img_encoder.patch_embed.norm""" ,"""vision_model.embeddings.layernorm""" ) if "img_encoder.layers" in name: A_ : Dict = name.replace("""img_encoder.layers""" ,"""vision_model.encoder.stages""" ) if "blocks" in name and "res" not in name: A_ : str = name.replace("""blocks""" ,"""layers""" ) if "attn" in name and "pre_assign" not in name: A_ : Optional[int] = name.replace("""attn""" ,"""self_attn""" ) if "proj" in name and "self_attn" in name and "text" not in name: A_ : Any = name.replace("""proj""" ,"""out_proj""" ) if "pre_assign_attn.attn.proj" in name: A_ : Optional[int] = name.replace("""pre_assign_attn.attn.proj""" ,"""pre_assign_attn.attn.out_proj""" ) if "norm1" in name: A_ : List[str] = name.replace("""norm1""" ,"""layer_norm1""" ) if "norm2" in name and "pre_assign" not in name: A_ : str = name.replace("""norm2""" ,"""layer_norm2""" ) if "img_encoder.norm" in name: A_ : Dict = name.replace("""img_encoder.norm""" ,"""vision_model.layernorm""" ) # text encoder if "text_encoder.token_embedding" in name: A_ : Union[str, Any] = name.replace("""text_encoder.token_embedding""" ,"""text_model.embeddings.token_embedding""" ) if "text_encoder.positional_embedding" in name: A_ : List[str] = name.replace("""text_encoder.positional_embedding""" ,"""text_model.embeddings.position_embedding.weight""" ) if "text_encoder.transformer.resblocks." in name: A_ : Union[str, Any] = name.replace("""text_encoder.transformer.resblocks.""" ,"""text_model.encoder.layers.""" ) if "ln_1" in name: A_ : Tuple = name.replace("""ln_1""" ,"""layer_norm1""" ) if "ln_2" in name: A_ : Any = name.replace("""ln_2""" ,"""layer_norm2""" ) if "c_fc" in name: A_ : int = name.replace("""c_fc""" ,"""fc1""" ) if "c_proj" in name: A_ : Optional[int] = name.replace("""c_proj""" ,"""fc2""" ) if "text_encoder" in name: A_ : Optional[int] = name.replace("""text_encoder""" ,"""text_model""" ) if "ln_final" in name: A_ : Any = name.replace("""ln_final""" ,"""final_layer_norm""" ) # projection layers if "img_projector.linear_hidden." in name: A_ : Tuple = name.replace("""img_projector.linear_hidden.""" ,"""visual_projection.""" ) if "img_projector.linear_out." in name: A_ : Any = name.replace("""img_projector.linear_out.""" ,"""visual_projection.3.""" ) if "text_projector.linear_hidden" in name: A_ : str = name.replace("""text_projector.linear_hidden""" ,"""text_projection""" ) if "text_projector.linear_out" in name: A_ : Dict = name.replace("""text_projector.linear_out""" ,"""text_projection.3""" ) return name def _lowerCAmelCase ( _lowerCAmelCase ,_lowerCAmelCase ): '''simple docstring''' for key in orig_state_dict.copy().keys(): A_ : Dict = orig_state_dict.pop(_lowerCAmelCase ) if "qkv" in key: # weights and biases of the key, value and query projections of vision encoder's attention layers require special treatment: # we need to split them up into separate matrices/vectors A_ : int = key.split(""".""" ) A_ , A_ : List[Any] = int(key_split[2] ), int(key_split[4] ) A_ : Any = config.vision_config.hidden_size if "weight" in key: A_ : Optional[Any] = val[:dim, :] A_ : Union[str, Any] = val[dim : dim * 2, :] A_ : List[str] = val[-dim:, :] else: A_ : Tuple = val[:dim] A_ : int = val[dim : dim * 2] A_ : Dict = val[-dim:] elif "in_proj" in key: # weights and biases of the key, value and query projections of text encoder's attention layers require special treatment: # we need to split them up into separate matrices/vectors A_ : int = key.split(""".""" ) A_ : Optional[int] = int(key_split[3] ) A_ : Dict = config.text_config.hidden_size if "weight" in key: A_ : str = val[:dim, :] A_ : Optional[int] = val[ dim : dim * 2, : ] A_ : int = val[-dim:, :] else: A_ : List[Any] = val[:dim] A_ : Tuple = val[dim : dim * 2] A_ : Any = val[-dim:] else: A_ : str = rename_key(_lowerCAmelCase ) # squeeze if necessary if ( "text_projection.0" in new_name or "text_projection.3" in new_name or "visual_projection.0" in new_name or "visual_projection.3" in new_name ): A_ : str = val.squeeze_() else: A_ : Tuple = val return orig_state_dict def _lowerCAmelCase ( ): '''simple docstring''' A_ : List[Any] = """http://images.cocodataset.org/val2017/000000039769.jpg""" A_ : Union[str, Any] = Image.open(requests.get(_lowerCAmelCase ,stream=_lowerCAmelCase ).raw ) return im @torch.no_grad() def _lowerCAmelCase ( _lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase="groupvit-gcc-yfcc" ,_lowerCAmelCase=False ): '''simple docstring''' A_ : int = GroupViTConfig() A_ : Tuple = GroupViTModel(_lowerCAmelCase ).eval() A_ : List[str] = torch.load(_lowerCAmelCase ,map_location="""cpu""" )["""model"""] A_ : Dict = convert_state_dict(_lowerCAmelCase ,_lowerCAmelCase ) A_ , A_ : Optional[int] = model.load_state_dict(_lowerCAmelCase ,strict=_lowerCAmelCase ) assert missing_keys == ["text_model.embeddings.position_ids"] assert (unexpected_keys == ["multi_label_logit_scale"]) or (len(_lowerCAmelCase ) == 0) # verify result A_ : int = CLIPProcessor.from_pretrained("""openai/clip-vit-base-patch32""" ) A_ : str = prepare_img() A_ : Dict = processor(text=["""a photo of a cat""", """a photo of a dog"""] ,images=_lowerCAmelCase ,padding=_lowerCAmelCase ,return_tensors="""pt""" ) with torch.no_grad(): A_ : Union[str, Any] = model(**_lowerCAmelCase ) if model_name == "groupvit-gcc-yfcc": A_ : List[str] = torch.tensor([[13.3523, 6.3629]] ) elif model_name == "groupvit-gcc-redcaps": A_ : Dict = torch.tensor([[16.1873, 8.6230]] ) else: raise ValueError(f"""Model name {model_name} not supported.""" ) assert torch.allclose(outputs.logits_per_image ,_lowerCAmelCase ,atol=1e-3 ) processor.save_pretrained(_lowerCAmelCase ) model.save_pretrained(_lowerCAmelCase ) print("""Successfully saved processor and model to""" ,_lowerCAmelCase ) if push_to_hub: print("""Pushing to the hub...""" ) processor.push_to_hub(_lowerCAmelCase ,organization="""nielsr""" ) model.push_to_hub(_lowerCAmelCase ,organization="""nielsr""" ) if __name__ == "__main__": _lowerCAmelCase = argparse.ArgumentParser() parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to dump the processor and PyTorch model.""" ) parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to GroupViT checkpoint""") parser.add_argument( """--model_name""", default="""groupvit-gccy-fcc""", type=str, help="""Name of the model. Expecting either 'groupvit-gcc-yfcc' or 'groupvit-gcc-redcaps'""", ) parser.add_argument( """--push_to_hub""", action="""store_true""", help="""Whether or not to push the converted model and processor to the 🤗 hub using the provided `model_name`.""", ) _lowerCAmelCase = parser.parse_args() convert_groupvit_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.model_name, args.push_to_hub)
481
_lowerCAmelCase = """ABCDEFGHIJKLMNOPQRSTUVWXYZ""" def _lowerCAmelCase ( ): '''simple docstring''' A_ : Any = input("""Enter message: """ ) A_ : Dict = input("""Enter key [alphanumeric]: """ ) A_ : Dict = input("""Encrypt/Decrypt [e/d]: """ ) if mode.lower().startswith("""e""" ): A_ : Union[str, Any] = """encrypt""" A_ : Optional[int] = encrypt_message(_lowerCAmelCase ,_lowerCAmelCase ) elif mode.lower().startswith("""d""" ): A_ : str = """decrypt""" A_ : Dict = decrypt_message(_lowerCAmelCase ,_lowerCAmelCase ) print(f"""\n{mode.title()}ed message:""" ) print(_lowerCAmelCase ) def _lowerCAmelCase ( _lowerCAmelCase ,_lowerCAmelCase ): '''simple docstring''' return translate_message(_lowerCAmelCase ,_lowerCAmelCase ,"""encrypt""" ) def _lowerCAmelCase ( _lowerCAmelCase ,_lowerCAmelCase ): '''simple docstring''' return translate_message(_lowerCAmelCase ,_lowerCAmelCase ,"""decrypt""" ) def _lowerCAmelCase ( _lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ): '''simple docstring''' A_ : Dict = [] A_ : List[Any] = 0 A_ : int = key.upper() for symbol in message: A_ : Optional[int] = LETTERS.find(symbol.upper() ) if num != -1: if mode == "encrypt": num += LETTERS.find(key[key_index] ) elif mode == "decrypt": num -= LETTERS.find(key[key_index] ) num %= len(_lowerCAmelCase ) if symbol.isupper(): translated.append(LETTERS[num] ) elif symbol.islower(): translated.append(LETTERS[num].lower() ) key_index += 1 if key_index == len(_lowerCAmelCase ): A_ : Dict = 0 else: translated.append(_lowerCAmelCase ) return "".join(_lowerCAmelCase ) if __name__ == "__main__": main()
481
1
from math import pi, sqrt, tan def A__ ( lowerCamelCase ) -> float: if side_length < 0: raise ValueError("""surface_area_cube() only accepts non-negative values""" ) return 6 * side_length**2 def A__ ( lowerCamelCase , lowerCamelCase , lowerCamelCase ) -> float: 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__ ( lowerCamelCase ) -> float: if radius < 0: raise ValueError("""surface_area_sphere() only accepts non-negative values""" ) return 4 * pi * radius**2 def A__ ( lowerCamelCase ) -> float: if radius < 0: raise ValueError("""surface_area_hemisphere() only accepts non-negative values""" ) return 3 * pi * radius**2 def A__ ( lowerCamelCase , lowerCamelCase ) -> float: 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__ ( lowerCamelCase , lowerCamelCase , lowerCamelCase ) -> float: if radius_a < 0 or radius_a < 0 or height < 0: raise ValueError( """surface_area_conical_frustum() only accepts non-negative values""" ) UpperCamelCase_: Tuple = (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__ ( lowerCamelCase , lowerCamelCase ) -> float: if radius < 0 or height < 0: raise ValueError("""surface_area_cylinder() only accepts non-negative values""" ) return 2 * pi * radius * (height + radius) def A__ ( lowerCamelCase , lowerCamelCase ) -> float: 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(lowerCamelCase , 2 ) * torus_radius * tube_radius def A__ ( lowerCamelCase , lowerCamelCase ) -> float: if length < 0 or width < 0: raise ValueError("""area_rectangle() only accepts non-negative values""" ) return length * width def A__ ( lowerCamelCase ) -> float: if side_length < 0: raise ValueError("""area_square() only accepts non-negative values""" ) return side_length**2 def A__ ( lowerCamelCase , lowerCamelCase ) -> float: if base < 0 or height < 0: raise ValueError("""area_triangle() only accepts non-negative values""" ) return (base * height) / 2 def A__ ( lowerCamelCase , lowerCamelCase , lowerCamelCase ) -> float: 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""" ) UpperCamelCase_: Optional[Any] = (sidea + sidea + sidea) / 2 UpperCamelCase_: Optional[int] = sqrt( semi_perimeter * (semi_perimeter - sidea) * (semi_perimeter - sidea) * (semi_perimeter - sidea) ) return area def A__ ( lowerCamelCase , lowerCamelCase ) -> float: if base < 0 or height < 0: raise ValueError("""area_parallelogram() only accepts non-negative values""" ) return base * height def A__ ( lowerCamelCase , lowerCamelCase , lowerCamelCase ) -> float: 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__ ( lowerCamelCase ) -> float: if radius < 0: raise ValueError("""area_circle() only accepts non-negative values""" ) return pi * radius**2 def A__ ( lowerCamelCase , lowerCamelCase ) -> float: 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__ ( lowerCamelCase , lowerCamelCase ) -> float: 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__ ( lowerCamelCase , lowerCamelCase ) -> float: if not isinstance(lowerCamelCase , lowerCamelCase ) 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) = }""")
548
import subprocess import sys from transformers import BertConfig, BertModel, BertTokenizer, pipeline from transformers.testing_utils import TestCasePlus, require_torch class _UpperCamelCase ( _A ): '''simple docstring''' @require_torch def lowerCAmelCase__ ( self : List[str] ): # this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before # `transformers` is loaded, and it's too late for inside pytest - so we are changing it # while running an external program # python one-liner segments # this must be loaded before socket.socket is monkey-patched UpperCamelCase_: Optional[Any] = """ from transformers import BertConfig, BertModel, BertTokenizer, pipeline """ UpperCamelCase_: List[Any] = """ mname = \"hf-internal-testing/tiny-random-bert\" BertConfig.from_pretrained(mname) BertModel.from_pretrained(mname) BertTokenizer.from_pretrained(mname) pipe = pipeline(task=\"fill-mask\", model=mname) print(\"success\") """ UpperCamelCase_: Dict = """ import socket def offline_socket(*args, **kwargs): raise RuntimeError(\"Offline mode is enabled, we shouldn't access internet\") socket.socket = offline_socket """ # Force fetching the files so that we can use the cache UpperCamelCase_: int = """hf-internal-testing/tiny-random-bert""" BertConfig.from_pretrained(snake_case_ ) BertModel.from_pretrained(snake_case_ ) BertTokenizer.from_pretrained(snake_case_ ) pipeline(task="""fill-mask""" , model=snake_case_ ) # baseline - just load from_pretrained with normal network UpperCamelCase_: Tuple = [sys.executable, """-c""", """\n""".join([load, run, mock] )] # should succeed UpperCamelCase_: Optional[int] = self.get_env() # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files UpperCamelCase_: int = """1""" UpperCamelCase_: Optional[Any] = subprocess.run(snake_case_ , env=snake_case_ , check=snake_case_ , capture_output=snake_case_ ) self.assertEqual(result.returncode , 0 , result.stderr ) self.assertIn("""success""" , result.stdout.decode() ) @require_torch def lowerCAmelCase__ ( self : Any ): # python one-liner segments # this must be loaded before socket.socket is monkey-patched UpperCamelCase_: str = """ from transformers import BertConfig, BertModel, BertTokenizer, pipeline """ UpperCamelCase_: Any = """ mname = \"hf-internal-testing/tiny-random-bert\" BertConfig.from_pretrained(mname) BertModel.from_pretrained(mname) BertTokenizer.from_pretrained(mname) pipe = pipeline(task=\"fill-mask\", model=mname) print(\"success\") """ UpperCamelCase_: Optional[int] = """ import socket def offline_socket(*args, **kwargs): raise socket.error(\"Faking flaky internet\") socket.socket = offline_socket """ # Force fetching the files so that we can use the cache UpperCamelCase_: Optional[int] = """hf-internal-testing/tiny-random-bert""" BertConfig.from_pretrained(snake_case_ ) BertModel.from_pretrained(snake_case_ ) BertTokenizer.from_pretrained(snake_case_ ) pipeline(task="""fill-mask""" , model=snake_case_ ) # baseline - just load from_pretrained with normal network UpperCamelCase_: Optional[int] = [sys.executable, """-c""", """\n""".join([load, run, mock] )] # should succeed UpperCamelCase_: List[str] = self.get_env() UpperCamelCase_: List[Any] = subprocess.run(snake_case_ , env=snake_case_ , check=snake_case_ , capture_output=snake_case_ ) self.assertEqual(result.returncode , 0 , result.stderr ) self.assertIn("""success""" , result.stdout.decode() ) @require_torch def lowerCAmelCase__ ( self : int ): # this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before # `transformers` is loaded, and it's too late for inside pytest - so we are changing it # while running an external program # python one-liner segments # this must be loaded before socket.socket is monkey-patched UpperCamelCase_: Dict = """ from transformers import BertConfig, BertModel, BertTokenizer """ UpperCamelCase_: Optional[Any] = """ mname = \"hf-internal-testing/tiny-random-bert-sharded\" BertConfig.from_pretrained(mname) BertModel.from_pretrained(mname) print(\"success\") """ UpperCamelCase_: Dict = """ import socket def offline_socket(*args, **kwargs): raise ValueError(\"Offline mode is enabled\") socket.socket = offline_socket """ # baseline - just load from_pretrained with normal network UpperCamelCase_: Union[str, Any] = [sys.executable, """-c""", """\n""".join([load, run] )] # should succeed UpperCamelCase_: Union[str, Any] = self.get_env() UpperCamelCase_: List[Any] = subprocess.run(snake_case_ , env=snake_case_ , check=snake_case_ , capture_output=snake_case_ ) self.assertEqual(result.returncode , 0 , result.stderr ) self.assertIn("""success""" , result.stdout.decode() ) # next emulate no network UpperCamelCase_: Optional[int] = [sys.executable, """-c""", """\n""".join([load, mock, run] )] # Doesn't fail anymore since the model is in the cache due to other tests, so commenting this. # env["TRANSFORMERS_OFFLINE"] = "0" # result = subprocess.run(cmd, env=env, check=False, capture_output=True) # self.assertEqual(result.returncode, 1, result.stderr) # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files UpperCamelCase_: Union[str, Any] = """1""" UpperCamelCase_: int = subprocess.run(snake_case_ , env=snake_case_ , check=snake_case_ , capture_output=snake_case_ ) self.assertEqual(result.returncode , 0 , result.stderr ) self.assertIn("""success""" , result.stdout.decode() ) @require_torch def lowerCAmelCase__ ( self : List[str] ): UpperCamelCase_: Dict = """ from transformers import pipeline """ UpperCamelCase_: Union[str, Any] = """ mname = \"hf-internal-testing/tiny-random-bert\" pipe = pipeline(model=mname) """ UpperCamelCase_: Dict = """ import socket def offline_socket(*args, **kwargs): raise socket.error(\"Offline mode is enabled\") socket.socket = offline_socket """ UpperCamelCase_: Optional[Any] = self.get_env() UpperCamelCase_: int = """1""" UpperCamelCase_: int = [sys.executable, """-c""", """\n""".join([load, mock, run] )] UpperCamelCase_: Any = subprocess.run(snake_case_ , env=snake_case_ , check=snake_case_ , capture_output=snake_case_ ) self.assertEqual(result.returncode , 1 , result.stderr ) self.assertIn( """You cannot infer task automatically within `pipeline` when using offline mode""" , result.stderr.decode().replace("""\n""" , """""" ) , ) @require_torch def lowerCAmelCase__ ( self : Optional[int] ): UpperCamelCase_: str = """ from transformers import AutoModel """ UpperCamelCase_: Dict = """ mname = \"hf-internal-testing/test_dynamic_model\" AutoModel.from_pretrained(mname, trust_remote_code=True) print(\"success\") """ # baseline - just load from_pretrained with normal network UpperCamelCase_: Optional[int] = [sys.executable, """-c""", """\n""".join([load, run] )] # should succeed UpperCamelCase_: Optional[Any] = self.get_env() UpperCamelCase_: int = subprocess.run(snake_case_ , env=snake_case_ , check=snake_case_ , capture_output=snake_case_ ) self.assertEqual(result.returncode , 0 , result.stderr ) self.assertIn("""success""" , result.stdout.decode() ) # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files UpperCamelCase_: Union[str, Any] = """1""" UpperCamelCase_: List[str] = subprocess.run(snake_case_ , env=snake_case_ , check=snake_case_ , capture_output=snake_case_ ) self.assertEqual(result.returncode , 0 , result.stderr ) self.assertIn("""success""" , result.stdout.decode() )
548
1
"""simple docstring""" import contextlib import os import sqlitea import pytest from datasets import Dataset, Features, Value from datasets.io.sql import SqlDatasetReader, SqlDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases, require_sqlalchemy def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Union[str, Any]: assert isinstance(__lowerCAmelCase , __lowerCAmelCase ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @require_sqlalchemy @pytest.mark.parametrize("""keep_in_memory""" , [False, True] ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Any: SCREAMING_SNAKE_CASE__ : int = tmp_path / """cache""" SCREAMING_SNAKE_CASE__ : Optional[Any] = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): SCREAMING_SNAKE_CASE__ : int = SqlDatasetReader( """dataset""" , """sqlite:///""" + sqlite_path , cache_dir=__lowerCAmelCase , keep_in_memory=__lowerCAmelCase ).read() _check_sql_dataset(__lowerCAmelCase , __lowerCAmelCase ) @require_sqlalchemy @pytest.mark.parametrize( """features""" , [ None, {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}, {"""col_1""": """string""", """col_2""": """string""", """col_3""": """string"""}, {"""col_1""": """int32""", """col_2""": """int32""", """col_3""": """int32"""}, {"""col_1""": """float32""", """col_2""": """float32""", """col_3""": """float32"""}, ] , ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> List[Any]: SCREAMING_SNAKE_CASE__ : Dict = tmp_path / """cache""" SCREAMING_SNAKE_CASE__ : Tuple = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} SCREAMING_SNAKE_CASE__ : Optional[Any] = features.copy() if features else default_expected_features SCREAMING_SNAKE_CASE__ : List[str] = ( Features({feature: Value(__lowerCAmelCase ) for feature, dtype in features.items()} ) if features is not None else None ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = SqlDatasetReader("""dataset""" , """sqlite:///""" + sqlite_path , features=__lowerCAmelCase , cache_dir=__lowerCAmelCase ).read() _check_sql_dataset(__lowerCAmelCase , __lowerCAmelCase ) def _lowercase ( __lowerCAmelCase ) -> Any: with contextlib.closing(sqlitea.connect(__lowerCAmelCase ) ) as con: SCREAMING_SNAKE_CASE__ : Union[str, Any] = con.cursor() cur.execute("""SELECT * FROM dataset""" ) for row in cur: yield row @require_sqlalchemy def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Dict: SCREAMING_SNAKE_CASE__ : Tuple = tmp_path / """cache""" SCREAMING_SNAKE_CASE__ : Dict = os.path.join(__lowerCAmelCase , """tmp.sql""" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = SqlDatasetReader("""dataset""" , """sqlite:///""" + sqlite_path , cache_dir=__lowerCAmelCase ).read() SqlDatasetWriter(__lowerCAmelCase , """dataset""" , """sqlite:///""" + output_sqlite_path , num_proc=1 ).write() SCREAMING_SNAKE_CASE__ : Tuple = iter_sql_file(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = iter_sql_file(__lowerCAmelCase ) for rowa, rowa in zip(__lowerCAmelCase , __lowerCAmelCase ): assert rowa == rowa @require_sqlalchemy def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Any: SCREAMING_SNAKE_CASE__ : Any = tmp_path / """cache""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = os.path.join(__lowerCAmelCase , """tmp.sql""" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = SqlDatasetReader("""dataset""" , """sqlite:///""" + sqlite_path , cache_dir=__lowerCAmelCase ).read() SqlDatasetWriter(__lowerCAmelCase , """dataset""" , """sqlite:///""" + output_sqlite_path , num_proc=2 ).write() SCREAMING_SNAKE_CASE__ : Union[str, Any] = iter_sql_file(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = iter_sql_file(__lowerCAmelCase ) for rowa, rowa in zip(__lowerCAmelCase , __lowerCAmelCase ): assert rowa == rowa @require_sqlalchemy def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> List[Any]: SCREAMING_SNAKE_CASE__ : Union[str, Any] = tmp_path / """cache""" SCREAMING_SNAKE_CASE__ : Tuple = os.path.join(__lowerCAmelCase , """tmp.sql""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = SqlDatasetReader("""dataset""" , """sqlite:///""" + sqlite_path , cache_dir=__lowerCAmelCase ).read() with pytest.raises(__lowerCAmelCase ): SqlDatasetWriter(__lowerCAmelCase , """dataset""" , """sqlite:///""" + output_sqlite_path , num_proc=0 ).write()
12
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices a :List[Any] = logging.get_logger(__name__) a :Optional[int] = { "microsoft/focalnet-tiny": "https://huggingface.co/microsoft/focalnet-tiny/resolve/main/config.json", } class __a (UpperCamelCase_ , UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Any = """focalnet""" def __init__( self , _a=224 , _a=4 , _a=3 , _a=96 , _a=False , _a=[192, 384, 768, 768] , _a=[2, 2, 6, 2] , _a=[2, 2, 2, 2] , _a=[3, 3, 3, 3] , _a="gelu" , _a=4.0 , _a=0.0 , _a=0.1 , _a=False , _a=1E-4 , _a=False , _a=False , _a=False , _a=0.02 , _a=1E-5 , _a=32 , _a=None , _a=None , **_a , ) -> Optional[Any]: """simple docstring""" super().__init__(**_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = image_size SCREAMING_SNAKE_CASE__ : str = patch_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_channels SCREAMING_SNAKE_CASE__ : Union[str, Any] = embed_dim SCREAMING_SNAKE_CASE__ : List[str] = use_conv_embed SCREAMING_SNAKE_CASE__ : List[str] = hidden_sizes SCREAMING_SNAKE_CASE__ : Optional[int] = depths SCREAMING_SNAKE_CASE__ : Any = focal_levels SCREAMING_SNAKE_CASE__ : Optional[Any] = focal_windows SCREAMING_SNAKE_CASE__ : Any = hidden_act SCREAMING_SNAKE_CASE__ : Tuple = mlp_ratio SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[Any] = drop_path_rate SCREAMING_SNAKE_CASE__ : str = use_layerscale SCREAMING_SNAKE_CASE__ : int = layerscale_value SCREAMING_SNAKE_CASE__ : Optional[int] = use_post_layernorm SCREAMING_SNAKE_CASE__ : Any = use_post_layernorm_in_modulation SCREAMING_SNAKE_CASE__ : Union[str, Any] = normalize_modulator SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : Any = layer_norm_eps SCREAMING_SNAKE_CASE__ : Any = encoder_stride SCREAMING_SNAKE_CASE__ : Optional[int] = ["""stem"""] + [f'''stage{idx}''' for idx in range(1 , len(self.depths ) + 1 )] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = get_aligned_output_features_output_indices( out_features=_a , out_indices=_a , stage_names=self.stage_names )
12
1
'''simple docstring''' from __future__ import annotations def a__ ( lowerCAmelCase__ , lowerCAmelCase__ ) -> tuple[int, int]: if b == 0: return (1, 0) ((UpperCAmelCase__) , (UpperCAmelCase__)) : List[str] = extended_euclid(lowerCAmelCase__ , a % b ) UpperCAmelCase__ : List[str] = a // b return (y, x - k * y) def a__ ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> int: ((UpperCAmelCase__) , (UpperCAmelCase__)) : Optional[int] = extended_euclid(lowerCAmelCase__ , lowerCAmelCase__ ) UpperCAmelCase__ : Optional[int] = na * na UpperCAmelCase__ : Any = ra * x * na + ra * y * na return (n % m + m) % m def a__ ( lowerCAmelCase__ , lowerCAmelCase__ ) -> int: ((UpperCAmelCase__) , (UpperCAmelCase__)) : Tuple = extended_euclid(lowerCAmelCase__ , lowerCAmelCase__ ) if b < 0: UpperCAmelCase__ : int = (b % n + n) % n return b def a__ ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> int: UpperCAmelCase__ , UpperCAmelCase__ : List[str] = invert_modulo(lowerCAmelCase__ , lowerCAmelCase__ ), invert_modulo(lowerCAmelCase__ , lowerCAmelCase__ ) UpperCAmelCase__ : Any = na * na UpperCAmelCase__ : Optional[int] = ra * x * na + ra * y * na return (n % m + m) % m if __name__ == "__main__": from doctest import testmod testmod(name='''chinese_remainder_theorem''', verbose=True) testmod(name='''chinese_remainder_theorem2''', verbose=True) testmod(name='''invert_modulo''', verbose=True) testmod(name='''extended_euclid''', verbose=True)
75
def _A ( SCREAMING_SNAKE_CASE : list[int] , SCREAMING_SNAKE_CASE : int ): """simple docstring""" a__ : List[str] =len(SCREAMING_SNAKE_CASE ) a__ : Optional[int] =[[False] * (required_sum + 1) for _ in range(arr_len + 1 )] # for each arr value, a sum of zero(0) can be formed by not taking any element # hence True/1 for i in range(arr_len + 1 ): a__ : Optional[int] =True # sum is not zero and set is empty then false for i in range(1 , required_sum + 1 ): a__ : str =False for i in range(1 , arr_len + 1 ): for j in range(1 , required_sum + 1 ): if arr[i - 1] > j: a__ : str =subset[i - 1][j] if arr[i - 1] <= j: a__ : Tuple =subset[i - 1][j] or subset[i - 1][j - arr[i - 1]] return subset[arr_len][required_sum] if __name__ == "__main__": import doctest doctest.testmod()
563
0
'''simple docstring''' from __future__ import annotations from collections.abc import Callable from typing import Any, Generic, TypeVar lowerCAmelCase = TypeVar("""T""") class lowerCamelCase ( Generic[T] ): def __init__( self , a_ , a_ ): lowerCAmelCase : Any | T = None lowerCAmelCase : int = len(a_ ) lowerCAmelCase : list[T] = [any_type for _ in range(self.N )] + arr lowerCAmelCase : Dict = fnc self.build() def _lowerCamelCase ( self ): for p in range(self.N - 1 , 0 , -1 ): lowerCAmelCase : Dict = self.fn(self.st[p * 2] , self.st[p * 2 + 1] ) def _lowerCamelCase ( self , a_ , a_ ): p += self.N lowerCAmelCase : str = v while p > 1: lowerCAmelCase : Dict = p // 2 lowerCAmelCase : Union[str, Any] = self.fn(self.st[p * 2] , self.st[p * 2 + 1] ) def _lowerCamelCase ( self , a_ , a_ ): # noqa: E741 lowerCAmelCase , lowerCAmelCase : Dict = l + self.N, r + self.N lowerCAmelCase : T | None = None while l <= r: if l % 2 == 1: lowerCAmelCase : Dict = self.st[l] if res is None else self.fn(a_ , self.st[l] ) if r % 2 == 0: lowerCAmelCase : str = self.st[r] if res is None else self.fn(a_ , self.st[r] ) lowerCAmelCase , lowerCAmelCase : Any = (l + 1) // 2, (r - 1) // 2 return res if __name__ == "__main__": from functools import reduce lowerCAmelCase = [1, 10, -2, 9, -3, 8, 4, -7, 5, 6, 11, -12] lowerCAmelCase = { 0: 7, 1: 2, 2: 6, 3: -14, 4: 5, 5: 4, 6: 7, 7: -10, 8: 9, 9: 10, 10: 12, 11: 1, } lowerCAmelCase = SegmentTree(test_array, min) lowerCAmelCase = SegmentTree(test_array, max) lowerCAmelCase = SegmentTree(test_array, lambda a, b: a + b) def __A ( ): for i in range(len(a_ ) ): for j in range(a_ ,len(a_ ) ): lowerCAmelCase : Tuple = reduce(a_ ,test_array[i : j + 1] ) lowerCAmelCase : str = reduce(a_ ,test_array[i : j + 1] ) lowerCAmelCase : Tuple = reduce(lambda a_ ,a_ : a + b ,test_array[i : j + 1] ) assert min_range == min_segment_tree.query(a_ ,a_ ) assert max_range == max_segment_tree.query(a_ ,a_ ) assert sum_range == sum_segment_tree.query(a_ ,a_ ) test_all_segments() for index, value in test_updates.items(): lowerCAmelCase = value min_segment_tree.update(index, value) max_segment_tree.update(index, value) sum_segment_tree.update(index, value) test_all_segments()
551
'''simple docstring''' import numpy as np def __A ( a_ : np.array ): return (2 / (1 + np.exp(-2 * vector ))) - 1 if __name__ == "__main__": import doctest doctest.testmod()
551
1
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, MobileNetVaForSemanticSegmentation, MobileNetVaModel from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileNetVaImageProcessor class lowercase ( SCREAMING_SNAKE_CASE_): '''simple docstring''' def lowerCamelCase_ ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(snake_case , 'tf_padding' ) ) self.parent.assertTrue(hasattr(snake_case , 'depth_multiplier' ) ) class lowercase : '''simple docstring''' def __init__( self : Tuple , snake_case : List[Any] , snake_case : Union[str, Any]=13 , snake_case : Tuple=3 , snake_case : Dict=32 , snake_case : Union[str, Any]=0.25 , snake_case : str=8 , snake_case : List[str]=8 , snake_case : Union[str, Any]=6 , snake_case : List[Any]=32 , snake_case : List[str]=True , snake_case : Tuple=True , snake_case : Dict=True , snake_case : Optional[Any]="relu6" , snake_case : List[str]=1280 , snake_case : Optional[int]=0.1 , snake_case : Any=0.02 , snake_case : int=True , snake_case : Optional[Any]=True , snake_case : Dict=10 , snake_case : Any=None , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = parent SCREAMING_SNAKE_CASE : Union[str, Any] = batch_size SCREAMING_SNAKE_CASE : Union[str, Any] = num_channels SCREAMING_SNAKE_CASE : str = image_size SCREAMING_SNAKE_CASE : Tuple = depth_multiplier SCREAMING_SNAKE_CASE : Dict = depth_divisible_by SCREAMING_SNAKE_CASE : List[Any] = min_depth SCREAMING_SNAKE_CASE : Union[str, Any] = expand_ratio SCREAMING_SNAKE_CASE : Tuple = tf_padding SCREAMING_SNAKE_CASE : Tuple = output_stride SCREAMING_SNAKE_CASE : Tuple = first_layer_is_expansion SCREAMING_SNAKE_CASE : Dict = finegrained_output SCREAMING_SNAKE_CASE : List[str] = hidden_act SCREAMING_SNAKE_CASE : List[str] = last_hidden_size if finegrained_output else int(last_hidden_size * depth_multiplier ) SCREAMING_SNAKE_CASE : Dict = classifier_dropout_prob SCREAMING_SNAKE_CASE : int = use_labels SCREAMING_SNAKE_CASE : Optional[int] = is_training SCREAMING_SNAKE_CASE : Dict = num_labels SCREAMING_SNAKE_CASE : Dict = initializer_range SCREAMING_SNAKE_CASE : List[Any] = scope def lowerCamelCase_ ( self : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE : Dict = None SCREAMING_SNAKE_CASE : str = None if self.use_labels: SCREAMING_SNAKE_CASE : str = ids_tensor([self.batch_size] , self.num_labels ) SCREAMING_SNAKE_CASE : List[str] = 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 lowerCamelCase_ ( self : Tuple ): '''simple docstring''' return MobileNetVaConfig( num_channels=self.num_channels , image_size=self.image_size , depth_multiplier=self.depth_multiplier , depth_divisible_by=self.depth_divisible_by , min_depth=self.min_depth , expand_ratio=self.expand_ratio , output_stride=self.output_stride , first_layer_is_expansion=self.first_layer_is_expansion , finegrained_output=self.finegrained_output , hidden_act=self.hidden_act , tf_padding=self.tf_padding , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , ) def lowerCamelCase_ ( self : Tuple , snake_case : str , snake_case : Any , snake_case : Any , snake_case : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = MobileNetVaModel(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE : Union[str, Any] = model(snake_case ) 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, ) , ) self.parent.assertEqual( result.pooler_output.shape , (self.batch_size, self.last_hidden_size) , ) def lowerCamelCase_ ( self : Any , snake_case : Tuple , snake_case : Any , snake_case : Dict , snake_case : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = self.num_labels SCREAMING_SNAKE_CASE : int = MobileNetVaForImageClassification(snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE : Tuple = model(snake_case , labels=snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCamelCase_ ( self : Dict , snake_case : Tuple , snake_case : List[Any] , snake_case : Optional[int] , snake_case : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = self.num_labels SCREAMING_SNAKE_CASE : Optional[int] = MobileNetVaForSemanticSegmentation(snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE : int = model(snake_case ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) SCREAMING_SNAKE_CASE : Tuple = model(snake_case , labels=snake_case ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : str = config_and_inputs SCREAMING_SNAKE_CASE : int = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class lowercase ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , unittest.TestCase): '''simple docstring''' UpperCAmelCase : Union[str, Any] = ( (MobileNetVaModel, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation) if is_torch_available() else () ) UpperCAmelCase : Optional[Any] = ( { 'feature-extraction': MobileNetVaModel, 'image-classification': MobileNetVaForImageClassification, 'image-segmentation': MobileNetVaForSemanticSegmentation, } if is_torch_available() else {} ) UpperCAmelCase : Optional[Any] = False UpperCAmelCase : Tuple = False UpperCAmelCase : Union[str, Any] = False UpperCAmelCase : Union[str, Any] = False def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = MobileNetVaModelTester(self ) SCREAMING_SNAKE_CASE : Optional[int] = MobileNetVaConfigTester(self , config_class=snake_case , has_text_modality=snake_case ) def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason='MobileNetV2 does not use inputs_embeds' ) def lowerCamelCase_ ( self : int ): '''simple docstring''' pass @unittest.skip(reason='MobileNetV2 does not support input and output embeddings' ) def lowerCamelCase_ ( self : str ): '''simple docstring''' pass @unittest.skip(reason='MobileNetV2 does not output attentions' ) def lowerCamelCase_ ( self : Optional[Any] ): '''simple docstring''' pass def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : int = model_class(snake_case ) SCREAMING_SNAKE_CASE : List[str] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE : List[str] = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE : Union[str, Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] , snake_case ) def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case ) def lowerCamelCase_ ( self : Optional[Any] ): '''simple docstring''' def check_hidden_states_output(snake_case : List[str] , snake_case : Any , snake_case : Tuple ): SCREAMING_SNAKE_CASE : Union[str, Any] = model_class(snake_case ) model.to(snake_case ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE : Optional[int] = model(**self._prepare_for_class(snake_case , snake_case ) ) SCREAMING_SNAKE_CASE : int = outputs.hidden_states SCREAMING_SNAKE_CASE : Any = 16 self.assertEqual(len(snake_case ) , snake_case ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : Optional[int] = True check_hidden_states_output(snake_case , snake_case , snake_case ) # 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(snake_case , snake_case , snake_case ) def lowerCamelCase_ ( self : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*snake_case ) def lowerCamelCase_ ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*snake_case ) @slow def lowerCamelCase_ ( self : int ): '''simple docstring''' for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE : List[Any] = MobileNetVaModel.from_pretrained(snake_case ) self.assertIsNotNone(snake_case ) def __a ( ) -> Optional[int]: SCREAMING_SNAKE_CASE : str = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class lowercase ( unittest.TestCase): '''simple docstring''' @cached_property def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' return ( MobileNetVaImageProcessor.from_pretrained('google/mobilenet_v2_1.0_224' ) if is_vision_available() else None ) @slow def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = MobileNetVaForImageClassification.from_pretrained('google/mobilenet_v2_1.0_224' ).to(snake_case ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.default_image_processor SCREAMING_SNAKE_CASE : int = prepare_img() SCREAMING_SNAKE_CASE : str = image_processor(images=snake_case , return_tensors='pt' ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE : Optional[int] = model(**snake_case ) # verify the logits SCREAMING_SNAKE_CASE : Optional[Any] = torch.Size((1, 1001) ) self.assertEqual(outputs.logits.shape , snake_case ) SCREAMING_SNAKE_CASE : Any = torch.tensor([0.2445, -1.1993, 0.1905] ).to(snake_case ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , snake_case , atol=1E-4 ) ) @slow def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = MobileNetVaForSemanticSegmentation.from_pretrained('google/deeplabv3_mobilenet_v2_1.0_513' ) SCREAMING_SNAKE_CASE : int = model.to(snake_case ) SCREAMING_SNAKE_CASE : Union[str, Any] = MobileNetVaImageProcessor.from_pretrained('google/deeplabv3_mobilenet_v2_1.0_513' ) SCREAMING_SNAKE_CASE : Any = prepare_img() SCREAMING_SNAKE_CASE : List[Any] = image_processor(images=snake_case , return_tensors='pt' ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE : Union[str, Any] = model(**snake_case ) SCREAMING_SNAKE_CASE : int = outputs.logits # verify the logits SCREAMING_SNAKE_CASE : Optional[Any] = torch.Size((1, 21, 65, 65) ) self.assertEqual(logits.shape , snake_case ) SCREAMING_SNAKE_CASE : List[Any] = torch.tensor( [ [[17.5790, 17.7581, 18.3355], [18.3257, 18.4230, 18.8973], [18.6169, 18.8650, 19.2187]], [[-2.1595, -2.0977, -2.3741], [-2.4226, -2.3028, -2.6835], [-2.7819, -2.5991, -2.7706]], [[4.2058, 4.8317, 4.7638], [4.4136, 5.0361, 4.9383], [4.5028, 4.9644, 4.8734]], ] , device=snake_case , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , snake_case , atol=1E-4 ) )
352
import unittest import numpy as np from transformers import DistilBertConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.distilbert.modeling_flax_distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, ) class lowercase ( unittest.TestCase): '''simple docstring''' def __init__( self : int , snake_case : Optional[Any] , snake_case : Optional[Any]=13 , snake_case : str=7 , snake_case : Optional[Any]=True , snake_case : int=True , snake_case : str=True , snake_case : List[str]=True , snake_case : Optional[Any]=99 , snake_case : Optional[int]=32 , snake_case : Optional[int]=5 , snake_case : Optional[Any]=4 , snake_case : Optional[Any]=37 , snake_case : str="gelu" , snake_case : List[str]=0.1 , snake_case : List[str]=0.1 , snake_case : int=512 , snake_case : Union[str, Any]=16 , snake_case : Optional[Any]=2 , snake_case : int=0.02 , snake_case : str=4 , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = parent SCREAMING_SNAKE_CASE : str = batch_size SCREAMING_SNAKE_CASE : Union[str, Any] = seq_length SCREAMING_SNAKE_CASE : int = is_training SCREAMING_SNAKE_CASE : List[str] = use_attention_mask SCREAMING_SNAKE_CASE : Optional[Any] = use_token_type_ids SCREAMING_SNAKE_CASE : Optional[int] = use_labels SCREAMING_SNAKE_CASE : Optional[int] = vocab_size SCREAMING_SNAKE_CASE : Optional[int] = hidden_size SCREAMING_SNAKE_CASE : Any = num_hidden_layers SCREAMING_SNAKE_CASE : Tuple = num_attention_heads SCREAMING_SNAKE_CASE : Any = intermediate_size SCREAMING_SNAKE_CASE : Tuple = hidden_act SCREAMING_SNAKE_CASE : Optional[int] = hidden_dropout_prob SCREAMING_SNAKE_CASE : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : Tuple = max_position_embeddings SCREAMING_SNAKE_CASE : Any = type_vocab_size SCREAMING_SNAKE_CASE : List[Any] = type_sequence_label_size SCREAMING_SNAKE_CASE : Tuple = initializer_range SCREAMING_SNAKE_CASE : List[str] = num_choices def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE : Optional[int] = None if self.use_attention_mask: SCREAMING_SNAKE_CASE : Any = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE : Tuple = DistilBertConfig( vocab_size=self.vocab_size , dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , hidden_dim=self.intermediate_size , hidden_act=self.hidden_act , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , tie_weights_=snake_case , ) return config, input_ids, attention_mask def lowerCamelCase_ ( self : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = config_and_inputs SCREAMING_SNAKE_CASE : int = {'input_ids': input_ids, 'attention_mask': attention_mask} return config, inputs_dict @require_flax class lowercase ( SCREAMING_SNAKE_CASE_ , unittest.TestCase): '''simple docstring''' UpperCAmelCase : int = ( ( FlaxDistilBertModel, FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertForQuestionAnswering, ) if is_flax_available() else () ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = FlaxDistilBertModelTester(self ) @slow def lowerCamelCase_ ( self : Any ): '''simple docstring''' for model_class_name in self.all_model_classes: SCREAMING_SNAKE_CASE : Dict = model_class_name.from_pretrained('distilbert-base-uncased' ) SCREAMING_SNAKE_CASE : Dict = model(np.ones((1, 1) ) ) self.assertIsNotNone(snake_case ) @require_flax class lowercase ( unittest.TestCase): '''simple docstring''' @slow def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = FlaxDistilBertModel.from_pretrained('distilbert-base-uncased' ) SCREAMING_SNAKE_CASE : List[str] = np.array([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] ) SCREAMING_SNAKE_CASE : Dict = np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) SCREAMING_SNAKE_CASE : str = model(snake_case , attention_mask=snake_case )[0] SCREAMING_SNAKE_CASE : int = (1, 11, 768) self.assertEqual(output.shape , snake_case ) SCREAMING_SNAKE_CASE : Optional[int] = np.array([[[-0.1639, 0.3299, 0.1648], [-0.1746, 0.3289, 0.1710], [-0.1884, 0.3357, 0.1810]]] ) self.assertTrue(jnp.allclose(output[:, 1:4, 1:4] , snake_case , atol=1E-4 ) )
352
1
from importlib import import_module from .logging import get_logger snake_case_ : str = get_logger(__name__) class lowercase__ : '''simple docstring''' def __init__( self , lowerCamelCase__ , lowerCamelCase__=None ): '''simple docstring''' UpperCamelCase = attrs or [] if module is not None: for key in module.__dict__: if key in attrs or not key.startswith('''__''' ): setattr(self , lowerCamelCase__ , getattr(lowerCamelCase__ , lowerCamelCase__ ) ) UpperCamelCase = module._original_module if isinstance(lowerCamelCase__ , _PatchedModuleObj ) else module class lowercase__ : '''simple docstring''' _snake_case = [] def __init__( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=None ): '''simple docstring''' UpperCamelCase = obj UpperCamelCase = target UpperCamelCase = new UpperCamelCase = target.split('''.''' )[0] UpperCamelCase = {} UpperCamelCase = attrs or [] def __enter__( self ): '''simple docstring''' *UpperCamelCase , UpperCamelCase = self.target.split('''.''' ) # Patch modules: # it's used to patch attributes of submodules like "os.path.join"; # in this case we need to patch "os" and "os.path" for i in range(len(lowerCamelCase__ ) ): try: UpperCamelCase = import_module('''.'''.join(submodules[: i + 1] ) ) except ModuleNotFoundError: continue # We iterate over all the globals in self.obj in case we find "os" or "os.path" for attr in self.obj.__dir__(): UpperCamelCase = getattr(self.obj , lowerCamelCase__ ) # We don't check for the name of the global, but rather if its value *is* "os" or "os.path". # This allows to patch renamed modules like "from os import path as ospath". if obj_attr is submodule or ( (isinstance(lowerCamelCase__ , _PatchedModuleObj ) and obj_attr._original_module is submodule) ): UpperCamelCase = obj_attr # patch at top level setattr(self.obj , lowerCamelCase__ , _PatchedModuleObj(lowerCamelCase__ , attrs=self.attrs ) ) UpperCamelCase = getattr(self.obj , lowerCamelCase__ ) # construct lower levels patches for key in submodules[i + 1 :]: setattr(lowerCamelCase__ , lowerCamelCase__ , _PatchedModuleObj(getattr(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) , attrs=self.attrs ) ) UpperCamelCase = getattr(lowerCamelCase__ , lowerCamelCase__ ) # finally set the target attribute setattr(lowerCamelCase__ , lowerCamelCase__ , self.new ) # Patch attribute itself: # it's used for builtins like "open", # and also to patch "os.path.join" we may also need to patch "join" # itself if it was imported as "from os.path import join". if submodules: # if it's an attribute of a submodule like "os.path.join" try: UpperCamelCase = getattr(import_module('''.'''.join(lowerCamelCase__ ) ) , lowerCamelCase__ ) except (AttributeError, ModuleNotFoundError): return # We iterate over all the globals in self.obj in case we find "os.path.join" for attr in self.obj.__dir__(): # We don't check for the name of the global, but rather if its value *is* "os.path.join". # This allows to patch renamed attributes like "from os.path import join as pjoin". if getattr(self.obj , lowerCamelCase__ ) is attr_value: UpperCamelCase = getattr(self.obj , lowerCamelCase__ ) setattr(self.obj , lowerCamelCase__ , self.new ) elif target_attr in globals()["__builtins__"]: # if it'a s builtin like "open" UpperCamelCase = globals()['''__builtins__'''][target_attr] setattr(self.obj , lowerCamelCase__ , self.new ) else: raise RuntimeError(f'Tried to patch attribute {target_attr} instead of a submodule.' ) def __exit__( self , *lowerCamelCase__ ): '''simple docstring''' for attr in list(self.original ): setattr(self.obj , lowerCamelCase__ , self.original.pop(lowerCamelCase__ ) ) def UpperCAmelCase ( self ): '''simple docstring''' self.__enter__() self._active_patches.append(self ) def UpperCAmelCase ( self ): '''simple docstring''' try: self._active_patches.remove(self ) except ValueError: # If the patch hasn't been started this will fail return None return self.__exit__()
707
'''simple docstring''' import argparse import json import os import re import torch from transformers import BloomConfig, BloomModel from transformers.file_utils import CONFIG_NAME, WEIGHTS_NAME from transformers.utils import logging logging.set_verbosity_info() snake_case_ : Tuple = [ 'word_embeddings_layernorm.weight', 'word_embeddings_layernorm.bias', 'input_layernorm.weight', 'input_layernorm.bias', 'post_attention_layernorm.weight', 'post_attention_layernorm.bias', 'self_attention.dense.bias', 'mlp.dense_4h_to_h.bias', 'ln_f.weight', 'ln_f.bias', ] snake_case_ : Union[str, Any] = [ 'mlp.dense_4h_to_h.weight', 'self_attention.dense.weight', ] def __snake_case ( _UpperCAmelCase : List[str], _UpperCAmelCase : List[str]): UpperCamelCase = { '''word_embeddings.weight''': '''word_embeddings.weight''', '''word_embeddings.norm.weight''': '''word_embeddings_layernorm.weight''', '''word_embeddings.norm.bias''': '''word_embeddings_layernorm.bias''', '''weight''': '''ln_f.weight''', '''bias''': '''ln_f.bias''', } if key in layer_rename_map: return layer_rename_map[key] # Handle transformer blocks UpperCamelCase = int(re.match(R'''.*layer_(\d*).*''', _UpperCAmelCase)[1]) layer_number -= 3 return f'h.{layer_number}.' + key def __snake_case ( _UpperCAmelCase : str): if dtype == torch.bool: return 1 / 8 UpperCamelCase = re.search(R'''[^\d](\d+)$''', str(_UpperCAmelCase)) if bit_search is None: raise ValueError(f'`dtype` is not a valid dtype: {dtype}.') UpperCamelCase = int(bit_search.groups()[0]) return bit_size // 8 def __snake_case ( _UpperCAmelCase : int, _UpperCAmelCase : Optional[Any], _UpperCAmelCase : str, _UpperCAmelCase : List[Any], _UpperCAmelCase : Optional[int]): # Construct model if bloom_config_file == "": UpperCamelCase = BloomConfig() else: UpperCamelCase = BloomConfig.from_json_file(_UpperCAmelCase) if shard_model: UpperCamelCase = os.listdir(_UpperCAmelCase) UpperCamelCase = sorted(filter(lambda _UpperCAmelCase: s.startswith('''layer''') and "model_00" in s, _UpperCAmelCase)) UpperCamelCase = {'''weight_map''': {}, '''metadata''': {}} UpperCamelCase = 0 UpperCamelCase = None UpperCamelCase = BloomConfig() for j, file in enumerate(_UpperCAmelCase): print('''Processing file: {}'''.format(_UpperCAmelCase)) UpperCamelCase = None for i in range(_UpperCAmelCase): # load all TP files UpperCamelCase = file.replace('''model_00''', f'model_0{i}') UpperCamelCase = torch.load(os.path.join(_UpperCAmelCase, _UpperCAmelCase), map_location='''cpu''') # Rename keys in the transformers names UpperCamelCase = list(temp.keys()) for key in keys: UpperCamelCase = temp.pop(_UpperCAmelCase) if tensors is None: UpperCamelCase = temp else: for key in tensors.keys(): if any(key.endswith(_UpperCAmelCase) for end in WEIGHTS_TO_AVERAGE_ENDSWITH): # We average (sum and then divide) some weights accross TP ranks (see https://github.com/bigscience-workshop/Megatron-DeepSpeed/blob/olruwase/sync_layer_norms/megatron/training.py#L425) tensors[key] += temp[key] else: # Some weights are RowParallelLinear in Megatron-Deepspeed, others are ColumnParallel UpperCamelCase = 1 if any(text in key for text in WEIGHTS_WITH_ROW_PARALLELISM_CONTAIN) else 0 # We concatenate these weights accross TP ranks UpperCamelCase = torch.cat([tensors[key], temp[key]], dim=_UpperCAmelCase) # Divide by the number of TP the weights we want to average for key in tensors.keys(): if any(key.endswith(_UpperCAmelCase) for end in WEIGHTS_TO_AVERAGE_ENDSWITH): UpperCamelCase = tensors[key] / pretraining_tp torch.save( _UpperCAmelCase, os.path.join( _UpperCAmelCase, '''pytorch_model_{}-of-{}.bin'''.format(str(j + 1).zfill(5), str(len(_UpperCAmelCase)).zfill(5)), ), ) for key in tensors.keys(): UpperCamelCase = tensors[key] total_size += value.numel() * get_dtype_size(value.dtype) if key not in index_dict["weight_map"]: UpperCamelCase = '''pytorch_model_{}-of-{}.bin'''.format( str(j + 1).zfill(5), str(len(_UpperCAmelCase)).zfill(5)) UpperCamelCase = BloomConfig() UpperCamelCase = pytorch_dump_folder_path + '''/''' + CONFIG_NAME UpperCamelCase = total_size with open(_UpperCAmelCase, '''w''', encoding='''utf-8''') as f: f.write(config.to_json_string()) with open(os.path.join(_UpperCAmelCase, WEIGHTS_NAME + '''.index.json'''), '''w''', encoding='''utf-8''') as f: UpperCamelCase = json.dumps(_UpperCAmelCase, indent=2, sort_keys=_UpperCAmelCase) + '''\n''' f.write(_UpperCAmelCase) else: UpperCamelCase = BloomModel(_UpperCAmelCase) UpperCamelCase = os.listdir(_UpperCAmelCase) UpperCamelCase = sorted(filter(lambda _UpperCAmelCase: s.startswith('''layer''') and "model_00" in s, _UpperCAmelCase)) UpperCamelCase = None for i, file in enumerate(_UpperCAmelCase): UpperCamelCase = None for i in range(_UpperCAmelCase): # load all TP files UpperCamelCase = file.replace('''model_00''', f'model_0{i}') UpperCamelCase = torch.load(os.path.join(_UpperCAmelCase, _UpperCAmelCase), map_location='''cpu''') # Rename keys in the transformers names UpperCamelCase = list(temp.keys()) for key in keys: UpperCamelCase = temp.pop(_UpperCAmelCase) if tensors is None: UpperCamelCase = temp else: for key in tensors.keys(): # We average (sum and then divide) some weights accross TP ranks (see https://github.com/bigscience-workshop/Megatron-DeepSpeed/blob/olruwase/sync_layer_norms/megatron/training.py#L425) if any(key.endswith(_UpperCAmelCase) for end in WEIGHTS_TO_AVERAGE_ENDSWITH): tensors[key] += temp[key] else: # Some weights are RowParallelLinear in Megatron-Deepspeed, others are ColumnParallel UpperCamelCase = 1 if any(text in key for text in WEIGHTS_WITH_ROW_PARALLELISM_CONTAIN) else 0 # We concatenate these weights accross TP ranks UpperCamelCase = torch.cat([tensors[key], temp[key]], dim=_UpperCAmelCase) # Divide by the number of TP the weights we want to average for key in tensors.keys(): if any(key.endswith(_UpperCAmelCase) for end in WEIGHTS_TO_AVERAGE_ENDSWITH): UpperCamelCase = tensors[key] / pretraining_tp UpperCamelCase = model.load_state_dict(_UpperCAmelCase, strict=_UpperCAmelCase) assert not other_keys.unexpected_keys, f'The keys {other_keys.unexpected_keys} are unexpected' if missing_keys is None: UpperCamelCase = set(other_keys.missing_keys) else: UpperCamelCase = missing_keys.intersection(set(other_keys.missing_keys)) assert not missing_keys, f'The keys {missing_keys} are missing' # Save pytorch-model os.makedirs(_UpperCAmelCase, exist_ok=_UpperCAmelCase) UpperCamelCase = pytorch_dump_folder_path + '''/''' + WEIGHTS_NAME UpperCamelCase = pytorch_dump_folder_path + '''/''' + CONFIG_NAME print(f'Save PyTorch model to {pytorch_weights_dump_path} with dtype {config.torch_dtype}') if config.torch_dtype is not None: UpperCamelCase = model.to(config.torch_dtype) torch.save(model.state_dict(), _UpperCAmelCase) print(f'Save configuration file to {pytorch_config_dump_path}') with open(_UpperCAmelCase, '''w''', encoding='''utf-8''') as f: f.write(config.to_json_string()) if __name__ == "__main__": snake_case_ : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( '--bloom_checkpoint_path', default=None, type=str, required=True, help='Path to the Megatron-LM checkpoint path.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) parser.add_argument( '--bloom_config_file', default='', type=str, help=( 'An optional config json file corresponding to the pre-trained model. \n' 'This specifies the model architecture.' ), ) parser.add_argument( '--shard_model', action='store_true', help='An optional setting to shard the output model \nThis enables sharding the converted checkpoint', ) parser.add_argument( '--pretraining_tp', default=4, type=int, help='Pretraining TP rank that has been used when training the model in Megatron-LM \n', ) snake_case_ : List[str] = parser.parse_args() convert_bloom_checkpoint_to_pytorch( args.bloom_checkpoint_path, args.bloom_config_file, args.pytorch_dump_folder_path, args.shard_model, args.pretraining_tp, )
350
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase : Tuple = {"configuration_xglm": ["XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP", "XGLMConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Any = ["XGLMTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Tuple = ["XGLMTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Tuple = [ "XGLM_PRETRAINED_MODEL_ARCHIVE_LIST", "XGLMForCausalLM", "XGLMModel", "XGLMPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Union[str, Any] = [ "FlaxXGLMForCausalLM", "FlaxXGLMModel", "FlaxXGLMPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Tuple = [ "TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST", "TFXGLMForCausalLM", "TFXGLMModel", "TFXGLMPreTrainedModel", ] if TYPE_CHECKING: from .configuration_xglm import XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XGLMConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm import XGLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm_fast import XGLMTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xglm import XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, XGLMForCausalLM, XGLMModel, XGLMPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_xglm import FlaxXGLMForCausalLM, FlaxXGLMModel, FlaxXGLMPreTrainedModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, TFXGLMPreTrainedModel, ) else: import sys UpperCAmelCase : Union[str, Any] = _LazyModule(__name__, globals()["__file__"], _import_structure)
457
import itertools import random import unittest import numpy as np from transformers import is_speech_available from transformers.testing_utils import require_torch, require_torchaudio from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import SpeechaTextFeatureExtractor UpperCAmelCase : Any = random.Random() def __lowerCamelCase ( lowerCamelCase__ : int , lowerCamelCase__ : Union[str, Any]=1.0 , lowerCamelCase__ : Union[str, Any]=None , lowerCamelCase__ : int=None ): '''simple docstring''' if rng is None: lowerCamelCase = global_rng lowerCamelCase = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch @require_torchaudio class __lowercase ( unittest.TestCase ): """simple docstring""" def __init__( self , A , A=7 , A=4_00 , A=20_00 , A=24 , A=24 , A=0.0 , A=1_60_00 , A=True , A=True , ) -> str: '''simple docstring''' lowerCamelCase = parent lowerCamelCase = batch_size lowerCamelCase = min_seq_length lowerCamelCase = max_seq_length lowerCamelCase = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) lowerCamelCase = feature_size lowerCamelCase = num_mel_bins lowerCamelCase = padding_value lowerCamelCase = sampling_rate lowerCamelCase = return_attention_mask lowerCamelCase = do_normalize def __A ( self ) -> List[str]: '''simple docstring''' return { "feature_size": self.feature_size, "num_mel_bins": self.num_mel_bins, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def __A ( self , A=False , A=False ) -> Tuple: '''simple docstring''' def _flatten(A ): return list(itertools.chain(*A ) ) if equal_length: lowerCamelCase = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size lowerCamelCase = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: lowerCamelCase = [np.asarray(A ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class __lowercase ( a_ , unittest.TestCase ): """simple docstring""" UpperCamelCase : str = SpeechaTextFeatureExtractor if is_speech_available() else None def __A ( self ) -> int: '''simple docstring''' lowerCamelCase = SpeechaTextFeatureExtractionTester(self ) def __A ( self , A ) -> List[Any]: '''simple docstring''' self.assertTrue(np.all(np.mean(A , axis=0 ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(A , axis=0 ) - 1 ) < 1e-3 ) ) def __A ( self ) -> Optional[int]: '''simple docstring''' lowerCamelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 lowerCamelCase = [floats_list((1, x) )[0] for x in range(8_00 , 14_00 , 2_00 )] lowerCamelCase = [np.asarray(A ) for speech_input in speech_inputs] # Test feature size lowerCamelCase = feature_extractor(A , padding=A , return_tensors="""np""" ).input_features self.assertTrue(input_features.ndim == 3 ) self.assertTrue(input_features.shape[-1] == feature_extractor.feature_size ) # Test not batched input lowerCamelCase = feature_extractor(speech_inputs[0] , return_tensors="""np""" ).input_features lowerCamelCase = feature_extractor(np_speech_inputs[0] , return_tensors="""np""" ).input_features self.assertTrue(np.allclose(A , A , atol=1e-3 ) ) # Test batched lowerCamelCase = feature_extractor(A , return_tensors="""np""" ).input_features lowerCamelCase = feature_extractor(A , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(A , A ): self.assertTrue(np.allclose(A , A , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. lowerCamelCase = [floats_list((1, x) )[0] for x in (8_00, 8_00, 8_00)] lowerCamelCase = np.asarray(A ) lowerCamelCase = feature_extractor(A , return_tensors="""np""" ).input_features lowerCamelCase = feature_extractor(A , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(A , A ): self.assertTrue(np.allclose(A , A , atol=1e-3 ) ) def __A ( self ) -> Optional[Any]: '''simple docstring''' lowerCamelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) lowerCamelCase = [floats_list((1, x) )[0] for x in range(8_00 , 14_00 , 2_00 )] lowerCamelCase = ["""longest""", """max_length""", """do_not_pad"""] lowerCamelCase = [None, 16, None] for max_length, padding in zip(A , A ): lowerCamelCase = feature_extractor( A , padding=A , max_length=A , return_attention_mask=A ) lowerCamelCase = inputs.input_features lowerCamelCase = inputs.attention_mask lowerCamelCase = [np.sum(A ) for x in attention_mask] self._check_zero_mean_unit_variance(input_features[0][: fbank_feat_lengths[0]] ) self._check_zero_mean_unit_variance(input_features[1][: fbank_feat_lengths[1]] ) self._check_zero_mean_unit_variance(input_features[2][: fbank_feat_lengths[2]] ) def __A ( self ) -> List[Any]: '''simple docstring''' lowerCamelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) lowerCamelCase = [floats_list((1, x) )[0] for x in range(8_00 , 14_00 , 2_00 )] lowerCamelCase = ["""longest""", """max_length""", """do_not_pad"""] lowerCamelCase = [None, 16, None] for max_length, padding in zip(A , A ): lowerCamelCase = feature_extractor( A , max_length=A , padding=A , return_tensors="""np""" , return_attention_mask=A ) lowerCamelCase = inputs.input_features lowerCamelCase = inputs.attention_mask lowerCamelCase = [np.sum(A ) for x in attention_mask] self._check_zero_mean_unit_variance(input_features[0][: fbank_feat_lengths[0]] ) self.assertTrue(input_features[0][fbank_feat_lengths[0] :].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_features[1][: fbank_feat_lengths[1]] ) self.assertTrue(input_features[0][fbank_feat_lengths[1] :].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_features[2][: fbank_feat_lengths[2]] ) def __A ( self ) -> int: '''simple docstring''' lowerCamelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) lowerCamelCase = [floats_list((1, x) )[0] for x in range(8_00 , 14_00 , 2_00 )] lowerCamelCase = feature_extractor( A , padding="""max_length""" , max_length=4 , truncation=A , return_tensors="""np""" , return_attention_mask=A , ) lowerCamelCase = inputs.input_features lowerCamelCase = inputs.attention_mask lowerCamelCase = np.sum(attention_mask == 1 , axis=1 ) self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]] ) self._check_zero_mean_unit_variance(input_features[1] ) self._check_zero_mean_unit_variance(input_features[2] ) def __A ( self ) -> List[Any]: '''simple docstring''' lowerCamelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) lowerCamelCase = [floats_list((1, x) )[0] for x in range(8_00 , 14_00 , 2_00 )] lowerCamelCase = feature_extractor( A , padding="""longest""" , max_length=4 , truncation=A , return_tensors="""np""" , return_attention_mask=A , ) lowerCamelCase = inputs.input_features lowerCamelCase = inputs.attention_mask lowerCamelCase = np.sum(attention_mask == 1 , axis=1 ) self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]] ) self._check_zero_mean_unit_variance(input_features[1, : fbank_feat_lengths[1]] ) self._check_zero_mean_unit_variance(input_features[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertEqual(input_features.shape , (3, 4, 24) ) lowerCamelCase = [floats_list((1, x) )[0] for x in range(8_00 , 14_00 , 2_00 )] lowerCamelCase = feature_extractor( A , padding="""longest""" , max_length=16 , truncation=A , return_tensors="""np""" , return_attention_mask=A , ) lowerCamelCase = inputs.input_features lowerCamelCase = inputs.attention_mask lowerCamelCase = np.sum(attention_mask == 1 , axis=1 ) self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]] ) self._check_zero_mean_unit_variance(input_features[1, : fbank_feat_lengths[1]] ) self._check_zero_mean_unit_variance(input_features[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertEqual(input_features.shape , (3, 6, 24) ) def __A ( self ) -> Optional[int]: '''simple docstring''' import torch lowerCamelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) lowerCamelCase = np.random.rand(1_00 , 32 ).astype(np.floataa ) lowerCamelCase = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: lowerCamelCase = feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""np""" ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) lowerCamelCase = feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""pt""" ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def __A ( self , A ) -> Any: '''simple docstring''' from datasets import load_dataset lowerCamelCase = load_dataset("""hf-internal-testing/librispeech_asr_dummy""" , """clean""" , split="""validation""" ) # automatic decoding with librispeech lowerCamelCase = ds.sort("""id""" ).select(range(A ) )[:num_samples]["""audio"""] return [x["array"] for x in speech_samples] def __A ( self ) -> Any: '''simple docstring''' lowerCamelCase = np.array([ -1.5745, -1.7713, -1.7020, -1.6069, -1.2250, -1.1105, -0.9072, -0.8241, -1.2310, -0.8098, -0.3320, -0.4101, -0.7985, -0.4996, -0.8213, -0.9128, -1.0420, -1.1286, -1.0440, -0.7999, -0.8405, -1.2275, -1.5443, -1.4625, ] ) # fmt: on lowerCamelCase = self._load_datasamples(1 ) lowerCamelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) lowerCamelCase = feature_extractor(A , return_tensors="""pt""" ).input_features self.assertEquals(input_features.shape , (1, 5_84, 24) ) self.assertTrue(np.allclose(input_features[0, 0, :30] , A , atol=1e-4 ) )
457
1
import math import random from typing import Any from .hill_climbing import SearchProblem def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : bool = True , _SCREAMING_SNAKE_CASE : float = math.inf , _SCREAMING_SNAKE_CASE : float = -math.inf , _SCREAMING_SNAKE_CASE : float = math.inf , _SCREAMING_SNAKE_CASE : float = -math.inf , _SCREAMING_SNAKE_CASE : bool = False , _SCREAMING_SNAKE_CASE : float = 100 , _SCREAMING_SNAKE_CASE : float = 0.01 , _SCREAMING_SNAKE_CASE : float = 1 , ): """simple docstring""" __a = False __a = search_prob __a = start_temperate __a = [] __a = 0 __a = None while not search_end: __a = current_state.score() if best_state is None or current_score > best_state.score(): __a = current_state scores.append(_SCREAMING_SNAKE_CASE ) iterations += 1 __a = None __a = current_state.get_neighbors() while ( next_state is None and neighbors ): # till we do not find a neighbor that we can move to __a = random.randint(0 , len(_SCREAMING_SNAKE_CASE ) - 1 ) # picking a random neighbor __a = neighbors.pop(_SCREAMING_SNAKE_CASE ) __a = picked_neighbor.score() - current_score if ( picked_neighbor.x > max_x or picked_neighbor.x < min_x or picked_neighbor.y > max_y or picked_neighbor.y < min_y ): continue # neighbor outside our bounds if not find_max: __a = change * -1 # in case we are finding minimum if change > 0: # improves the solution __a = picked_neighbor else: __a = (math.e) ** ( change / current_temp ) # probability generation function if random.random() < probability: # random number within probability __a = picked_neighbor __a = current_temp - (current_temp * rate_of_decrease) if current_temp < threshold_temp or next_state is None: # temperature below threshold, or could not find a suitable neighbor __a = True else: __a = next_state if visualization: from matplotlib import pyplot as plt plt.plot(range(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) plt.xlabel("""Iterations""" ) plt.ylabel("""Function values""" ) plt.show() return best_state if __name__ == "__main__": def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" return (x**2) + (y**2) # starting the problem with initial coordinates (12, 47) lowerCamelCase__ = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_fa) lowerCamelCase__ = simulated_annealing( prob, find_max=False, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True ) print( """The minimum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 """ F"""and 50 > y > - 5 found via hill climbing: {local_min.score()}""" ) # starting the problem with initial coordinates (12, 47) lowerCamelCase__ = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_fa) lowerCamelCase__ = simulated_annealing( prob, find_max=True, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True ) print( """The maximum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 """ F"""and 50 > y > - 5 found via hill climbing: {local_min.score()}""" ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" return (3 * x**2) - (6 * y) lowerCamelCase__ = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa) lowerCamelCase__ = simulated_annealing(prob, find_max=False, visualization=True) print( """The minimum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: """ F"""{local_min.score()}""" ) lowerCamelCase__ = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa) lowerCamelCase__ = simulated_annealing(prob, find_max=True, visualization=True) print( """The maximum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: """ F"""{local_min.score()}""" )
718
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available lowerCamelCase__ = { """configuration_nezha""": ["""NEZHA_PRETRAINED_CONFIG_ARCHIVE_MAP""", """NezhaConfig"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ """NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST""", """NezhaForNextSentencePrediction""", """NezhaForMaskedLM""", """NezhaForPreTraining""", """NezhaForMultipleChoice""", """NezhaForQuestionAnswering""", """NezhaForSequenceClassification""", """NezhaForTokenClassification""", """NezhaModel""", """NezhaPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_nezha import NEZHA_PRETRAINED_CONFIG_ARCHIVE_MAP, NezhaConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_nezha import ( NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, NezhaModel, NezhaPreTrainedModel, ) else: import sys lowerCamelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
547
0
'''simple docstring''' from copy import deepcopy from typing import Optional, Union import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, is_tf_available, is_torch_available if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''image_processor'''] lowerCamelCase__ = '''SamImageProcessor''' def __init__( self , __SCREAMING_SNAKE_CASE ): super().__init__(__SCREAMING_SNAKE_CASE ) snake_case__ : Tuple = self.image_processor snake_case__ : List[Any] = -1_0 snake_case__ : Any = self.image_processor.size["""longest_edge"""] def __call__( self , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE = None , **__SCREAMING_SNAKE_CASE , ): snake_case__ : Dict = self.image_processor( __SCREAMING_SNAKE_CASE , return_tensors=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) # pop arguments that are not used in the foward but used nevertheless snake_case__ : Union[str, Any] = encoding_image_processor["""original_sizes"""] if hasattr(__SCREAMING_SNAKE_CASE , """numpy""" ): # Checks if Torch or TF tensor snake_case__ : Optional[int] = original_sizes.numpy() snake_case__ , snake_case__ , snake_case__ : Dict = self._check_and_preprocess_points( input_points=__SCREAMING_SNAKE_CASE , input_labels=__SCREAMING_SNAKE_CASE , input_boxes=__SCREAMING_SNAKE_CASE , ) snake_case__ : Optional[Any] = self._normalize_and_convert( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , input_points=__SCREAMING_SNAKE_CASE , input_labels=__SCREAMING_SNAKE_CASE , input_boxes=__SCREAMING_SNAKE_CASE , return_tensors=__SCREAMING_SNAKE_CASE , ) return encoding_image_processor def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE="pt" , ): if input_points is not None: if len(__SCREAMING_SNAKE_CASE ) != len(__SCREAMING_SNAKE_CASE ): snake_case__ : List[Any] = [ self._normalize_coordinates(self.target_size , __SCREAMING_SNAKE_CASE , original_sizes[0] ) for point in input_points ] else: snake_case__ : Any = [ self._normalize_coordinates(self.target_size , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) for point, original_size in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ] # check that all arrays have the same shape if not all(point.shape == input_points[0].shape for point in input_points ): if input_labels is not None: snake_case__ , snake_case__ : int = self._pad_points_and_labels(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) snake_case__ : Union[str, Any] = np.array(__SCREAMING_SNAKE_CASE ) if input_labels is not None: snake_case__ : Tuple = np.array(__SCREAMING_SNAKE_CASE ) if input_boxes is not None: if len(__SCREAMING_SNAKE_CASE ) != len(__SCREAMING_SNAKE_CASE ): snake_case__ : int = [ self._normalize_coordinates(self.target_size , __SCREAMING_SNAKE_CASE , original_sizes[0] , is_bounding_box=__SCREAMING_SNAKE_CASE ) for box in input_boxes ] else: snake_case__ : int = [ self._normalize_coordinates(self.target_size , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , is_bounding_box=__SCREAMING_SNAKE_CASE ) for box, original_size in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ] snake_case__ : List[str] = np.array(__SCREAMING_SNAKE_CASE ) if input_boxes is not None: if return_tensors == "pt": snake_case__ : Union[str, Any] = torch.from_numpy(__SCREAMING_SNAKE_CASE ) # boxes batch size of 1 by default snake_case__ : Any = input_boxes.unsqueeze(1 ) if len(input_boxes.shape ) != 3 else input_boxes elif return_tensors == "tf": snake_case__ : int = tf.convert_to_tensor(__SCREAMING_SNAKE_CASE ) # boxes batch size of 1 by default snake_case__ : List[str] = tf.expand_dims(__SCREAMING_SNAKE_CASE , 1 ) if len(input_boxes.shape ) != 3 else input_boxes encoding_image_processor.update({"""input_boxes""": input_boxes} ) if input_points is not None: if return_tensors == "pt": snake_case__ : Optional[Any] = torch.from_numpy(__SCREAMING_SNAKE_CASE ) # point batch size of 1 by default snake_case__ : List[Any] = input_points.unsqueeze(1 ) if len(input_points.shape ) != 4 else input_points elif return_tensors == "tf": snake_case__ : List[Any] = tf.convert_to_tensor(__SCREAMING_SNAKE_CASE ) # point batch size of 1 by default snake_case__ : Union[str, Any] = tf.expand_dims(__SCREAMING_SNAKE_CASE , 1 ) if len(input_points.shape ) != 4 else input_points encoding_image_processor.update({"""input_points""": input_points} ) if input_labels is not None: if return_tensors == "pt": snake_case__ : Any = torch.from_numpy(__SCREAMING_SNAKE_CASE ) # point batch size of 1 by default snake_case__ : Optional[Any] = input_labels.unsqueeze(1 ) if len(input_labels.shape ) != 3 else input_labels elif return_tensors == "tf": snake_case__ : Optional[Any] = tf.convert_to_tensor(__SCREAMING_SNAKE_CASE ) # point batch size of 1 by default snake_case__ : str = tf.expand_dims(__SCREAMING_SNAKE_CASE , 1 ) if len(input_labels.shape ) != 3 else input_labels encoding_image_processor.update({"""input_labels""": input_labels} ) return encoding_image_processor def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : Dict = max([point.shape[0] for point in input_points] ) snake_case__ : List[str] = [] for i, point in enumerate(__SCREAMING_SNAKE_CASE ): if point.shape[0] != expected_nb_points: snake_case__ : Optional[int] = np.concatenate( [point, np.zeros((expected_nb_points - point.shape[0], 2) ) + self.point_pad_value] , axis=0 ) snake_case__ : Dict = np.append(input_labels[i] , [self.point_pad_value] ) processed_input_points.append(__SCREAMING_SNAKE_CASE ) snake_case__ : str = processed_input_points return input_points, input_labels def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=False ): snake_case__ , snake_case__ : Any = original_size snake_case__ , snake_case__ : str = self.image_processor._get_preprocess_shape(__SCREAMING_SNAKE_CASE , longest_edge=__SCREAMING_SNAKE_CASE ) snake_case__ : Union[str, Any] = deepcopy(__SCREAMING_SNAKE_CASE ).astype(__SCREAMING_SNAKE_CASE ) if is_bounding_box: snake_case__ : Dict = coords.reshape(-1 , 2 , 2 ) snake_case__ : str = coords[..., 0] * (new_w / old_w) snake_case__ : Union[str, Any] = coords[..., 1] * (new_h / old_h) if is_bounding_box: snake_case__ : Tuple = coords.reshape(-1 , 4 ) return coords def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , ): if input_points is not None: if hasattr(__SCREAMING_SNAKE_CASE , """numpy""" ): # Checks for TF or Torch tensor snake_case__ : int = input_points.numpy().tolist() if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) or not isinstance(input_points[0] , __SCREAMING_SNAKE_CASE ): raise ValueError("""Input points must be a list of list of floating points.""" ) snake_case__ : Optional[Any] = [np.array(__SCREAMING_SNAKE_CASE ) for input_point in input_points] else: snake_case__ : Any = None if input_labels is not None: if hasattr(__SCREAMING_SNAKE_CASE , """numpy""" ): snake_case__ : int = input_labels.numpy().tolist() if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) or not isinstance(input_labels[0] , __SCREAMING_SNAKE_CASE ): raise ValueError("""Input labels must be a list of list integers.""" ) snake_case__ : Union[str, Any] = [np.array(__SCREAMING_SNAKE_CASE ) for label in input_labels] else: snake_case__ : str = None if input_boxes is not None: if hasattr(__SCREAMING_SNAKE_CASE , """numpy""" ): snake_case__ : int = input_boxes.numpy().tolist() if ( not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) or not isinstance(input_boxes[0] , __SCREAMING_SNAKE_CASE ) or not isinstance(input_boxes[0][0] , __SCREAMING_SNAKE_CASE ) ): raise ValueError("""Input boxes must be a list of list of list of floating points.""" ) snake_case__ : Union[str, Any] = [np.array(__SCREAMING_SNAKE_CASE ).astype(np.floataa ) for box in input_boxes] else: snake_case__ : Any = None return input_points, input_labels, input_boxes @property def __UpperCamelCase ( self ): snake_case__ : Any = self.image_processor.model_input_names return list(dict.fromkeys(__SCREAMING_SNAKE_CASE ) ) def __UpperCamelCase ( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): return self.image_processor.post_process_masks(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE )
38
import unittest from transformers import MraConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_torch_available(): import torch from transformers import ( MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, MraModel, ) from transformers.models.mra.modeling_mra import MRA_PRETRAINED_MODEL_ARCHIVE_LIST class a : """simple docstring""" def __init__( self : Optional[Any] , lowerCamelCase__ : List[str] , lowerCamelCase__ : List[str]=2 , lowerCamelCase__ : Optional[int]=8 , lowerCamelCase__ : Any=True , lowerCamelCase__ : Any=True , lowerCamelCase__ : Optional[Any]=True , lowerCamelCase__ : Dict=True , lowerCamelCase__ : Any=99 , lowerCamelCase__ : int=16 , lowerCamelCase__ : Tuple=5 , lowerCamelCase__ : int=2 , lowerCamelCase__ : Optional[int]=36 , lowerCamelCase__ : List[str]="gelu" , lowerCamelCase__ : int=0.0 , lowerCamelCase__ : Union[str, Any]=0.0 , lowerCamelCase__ : Union[str, Any]=512 , lowerCamelCase__ : Tuple=16 , lowerCamelCase__ : Union[str, Any]=2 , lowerCamelCase__ : Optional[Any]=0.0_2 , lowerCamelCase__ : List[str]=3 , lowerCamelCase__ : Optional[int]=4 , lowerCamelCase__ : Optional[Any]=None , ) -> int: """simple docstring""" __lowercase = parent __lowercase = batch_size __lowercase = seq_length __lowercase = is_training __lowercase = use_input_mask __lowercase = use_token_type_ids __lowercase = use_labels __lowercase = vocab_size __lowercase = hidden_size __lowercase = num_hidden_layers __lowercase = num_attention_heads __lowercase = intermediate_size __lowercase = hidden_act __lowercase = hidden_dropout_prob __lowercase = attention_probs_dropout_prob __lowercase = max_position_embeddings __lowercase = type_vocab_size __lowercase = type_sequence_label_size __lowercase = initializer_range __lowercase = num_labels __lowercase = num_choices __lowercase = scope def UpperCAmelCase_ ( self : Optional[int] ) -> Any: """simple docstring""" __lowercase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __lowercase = None if self.use_input_mask: __lowercase = random_attention_mask([self.batch_size, self.seq_length] ) __lowercase = None if self.use_token_type_ids: __lowercase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __lowercase = None __lowercase = None __lowercase = None if self.use_labels: __lowercase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowercase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __lowercase = ids_tensor([self.batch_size] , self.num_choices ) __lowercase = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ ( self : Union[str, Any] ) -> Tuple: """simple docstring""" return MraConfig( 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 , is_decoder=lowerCamelCase__ , initializer_range=self.initializer_range , ) def UpperCAmelCase_ ( self : int ) -> int: """simple docstring""" __lowercase = self.get_config() __lowercase = 300 return config def UpperCAmelCase_ ( self : Optional[Any] ) -> Any: """simple docstring""" ( ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ) = self.prepare_config_and_inputs() __lowercase = True __lowercase = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __lowercase = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def UpperCAmelCase_ ( self : Tuple , lowerCamelCase__ : Optional[int] , lowerCamelCase__ : Union[str, Any] , lowerCamelCase__ : Dict , lowerCamelCase__ : List[Any] , lowerCamelCase__ : Union[str, Any] , lowerCamelCase__ : List[str] , lowerCamelCase__ : str ) -> List[Any]: """simple docstring""" __lowercase = MraModel(config=lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() __lowercase = model(lowerCamelCase__ , attention_mask=lowerCamelCase__ , token_type_ids=lowerCamelCase__ ) __lowercase = model(lowerCamelCase__ , token_type_ids=lowerCamelCase__ ) __lowercase = model(lowerCamelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self : Any , lowerCamelCase__ : Any , lowerCamelCase__ : List[Any] , lowerCamelCase__ : int , lowerCamelCase__ : int , lowerCamelCase__ : Any , lowerCamelCase__ : Union[str, Any] , lowerCamelCase__ : Any , lowerCamelCase__ : Any , lowerCamelCase__ : Any , ) -> str: """simple docstring""" __lowercase = True __lowercase = MraModel(lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() __lowercase = model( lowerCamelCase__ , attention_mask=lowerCamelCase__ , token_type_ids=lowerCamelCase__ , encoder_hidden_states=lowerCamelCase__ , encoder_attention_mask=lowerCamelCase__ , ) __lowercase = model( lowerCamelCase__ , attention_mask=lowerCamelCase__ , token_type_ids=lowerCamelCase__ , encoder_hidden_states=lowerCamelCase__ , ) __lowercase = model(lowerCamelCase__ , attention_mask=lowerCamelCase__ , token_type_ids=lowerCamelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self : Optional[Any] , lowerCamelCase__ : Optional[int] , lowerCamelCase__ : Tuple , lowerCamelCase__ : int , lowerCamelCase__ : Any , lowerCamelCase__ : Any , lowerCamelCase__ : str , lowerCamelCase__ : Union[str, Any] ) -> Optional[Any]: """simple docstring""" __lowercase = MraForMaskedLM(config=lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() __lowercase = model(lowerCamelCase__ , attention_mask=lowerCamelCase__ , token_type_ids=lowerCamelCase__ , labels=lowerCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ ( self : Union[str, Any] , lowerCamelCase__ : Any , lowerCamelCase__ : int , lowerCamelCase__ : Dict , lowerCamelCase__ : Any , lowerCamelCase__ : List[str] , lowerCamelCase__ : Optional[Any] , lowerCamelCase__ : str ) -> Dict: """simple docstring""" __lowercase = MraForQuestionAnswering(config=lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() __lowercase = model( lowerCamelCase__ , attention_mask=lowerCamelCase__ , token_type_ids=lowerCamelCase__ , start_positions=lowerCamelCase__ , end_positions=lowerCamelCase__ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def UpperCAmelCase_ ( self : Optional[int] , lowerCamelCase__ : Union[str, Any] , lowerCamelCase__ : Optional[Any] , lowerCamelCase__ : Tuple , lowerCamelCase__ : int , lowerCamelCase__ : List[str] , lowerCamelCase__ : Dict , lowerCamelCase__ : Dict ) -> str: """simple docstring""" __lowercase = self.num_labels __lowercase = MraForSequenceClassification(lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() __lowercase = model(lowerCamelCase__ , attention_mask=lowerCamelCase__ , token_type_ids=lowerCamelCase__ , labels=lowerCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCAmelCase_ ( self : Dict , lowerCamelCase__ : Any , lowerCamelCase__ : Tuple , lowerCamelCase__ : Dict , lowerCamelCase__ : Union[str, Any] , lowerCamelCase__ : Tuple , lowerCamelCase__ : Optional[int] , lowerCamelCase__ : Any ) -> List[str]: """simple docstring""" __lowercase = self.num_labels __lowercase = MraForTokenClassification(config=lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() __lowercase = model(lowerCamelCase__ , attention_mask=lowerCamelCase__ , token_type_ids=lowerCamelCase__ , labels=lowerCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase_ ( self : int , lowerCamelCase__ : Union[str, Any] , lowerCamelCase__ : List[str] , lowerCamelCase__ : Any , lowerCamelCase__ : Any , lowerCamelCase__ : Any , lowerCamelCase__ : int , lowerCamelCase__ : Tuple ) -> Tuple: """simple docstring""" __lowercase = self.num_choices __lowercase = MraForMultipleChoice(config=lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() __lowercase = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __lowercase = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __lowercase = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __lowercase = model( lowerCamelCase__ , attention_mask=lowerCamelCase__ , token_type_ids=lowerCamelCase__ , labels=lowerCamelCase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCAmelCase_ ( self : List[Any] ) -> List[str]: """simple docstring""" __lowercase = self.prepare_config_and_inputs() ( ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ) = config_and_inputs __lowercase = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class a ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): """simple docstring""" UpperCamelCase_ : Dict = ( ( MraModel, MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, ) if is_torch_available() else () ) UpperCamelCase_ : Dict = False UpperCamelCase_ : List[str] = False UpperCamelCase_ : Optional[int] = False UpperCamelCase_ : str = False UpperCamelCase_ : int = () def UpperCAmelCase_ ( self : Optional[Any] ) -> List[str]: """simple docstring""" __lowercase = MraModelTester(self ) __lowercase = ConfigTester(self , config_class=lowerCamelCase__ , hidden_size=37 ) def UpperCAmelCase_ ( self : Any ) -> Tuple: """simple docstring""" self.config_tester.run_common_tests() def UpperCAmelCase_ ( self : Optional[int] ) -> Tuple: """simple docstring""" __lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCamelCase__ ) def UpperCAmelCase_ ( self : List[str] ) -> Dict: """simple docstring""" __lowercase = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __lowercase = type self.model_tester.create_and_check_model(*lowerCamelCase__ ) def UpperCAmelCase_ ( self : int ) -> Any: """simple docstring""" __lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*lowerCamelCase__ ) def UpperCAmelCase_ ( self : str ) -> str: """simple docstring""" __lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*lowerCamelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Tuple: """simple docstring""" __lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*lowerCamelCase__ ) def UpperCAmelCase_ ( self : str ) -> Optional[int]: """simple docstring""" __lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*lowerCamelCase__ ) def UpperCAmelCase_ ( self : Optional[int] ) -> Union[str, Any]: """simple docstring""" __lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*lowerCamelCase__ ) @slow def UpperCAmelCase_ ( self : Any ) -> Dict: """simple docstring""" for model_name in MRA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowercase = MraModel.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) @unittest.skip(reason='''MRA does not output attentions''' ) def UpperCAmelCase_ ( self : Dict ) -> Any: """simple docstring""" return @require_torch class a ( unittest.TestCase ): """simple docstring""" @slow def UpperCAmelCase_ ( self : Union[str, Any] ) -> Dict: """simple docstring""" __lowercase = MraModel.from_pretrained('''uw-madison/mra-base-512-4''' ) __lowercase = torch.arange(256 ).unsqueeze(0 ) with torch.no_grad(): __lowercase = model(lowerCamelCase__ )[0] __lowercase = torch.Size((1, 256, 768) ) self.assertEqual(output.shape , lowerCamelCase__ ) __lowercase = torch.tensor( [[[-0.0_1_4_0, 0.0_8_3_0, -0.0_3_8_1], [0.1_5_4_6, 0.1_4_0_2, 0.0_2_2_0], [0.1_1_6_2, 0.0_8_5_1, 0.0_1_6_5]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , lowerCamelCase__ , atol=1e-4 ) ) @slow def UpperCAmelCase_ ( self : Optional[int] ) -> Tuple: """simple docstring""" __lowercase = MraForMaskedLM.from_pretrained('''uw-madison/mra-base-512-4''' ) __lowercase = torch.arange(256 ).unsqueeze(0 ) with torch.no_grad(): __lowercase = model(lowerCamelCase__ )[0] __lowercase = 50_265 __lowercase = torch.Size((1, 256, vocab_size) ) self.assertEqual(output.shape , lowerCamelCase__ ) __lowercase = torch.tensor( [[[9.2_5_9_5, -3.6_0_3_8, 1_1.8_8_1_9], [9.3_8_6_9, -3.2_6_9_3, 1_1.0_9_5_6], [1_1.8_5_2_4, -3.4_9_3_8, 1_3.1_2_1_0]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , lowerCamelCase__ , atol=1e-4 ) ) @slow def UpperCAmelCase_ ( self : List[str] ) -> Tuple: """simple docstring""" __lowercase = MraForMaskedLM.from_pretrained('''uw-madison/mra-base-4096-8-d3''' ) __lowercase = torch.arange(4_096 ).unsqueeze(0 ) with torch.no_grad(): __lowercase = model(lowerCamelCase__ )[0] __lowercase = 50_265 __lowercase = torch.Size((1, 4_096, vocab_size) ) self.assertEqual(output.shape , lowerCamelCase__ ) __lowercase = torch.tensor( [[[5.4_7_8_9, -2.3_5_6_4, 7.5_0_6_4], [7.9_0_6_7, -1.3_3_6_9, 9.9_6_6_8], [9.0_7_1_2, -1.8_1_0_6, 7.0_3_8_0]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , lowerCamelCase__ , atol=1e-4 ) )
332
0
'''simple docstring''' def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__ ): if a < 0 or b < 0: raise ValueError("the value of both inputs must be positive" ) lowerCamelCase_ = str(bin(lowerCamelCase__ ) )[2:] # remove the leading "0b" lowerCamelCase_ = str(bin(lowerCamelCase__ ) )[2:] # remove the leading "0b" lowerCamelCase_ = max(len(lowerCamelCase__ ) , len(lowerCamelCase__ ) ) return "0b" + "".join( str(int(char_a != char_b ) ) for char_a, char_b in zip(a_binary.zfill(lowerCamelCase__ ) , b_binary.zfill(lowerCamelCase__ ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
702
from typing import Optional, Tuple, Union import flax import flax.linen as nn import jax import jax.numpy as jnp from flax.core.frozen_dict import FrozenDict from ..configuration_utils import ConfigMixin, flax_register_to_config from ..utils import BaseOutput from .embeddings_flax import FlaxTimestepEmbedding, FlaxTimesteps from .modeling_flax_utils import FlaxModelMixin from .unet_ad_blocks_flax import ( FlaxCrossAttnDownBlockaD, FlaxDownBlockaD, FlaxUNetMidBlockaDCrossAttn, ) @flax.struct.dataclass class _SCREAMING_SNAKE_CASE ( snake_case_ ): lowerCAmelCase__ = 42 lowerCAmelCase__ = 42 class _SCREAMING_SNAKE_CASE ( nn.Module ): lowerCAmelCase__ = 42 lowerCAmelCase__ = (16, 32, 96, 2_56) lowerCAmelCase__ = jnp.floataa def SCREAMING_SNAKE_CASE_( self ) -> Optional[Any]: lowerCamelCase_ = nn.Conv( self.block_out_channels[0] , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) lowerCamelCase_ = [] for i in range(len(self.block_out_channels ) - 1 ): lowerCamelCase_ = self.block_out_channels[i] lowerCamelCase_ = self.block_out_channels[i + 1] lowerCamelCase_ = nn.Conv( lowercase , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) blocks.append(lowercase ) lowerCamelCase_ = nn.Conv( lowercase , kernel_size=(3, 3) , strides=(2, 2) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) blocks.append(lowercase ) lowerCamelCase_ = blocks lowerCamelCase_ = nn.Conv( self.conditioning_embedding_channels , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) def __call__( self , lowercase ) -> Optional[Any]: lowerCamelCase_ = self.conv_in(lowercase ) lowerCamelCase_ = nn.silu(lowercase ) for block in self.blocks: lowerCamelCase_ = block(lowercase ) lowerCamelCase_ = nn.silu(lowercase ) lowerCamelCase_ = self.conv_out(lowercase ) return embedding @flax_register_to_config class _SCREAMING_SNAKE_CASE ( nn.Module , snake_case_ , snake_case_ ): lowerCAmelCase__ = 32 lowerCAmelCase__ = 4 lowerCAmelCase__ = ( "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D", ) lowerCAmelCase__ = False lowerCAmelCase__ = (3_20, 6_40, 12_80, 12_80) lowerCAmelCase__ = 2 lowerCAmelCase__ = 8 lowerCAmelCase__ = None lowerCAmelCase__ = 12_80 lowerCAmelCase__ = 0.0 lowerCAmelCase__ = False lowerCAmelCase__ = jnp.floataa lowerCAmelCase__ = True lowerCAmelCase__ = 0 lowerCAmelCase__ = "rgb" lowerCAmelCase__ = (16, 32, 96, 2_56) def SCREAMING_SNAKE_CASE_( self , lowercase ) -> FrozenDict: # init input tensors lowerCamelCase_ = (1, self.in_channels, self.sample_size, self.sample_size) lowerCamelCase_ = jnp.zeros(lowercase , dtype=jnp.floataa ) lowerCamelCase_ = jnp.ones((1,) , dtype=jnp.intaa ) lowerCamelCase_ = jnp.zeros((1, 1, self.cross_attention_dim) , dtype=jnp.floataa ) lowerCamelCase_ = (1, 3, self.sample_size * 8, self.sample_size * 8) lowerCamelCase_ = jnp.zeros(lowercase , dtype=jnp.floataa ) lowerCamelCase_ , lowerCamelCase_ = jax.random.split(lowercase ) lowerCamelCase_ = {"params": params_rng, "dropout": dropout_rng} return self.init(lowercase , lowercase , lowercase , lowercase , lowercase )["params"] def SCREAMING_SNAKE_CASE_( self ) -> List[str]: lowerCamelCase_ = self.block_out_channels lowerCamelCase_ = block_out_channels[0] * 4 # If `num_attention_heads` is not defined (which is the case for most models) # it will default to `attention_head_dim`. This looks weird upon first reading it and it is. # The reason for this behavior is to correct for incorrectly named variables that were introduced # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking # which is why we correct for the naming here. lowerCamelCase_ = self.num_attention_heads or self.attention_head_dim # input lowerCamelCase_ = nn.Conv( block_out_channels[0] , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) # time lowerCamelCase_ = FlaxTimesteps( block_out_channels[0] , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.config.freq_shift ) lowerCamelCase_ = FlaxTimestepEmbedding(lowercase , dtype=self.dtype ) lowerCamelCase_ = FlaxControlNetConditioningEmbedding( conditioning_embedding_channels=block_out_channels[0] , block_out_channels=self.conditioning_embedding_out_channels , ) lowerCamelCase_ = self.only_cross_attention if isinstance(lowercase , lowercase ): lowerCamelCase_ = (only_cross_attention,) * len(self.down_block_types ) if isinstance(lowercase , lowercase ): lowerCamelCase_ = (num_attention_heads,) * len(self.down_block_types ) # down lowerCamelCase_ = [] lowerCamelCase_ = [] lowerCamelCase_ = block_out_channels[0] lowerCamelCase_ = nn.Conv( lowercase , kernel_size=(1, 1) , padding="VALID" , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(lowercase ) for i, down_block_type in enumerate(self.down_block_types ): lowerCamelCase_ = output_channel lowerCamelCase_ = block_out_channels[i] lowerCamelCase_ = i == len(lowercase ) - 1 if down_block_type == "CrossAttnDownBlock2D": lowerCamelCase_ = FlaxCrossAttnDownBlockaD( in_channels=lowercase , out_channels=lowercase , dropout=self.dropout , num_layers=self.layers_per_block , num_attention_heads=num_attention_heads[i] , add_downsample=not is_final_block , use_linear_projection=self.use_linear_projection , only_cross_attention=only_cross_attention[i] , dtype=self.dtype , ) else: lowerCamelCase_ = FlaxDownBlockaD( in_channels=lowercase , out_channels=lowercase , dropout=self.dropout , num_layers=self.layers_per_block , add_downsample=not is_final_block , dtype=self.dtype , ) down_blocks.append(lowercase ) for _ in range(self.layers_per_block ): lowerCamelCase_ = nn.Conv( lowercase , kernel_size=(1, 1) , padding="VALID" , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(lowercase ) if not is_final_block: lowerCamelCase_ = nn.Conv( lowercase , kernel_size=(1, 1) , padding="VALID" , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(lowercase ) lowerCamelCase_ = down_blocks lowerCamelCase_ = controlnet_down_blocks # mid lowerCamelCase_ = block_out_channels[-1] lowerCamelCase_ = FlaxUNetMidBlockaDCrossAttn( in_channels=lowercase , dropout=self.dropout , num_attention_heads=num_attention_heads[-1] , use_linear_projection=self.use_linear_projection , dtype=self.dtype , ) lowerCamelCase_ = nn.Conv( lowercase , kernel_size=(1, 1) , padding="VALID" , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) def __call__( self , lowercase , lowercase , lowercase , lowercase , lowercase = 1.0 , lowercase = True , lowercase = False , ) -> Union[FlaxControlNetOutput, Tuple]: lowerCamelCase_ = self.controlnet_conditioning_channel_order if channel_order == "bgr": lowerCamelCase_ = jnp.flip(lowercase , axis=1 ) # 1. time if not isinstance(lowercase , jnp.ndarray ): lowerCamelCase_ = jnp.array([timesteps] , dtype=jnp.intaa ) elif isinstance(lowercase , jnp.ndarray ) and len(timesteps.shape ) == 0: lowerCamelCase_ = timesteps.astype(dtype=jnp.floataa ) lowerCamelCase_ = jnp.expand_dims(lowercase , 0 ) lowerCamelCase_ = self.time_proj(lowercase ) lowerCamelCase_ = self.time_embedding(lowercase ) # 2. pre-process lowerCamelCase_ = jnp.transpose(lowercase , (0, 2, 3, 1) ) lowerCamelCase_ = self.conv_in(lowercase ) lowerCamelCase_ = jnp.transpose(lowercase , (0, 2, 3, 1) ) lowerCamelCase_ = self.controlnet_cond_embedding(lowercase ) sample += controlnet_cond # 3. down lowerCamelCase_ = (sample,) for down_block in self.down_blocks: if isinstance(lowercase , lowercase ): lowerCamelCase_ , lowerCamelCase_ = down_block(lowercase , lowercase , lowercase , deterministic=not train ) else: lowerCamelCase_ , lowerCamelCase_ = down_block(lowercase , lowercase , deterministic=not train ) down_block_res_samples += res_samples # 4. mid lowerCamelCase_ = self.mid_block(lowercase , lowercase , lowercase , deterministic=not train ) # 5. contronet blocks lowerCamelCase_ = () for down_block_res_sample, controlnet_block in zip(lowercase , self.controlnet_down_blocks ): lowerCamelCase_ = controlnet_block(lowercase ) controlnet_down_block_res_samples += (down_block_res_sample,) lowerCamelCase_ = controlnet_down_block_res_samples lowerCamelCase_ = self.controlnet_mid_block(lowercase ) # 6. scaling lowerCamelCase_ = [sample * conditioning_scale for sample in down_block_res_samples] mid_block_res_sample *= conditioning_scale if not return_dict: return (down_block_res_samples, mid_block_res_sample) return FlaxControlNetOutput( down_block_res_samples=lowercase , mid_block_res_sample=lowercase )
313
0
import argparse import os from pathlib import Path from typing import Dict import tensorflow as tf import torch from tqdm import tqdm from transformers import PegasusConfig, PegasusForConditionalGeneration, PegasusTokenizer from transformers.models.pegasus.configuration_pegasus import DEFAULTS, task_specific_params lowerCamelCase__ = [ # replace left string with right string to get the relevant state_dict key (identical state dict to bart) ["""memory_attention""", """encoder_attn"""], ["""attention""", """attn"""], ["""/""", """."""], [""".LayerNorm.gamma""", """_layer_norm.weight"""], [""".LayerNorm.beta""", """_layer_norm.bias"""], ["""r.layer_""", """r.layers."""], ["""output_proj""", """out_proj"""], ["""ffn.dense_1.""", """fc2."""], ["""ffn.dense.""", """fc1."""], ["""ffn_layer_norm""", """final_layer_norm"""], ["""kernel""", """weight"""], ["""encoder_layer_norm.""", """encoder.layer_norm."""], ["""decoder_layer_norm.""", """decoder.layer_norm."""], ["""embeddings.weights""", """shared.weight"""], ] def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : List[Any] ): """simple docstring""" for pegasus_name, hf_name in PATTERNS: __a = k.replace(lowerCAmelCase__ , lowerCAmelCase__ ) return k def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : List[Any] ): """simple docstring""" __a = DEFAULTS.copy() cfg_kwargs.update(lowerCAmelCase__ ) __a = PegasusConfig(**lowerCAmelCase__ ) __a = PegasusForConditionalGeneration(lowerCAmelCase__ ) __a = torch_model.model.state_dict() __a = {} for k, v in tf_weights.items(): __a = rename_state_dict_key(lowerCAmelCase__ ) if new_k not in sd: raise ValueError(f"could not find new key {new_k} in state dict. (converted from {k})" ) if "dense" in k or "proj" in new_k: __a = v.T __a = torch.tensor(lowerCAmelCase__ , dtype=sd[new_k].dtype ) assert v.shape == sd[new_k].shape, f"{new_k}, {k}, {v.shape}, {sd[new_k].shape}" # make sure embedding.padding_idx is respected __a = torch.zeros_like(mapping["""shared.weight"""][cfg.pad_token_id + 1] ) __a = mapping["shared.weight"] __a = mapping["shared.weight"] __a = {k: torch.zeros_like(lowerCAmelCase__ ) for k, v in sd.items() if k.endswith("""bias""" ) and k not in mapping} mapping.update(**lowerCAmelCase__ ) __a = torch_model.model.load_state_dict(lowerCAmelCase__ , strict=lowerCAmelCase__ ) __a = [ k for k in missing if k not in ["encoder.embed_positions.weight", "decoder.embed_positions.weight"] ] assert unexpected_missing == [], f"no matches found for the following torch keys {unexpected_missing}" assert extra == [], f"no matches found for the following tf keys {extra}" return torch_model def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Union[str, Any]="./ckpt/aeslc/model.ckpt-32000" ): """simple docstring""" __a = tf.train.list_variables(lowerCAmelCase__ ) __a = {} __a = ["Adafactor", "global_step"] for name, shape in tqdm(lowerCAmelCase__ , desc="""converting tf checkpoint to dict""" ): __a = any(pat in name for pat in ignore_name ) if skip_key: continue __a = tf.train.load_variable(lowerCAmelCase__ , lowerCAmelCase__ ) __a = array return tf_weights def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Optional[int] ): """simple docstring""" __a = Path(lowerCAmelCase__ ).parent.name __a = task_specific_params[f"summarization_{dataset}"]["max_position_embeddings"] __a = PegasusTokenizer.from_pretrained("""sshleifer/pegasus""" , model_max_length=lowerCAmelCase__ ) assert tok.model_max_length == desired_max_model_length tok.save_pretrained(lowerCAmelCase__ ) # convert model __a = get_tf_weights_as_numpy(lowerCAmelCase__ ) __a = task_specific_params[f"summarization_{dataset}"] if dataset == "large": __a = task_specific_params __a = convert_pegasus(lowerCAmelCase__ , lowerCAmelCase__ ) torch_model.save_pretrained(lowerCAmelCase__ ) __a = torch_model.state_dict() sd.pop("""model.decoder.embed_positions.weight""" ) sd.pop("""model.encoder.embed_positions.weight""" ) torch.save(lowerCAmelCase__ , Path(lowerCAmelCase__ ) / """pytorch_model.bin""" ) if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument("""tf_ckpt_path""", type=str, help="""passed to tf.train.list_variables""") parser.add_argument("""save_dir""", default=None, type=str, help="""Path to the output PyTorch model.""") lowerCamelCase__ = parser.parse_args() if args.save_dir is None: lowerCamelCase__ = Path(args.tf_ckpt_path).parent.name lowerCamelCase__ = os.path.join("""pegasus""", dataset) convert_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir)
225
class __A : '''simple docstring''' def __init__( self ): _lowerCAmelCase : Dict = "" _lowerCAmelCase : Optional[Any] = "" _lowerCAmelCase : List[Any] = [] def SCREAMING_SNAKE_CASE__ ( self , _snake_case , _snake_case ): if m == -1: return n + 1 elif n == -1: return m + 1 elif self.dp[m][n] > -1: return self.dp[m][n] else: if self.worda[m] == self.worda[n]: _lowerCAmelCase : Optional[Any] = self.__min_dist_top_down_dp(m - 1 , n - 1 ) else: _lowerCAmelCase : Optional[int] = self.__min_dist_top_down_dp(_snake_case , n - 1 ) _lowerCAmelCase : List[str] = self.__min_dist_top_down_dp(m - 1 , _snake_case ) _lowerCAmelCase : str = self.__min_dist_top_down_dp(m - 1 , n - 1 ) _lowerCAmelCase : Optional[int] = 1 + min(_snake_case , _snake_case , _snake_case ) return self.dp[m][n] def SCREAMING_SNAKE_CASE__ ( self , _snake_case , _snake_case ): _lowerCAmelCase : Union[str, Any] = worda _lowerCAmelCase : int = worda _lowerCAmelCase : Tuple = [[-1 for _ in range(len(_snake_case ) )] for _ in range(len(_snake_case ) )] return self.__min_dist_top_down_dp(len(_snake_case ) - 1 , len(_snake_case ) - 1 ) def SCREAMING_SNAKE_CASE__ ( self , _snake_case , _snake_case ): _lowerCAmelCase : str = worda _lowerCAmelCase : Union[str, Any] = worda _lowerCAmelCase : str = len(_snake_case ) _lowerCAmelCase : List[Any] = len(_snake_case ) _lowerCAmelCase : str = [[0 for _ in range(n + 1 )] for _ in range(m + 1 )] for i in range(m + 1 ): for j in range(n + 1 ): if i == 0: # first string is empty _lowerCAmelCase : int = j elif j == 0: # second string is empty _lowerCAmelCase : Optional[Any] = i elif worda[i - 1] == worda[j - 1]: # last characters are equal _lowerCAmelCase : Union[str, Any] = self.dp[i - 1][j - 1] else: _lowerCAmelCase : Tuple = self.dp[i][j - 1] _lowerCAmelCase : Dict = self.dp[i - 1][j] _lowerCAmelCase : List[Any] = self.dp[i - 1][j - 1] _lowerCAmelCase : Tuple = 1 + min(_snake_case , _snake_case , _snake_case ) return self.dp[m][n] if __name__ == "__main__": snake_case = EditDistance() print("****************** Testing Edit Distance DP Algorithm ******************") print() snake_case = input("Enter the first string: ").strip() snake_case = input("Enter the second string: ").strip() print() print(F'''The minimum edit distance is: {solver.min_dist_top_down(Sa, Sa)}''') print(F'''The minimum edit distance is: {solver.min_dist_bottom_up(Sa, Sa)}''') print() print("*************** End of Testing Edit Distance DP Algorithm ***************")
424
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 __magic_name__ = logging.get_logger(__name__) __magic_name__ = {'''vocab_file''': '''spiece.model'''} __magic_name__ = { '''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''', } } __magic_name__ = { '''xlnet-base-cased''': None, '''xlnet-large-cased''': None, } # Segments (not really needed) __magic_name__ = 0 __magic_name__ = 1 __magic_name__ = 2 __magic_name__ = 3 __magic_name__ = 4 class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" __UpperCAmelCase : Tuple = VOCAB_FILES_NAMES __UpperCAmelCase : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase : Optional[int] = '''left''' def __init__( self , a_ , a_=False , a_=True , a_=False , a_="<s>" , a_="</s>" , a_="<unk>" , a_="<sep>" , a_="<pad>" , a_="<cls>" , a_="<mask>" , a_=["<eop>", "<eod>"] , a_ = None , **a_ , ): # Mask token behave like a normal word, i.e. include the space before it lowerCamelCase_ : str = AddedToken(a_ , lstrip=a_ , rstrip=a_ ) if isinstance(a_ , a_ ) else mask_token lowerCamelCase_ : int = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=a_ , remove_space=a_ , keep_accents=a_ , bos_token=a_ , eos_token=a_ , unk_token=a_ , sep_token=a_ , pad_token=a_ , cls_token=a_ , mask_token=a_ , additional_special_tokens=a_ , sp_model_kwargs=self.sp_model_kwargs , **a_ , ) lowerCamelCase_ : str = 3 lowerCamelCase_ : Dict = do_lower_case lowerCamelCase_ : str = remove_space lowerCamelCase_ : Tuple = keep_accents lowerCamelCase_ : Dict = vocab_file lowerCamelCase_ : List[str] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(a_ ) @property def _UpperCamelCase ( self ): return len(self.sp_model ) def _UpperCamelCase ( self ): lowerCamelCase_ : List[str] = {self.convert_ids_to_tokens(a_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ): lowerCamelCase_ : Any = self.__dict__.copy() lowerCamelCase_ : Optional[int] = None return state def __setstate__( self , a_ ): lowerCamelCase_ : Union[str, Any] = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): lowerCamelCase_ : int = {} lowerCamelCase_ : Union[str, Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _UpperCamelCase ( self , a_ ): if self.remove_space: lowerCamelCase_ : Optional[int] = " ".join(inputs.strip().split() ) else: lowerCamelCase_ : str = inputs lowerCamelCase_ : Any = outputs.replace("``" , "\"" ).replace("''" , "\"" ) if not self.keep_accents: lowerCamelCase_ : Dict = unicodedata.normalize("NFKD" , a_ ) lowerCamelCase_ : int = "".join([c for c in outputs if not unicodedata.combining(a_ )] ) if self.do_lower_case: lowerCamelCase_ : Any = outputs.lower() return outputs def _UpperCamelCase ( self , a_ ): lowerCamelCase_ : List[Any] = self.preprocess_text(a_ ) lowerCamelCase_ : Optional[int] = self.sp_model.encode(a_ , out_type=a_ ) lowerCamelCase_ : List[str] = [] for piece in pieces: if len(a_ ) > 1 and piece[-1] == str("," ) and piece[-2].isdigit(): lowerCamelCase_ : Tuple = self.sp_model.EncodeAsPieces(piece[:-1].replace(a_ , "" ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: lowerCamelCase_ : int = cur_pieces[1:] else: lowerCamelCase_ : Union[str, Any] = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(a_ ) else: new_pieces.append(a_ ) return new_pieces def _UpperCamelCase ( self , a_ ): return self.sp_model.PieceToId(a_ ) def _UpperCamelCase ( self , a_ ): return self.sp_model.IdToPiece(a_ ) def _UpperCamelCase ( self , a_ ): lowerCamelCase_ : Dict = "".join(a_ ).replace(a_ , " " ).strip() return out_string def _UpperCamelCase ( self , a_ , a_ = False , a_ = None , a_ = True , **a_ , ): lowerCamelCase_ : int = kwargs.pop("use_source_tokenizer" , a_ ) lowerCamelCase_ : List[str] = self.convert_ids_to_tokens(a_ , skip_special_tokens=a_ ) # 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 lowerCamelCase_ : Optional[int] = [] lowerCamelCase_ : List[str] = [] 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(a_ ) ) lowerCamelCase_ : Union[str, Any] = [] sub_texts.append(a_ ) else: current_sub_text.append(a_ ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(a_ ) ) # Mimic the behavior of the Rust tokenizer: # By default, there are no spaces between special tokens lowerCamelCase_ : Union[str, Any] = "".join(a_ ) lowerCamelCase_ : Optional[Any] = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: lowerCamelCase_ : List[Any] = self.clean_up_tokenization(a_ ) return clean_text else: return text def _UpperCamelCase ( self , a_ , a_ = None ): lowerCamelCase_ : Optional[Any] = [self.sep_token_id] lowerCamelCase_ : Union[str, Any] = [self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def _UpperCamelCase ( self , a_ , a_ = None , a_ = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=a_ , token_ids_a=a_ , already_has_special_tokens=a_ ) if token_ids_a is not None: return ([0] * len(a_ )) + [1] + ([0] * len(a_ )) + [1, 1] return ([0] * len(a_ )) + [1, 1] def _UpperCamelCase ( self , a_ , a_ = None ): lowerCamelCase_ : Optional[Any] = [self.sep_token_id] lowerCamelCase_ : Union[str, Any] = [2] if token_ids_a is None: return len(token_ids_a + sep ) * [0] + cls_segment_id return len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] + cls_segment_id def _UpperCamelCase ( self , a_ , a_ = None ): if not os.path.isdir(a_ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return lowerCamelCase_ : Any = os.path.join( a_ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(a_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , a_ ) elif not os.path.isfile(self.vocab_file ): with open(a_ , "wb" ) as fi: lowerCamelCase_ : Dict = self.sp_model.serialized_model_proto() fi.write(a_ ) return (out_vocab_file,)
73
import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __init__( self , a_ , a_=7 , a_=3 , a_=18 , a_=30 , a_=400 , a_=True , a_=None , a_=True , ): lowerCamelCase_ : int = size if size is not None else {"height": 18, "width": 18} lowerCamelCase_ : str = parent lowerCamelCase_ : str = batch_size lowerCamelCase_ : Tuple = num_channels lowerCamelCase_ : Optional[int] = image_size lowerCamelCase_ : List[str] = min_resolution lowerCamelCase_ : Tuple = max_resolution lowerCamelCase_ : Tuple = do_resize lowerCamelCase_ : Dict = size lowerCamelCase_ : List[str] = apply_ocr def _UpperCamelCase ( self ): return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class lowerCAmelCase__ ( __lowerCamelCase, unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Union[str, Any] = LayoutLMvaImageProcessor if is_pytesseract_available() else None def _UpperCamelCase ( self ): lowerCamelCase_ : List[str] = LayoutLMvaImageProcessingTester(self ) @property def _UpperCamelCase ( self ): return self.image_processor_tester.prepare_image_processor_dict() def _UpperCamelCase ( self ): lowerCamelCase_ : List[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a_ , "do_resize" ) ) self.assertTrue(hasattr(a_ , "size" ) ) self.assertTrue(hasattr(a_ , "apply_ocr" ) ) def _UpperCamelCase ( self ): lowerCamelCase_ : Tuple = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"height": 18, "width": 18} ) lowerCamelCase_ : Dict = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {"height": 42, "width": 42} ) def _UpperCamelCase ( self ): pass def _UpperCamelCase ( self ): # Initialize image_processing lowerCamelCase_ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowerCamelCase_ : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ ) for image in image_inputs: self.assertIsInstance(a_ , Image.Image ) # Test not batched input lowerCamelCase_ : List[str] = image_processing(image_inputs[0] , return_tensors="pt" ) self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) self.assertIsInstance(encoding.words , a_ ) self.assertIsInstance(encoding.boxes , a_ ) # Test batched lowerCamelCase_ : int = image_processing(a_ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) def _UpperCamelCase ( self ): # Initialize image_processing lowerCamelCase_ : Any = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowerCamelCase_ : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ , numpify=a_ ) for image in image_inputs: self.assertIsInstance(a_ , np.ndarray ) # Test not batched input lowerCamelCase_ : List[Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) # Test batched lowerCamelCase_ : Any = image_processing(a_ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) def _UpperCamelCase ( self ): # Initialize image_processing lowerCamelCase_ : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowerCamelCase_ : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ , torchify=a_ ) for image in image_inputs: self.assertIsInstance(a_ , torch.Tensor ) # Test not batched input lowerCamelCase_ : Union[str, Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) # Test batched lowerCamelCase_ : Union[str, Any] = image_processing(a_ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) def _UpperCamelCase ( self ): # with apply_OCR = True lowerCamelCase_ : Any = LayoutLMvaImageProcessor() from datasets import load_dataset lowerCamelCase_ : Optional[Any] = load_dataset("hf-internal-testing/fixtures_docvqa" , split="test" ) lowerCamelCase_ : Optional[Any] = Image.open(ds[0]["file"] ).convert("RGB" ) lowerCamelCase_ : List[Any] = image_processing(a_ , return_tensors="pt" ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 lowerCamelCase_ : List[Any] = [["11:14", "to", "11:39", "a.m", "11:39", "to", "11:44", "a.m.", "11:44", "a.m.", "to", "12:25", "p.m.", "12:25", "to", "12:58", "p.m.", "12:58", "to", "4:00", "p.m.", "2:00", "to", "5:00", "p.m.", "Coffee", "Break", "Coffee", "will", "be", "served", "for", "men", "and", "women", "in", "the", "lobby", "adjacent", "to", "exhibit", "area.", "Please", "move", "into", "exhibit", "area.", "(Exhibits", "Open)", "TRRF", "GENERAL", "SESSION", "(PART", "|)", "Presiding:", "Lee", "A.", "Waller", "TRRF", "Vice", "President", "“Introductory", "Remarks”", "Lee", "A.", "Waller,", "TRRF", "Vice", "Presi-", "dent", "Individual", "Interviews", "with", "TRRF", "Public", "Board", "Members", "and", "Sci-", "entific", "Advisory", "Council", "Mem-", "bers", "Conducted", "by", "TRRF", "Treasurer", "Philip", "G.", "Kuehn", "to", "get", "answers", "which", "the", "public", "refrigerated", "warehousing", "industry", "is", "looking", "for.", "Plus", "questions", "from", "the", "floor.", "Dr.", "Emil", "M.", "Mrak,", "University", "of", "Cal-", "ifornia,", "Chairman,", "TRRF", "Board;", "Sam", "R.", "Cecil,", "University", "of", "Georgia", "College", "of", "Agriculture;", "Dr.", "Stanley", "Charm,", "Tufts", "University", "School", "of", "Medicine;", "Dr.", "Robert", "H.", "Cotton,", "ITT", "Continental", "Baking", "Company;", "Dr.", "Owen", "Fennema,", "University", "of", "Wis-", "consin;", "Dr.", "Robert", "E.", "Hardenburg,", "USDA.", "Questions", "and", "Answers", "Exhibits", "Open", "Capt.", "Jack", "Stoney", "Room", "TRRF", "Scientific", "Advisory", "Council", "Meeting", "Ballroom", "Foyer"]] # noqa: E231 lowerCamelCase_ : Tuple = [[[141, 57, 214, 69], [228, 58, 252, 69], [141, 75, 216, 88], [230, 79, 280, 88], [142, 260, 218, 273], [230, 261, 255, 273], [143, 279, 218, 290], [231, 282, 290, 291], [143, 342, 218, 354], [231, 345, 289, 355], [202, 362, 227, 373], [143, 379, 220, 392], [231, 382, 291, 394], [144, 714, 220, 726], [231, 715, 256, 726], [144, 732, 220, 745], [232, 736, 291, 747], [144, 769, 218, 782], [231, 770, 256, 782], [141, 788, 202, 801], [215, 791, 274, 804], [143, 826, 204, 838], [215, 826, 240, 838], [142, 844, 202, 857], [215, 847, 274, 859], [334, 57, 427, 69], [440, 57, 522, 69], [369, 75, 461, 88], [469, 75, 516, 88], [528, 76, 562, 88], [570, 76, 667, 88], [675, 75, 711, 87], [721, 79, 778, 88], [789, 75, 840, 88], [369, 97, 470, 107], [484, 94, 507, 106], [518, 94, 562, 107], [576, 94, 655, 110], [668, 94, 792, 109], [804, 95, 829, 107], [369, 113, 465, 125], [477, 116, 547, 125], [562, 113, 658, 125], [671, 116, 748, 125], [761, 113, 811, 125], [369, 131, 465, 143], [477, 133, 548, 143], [563, 130, 698, 145], [710, 130, 802, 146], [336, 171, 412, 183], [423, 171, 572, 183], [582, 170, 716, 184], [728, 171, 817, 187], [829, 171, 844, 186], [338, 197, 482, 212], [507, 196, 557, 209], [569, 196, 595, 208], [610, 196, 702, 209], [505, 214, 583, 226], [595, 214, 656, 227], [670, 215, 807, 227], [335, 259, 543, 274], [556, 259, 708, 272], [372, 279, 422, 291], [435, 279, 460, 291], [474, 279, 574, 292], [587, 278, 664, 291], [676, 278, 738, 291], [751, 279, 834, 291], [372, 298, 434, 310], [335, 341, 483, 354], [497, 341, 655, 354], [667, 341, 728, 354], [740, 341, 825, 354], [335, 360, 430, 372], [442, 360, 534, 372], [545, 359, 687, 372], [697, 360, 754, 372], [765, 360, 823, 373], [334, 378, 428, 391], [440, 378, 577, 394], [590, 378, 705, 391], [720, 378, 801, 391], [334, 397, 400, 409], [370, 416, 529, 429], [544, 416, 576, 432], [587, 416, 665, 428], [677, 416, 814, 429], [372, 435, 452, 450], [465, 434, 495, 447], [511, 434, 600, 447], [611, 436, 637, 447], [649, 436, 694, 451], [705, 438, 824, 447], [369, 453, 452, 466], [464, 454, 509, 466], [522, 453, 611, 469], [625, 453, 792, 469], [370, 472, 556, 488], [570, 472, 684, 487], [697, 472, 718, 485], [732, 472, 835, 488], [369, 490, 411, 503], [425, 490, 484, 503], [496, 490, 635, 506], [645, 490, 707, 503], [718, 491, 761, 503], [771, 490, 840, 503], [336, 510, 374, 521], [388, 510, 447, 522], [460, 510, 489, 521], [503, 510, 580, 522], [592, 509, 736, 525], [745, 509, 770, 522], [781, 509, 840, 522], [338, 528, 434, 541], [448, 528, 596, 541], [609, 527, 687, 540], [700, 528, 792, 541], [336, 546, 397, 559], [407, 546, 431, 559], [443, 546, 525, 560], [537, 546, 680, 562], [688, 546, 714, 559], [722, 546, 837, 562], [336, 565, 449, 581], [461, 565, 485, 577], [497, 565, 665, 581], [681, 565, 718, 577], [732, 565, 837, 580], [337, 584, 438, 597], [452, 583, 521, 596], [535, 584, 677, 599], [690, 583, 787, 596], [801, 583, 825, 596], [338, 602, 478, 615], [492, 602, 530, 614], [543, 602, 638, 615], [650, 602, 676, 614], [688, 602, 788, 615], [802, 602, 843, 614], [337, 621, 502, 633], [516, 621, 615, 637], [629, 621, 774, 636], [789, 621, 827, 633], [337, 639, 418, 652], [432, 640, 571, 653], [587, 639, 731, 655], [743, 639, 769, 652], [780, 639, 841, 652], [338, 658, 440, 673], [455, 658, 491, 670], [508, 658, 602, 671], [616, 658, 638, 670], [654, 658, 835, 674], [337, 677, 429, 689], [337, 714, 482, 726], [495, 714, 548, 726], [561, 714, 683, 726], [338, 770, 461, 782], [474, 769, 554, 785], [489, 788, 562, 803], [576, 788, 643, 801], [656, 787, 751, 804], [764, 788, 844, 801], [334, 825, 421, 838], [430, 824, 574, 838], [584, 824, 723, 841], [335, 844, 450, 857], [464, 843, 583, 860], [628, 862, 755, 875], [769, 861, 848, 878]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , a_ ) self.assertListEqual(encoding.boxes , a_ ) # with apply_OCR = False lowerCamelCase_ : List[str] = LayoutLMvaImageProcessor(apply_ocr=a_ ) lowerCamelCase_ : List[str] = image_processing(a_ , return_tensors="pt" ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) )
73
1
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { '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 UpperCamelCase_ ( UpperCamelCase__ , UpperCamelCase__ ): lowerCamelCase_ = "nat" lowerCamelCase_ = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self :List[Any] , __A :Union[str, Any]=4 , __A :Dict=3 , __A :str=64 , __A :Optional[int]=[3, 4, 6, 5] , __A :Tuple=[2, 4, 8, 16] , __A :List[str]=7 , __A :Optional[Any]=3.0 , __A :Tuple=True , __A :Tuple=0.0 , __A :Dict=0.0 , __A :Tuple=0.1 , __A :str="gelu" , __A :Tuple=0.0_2 , __A :str=1E-5 , __A :Tuple=0.0 , __A :List[str]=None , __A :Optional[Any]=None , **__A :Optional[Any] , ) -> List[str]: """simple docstring""" super().__init__(**__A ) SCREAMING_SNAKE_CASE__ = patch_size SCREAMING_SNAKE_CASE__ = num_channels SCREAMING_SNAKE_CASE__ = embed_dim SCREAMING_SNAKE_CASE__ = depths SCREAMING_SNAKE_CASE__ = len(__A ) SCREAMING_SNAKE_CASE__ = num_heads SCREAMING_SNAKE_CASE__ = kernel_size SCREAMING_SNAKE_CASE__ = mlp_ratio SCREAMING_SNAKE_CASE__ = qkv_bias SCREAMING_SNAKE_CASE__ = hidden_dropout_prob SCREAMING_SNAKE_CASE__ = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ = drop_path_rate SCREAMING_SNAKE_CASE__ = hidden_act SCREAMING_SNAKE_CASE__ = layer_norm_eps SCREAMING_SNAKE_CASE__ = 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__ = int(embed_dim * 2 ** (len(__A ) - 1) ) SCREAMING_SNAKE_CASE__ = layer_scale_init_value SCREAMING_SNAKE_CASE__ = ["""stem"""] + [f'''stage{idx}''' for idx in range(1 , len(__A ) + 1 )] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = get_aligned_output_features_output_indices( out_features=__A , out_indices=__A , stage_names=self.stage_names )
6
import inspect import os import unittest from pathlib import Path import torch import accelerate from accelerate.test_utils import execute_subprocess_async from accelerate.test_utils.testing import run_command class __lowerCAmelCase ( unittest.TestCase ): lowerCamelCase_ : Tuple = inspect.getfile(accelerate.test_utils ) lowerCamelCase_ : Optional[Any] = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_cli.py'''] ) lowerCamelCase_ : Union[str, Any] = ['''accelerate''', '''launch'''] lowerCamelCase_ : Tuple = Path.home() / '''.cache/huggingface/accelerate''' lowerCamelCase_ : Tuple = '''default_config.yaml''' lowerCamelCase_ : str = config_folder / config_file lowerCamelCase_ : List[Any] = config_folder / '''_default_config.yaml''' lowerCamelCase_ : Dict = Path('''tests/test_configs''' ) @classmethod def lowerCamelCase (cls ) -> Dict: '''simple docstring''' if cls.config_path.is_file(): cls.config_path.rename(cls.changed_path ) @classmethod def lowerCamelCase (cls ) -> Any: '''simple docstring''' if cls.changed_path.is_file(): cls.changed_path.rename(cls.config_path ) def lowerCamelCase (self ) -> Tuple: '''simple docstring''' snake_case_ : Dict = self.base_cmd if torch.cuda.is_available() and (torch.cuda.device_count() > 1): cmd += ["--multi_gpu"] execute_subprocess_async(cmd + [self.test_file_path] , env=os.environ.copy() ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' for config in sorted(self.test_config_path.glob('''**/*.yaml''' ) ): with self.subTest(config_file=__magic_name__ ): execute_subprocess_async( self.base_cmd + ['''--config_file''', str(__magic_name__ ), self.test_file_path] , env=os.environ.copy() ) def lowerCamelCase (self ) -> List[Any]: '''simple docstring''' execute_subprocess_async(['''accelerate''', '''test'''] , env=os.environ.copy() ) class __lowerCAmelCase ( unittest.TestCase ): lowerCamelCase_ : List[str] = '''test-tpu''' lowerCamelCase_ : Dict = '''us-central1-a''' lowerCamelCase_ : Any = '''ls''' lowerCamelCase_ : Dict = ['''accelerate''', '''tpu-config'''] lowerCamelCase_ : Tuple = '''cd /usr/share''' lowerCamelCase_ : List[Any] = '''tests/test_samples/test_command_file.sh''' lowerCamelCase_ : List[Any] = '''Running gcloud compute tpus tpu-vm ssh''' def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : int = run_command( self.cmd + ['''--command''', self.command, '''--tpu_zone''', self.tpu_zone, '''--tpu_name''', self.tpu_name, '''--debug'''] , return_stdout=__magic_name__ , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all''' , __magic_name__ , ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : Optional[int] = run_command( self.cmd + [ '''--config_file''', '''tests/test_configs/0_12_0.yaml''', '''--command''', self.command, '''--tpu_zone''', self.tpu_zone, '''--tpu_name''', self.tpu_name, '''--debug''', ] , return_stdout=__magic_name__ , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all''' , __magic_name__ , ) def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : List[str] = run_command( self.cmd + ['''--config_file''', '''tests/test_configs/latest.yaml''', '''--debug'''] , return_stdout=__magic_name__ ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all''' , __magic_name__ , ) def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : List[Any] = run_command( self.cmd + ['''--config_file''', '''tests/test_configs/latest.yaml''', '''--command''', self.command, '''--debug'''] , return_stdout=__magic_name__ , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all''' , __magic_name__ , ) def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : Any = run_command( self.cmd + [ '''--config_file''', '''tests/test_configs/latest.yaml''', '''--command''', self.command, '''--command''', '''echo "Hello World"''', '''--debug''', ] , return_stdout=__magic_name__ , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls; echo "Hello World" --worker all''' , __magic_name__ , ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : str = run_command( self.cmd + ['''--config_file''', '''tests/test_configs/latest.yaml''', '''--command_file''', self.command_file, '''--debug'''] , return_stdout=__magic_name__ , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all''' , __magic_name__ , ) def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : Tuple = run_command( self.cmd + [ '''--config_file''', '''tests/test_configs/0_12_0.yaml''', '''--command_file''', self.command_file, '''--tpu_zone''', self.tpu_zone, '''--tpu_name''', self.tpu_name, '''--debug''', ] , return_stdout=__magic_name__ , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all''' , __magic_name__ , ) def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' snake_case_ : Any = run_command( self.cmd + ['''--config_file''', '''tests/test_configs/latest.yaml''', '''--install_accelerate''', '''--debug'''] , return_stdout=__magic_name__ , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate -U; echo "hello world"; echo "this is a second command" --worker all''' , __magic_name__ , ) def lowerCamelCase (self ) -> str: '''simple docstring''' snake_case_ : Optional[Any] = run_command( self.cmd + [ '''--config_file''', '''tests/test_configs/latest.yaml''', '''--install_accelerate''', '''--accelerate_version''', '''12.0.0''', '''--debug''', ] , return_stdout=__magic_name__ , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate==12.0.0; echo "hello world"; echo "this is a second command" --worker all''' , __magic_name__ , )
60
0
from typing import List, Optional, Union import numpy as np import tensorflow as tf from .utils import logging a : Optional[int] = logging.get_logger(__name__) def __lowerCamelCase ( _lowercase ) -> Tuple: if isinstance(SCREAMING_SNAKE_CASE__ , np.ndarray ): return list(tensor.shape ) UpperCAmelCase : Optional[int] = tf.shape(SCREAMING_SNAKE_CASE__ ) if tensor.shape == tf.TensorShape(SCREAMING_SNAKE_CASE__ ): return dynamic UpperCAmelCase : List[str] = tensor.shape.as_list() return [dynamic[i] if s is None else s for i, s in enumerate(SCREAMING_SNAKE_CASE__ )] def __lowerCamelCase ( _lowercase , _lowercase = None , _lowercase = None ) -> str: return tf.nn.softmax(logits=logits + 1e-9 , axis=SCREAMING_SNAKE_CASE__ , name=SCREAMING_SNAKE_CASE__ ) def __lowerCamelCase ( _lowercase , _lowercase , _lowercase , _lowercase=1e-5 , _lowercase=-1 ) -> Optional[int]: if weight.shape.rank != 1 or bias.shape.rank != 1 or not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): raise NotImplementedError("""Only 1D weight and bias tensors are supported for now, with only a single axis.""" ) # Get mean and variance on the axis to be normalized UpperCAmelCase : str = tf.nn.moments(SCREAMING_SNAKE_CASE__ , axes=[axis] , keepdims=SCREAMING_SNAKE_CASE__ ) if axis != -1: # Reshape scale and weight to have the same rank as inputs, but with 1 dimensions # on every dimension except axis UpperCAmelCase : Optional[Any] = [1] * inputs.shape.rank UpperCAmelCase : Any = shape_list(SCREAMING_SNAKE_CASE__ )[axis] UpperCAmelCase : List[str] = tf.reshape(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) UpperCAmelCase : List[Any] = tf.reshape(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Compute layer normalization using the batch_normalization # function. UpperCAmelCase : List[Any] = tf.nn.batch_normalization( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , offset=SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ , variance_epsilon=SCREAMING_SNAKE_CASE__ , ) return outputs def __lowerCamelCase ( _lowercase , _lowercase=0 , _lowercase=-1 ) -> int: if end_dim < 0: end_dim += input.shape.rank if start_dim < 0: start_dim += input.shape.rank if start_dim == end_dim: return input UpperCAmelCase : int = tf.shape(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase : str = tf.math.reduce_prod(in_shape[start_dim : end_dim + 1] ) UpperCAmelCase : List[str] = tf.concat([in_shape[:start_dim], [flattened_dim], in_shape[end_dim + 1 :]] , axis=0 ) return tf.reshape(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __lowerCamelCase ( _lowercase ) -> str: if not isinstance(SCREAMING_SNAKE_CASE__ , tf.Tensor ): UpperCAmelCase : Optional[Any] = tf.convert_to_tensor(SCREAMING_SNAKE_CASE__ ) # Catches stray NumPy inputs if encoder_attention_mask.shape.rank == 3: UpperCAmelCase : Optional[int] = encoder_attention_mask[:, None, :, :] if encoder_attention_mask.shape.rank == 2: UpperCAmelCase : List[Any] = encoder_attention_mask[:, None, None, :] # T5 has a mask that can compare sequence ids, we can simulate this here with this transposition # Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow # /transformer/transformer_layers.py#L270 # encoder_extended_attention_mask = (encoder_extended_attention_mask == # encoder_extended_attention_mask.transpose(-1, -2)) UpperCAmelCase : int = ( tf.cast(1 , encoder_attention_mask.dtype ) - encoder_extended_attention_mask ) * encoder_extended_attention_mask.dtype.min return encoder_extended_attention_mask def __lowerCamelCase ( _lowercase , _lowercase , _lowercase = "input_ids" ) -> Union[str, Any]: tf.debugging.assert_less( SCREAMING_SNAKE_CASE__ , tf.cast(SCREAMING_SNAKE_CASE__ , dtype=tensor.dtype ) , message=( F'''The maximum value of {tensor_name} ({tf.math.reduce_max(SCREAMING_SNAKE_CASE__ )}) must be smaller than the embedding ''' F'''layer\'s input dimension ({embed_dim}). The likely cause is some problem at tokenization time.''' ) , ) def __lowerCamelCase ( _lowercase , _lowercase , _lowercase ) -> Tuple: UpperCAmelCase : Any = 6_4_5_1_2 # Check that no item in `data` is larger than `HDF5_OBJECT_HEADER_LIMIT` # because in that case even chunking the array would not make the saving # possible. UpperCAmelCase : Optional[int] = [x for x in data if len(SCREAMING_SNAKE_CASE__ ) > HDF5_OBJECT_HEADER_LIMIT] # Expecting this to never be true. if bad_attributes: raise RuntimeError( """The following attributes cannot be saved to HDF5 file because """ F'''they are larger than {HDF5_OBJECT_HEADER_LIMIT} ''' F'''bytes: {bad_attributes}''' ) UpperCAmelCase : str = np.asarray(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase : Union[str, Any] = 1 UpperCAmelCase : Optional[Any] = np.array_split(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # This will never loop forever thanks to the test above. while any(x.nbytes > HDF5_OBJECT_HEADER_LIMIT for x in chunked_data ): num_chunks += 1 UpperCAmelCase : Any = np.array_split(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if num_chunks > 1: for chunk_id, chunk_data in enumerate(SCREAMING_SNAKE_CASE__ ): UpperCAmelCase : List[Any] = chunk_data else: UpperCAmelCase : Union[str, Any] = data def __lowerCamelCase ( _lowercase , _lowercase ) -> Tuple: if name in group.attrs: UpperCAmelCase : Tuple = [n.decode("""utf8""" ) if hasattr(SCREAMING_SNAKE_CASE__ , """decode""" ) else n for n in group.attrs[name]] else: UpperCAmelCase : Tuple = [] UpperCAmelCase : Optional[Any] = 0 while "%s%d" % (name, chunk_id) in group.attrs: data.extend( [n.decode("""utf8""" ) if hasattr(SCREAMING_SNAKE_CASE__ , """decode""" ) else n for n in group.attrs["""%s%d""" % (name, chunk_id)]] ) chunk_id += 1 return data def __lowerCamelCase ( _lowercase ) -> Tuple: def _expand_single_ad_tensor(_lowercase ): if isinstance(SCREAMING_SNAKE_CASE__ , tf.Tensor ) and t.shape.rank == 1: return tf.expand_dims(SCREAMING_SNAKE_CASE__ , axis=-1 ) return t return tf.nest.map_structure(_expand_single_ad_tensor , SCREAMING_SNAKE_CASE__ )
704
'''simple docstring''' a : List[Any] = """Alexander Joslin""" import operator as op from .stack import Stack def __lowerCamelCase ( _lowercase ) -> int: UpperCAmelCase : Dict = {"""*""": op.mul, """/""": op.truediv, """+""": op.add, """-""": op.sub} UpperCAmelCase : Stack[int] = Stack() UpperCAmelCase : Stack[str] = Stack() for i in equation: if i.isdigit(): # RULE 1 operand_stack.push(int(_lowercase ) ) elif i in operators: # RULE 2 operator_stack.push(_lowercase ) elif i == ")": # RULE 4 UpperCAmelCase : List[Any] = operator_stack.peek() operator_stack.pop() UpperCAmelCase : str = operand_stack.peek() operand_stack.pop() UpperCAmelCase : str = operand_stack.peek() operand_stack.pop() UpperCAmelCase : List[Any] = operators[opr](_lowercase , _lowercase ) operand_stack.push(_lowercase ) # RULE 5 return operand_stack.peek() if __name__ == "__main__": a : Tuple = """(5 + ((4 * 2) * (2 + 3)))""" # answer = 45 print(F'''{equation} = {dijkstras_two_stack_algorithm(equation)}''')
672
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 GLPNImageProcessor class lowerCAmelCase_ ( unittest.TestCase ): def __init__( self : int , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Tuple=7 , SCREAMING_SNAKE_CASE_ : Any=3 , SCREAMING_SNAKE_CASE_ : List[str]=18 , SCREAMING_SNAKE_CASE_ : Optional[int]=30 , SCREAMING_SNAKE_CASE_ : Optional[Any]=400 , SCREAMING_SNAKE_CASE_ : Any=True , SCREAMING_SNAKE_CASE_ : Optional[Any]=32 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=True , ): lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = num_channels lowerCAmelCase__ = image_size lowerCAmelCase__ = min_resolution lowerCAmelCase__ = max_resolution lowerCAmelCase__ = do_resize lowerCAmelCase__ = size_divisor lowerCAmelCase__ = do_rescale def __snake_case ( self : Optional[Any] ): return { "do_resize": self.do_resize, "size_divisor": self.size_divisor, "do_rescale": self.do_rescale, } @require_torch @require_vision class lowerCAmelCase_ ( snake_case__ , unittest.TestCase ): UpperCamelCase_ :Union[str, Any] = GLPNImageProcessor if is_vision_available() else None def __snake_case ( self : str ): lowerCAmelCase__ = GLPNImageProcessingTester(self ) @property def __snake_case ( self : str ): return self.image_processor_tester.prepare_image_processor_dict() def __snake_case ( self : List[str] ): lowerCAmelCase__ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , '''do_resize''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , '''size_divisor''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , '''resample''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , '''do_rescale''' ) ) def __snake_case ( self : Tuple ): pass def __snake_case ( self : Optional[Any] ): # Initialize image_processing lowerCAmelCase__ = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowerCAmelCase__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE_ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE_ , Image.Image ) # Test not batched input (GLPNImageProcessor doesn't support batching) lowerCAmelCase__ = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 ) def __snake_case ( self : int ): # Initialize image_processing lowerCAmelCase__ = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowerCAmelCase__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE_ , numpify=SCREAMING_SNAKE_CASE_ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE_ , np.ndarray ) # Test not batched input (GLPNImageProcessor doesn't support batching) lowerCAmelCase__ = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 ) def __snake_case ( self : Optional[int] ): # Initialize image_processing lowerCAmelCase__ = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowerCAmelCase__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE_ , torchify=SCREAMING_SNAKE_CASE_ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE_ , torch.Tensor ) # Test not batched input (GLPNImageProcessor doesn't support batching) lowerCAmelCase__ = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 )
668
import os import tempfile import unittest from transformers import DistilBertConfig, is_torch_available from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, DistilBertModel, ) class lowerCAmelCase_ ( snake_case__ ): def __init__( self : Dict , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : Optional[Any]=13 , SCREAMING_SNAKE_CASE_ : Dict=7 , SCREAMING_SNAKE_CASE_ : List[Any]=True , SCREAMING_SNAKE_CASE_ : Dict=True , SCREAMING_SNAKE_CASE_ : Optional[int]=False , SCREAMING_SNAKE_CASE_ : Dict=True , SCREAMING_SNAKE_CASE_ : str=99 , SCREAMING_SNAKE_CASE_ : str=32 , SCREAMING_SNAKE_CASE_ : int=5 , SCREAMING_SNAKE_CASE_ : Tuple=4 , SCREAMING_SNAKE_CASE_ : Tuple=37 , SCREAMING_SNAKE_CASE_ : Tuple="gelu" , SCREAMING_SNAKE_CASE_ : Union[str, Any]=0.1 , SCREAMING_SNAKE_CASE_ : List[Any]=0.1 , SCREAMING_SNAKE_CASE_ : Dict=512 , SCREAMING_SNAKE_CASE_ : Any=16 , SCREAMING_SNAKE_CASE_ : List[Any]=2 , SCREAMING_SNAKE_CASE_ : Optional[Any]=0.02 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=3 , SCREAMING_SNAKE_CASE_ : Optional[Any]=4 , SCREAMING_SNAKE_CASE_ : int=None , ): lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = seq_length lowerCAmelCase__ = is_training lowerCAmelCase__ = use_input_mask lowerCAmelCase__ = use_token_type_ids lowerCAmelCase__ = use_labels lowerCAmelCase__ = vocab_size lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = max_position_embeddings lowerCAmelCase__ = type_vocab_size lowerCAmelCase__ = type_sequence_label_size lowerCAmelCase__ = initializer_range lowerCAmelCase__ = num_labels lowerCAmelCase__ = num_choices lowerCAmelCase__ = scope def __snake_case ( self : Union[str, Any] ): lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCAmelCase__ = None if self.use_input_mask: lowerCAmelCase__ = random_attention_mask([self.batch_size, self.seq_length] ) lowerCAmelCase__ = None lowerCAmelCase__ = None lowerCAmelCase__ = None if self.use_labels: lowerCAmelCase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) lowerCAmelCase__ = ids_tensor([self.batch_size] , self.num_choices ) lowerCAmelCase__ = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def __snake_case ( self : Tuple ): return DistilBertConfig( vocab_size=self.vocab_size , dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , hidden_dim=self.intermediate_size , hidden_act=self.hidden_act , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , ) def __snake_case ( self : Any , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Optional[int] ): lowerCAmelCase__ = DistilBertModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __snake_case ( self : int , SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : Optional[Any] ): lowerCAmelCase__ = DistilBertForMaskedLM(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __snake_case ( self : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Tuple ): lowerCAmelCase__ = DistilBertForQuestionAnswering(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() lowerCAmelCase__ = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __snake_case ( self : Optional[int] , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : int ): lowerCAmelCase__ = self.num_labels lowerCAmelCase__ = DistilBertForSequenceClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __snake_case ( self : int , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : List[str] ): lowerCAmelCase__ = self.num_labels lowerCAmelCase__ = DistilBertForTokenClassification(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __snake_case ( self : Optional[Any] , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : Optional[Any] ): lowerCAmelCase__ = self.num_choices lowerCAmelCase__ = DistilBertForMultipleChoice(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() lowerCAmelCase__ = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() lowerCAmelCase__ = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() lowerCAmelCase__ = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __snake_case ( self : Optional[int] ): lowerCAmelCase__ = self.prepare_config_and_inputs() ((lowerCAmelCase__) , (lowerCAmelCase__) , (lowerCAmelCase__) , (lowerCAmelCase__) , (lowerCAmelCase__) , (lowerCAmelCase__)) = config_and_inputs lowerCAmelCase__ = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class lowerCAmelCase_ ( snake_case__ , snake_case__ , unittest.TestCase ): UpperCamelCase_ :Any = ( ( DistilBertModel, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, ) if is_torch_available() else None ) UpperCamelCase_ :Union[str, Any] = ( { 'feature-extraction': DistilBertModel, 'fill-mask': DistilBertForMaskedLM, 'question-answering': DistilBertForQuestionAnswering, 'text-classification': DistilBertForSequenceClassification, 'token-classification': DistilBertForTokenClassification, 'zero-shot': DistilBertForSequenceClassification, } if is_torch_available() else {} ) UpperCamelCase_ :int = True UpperCamelCase_ :List[str] = True UpperCamelCase_ :List[Any] = True UpperCamelCase_ :Dict = True def __snake_case ( self : Dict ): lowerCAmelCase__ = DistilBertModelTester(self ) lowerCAmelCase__ = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , dim=37 ) def __snake_case ( self : List[Any] ): self.config_tester.run_common_tests() def __snake_case ( self : Dict ): lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_model(*SCREAMING_SNAKE_CASE_ ) def __snake_case ( self : Optional[Any] ): lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_masked_lm(*SCREAMING_SNAKE_CASE_ ) def __snake_case ( self : Dict ): lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_question_answering(*SCREAMING_SNAKE_CASE_ ) def __snake_case ( self : Union[str, Any] ): lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_sequence_classification(*SCREAMING_SNAKE_CASE_ ) def __snake_case ( self : int ): lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_token_classification(*SCREAMING_SNAKE_CASE_ ) def __snake_case ( self : Optional[Any] ): lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_multiple_choice(*SCREAMING_SNAKE_CASE_ ) @slow def __snake_case ( self : Tuple ): for model_name in DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCAmelCase__ = DistilBertModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) @slow @require_torch_gpu def __snake_case ( self : Any ): lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # BertForMultipleChoice behaves incorrectly in JIT environments. if model_class == DistilBertForMultipleChoice: return lowerCAmelCase__ = True lowerCAmelCase__ = model_class(config=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase__ = self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) lowerCAmelCase__ = torch.jit.trace( SCREAMING_SNAKE_CASE_ , (inputs_dict['''input_ids'''].to('''cpu''' ), inputs_dict['''attention_mask'''].to('''cpu''' )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(SCREAMING_SNAKE_CASE_ , os.path.join(SCREAMING_SNAKE_CASE_ , '''traced_model.pt''' ) ) lowerCAmelCase__ = torch.jit.load(os.path.join(SCREAMING_SNAKE_CASE_ , '''traced_model.pt''' ) , map_location=SCREAMING_SNAKE_CASE_ ) loaded(inputs_dict['''input_ids'''].to(SCREAMING_SNAKE_CASE_ ) , inputs_dict['''attention_mask'''].to(SCREAMING_SNAKE_CASE_ ) ) @require_torch class lowerCAmelCase_ ( unittest.TestCase ): @slow def __snake_case ( self : str ): lowerCAmelCase__ = DistilBertModel.from_pretrained('''distilbert-base-uncased''' ) lowerCAmelCase__ = torch.tensor([[0, 345, 232, 328, 740, 140, 1_695, 69, 6_078, 1_588, 2]] ) lowerCAmelCase__ = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ )[0] lowerCAmelCase__ = torch.Size((1, 11, 768) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE_ ) lowerCAmelCase__ = torch.tensor( [[[-0.1_639, 0.3_299, 0.1_648], [-0.1_746, 0.3_289, 0.1_710], [-0.1_884, 0.3_357, 0.1_810]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) )
668
1
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCAmelCase_ : Any = logging.get_logger(__name__) lowerCAmelCase_ : Optional[Any] = { """junnyu/roformer_chinese_small""": """https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/config.json""", """junnyu/roformer_chinese_base""": """https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/config.json""", """junnyu/roformer_chinese_char_small""": ( """https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/config.json""" ), """junnyu/roformer_chinese_char_base""": ( """https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/config.json""" ), """junnyu/roformer_small_discriminator""": ( """https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/config.json""" ), """junnyu/roformer_small_generator""": ( """https://huggingface.co/junnyu/roformer_small_generator/resolve/main/config.json""" ), # See all RoFormer models at https://huggingface.co/models?filter=roformer } class SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' UpperCAmelCase__ = '''roformer''' def __init__( self : List[Any] , lowercase__ : Tuple=50_000 , lowercase__ : List[str]=None , lowercase__ : int=768 , lowercase__ : List[str]=12 , lowercase__ : Optional[Any]=12 , lowercase__ : Union[str, Any]=3_072 , lowercase__ : Optional[int]="gelu" , lowercase__ : Dict=0.1 , lowercase__ : List[str]=0.1 , lowercase__ : Any=1_536 , lowercase__ : Optional[Any]=2 , lowercase__ : List[Any]=0.0_2 , lowercase__ : Dict=1e-12 , lowercase__ : Union[str, Any]=0 , lowercase__ : List[str]=False , lowercase__ : str=True , **lowercase__ : Optional[Any] , ) ->Dict: '''simple docstring''' super().__init__(pad_token_id=_a , **_a ) _UpperCamelCase : Optional[int] = vocab_size _UpperCamelCase : str = hidden_size if embedding_size is None else embedding_size _UpperCamelCase : int = hidden_size _UpperCamelCase : Any = num_hidden_layers _UpperCamelCase : Tuple = num_attention_heads _UpperCamelCase : List[str] = hidden_act _UpperCamelCase : str = intermediate_size _UpperCamelCase : Union[str, Any] = hidden_dropout_prob _UpperCamelCase : Any = attention_probs_dropout_prob _UpperCamelCase : Union[str, Any] = max_position_embeddings _UpperCamelCase : List[str] = type_vocab_size _UpperCamelCase : List[str] = initializer_range _UpperCamelCase : List[str] = layer_norm_eps _UpperCamelCase : Optional[Any] = rotary_value _UpperCamelCase : Union[str, Any] = use_cache class SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' @property def snake_case__ ( self : Any ) ->Optional[Any]: '''simple docstring''' if self.task == "multiple-choice": _UpperCamelCase : Tuple = {0: """batch""", 1: """choice""", 2: """sequence"""} else: _UpperCamelCase : int = {0: """batch""", 1: """sequence"""} _UpperCamelCase : Union[str, Any] = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ("token_type_ids", dynamic_axis), ] )
705
'''simple docstring''' import math import os from copy import deepcopy import datasets import evaluate import torch import transformers from datasets import load_dataset from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer from accelerate import Accelerator from accelerate.test_utils import RegressionDataset, RegressionModel from accelerate.utils import is_tpu_available, set_seed lowerCAmelCase_ : Tuple = """true""" def __A ( UpperCAmelCase ,UpperCAmelCase=8_2 ,UpperCAmelCase=1_6 ) -> Union[str, Any]: '''simple docstring''' set_seed(4_2 ) _UpperCamelCase : List[Any] = RegressionModel() _UpperCamelCase : Any = deepcopy(UpperCAmelCase ) _UpperCamelCase : Tuple = RegressionDataset(length=UpperCAmelCase ) _UpperCamelCase : Union[str, Any] = DataLoader(UpperCAmelCase ,batch_size=UpperCAmelCase ) model.to(accelerator.device ) _UpperCamelCase , _UpperCamelCase : Dict = accelerator.prepare(UpperCAmelCase ,UpperCAmelCase ) return model, ddp_model, dataloader def __A ( UpperCAmelCase ,UpperCAmelCase=False ) -> List[str]: '''simple docstring''' _UpperCamelCase : str = AutoTokenizer.from_pretrained("hf-internal-testing/mrpc-bert-base-cased" ) _UpperCamelCase : Optional[Any] = load_dataset("glue" ,"mrpc" ,split="validation" ) def tokenize_function(UpperCAmelCase ): _UpperCamelCase : Tuple = tokenizer(examples["sentence1"] ,examples["sentence2"] ,truncation=UpperCAmelCase ,max_length=UpperCAmelCase ) return outputs with accelerator.main_process_first(): _UpperCamelCase : str = dataset.map( UpperCAmelCase ,batched=UpperCAmelCase ,remove_columns=["idx", "sentence1", "sentence2"] ,) _UpperCamelCase : Optional[int] = tokenized_datasets.rename_column("label" ,"labels" ) def collate_fn(UpperCAmelCase ): if use_longest: return tokenizer.pad(UpperCAmelCase ,padding="longest" ,return_tensors="pt" ) return tokenizer.pad(UpperCAmelCase ,padding="max_length" ,max_length=1_2_8 ,return_tensors="pt" ) return DataLoader(UpperCAmelCase ,shuffle=UpperCAmelCase ,collate_fn=UpperCAmelCase ,batch_size=1_6 ) def __A ( UpperCAmelCase ,UpperCAmelCase ) -> Dict: '''simple docstring''' _UpperCamelCase : str = Accelerator(dispatch_batches=UpperCAmelCase ,split_batches=UpperCAmelCase ) _UpperCamelCase : Union[str, Any] = get_dataloader(UpperCAmelCase ,not dispatch_batches ) _UpperCamelCase : Optional[int] = AutoModelForSequenceClassification.from_pretrained( "hf-internal-testing/mrpc-bert-base-cased" ,return_dict=UpperCAmelCase ) _UpperCamelCase , _UpperCamelCase : Union[str, Any] = accelerator.prepare(UpperCAmelCase ,UpperCAmelCase ) return {"ddp": [ddp_model, ddp_dataloader, "cuda:0"], "no": [model, dataloader, accelerator.device]}, accelerator def __A ( UpperCAmelCase ,UpperCAmelCase ,UpperCAmelCase ) -> int: '''simple docstring''' _UpperCamelCase : List[str] = [] for batch in dataloader: _UpperCamelCase , _UpperCamelCase : int = batch.values() with torch.no_grad(): _UpperCamelCase : Tuple = model(UpperCAmelCase ) _UpperCamelCase , _UpperCamelCase : List[Any] = accelerator.gather_for_metrics((logit, target) ) logits_and_targets.append((logit, target) ) _UpperCamelCase , _UpperCamelCase : Optional[Any] = [], [] for logit, targ in logits_and_targets: logits.append(UpperCAmelCase ) targs.append(UpperCAmelCase ) _UpperCamelCase , _UpperCamelCase : int = torch.cat(UpperCAmelCase ), torch.cat(UpperCAmelCase ) return logits, targs def __A ( UpperCAmelCase ,UpperCAmelCase=8_2 ,UpperCAmelCase=False ,UpperCAmelCase=False ,UpperCAmelCase=1_6 ) -> Any: '''simple docstring''' _UpperCamelCase , _UpperCamelCase , _UpperCamelCase : Union[str, Any] = get_basic_setup(UpperCAmelCase ,UpperCAmelCase ,UpperCAmelCase ) _UpperCamelCase , _UpperCamelCase : Tuple = generate_predictions(UpperCAmelCase ,UpperCAmelCase ,UpperCAmelCase ) assert ( len(UpperCAmelCase ) == num_samples ), f'''Unexpected number of inputs:\n Expected: {num_samples}\n Actual: {len(UpperCAmelCase )}''' def __A ( UpperCAmelCase = False ,UpperCAmelCase = False ) -> Tuple: '''simple docstring''' _UpperCamelCase : int = evaluate.load("glue" ,"mrpc" ) _UpperCamelCase , _UpperCamelCase : Any = get_mrpc_setup(UpperCAmelCase ,UpperCAmelCase ) # First do baseline _UpperCamelCase , _UpperCamelCase , _UpperCamelCase : Tuple = setup["no"] model.to(UpperCAmelCase ) model.eval() for batch in dataloader: batch.to(UpperCAmelCase ) with torch.inference_mode(): _UpperCamelCase : Optional[Any] = model(**UpperCAmelCase ) _UpperCamelCase : Any = outputs.logits.argmax(dim=-1 ) metric.add_batch(predictions=UpperCAmelCase ,references=batch["labels"] ) _UpperCamelCase : List[str] = metric.compute() # Then do distributed _UpperCamelCase , _UpperCamelCase , _UpperCamelCase : List[Any] = setup["ddp"] model.eval() for batch in dataloader: with torch.inference_mode(): _UpperCamelCase : int = model(**UpperCAmelCase ) _UpperCamelCase : Tuple = outputs.logits.argmax(dim=-1 ) _UpperCamelCase : List[str] = batch["labels"] _UpperCamelCase , _UpperCamelCase : List[str] = accelerator.gather_for_metrics((preds, references) ) metric.add_batch(predictions=UpperCAmelCase ,references=UpperCAmelCase ) _UpperCamelCase : int = metric.compute() for key in "accuracy f1".split(): assert math.isclose( baseline[key] ,distributed[key] ), f'''Baseline and Distributed are not the same for key {key}:\n\tBaseline: {baseline[key]}\n\tDistributed: {distributed[key]}\n''' def __A ( ) -> Union[str, Any]: '''simple docstring''' _UpperCamelCase : Dict = Accelerator(split_batches=UpperCAmelCase ,dispatch_batches=UpperCAmelCase ) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_warning() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # These are a bit slower so they should only be ran on the GPU or TPU if torch.cuda.is_available() or is_tpu_available(): if accelerator.is_local_main_process: print("**Testing gather_for_metrics**" ) for split_batches in [True, False]: for dispatch_batches in [True, False]: if accelerator.is_local_main_process: print(f'''With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`''' ) test_mrpc(UpperCAmelCase ,UpperCAmelCase ) accelerator.state._reset_state() if accelerator.is_local_main_process: print("**Test torch metrics**" ) for split_batches in [True, False]: for dispatch_batches in [True, False]: _UpperCamelCase : int = Accelerator(split_batches=UpperCAmelCase ,dispatch_batches=UpperCAmelCase ) if accelerator.is_local_main_process: print(f'''With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`, length=99''' ) test_torch_metrics(UpperCAmelCase ,9_9 ) accelerator.state._reset_state() if accelerator.is_local_main_process: print("**Test last batch is not dropped when perfectly divisible**" ) _UpperCamelCase : int = Accelerator() test_torch_metrics(UpperCAmelCase ,5_1_2 ) accelerator.state._reset_state() def __A ( UpperCAmelCase ) -> List[str]: '''simple docstring''' # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
204
0
"""simple docstring""" import argparse from pathlib import Path import fairseq import torch from fairseq.models.xmod import XMODModel as FairseqXmodModel from packaging import version from transformers import XmodConfig, XmodForMaskedLM, XmodForSequenceClassification from transformers.utils import logging if version.parse(fairseq.__version__) < version.parse("""0.12.2"""): raise Exception("""requires fairseq >= 0.12.2""") if version.parse(fairseq.__version__) > version.parse("""2"""): raise Exception("""requires fairseq < v2""") logging.set_verbosity_info() _A : Optional[Any] = logging.get_logger(__name__) _A : Union[str, Any] = """Hello, World!""" _A : List[str] = """en_XX""" def __magic_name__ ( __snake_case : Any , __snake_case : str , __snake_case : Dict ) -> Optional[Any]: lowercase : Dict = Path("data_bin" ) lowercase : Tuple = FairseqXmodModel.from_pretrained( model_name_or_path=str(Path(__snake_case ).parent ) , checkpoint_file=Path(__snake_case ).name , _name="xmod_base" , arch="xmod_base" , task="multilingual_masked_lm" , data_name_or_path=str(__snake_case ) , bpe="sentencepiece" , sentencepiece_model=str(Path(__snake_case ).parent / "sentencepiece.bpe.model" ) , src_dict=str(data_dir / "dict.txt" ) , ) xmod.eval() # disable dropout print(__snake_case ) lowercase : int = xmod.model.encoder.sentence_encoder lowercase : int = XmodConfig( vocab_size=xmod_sent_encoder.embed_tokens.num_embeddings , hidden_size=xmod.cfg.model.encoder_embed_dim , num_hidden_layers=xmod.cfg.model.encoder_layers , num_attention_heads=xmod.cfg.model.encoder_attention_heads , intermediate_size=xmod.cfg.model.encoder_ffn_embed_dim , max_position_embeddings=514 , type_vocab_size=1 , layer_norm_eps=1E-5 , pre_norm=xmod.cfg.model.encoder_normalize_before , adapter_reduction_factor=getattr(xmod.cfg.model , "bottleneck" , 2 ) , adapter_layer_norm=xmod.cfg.model.adapter_layer_norm , adapter_reuse_layer_norm=xmod.cfg.model.adapter_reuse_layer_norm , ln_before_adapter=xmod.cfg.model.ln_before_adapter , languages=xmod.cfg.model.languages , ) if classification_head: lowercase : int = xmod.model.classification_heads["""mnli"""].out_proj.weight.shape[0] print("Our X-MOD config:" , __snake_case ) lowercase : str = XmodForSequenceClassification(__snake_case ) if classification_head else XmodForMaskedLM(__snake_case ) model.eval() # Now let's copy all the weights. # Embeddings lowercase : List[Any] = xmod_sent_encoder.embed_tokens.weight lowercase : Tuple = xmod_sent_encoder.embed_positions.weight lowercase : Tuple = torch.zeros_like( model.roberta.embeddings.token_type_embeddings.weight ) # just zero them out b/c xmod doesn't use them. lowercase : Optional[Any] = xmod_sent_encoder.layernorm_embedding.weight lowercase : Optional[Any] = xmod_sent_encoder.layernorm_embedding.bias for i in range(config.num_hidden_layers ): # Encoder: start of layer lowercase : List[str] = model.roberta.encoder.layer[i] lowercase : Any = xmod_sent_encoder.layers[i] # self attention lowercase : Union[str, Any] = layer.attention.self if not ( xmod_layer.self_attn.k_proj.weight.data.shape == xmod_layer.self_attn.q_proj.weight.data.shape == xmod_layer.self_attn.v_proj.weight.data.shape == torch.Size((config.hidden_size, config.hidden_size) ) ): raise AssertionError("Dimensions of self-attention weights do not match." ) lowercase : Any = xmod_layer.self_attn.q_proj.weight lowercase : List[str] = xmod_layer.self_attn.q_proj.bias lowercase : Union[str, Any] = xmod_layer.self_attn.k_proj.weight lowercase : Optional[Any] = xmod_layer.self_attn.k_proj.bias lowercase : Optional[int] = xmod_layer.self_attn.v_proj.weight lowercase : int = xmod_layer.self_attn.v_proj.bias # self-attention output lowercase : Tuple = layer.attention.output if self_output.dense.weight.shape != xmod_layer.self_attn.out_proj.weight.shape: raise AssertionError("Dimensions of self-attention output weights do not match." ) lowercase : Tuple = xmod_layer.self_attn.out_proj.weight lowercase : List[Any] = xmod_layer.self_attn.out_proj.bias lowercase : int = xmod_layer.self_attn_layer_norm.weight lowercase : Tuple = xmod_layer.self_attn_layer_norm.bias # intermediate lowercase : List[Any] = layer.intermediate if intermediate.dense.weight.shape != xmod_layer.fca.weight.shape: raise AssertionError("Dimensions of intermediate weights do not match." ) lowercase : Tuple = xmod_layer.fca.weight lowercase : Optional[Any] = xmod_layer.fca.bias # output lowercase : str = layer.output if bert_output.dense.weight.shape != xmod_layer.fca.weight.shape: raise AssertionError("Dimensions of feed-forward weights do not match." ) lowercase : str = xmod_layer.fca.weight lowercase : int = xmod_layer.fca.bias lowercase : Optional[Any] = xmod_layer.final_layer_norm.weight lowercase : Tuple = xmod_layer.final_layer_norm.bias if bert_output.adapter_layer_norm is not None: lowercase : Tuple = xmod_layer.adapter_layer_norm.weight lowercase : Any = xmod_layer.adapter_layer_norm.bias if sorted(bert_output.adapter_modules.keys() ) != sorted(xmod_layer.adapter_modules.keys() ): raise AssertionError("Lists of language adapters do not match." ) for lang_code, adapter in xmod_layer.adapter_modules.items(): lowercase : List[str] = bert_output.adapter_modules[lang_code] lowercase : Dict = xmod_layer.adapter_modules[lang_code] lowercase : List[Any] = from_adapter.fca.weight lowercase : Union[str, Any] = from_adapter.fca.bias lowercase : str = from_adapter.fca.weight lowercase : Tuple = from_adapter.fca.bias # end of layer if xmod_sent_encoder.layer_norm is not None: lowercase : int = xmod_sent_encoder.layer_norm.weight lowercase : Optional[Any] = xmod_sent_encoder.layer_norm.bias if classification_head: lowercase : List[Any] = xmod.model.classification_heads["""mnli"""].dense.weight lowercase : Dict = xmod.model.classification_heads["""mnli"""].dense.bias lowercase : Union[str, Any] = xmod.model.classification_heads["""mnli"""].out_proj.weight lowercase : Optional[int] = xmod.model.classification_heads["""mnli"""].out_proj.bias else: # LM Head lowercase : List[str] = xmod.model.encoder.lm_head.dense.weight lowercase : Optional[Any] = xmod.model.encoder.lm_head.dense.bias lowercase : Any = xmod.model.encoder.lm_head.layer_norm.weight lowercase : List[str] = xmod.model.encoder.lm_head.layer_norm.bias lowercase : Union[str, Any] = xmod.model.encoder.lm_head.weight lowercase : Union[str, Any] = xmod.model.encoder.lm_head.bias # Let's check that we get the same results. lowercase : Any = xmod.encode(__snake_case ).unsqueeze(0 ) # batch of size 1 model.roberta.set_default_language(__snake_case ) lowercase : Optional[Any] = model(__snake_case )[0] if classification_head: lowercase : List[Any] = xmod.model.classification_heads["""mnli"""](xmod.extract_features(__snake_case ) ) else: lowercase : str = xmod.model(__snake_case , lang_id=[SAMPLE_LANGUAGE] )[0] print(our_output.shape , their_output.shape ) lowercase : Dict = torch.max(torch.abs(our_output - their_output ) ).item() print(f"""max_absolute_diff = {max_absolute_diff}""" ) # ~ 1e-7 lowercase : Any = torch.allclose(__snake_case , __snake_case , atol=1E-3 ) print("Do both models output the same tensors?" , "🔥" if success else "💩" ) if not success: raise Exception("Something went wRoNg" ) Path(__snake_case ).mkdir(parents=__snake_case , exist_ok=__snake_case ) print(f"""Saving model to {pytorch_dump_folder_path}""" ) model.save_pretrained(__snake_case ) if __name__ == "__main__": _A : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--xmod_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.""" ) parser.add_argument( """--classification_head""", action="""store_true""", help="""Whether to convert a final classification head.""" ) _A : Union[str, Any] = parser.parse_args() convert_xmod_checkpoint_to_pytorch( args.xmod_checkpoint_path, args.pytorch_dump_folder_path, args.classification_head )
361
"""simple docstring""" def A_ ( lowercase , lowercase ) -> int: """simple docstring""" return number | (1 << position) def A_ ( lowercase , lowercase ) -> int: """simple docstring""" return number & ~(1 << position) def A_ ( lowercase , lowercase ) -> int: """simple docstring""" return number ^ (1 << position) def A_ ( lowercase , lowercase ) -> bool: """simple docstring""" return ((number >> position) & 1) == 1 def A_ ( lowercase , lowercase ) -> int: """simple docstring""" return int((number & (1 << position)) != 0 ) if __name__ == "__main__": import doctest doctest.testmod()
470
0
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase_ = logging.get_logger(__name__) lowerCamelCase_ = { '''s-JoL/Open-Llama-V1''': '''https://huggingface.co/s-JoL/Open-Llama-V1/blob/main/config.json''', } class __A( __lowerCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = """open-llama""" def __init__(self , SCREAMING_SNAKE_CASE_=10_00_00 , SCREAMING_SNAKE_CASE_=40_96 , SCREAMING_SNAKE_CASE_=1_10_08 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_="silu" , SCREAMING_SNAKE_CASE_=20_48 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=1E-6 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ , ): UpperCamelCase__ = vocab_size UpperCamelCase__ = max_position_embeddings UpperCamelCase__ = hidden_size UpperCamelCase__ = intermediate_size UpperCamelCase__ = num_hidden_layers UpperCamelCase__ = num_attention_heads UpperCamelCase__ = hidden_act UpperCamelCase__ = initializer_range UpperCamelCase__ = rms_norm_eps UpperCamelCase__ = use_cache UpperCamelCase__ = kwargs.pop( """use_memorry_efficient_attention""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = hidden_dropout_prob UpperCamelCase__ = attention_dropout_prob UpperCamelCase__ = use_stable_embedding UpperCamelCase__ = shared_input_output_embedding UpperCamelCase__ = rope_scaling self._rope_scaling_validation() super().__init__( pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , tie_word_embeddings=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) def UpperCAmelCase_ (self ): if self.rope_scaling is None: return if not isinstance(self.rope_scaling , SCREAMING_SNAKE_CASE_ ) or len(self.rope_scaling ) != 2: raise ValueError( """`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, """ F"got {self.rope_scaling}" ) UpperCamelCase__ = self.rope_scaling.get("""type""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = self.rope_scaling.get("""factor""" , SCREAMING_SNAKE_CASE_ ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( F"`rope_scaling`'s name field must be one of ['linear', 'dynamic'], got {rope_scaling_type}" ) if rope_scaling_factor is None or not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) or rope_scaling_factor <= 1.0: raise ValueError(F"`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_factor}" )
86
import argparse import hashlib import os import urllib import warnings import torch from torch import nn from tqdm import tqdm from transformers import WhisperConfig, WhisperForConditionalGeneration lowerCamelCase_ = { '''tiny.en''': '''https://openaipublic.azureedge.net/main/whisper/models/d3dd57d32accea0b295c96e26691aa14d8822fac7d9d27d5dc00b4ca2826dd03/tiny.en.pt''', '''tiny''': '''https://openaipublic.azureedge.net/main/whisper/models/65147644a518d12f04e32d6f3b26facc3f8dd46e5390956a9424a650c0ce22b9/tiny.pt''', '''base.en''': '''https://openaipublic.azureedge.net/main/whisper/models/25a8566e1d0c1e2231d1c762132cd20e0f96a85d16145c3a00adf5d1ac670ead/base.en.pt''', '''base''': '''https://openaipublic.azureedge.net/main/whisper/models/ed3a0b6b1c0edf879ad9b11b1af5a0e6ab5db9205f891f668f8b0e6c6326e34e/base.pt''', '''small.en''': '''https://openaipublic.azureedge.net/main/whisper/models/f953ad0fd29cacd07d5a9eda5624af0f6bcf2258be67c92b79389873d91e0872/small.en.pt''', '''small''': '''https://openaipublic.azureedge.net/main/whisper/models/9ecf779972d90ba49c06d968637d720dd632c55bbf19d441fb42bf17a411e794/small.pt''', '''medium.en''': '''https://openaipublic.azureedge.net/main/whisper/models/d7440d1dc186f76616474e0ff0b3b6b879abc9d1a4926b7adfa41db2d497ab4f/medium.en.pt''', '''medium''': '''https://openaipublic.azureedge.net/main/whisper/models/345ae4da62f9b3d59415adc60127b97c714f32e89e936602e85993674d08dcb1/medium.pt''', '''large''': '''https://openaipublic.azureedge.net/main/whisper/models/e4b87e7e0bf463eb8e6956e646f1e277e901512310def2c24bf0e11bd3c28e9a/large.pt''', '''large-v2''': '''https://openaipublic.azureedge.net/main/whisper/models/81f7c96c852ee8fc832187b0132e569d6c3065a3252ed18e56effd0b6a73e524/large-v2.pt''', } def __magic_name__ ( __a : List[str] ): '''simple docstring''' UpperCamelCase__ = ["""layers""", """blocks"""] for k in ignore_keys: state_dict.pop(__a , __a ) lowerCamelCase_ = { '''blocks''': '''layers''', '''mlp.0''': '''fc1''', '''mlp.2''': '''fc2''', '''mlp_ln''': '''final_layer_norm''', '''.attn.query''': '''.self_attn.q_proj''', '''.attn.key''': '''.self_attn.k_proj''', '''.attn.value''': '''.self_attn.v_proj''', '''.attn_ln''': '''.self_attn_layer_norm''', '''.attn.out''': '''.self_attn.out_proj''', '''.cross_attn.query''': '''.encoder_attn.q_proj''', '''.cross_attn.key''': '''.encoder_attn.k_proj''', '''.cross_attn.value''': '''.encoder_attn.v_proj''', '''.cross_attn_ln''': '''.encoder_attn_layer_norm''', '''.cross_attn.out''': '''.encoder_attn.out_proj''', '''decoder.ln.''': '''decoder.layer_norm.''', '''encoder.ln.''': '''encoder.layer_norm.''', '''token_embedding''': '''embed_tokens''', '''encoder.positional_embedding''': '''encoder.embed_positions.weight''', '''decoder.positional_embedding''': '''decoder.embed_positions.weight''', '''ln_post''': '''layer_norm''', } def __magic_name__ ( __a : Dict ): '''simple docstring''' UpperCamelCase__ = list(s_dict.keys() ) for key in keys: UpperCamelCase__ = key for k, v in WHISPER_MAPPING.items(): if k in key: UpperCamelCase__ = new_key.replace(__a , __a ) print(f"{key} -> {new_key}" ) UpperCamelCase__ = s_dict.pop(__a ) return s_dict def __magic_name__ ( __a : Optional[Any] ): '''simple docstring''' UpperCamelCase__ , UpperCamelCase__ = emb.weight.shape UpperCamelCase__ = nn.Linear(__a , __a , bias=__a ) UpperCamelCase__ = emb.weight.data return lin_layer def __magic_name__ ( __a : str , __a : str ): '''simple docstring''' os.makedirs(__a , exist_ok=__a ) UpperCamelCase__ = os.path.basename(__a ) UpperCamelCase__ = url.split("""/""" )[-2] UpperCamelCase__ = os.path.join(__a , __a ) if os.path.exists(__a ) and not os.path.isfile(__a ): raise RuntimeError(f"{download_target} exists and is not a regular file" ) if os.path.isfile(__a ): UpperCamelCase__ = open(__a , """rb""" ).read() if hashlib.shaaaa(__a ).hexdigest() == expected_shaaaa: return model_bytes else: warnings.warn(f"{download_target} exists, but the SHA256 checksum does not match; re-downloading the file" ) with urllib.request.urlopen(__a ) as source, open(__a , """wb""" ) as output: with tqdm( total=int(source.info().get("""Content-Length""" ) ) , ncols=80 , unit="""iB""" , unit_scale=__a , unit_divisor=1_024 ) as loop: while True: UpperCamelCase__ = source.read(8_192 ) if not buffer: break output.write(__a ) loop.update(len(__a ) ) UpperCamelCase__ = open(__a , """rb""" ).read() if hashlib.shaaaa(__a ).hexdigest() != expected_shaaaa: raise RuntimeError( """Model has been downloaded but the SHA256 checksum does not not match. Please retry loading the model.""" ) return model_bytes def __magic_name__ ( __a : Union[str, Any] , __a : Optional[int] ): '''simple docstring''' if ".pt" not in checkpoint_path: UpperCamelCase__ = _download(_MODELS[checkpoint_path] ) else: UpperCamelCase__ = torch.load(__a , map_location="""cpu""" ) UpperCamelCase__ = original_checkpoint["""dims"""] UpperCamelCase__ = original_checkpoint["""model_state_dict"""] UpperCamelCase__ = state_dict["""decoder.token_embedding.weight"""] remove_ignore_keys_(__a ) rename_keys(__a ) UpperCamelCase__ = True UpperCamelCase__ = state_dict["""decoder.layers.0.fc1.weight"""].shape[0] UpperCamelCase__ = WhisperConfig( vocab_size=dimensions["""n_vocab"""] , encoder_ffn_dim=__a , decoder_ffn_dim=__a , num_mel_bins=dimensions["""n_mels"""] , d_model=dimensions["""n_audio_state"""] , max_target_positions=dimensions["""n_text_ctx"""] , encoder_layers=dimensions["""n_audio_layer"""] , encoder_attention_heads=dimensions["""n_audio_head"""] , decoder_layers=dimensions["""n_text_layer"""] , decoder_attention_heads=dimensions["""n_text_state"""] , max_source_positions=dimensions["""n_audio_ctx"""] , ) UpperCamelCase__ = WhisperForConditionalGeneration(__a ) UpperCamelCase__ , UpperCamelCase__ = model.model.load_state_dict(__a , strict=__a ) if len(__a ) > 0 and not set(__a ) <= { "encoder.embed_positions.weights", "decoder.embed_positions.weights", }: raise ValueError( """Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights` are allowed to be missing,""" f" but all the following weights are missing {missing}" ) if tie_embeds: UpperCamelCase__ = make_linear_from_emb(model.model.decoder.embed_tokens ) else: UpperCamelCase__ = proj_out_weights model.save_pretrained(__a ) if __name__ == "__main__": lowerCamelCase_ = argparse.ArgumentParser() # # Required parameters parser.add_argument('''--checkpoint_path''', type=str, help='''Patht to the downloaded checkpoints''') parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') lowerCamelCase_ = parser.parse_args() convert_openai_whisper_to_tfms(args.checkpoint_path, args.pytorch_dump_folder_path)
86
1
'''simple docstring''' import copy from typing import TYPE_CHECKING, Any, Mapping, Optional, OrderedDict from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto.configuration_auto import AutoConfig if TYPE_CHECKING: from ... import PreTrainedTokenizerBase, TensorType __magic_name__ : Tuple = logging.get_logger(__name__) class UpperCamelCase__ ( lowerCamelCase__ ): """simple docstring""" UpperCAmelCase__ = 'vision-encoder-decoder' UpperCAmelCase__ = True def __init__( self : str , **__A : List[str] ): """simple docstring""" super().__init__(**__A ) if "encoder" not in kwargs or "decoder" not in kwargs: raise ValueError( f"""A configuraton of type {self.model_type} cannot be instantiated because """ f"""not both `encoder` and `decoder` sub-configurations are passed, but only {kwargs}""" ) _lowercase = kwargs.pop("encoder" ) _lowercase = encoder_config.pop("model_type" ) _lowercase = kwargs.pop("decoder" ) _lowercase = decoder_config.pop("model_type" ) _lowercase = AutoConfig.for_model(__A , **__A ) _lowercase = AutoConfig.for_model(__A , **__A ) _lowercase = True @classmethod def snake_case ( cls : Tuple , __A : PretrainedConfig , __A : PretrainedConfig , **__A : List[Any] ): """simple docstring""" logger.info("Setting `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config" ) _lowercase = True _lowercase = True return cls(encoder=encoder_config.to_dict() , decoder=decoder_config.to_dict() , **__A ) def snake_case ( self : Optional[Any] ): """simple docstring""" _lowercase = copy.deepcopy(self.__dict__ ) _lowercase = self.encoder.to_dict() _lowercase = self.decoder.to_dict() _lowercase = self.__class__.model_type return output class UpperCamelCase__ ( lowerCamelCase__ ): """simple docstring""" UpperCAmelCase__ = version.parse('1.11' ) @property def snake_case ( self : List[str] ): """simple docstring""" return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ] ) @property def snake_case ( self : str ): """simple docstring""" return 1e-4 @property def snake_case ( self : Union[str, Any] ): """simple docstring""" return OrderedDict({"last_hidden_state": {0: "batch", 1: "encoder_sequence"}} ) class UpperCamelCase__ ( lowerCamelCase__ ): """simple docstring""" @property def snake_case ( self : int ): """simple docstring""" _lowercase = OrderedDict() _lowercase = {0: "batch", 1: "past_decoder_sequence + sequence"} _lowercase = {0: "batch", 1: "past_decoder_sequence + sequence"} _lowercase = {0: "batch", 1: "encoder_sequence"} return common_inputs def snake_case ( self : Any , __A : "PreTrainedTokenizerBase" , __A : int = -1 , __A : int = -1 , __A : bool = False , __A : Optional["TensorType"] = None , ): """simple docstring""" import torch _lowercase = OrderedDict() _lowercase = super().generate_dummy_inputs( __A , batch_size=__A , seq_length=__A , is_pair=__A , framework=__A ) _lowercase , _lowercase = dummy_input["input_ids"].shape _lowercase = (batch, encoder_sequence, self._config.encoder_hidden_size) _lowercase = dummy_input.pop("input_ids" ) _lowercase = dummy_input.pop("attention_mask" ) _lowercase = torch.zeros(__A ) return common_inputs class UpperCamelCase__ ( lowerCamelCase__ ): """simple docstring""" @property def snake_case ( self : Optional[int] ): """simple docstring""" pass def snake_case ( self : Dict , __A : PretrainedConfig ): """simple docstring""" return VisionEncoderDecoderEncoderOnnxConfig(__A ) def snake_case ( self : Optional[Any] , __A : PretrainedConfig , __A : PretrainedConfig , __A : str = "default" ): """simple docstring""" _lowercase = encoder_config.hidden_size return VisionEncoderDecoderDecoderOnnxConfig(__A , __A )
497
'''simple docstring''' from __future__ import annotations def A__ ( A_ , A_ ) -> list[str]: if nth_term == "": return [""] _lowercase = int(A_ ) _lowercase = int(A_ ) _lowercase = [] for temp in range(int(A_ ) ): series.append(F"""1 / {pow(temp + 1 , int(A_ ) )}""" if series else "1" ) return series if __name__ == "__main__": import doctest doctest.testmod() __magic_name__ : Any = int(input('''Enter the last number (nth term) of the P-Series''')) __magic_name__ : Dict = int(input('''Enter the power for P-Series''')) print('''Formula of P-Series => 1+1/2^p+1/3^p ..... 1/n^p''') print(p_series(nth_term, power))
497
1
"""simple docstring""" import math class _A : """simple docstring""" def __snake_case ( self : Optional[int] , __UpperCAmelCase : list[list[float]] , __UpperCAmelCase : list[int]): a : int = 0.0 a : List[Any] = 0.0 for i in range(len(__UpperCAmelCase)): da += math.pow((sample[i] - weights[0][i]) , 2) da += math.pow((sample[i] - weights[1][i]) , 2) return 0 if da > da else 1 return 0 def __snake_case ( self : Any , __UpperCAmelCase : list[list[int | float]] , __UpperCAmelCase : list[int] , __UpperCAmelCase : int , __UpperCAmelCase : float): for i in range(len(__UpperCAmelCase)): weights[j][i] += alpha * (sample[i] - weights[j][i]) return weights def lowercase ( )-> None: '''simple docstring''' a : Optional[int] = [[1, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 0, 1, 1]] # weight initialization ( n, C ) a : Optional[Any] = [[0.2, 0.6, 0.5, 0.9], [0.8, 0.4, 0.7, 0.3]] # training a : Tuple = SelfOrganizingMap() a : Optional[Any] = 3 a : Tuple = 0.5 for _ in range(A_ ): for j in range(len(A_ ) ): # training sample a : List[Any] = training_samples[j] # Compute the winning vector a : Tuple = self_organizing_map.get_winner(A_ , A_ ) # Update the winning vector a : List[Any] = self_organizing_map.update(A_ , A_ , A_ , A_ ) # classify test sample a : Dict = [0, 0, 0, 1] a : Union[str, Any] = self_organizing_map.get_winner(A_ , A_ ) # results print(F'''Clusters that the test sample belongs to : {winner}''' ) print(F'''Weights that have been trained : {weights}''' ) # running the main() function if __name__ == "__main__": main()
135
"""simple docstring""" from typing import Dict, List, Optional, Tuple, Union import torch from ...models import AutoencoderKL, TransformeraDModel from ...schedulers import KarrasDiffusionSchedulers from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class _A ( _a ): """simple docstring""" def __init__( self : Dict , __UpperCAmelCase : TransformeraDModel , __UpperCAmelCase : AutoencoderKL , __UpperCAmelCase : KarrasDiffusionSchedulers , __UpperCAmelCase : Optional[Dict[int, str]] = None , ): super().__init__() self.register_modules(transformer=__UpperCAmelCase , vae=__UpperCAmelCase , scheduler=__UpperCAmelCase) # create a imagenet -> id dictionary for easier use a : List[Any] = {} if idalabel is not None: for key, value in idalabel.items(): for label in value.split(","): a : Any = int(__UpperCAmelCase) a : str = dict(sorted(self.labels.items())) def __snake_case ( self : Union[str, Any] , __UpperCAmelCase : Union[str, List[str]]): if not isinstance(__UpperCAmelCase , __UpperCAmelCase): a : str = list(__UpperCAmelCase) for l in label: if l not in self.labels: raise ValueError( f'''{l} does not exist. Please make sure to select one of the following labels: \n {self.labels}.''') return [self.labels[l] for l in label] @torch.no_grad() def __call__( self : List[Any] , __UpperCAmelCase : List[int] , __UpperCAmelCase : float = 4.0 , __UpperCAmelCase : Optional[Union[torch.Generator, List[torch.Generator]]] = None , __UpperCAmelCase : int = 50 , __UpperCAmelCase : Optional[str] = "pil" , __UpperCAmelCase : bool = True , ): a : str = len(__UpperCAmelCase) a : List[str] = self.transformer.config.sample_size a : List[str] = self.transformer.config.in_channels a : Optional[Any] = randn_tensor( shape=(batch_size, latent_channels, latent_size, latent_size) , generator=__UpperCAmelCase , device=self.device , dtype=self.transformer.dtype , ) a : Any = torch.cat([latents] * 2) if guidance_scale > 1 else latents a : str = torch.tensor(__UpperCAmelCase , device=self.device).reshape(-1) a : str = torch.tensor([1000] * batch_size , device=self.device) a : int = torch.cat([class_labels, class_null] , 0) if guidance_scale > 1 else class_labels # set step values self.scheduler.set_timesteps(__UpperCAmelCase) for t in self.progress_bar(self.scheduler.timesteps): if guidance_scale > 1: a : Any = latent_model_input[: len(__UpperCAmelCase) // 2] a : Optional[Any] = torch.cat([half, half] , dim=0) a : List[str] = self.scheduler.scale_model_input(__UpperCAmelCase , __UpperCAmelCase) a : Optional[Any] = t if not torch.is_tensor(__UpperCAmelCase): # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can # This would be a good case for the `match` statement (Python 3.10+) a : List[str] = latent_model_input.device.type == "mps" if isinstance(__UpperCAmelCase , __UpperCAmelCase): a : List[str] = torch.floataa if is_mps else torch.floataa else: a : List[Any] = torch.intaa if is_mps else torch.intaa a : Any = torch.tensor([timesteps] , dtype=__UpperCAmelCase , device=latent_model_input.device) elif len(timesteps.shape) == 0: a : List[Any] = timesteps[None].to(latent_model_input.device) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML a : Optional[Any] = timesteps.expand(latent_model_input.shape[0]) # predict noise model_output a : str = self.transformer( __UpperCAmelCase , timestep=__UpperCAmelCase , class_labels=__UpperCAmelCase).sample # perform guidance if guidance_scale > 1: a , a : Optional[Any] = noise_pred[:, :latent_channels], noise_pred[:, latent_channels:] a , a : Dict = torch.split(__UpperCAmelCase , len(__UpperCAmelCase) // 2 , dim=0) a : Optional[Any] = uncond_eps + guidance_scale * (cond_eps - uncond_eps) a : List[Any] = torch.cat([half_eps, half_eps] , dim=0) a : List[str] = torch.cat([eps, rest] , dim=1) # learned sigma if self.transformer.config.out_channels // 2 == latent_channels: a , a : Optional[int] = torch.split(__UpperCAmelCase , __UpperCAmelCase , dim=1) else: a : int = noise_pred # compute previous image: x_t -> x_t-1 a : List[str] = self.scheduler.step(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase).prev_sample if guidance_scale > 1: a , a : Union[str, Any] = latent_model_input.chunk(2 , dim=0) else: a : Any = latent_model_input a : str = 1 / self.vae.config.scaling_factor * latents a : Dict = self.vae.decode(__UpperCAmelCase).sample a : List[str] = (samples / 2 + 0.5).clamp(0 , 1) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 a : Optional[Any] = samples.cpu().permute(0 , 2 , 3 , 1).float().numpy() if output_type == "pil": a : Tuple = self.numpy_to_pil(__UpperCAmelCase) if not return_dict: return (samples,) return ImagePipelineOutput(images=__UpperCAmelCase)
135
1
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 lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { '''facebook/deit-base-distilled-patch16-224''': ( '''https://huggingface.co/facebook/deit-base-patch16-224/resolve/main/config.json''' ), # See all DeiT models at https://huggingface.co/models?filter=deit } class SCREAMING_SNAKE_CASE ( __a ): __lowerCamelCase : Dict ='''deit''' def __init__( self : Optional[int] , __lowercase : List[Any]=768 , __lowercase : Union[str, Any]=12 , __lowercase : str=12 , __lowercase : Tuple=3072 , __lowercase : Optional[Any]="gelu" , __lowercase : Optional[Any]=0.0 , __lowercase : Union[str, Any]=0.0 , __lowercase : Union[str, Any]=0.02 , __lowercase : Optional[Any]=1E-12 , __lowercase : List[Any]=224 , __lowercase : Union[str, Any]=16 , __lowercase : List[str]=3 , __lowercase : int=True , __lowercase : Dict=16 , **__lowercase : Tuple , ): '''simple docstring''' super().__init__(**snake_case__ ) __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = initializer_range __a = layer_norm_eps __a = image_size __a = patch_size __a = num_channels __a = qkv_bias __a = encoder_stride class SCREAMING_SNAKE_CASE ( __a ): __lowerCamelCase : List[Any] =version.parse('1.11' ) @property def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def UpperCamelCase_ ( self : Any ): '''simple docstring''' return 1E-4
225
# A Bipartite Graph is a graph whose vertices can be divided into two independent sets, # U and V such that every edge (u, v) either connects a vertex from U to V or a vertex # from V to U. In other words, for every edge (u, v), either u belongs to U and v to V, # or u belongs to V and v to U. We can also say that there is no edge that connects # vertices of same set. def UpperCamelCase__ ( lowerCAmelCase__ ): lowercase = [False] * len(lowerCAmelCase__ ) lowercase = [-1] * len(lowerCAmelCase__ ) def dfs(lowerCAmelCase__ ,lowerCAmelCase__ ): lowercase = True lowercase = c for u in graph[v]: if not visited[u]: dfs(lowerCAmelCase__ ,1 - c ) for i in range(len(lowerCAmelCase__ ) ): if not visited[i]: dfs(lowerCAmelCase__ ,0 ) for i in range(len(lowerCAmelCase__ ) ): for j in graph[i]: if color[i] == color[j]: return False return True # Adjacency list of graph __SCREAMING_SNAKE_CASE : List[str] ={0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2], 4: []} print(check_bipartite_dfs(graph))
428
0
import json import logging import os import re import sys from dataclasses import dataclass, field from typing import Any, Dict, List, Optional, Union import datasets import numpy as np import torch import torchaudio from packaging import version from torch import nn import transformers from transformers import ( HfArgumentParser, Trainer, TrainingArguments, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaForCTC, WavaVecaProcessor, is_apex_available, set_seed, ) from transformers.trainer_utils import get_last_checkpoint, is_main_process if is_apex_available(): from apex import amp if version.parse(version.parse(torch.__version__).base_version) >= version.parse("1.6"): lowercase__ :Optional[int] = True from torch.cuda.amp import autocast lowercase__ :Any = logging.getLogger(__name__) def UpperCamelCase ( lowerCAmelCase__=None , lowerCAmelCase__=None ): '''simple docstring''' return field(default_factory=lambda: default , metadata=lowerCAmelCase__ ) @dataclass class lowercase : lowercase_ : str =field( metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''} ) lowercase_ : Optional[str] =field( default=SCREAMING_SNAKE_CASE__ , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''} , ) lowercase_ : Optional[bool] =field( default=SCREAMING_SNAKE_CASE__ , metadata={'''help''': '''Whether to freeze the feature extractor layers of the model.'''} ) lowercase_ : Optional[float] =field( default=0.1 , metadata={'''help''': '''The dropout ratio for the attention probabilities.'''} ) lowercase_ : Optional[float] =field( default=0.1 , metadata={'''help''': '''The dropout ratio for activations inside the fully connected layer.'''} ) lowercase_ : Optional[float] =field( default=0.1 , metadata={ '''help''': '''The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.''' } , ) lowercase_ : Optional[float] =field( default=0.1 , metadata={'''help''': '''The dropout probabilitiy for all 1D convolutional layers in feature extractor.'''} , ) lowercase_ : Optional[float] =field( default=0.05 , metadata={ '''help''': ( '''Propability of each feature vector along the time axis to be chosen as the start of the vector''' '''span to be masked. Approximately ``mask_time_prob * sequence_length // mask_time_length`` feature''' '''vectors will be masked along the time axis. This is only relevant if ``apply_spec_augment is True``.''' ) } , ) lowercase_ : Optional[float] =field(default=0.0 , metadata={'''help''': '''The LayerDrop probability.'''} ) @dataclass class lowercase : lowercase_ : Optional[str] =field( default=SCREAMING_SNAKE_CASE__ , metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''} ) lowercase_ : Optional[str] =field( default='''train+validation''' , metadata={ '''help''': '''The name of the training data set split to use (via the datasets library). Defaults to \'train\'''' } , ) lowercase_ : bool =field( default=SCREAMING_SNAKE_CASE__ , metadata={'''help''': '''Overwrite the cached preprocessed datasets or not.'''} ) lowercase_ : Optional[int] =field( default=SCREAMING_SNAKE_CASE__ , metadata={'''help''': '''The number of processes to use for the preprocessing.'''} , ) lowercase_ : Optional[int] =field( default=SCREAMING_SNAKE_CASE__ , metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of training examples to this ''' '''value if set.''' ) } , ) lowercase_ : Optional[int] =field( default=SCREAMING_SNAKE_CASE__ , metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of validation examples to this ''' '''value if set.''' ) } , ) lowercase_ : List[str] =list_field( default=[''',''', '''?''', '''.''', '''!''', '''-''', ''';''', ''':''', '''""''', '''%''', '''\'''', '''"''', '''�'''] , metadata={'''help''': '''A list of characters to remove from the transcripts.'''} , ) @dataclass class lowercase : lowercase_ : WavaVecaProcessor lowercase_ : Union[bool, str] =True lowercase_ : Optional[int] =None lowercase_ : Optional[int] =None lowercase_ : Optional[int] =None lowercase_ : Optional[int] =None def __call__( self ,A__): # split inputs and labels since they have to be of different lenghts and need # different padding methods lowercase = [{'''input_values''': feature['''input_values''']} for feature in features] lowercase = [{'''input_ids''': feature['''labels''']} for feature in features] lowercase = self.processor.pad( A__ ,padding=self.padding ,max_length=self.max_length ,pad_to_multiple_of=self.pad_to_multiple_of ,return_tensors='''pt''' ,) lowercase = self.processor.pad( labels=A__ ,padding=self.padding ,max_length=self.max_length_labels ,pad_to_multiple_of=self.pad_to_multiple_of_labels ,return_tensors='''pt''' ,) # replace padding with -100 to ignore loss correctly lowercase = labels_batch['''input_ids'''].masked_fill(labels_batch.attention_mask.ne(1) ,-1_0_0) lowercase = labels return batch class lowercase ( SCREAMING_SNAKE_CASE__ ): def A__ ( self ,A__ ,A__): model.train() lowercase = self._prepare_inputs(A__) if self.use_amp: with autocast(): lowercase = self.compute_loss(A__ ,A__) else: lowercase = self.compute_loss(A__ ,A__) if self.args.n_gpu > 1: if model.module.config.ctc_loss_reduction == "mean": lowercase = loss.mean() elif model.module.config.ctc_loss_reduction == "sum": lowercase = loss.sum() / (inputs['''labels'''] >= 0).sum() else: raise ValueError(f'{model.config.ctc_loss_reduction} is not valid. Choose one of [\'mean\', \'sum\']') if self.args.gradient_accumulation_steps > 1: lowercase = loss / self.args.gradient_accumulation_steps if self.use_amp: self.scaler.scale(A__).backward() elif self.use_apex: with amp.scale_loss(A__ ,self.optimizer) as scaled_loss: scaled_loss.backward() elif self.deepspeed: self.deepspeed.backward(A__) else: loss.backward() return loss.detach() def UpperCamelCase ( ): '''simple docstring''' lowercase = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('''.json''' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. lowercase , lowercase , lowercase = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: lowercase , lowercase , lowercase = parser.parse_args_into_dataclasses() # Detecting last checkpoint. lowercase = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: lowercase = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f'Output directory ({training_args.output_dir}) already exists and is not empty. ' '''Use --overwrite_output_dir to overcome.''' ) elif last_checkpoint is not None: logger.info( f'Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ' '''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.''' ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , handlers=[logging.StreamHandler(sys.stdout )] , ) logger.setLevel(logging.INFO if is_main_process(training_args.local_rank ) else logging.WARN ) # Log on each process the small summary: logger.warning( f'Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}' + f'distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}' ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() logger.info('''Training/evaluation parameters %s''' , lowerCAmelCase__ ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: lowercase = datasets.load_dataset( '''common_voice''' , data_args.dataset_config_name , split=data_args.train_split_name ) lowercase = datasets.load_dataset('''common_voice''' , data_args.dataset_config_name , split='''test''' ) # Create and save tokenizer lowercase = f'[{"".join(data_args.chars_to_ignore )}]' def remove_special_characters(lowerCAmelCase__ ): lowercase = re.sub(lowerCAmelCase__ , '''''' , batch['''sentence'''] ).lower() + ''' ''' return batch lowercase = train_dataset.map(lowerCAmelCase__ , remove_columns=['''sentence'''] ) lowercase = eval_dataset.map(lowerCAmelCase__ , remove_columns=['''sentence'''] ) def extract_all_chars(lowerCAmelCase__ ): lowercase = ''' '''.join(batch['''text'''] ) lowercase = list(set(lowerCAmelCase__ ) ) return {"vocab": [vocab], "all_text": [all_text]} lowercase = train_dataset.map( lowerCAmelCase__ , batched=lowerCAmelCase__ , batch_size=-1 , keep_in_memory=lowerCAmelCase__ , remove_columns=train_dataset.column_names , ) lowercase = train_dataset.map( lowerCAmelCase__ , batched=lowerCAmelCase__ , batch_size=-1 , keep_in_memory=lowerCAmelCase__ , remove_columns=eval_dataset.column_names , ) lowercase = list(set(vocab_train['''vocab'''][0] ) | set(vocab_test['''vocab'''][0] ) ) lowercase = {v: k for k, v in enumerate(lowerCAmelCase__ )} lowercase = vocab_dict[''' '''] del vocab_dict[" "] lowercase = len(lowerCAmelCase__ ) lowercase = len(lowerCAmelCase__ ) with open('''vocab.json''' , '''w''' ) as vocab_file: json.dump(lowerCAmelCase__ , lowerCAmelCase__ ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. lowercase = WavaVecaCTCTokenizer( '''vocab.json''' , unk_token='''[UNK]''' , pad_token='''[PAD]''' , word_delimiter_token='''|''' , ) lowercase = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6000 , padding_value=0.0 , do_normalize=lowerCAmelCase__ , return_attention_mask=lowerCAmelCase__ ) lowercase = WavaVecaProcessor(feature_extractor=lowerCAmelCase__ , tokenizer=lowerCAmelCase__ ) lowercase = WavaVecaForCTC.from_pretrained( model_args.model_name_or_path , cache_dir=model_args.cache_dir , activation_dropout=model_args.activation_dropout , attention_dropout=model_args.attention_dropout , hidden_dropout=model_args.hidden_dropout , feat_proj_dropout=model_args.feat_proj_dropout , mask_time_prob=model_args.mask_time_prob , gradient_checkpointing=training_args.gradient_checkpointing , layerdrop=model_args.layerdrop , ctc_loss_reduction='''mean''' , pad_token_id=processor.tokenizer.pad_token_id , vocab_size=len(processor.tokenizer ) , ) if data_args.max_train_samples is not None: lowercase = min(len(lowerCAmelCase__ ) , data_args.max_train_samples ) lowercase = train_dataset.select(range(lowerCAmelCase__ ) ) if data_args.max_val_samples is not None: lowercase = eval_dataset.select(range(data_args.max_val_samples ) ) lowercase = torchaudio.transforms.Resample(4_8000 , 1_6000 ) # Preprocessing the datasets. # We need to read the aduio files as arrays and tokenize the targets. def speech_file_to_array_fn(lowerCAmelCase__ ): lowercase , lowercase = torchaudio.load(batch['''path'''] ) lowercase = resampler(lowerCAmelCase__ ).squeeze().numpy() lowercase = 1_6000 lowercase = batch['''text'''] return batch lowercase = train_dataset.map( lowerCAmelCase__ , remove_columns=train_dataset.column_names , num_proc=data_args.preprocessing_num_workers , ) lowercase = eval_dataset.map( lowerCAmelCase__ , remove_columns=eval_dataset.column_names , num_proc=data_args.preprocessing_num_workers , ) def prepare_dataset(lowerCAmelCase__ ): # check that all files have the correct sampling rate assert ( len(set(batch['''sampling_rate'''] ) ) == 1 ), f'Make sure all inputs have the same sampling rate of {processor.feature_extractor.sampling_rate}.' lowercase = processor( audio=batch['''speech'''] , text=batch['''target_text'''] , sampling_rate=batch['''sampling_rate'''][0] ) batch.update(lowerCAmelCase__ ) return batch lowercase = train_dataset.map( lowerCAmelCase__ , remove_columns=train_dataset.column_names , batch_size=training_args.per_device_train_batch_size , batched=lowerCAmelCase__ , num_proc=data_args.preprocessing_num_workers , ) lowercase = eval_dataset.map( lowerCAmelCase__ , remove_columns=eval_dataset.column_names , batch_size=training_args.per_device_train_batch_size , batched=lowerCAmelCase__ , num_proc=data_args.preprocessing_num_workers , ) # Metric lowercase = datasets.load_metric('''wer''' ) def compute_metrics(lowerCAmelCase__ ): lowercase = pred.predictions lowercase = np.argmax(lowerCAmelCase__ , axis=-1 ) lowercase = processor.tokenizer.pad_token_id lowercase = processor.batch_decode(lowerCAmelCase__ ) # we do not want to group tokens when computing the metrics lowercase = processor.batch_decode(pred.label_ids , group_tokens=lowerCAmelCase__ ) lowercase = wer_metric.compute(predictions=lowerCAmelCase__ , references=lowerCAmelCase__ ) return {"wer": wer} if model_args.freeze_feature_extractor: model.freeze_feature_extractor() # Data collator lowercase = DataCollatorCTCWithPadding(processor=lowerCAmelCase__ , padding=lowerCAmelCase__ ) # Initialize our Trainer lowercase = CTCTrainer( model=lowerCAmelCase__ , data_collator=lowerCAmelCase__ , args=lowerCAmelCase__ , compute_metrics=lowerCAmelCase__ , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , tokenizer=processor.feature_extractor , ) # Training if training_args.do_train: if last_checkpoint is not None: lowercase = last_checkpoint elif os.path.isdir(model_args.model_name_or_path ): lowercase = model_args.model_name_or_path else: lowercase = None # Save the feature_extractor and the tokenizer if is_main_process(training_args.local_rank ): processor.save_pretrained(training_args.output_dir ) lowercase = trainer.train(resume_from_checkpoint=lowerCAmelCase__ ) trainer.save_model() lowercase = train_result.metrics lowercase = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(lowerCAmelCase__ ) ) lowercase = min(lowerCAmelCase__ , len(lowerCAmelCase__ ) ) trainer.log_metrics('''train''' , lowerCAmelCase__ ) trainer.save_metrics('''train''' , lowerCAmelCase__ ) trainer.save_state() # Evaluation lowercase = {} if training_args.do_eval: logger.info('''*** Evaluate ***''' ) lowercase = trainer.evaluate() lowercase = data_args.max_val_samples if data_args.max_val_samples is not None else len(lowerCAmelCase__ ) lowercase = min(lowerCAmelCase__ , len(lowerCAmelCase__ ) ) trainer.log_metrics('''eval''' , lowerCAmelCase__ ) trainer.save_metrics('''eval''' , lowerCAmelCase__ ) return results if __name__ == "__main__": main()
706
import argparse from collections import defaultdict import yaml lowercase__ :Optional[int] = "docs/source/en/_toctree.yml" def UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' lowercase = defaultdict(lowerCAmelCase__ ) for doc in model_doc: counts[doc["local"]] += 1 lowercase = [key for key, value in counts.items() if value > 1] lowercase = [] for duplicate_key in duplicates: lowercase = list({doc['''title'''] for doc in model_doc if doc['''local'''] == duplicate_key} ) if len(lowerCAmelCase__ ) > 1: raise ValueError( f'{duplicate_key} is present several times in the documentation table of content at ' '''`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the ''' '''others.''' ) # Only add this once new_doc.append({'''local''': duplicate_key, '''title''': titles[0]} ) # Add none duplicate-keys new_doc.extend([doc for doc in model_doc if counts[doc['''local''']] == 1] ) # Sort return sorted(lowerCAmelCase__ , key=lambda lowerCAmelCase__ : s["title"].lower() ) def UpperCamelCase ( lowerCAmelCase__=False ): '''simple docstring''' with open(lowerCAmelCase__ , encoding='''utf-8''' ) as f: lowercase = yaml.safe_load(f.read() ) # Get to the API doc lowercase = 0 while content[api_idx]["title"] != "API": api_idx += 1 lowercase = content[api_idx]['''sections'''] # Then to the model doc lowercase = 0 while api_doc[model_idx]["title"] != "Models": model_idx += 1 lowercase = api_doc[model_idx]['''sections'''] lowercase = [(idx, section) for idx, section in enumerate(lowerCAmelCase__ ) if '''sections''' in section] lowercase = False for idx, modality_doc in modalities_docs: lowercase = modality_doc['''sections'''] lowercase = clean_model_doc_toc(lowerCAmelCase__ ) if old_modality_doc != new_modality_doc: lowercase = True if overwrite: lowercase = new_modality_doc if diff: if overwrite: lowercase = model_doc lowercase = api_doc with open(lowerCAmelCase__ , '''w''' , encoding='''utf-8''' ) as f: f.write(yaml.dump(lowerCAmelCase__ , allow_unicode=lowerCAmelCase__ ) ) else: raise ValueError( '''The model doc part of the table of content is not properly sorted, run `make style` to fix this.''' ) if __name__ == "__main__": lowercase__ :Any = argparse.ArgumentParser() parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.") lowercase__ :int = parser.parse_args() check_model_doc(args.fix_and_overwrite)
633
0
import math import os import re import sys import unittest from pathlib import Path from typing import Tuple from unittest.mock import patch from parameterized import parameterized from transformers.testing_utils import ( CaptureStderr, ExtendSysPath, TestCasePlus, execute_subprocess_async, get_gpu_count, get_torch_dist_unique_port, require_apex, require_bitsandbytes, require_fairscale, require_torch, require_torch_gpu, require_torch_multi_gpu, require_torch_non_multi_gpu, slow, ) from transformers.trainer_callback import TrainerState from transformers.trainer_utils import set_seed __lowerCamelCase : Dict = os.path.abspath(os.path.dirname(__file__)) with ExtendSysPath(F"{bindir}/../../examples/pytorch/translation"): from run_translation import main # noqa set_seed(42) __lowerCamelCase : Dict = """sshleifer/student_marian_en_ro_6_1""" __lowerCamelCase : Union[str, Any] = """sshleifer/tiny-mbart""" @require_torch class _lowercase ( _A ): def lowercase__ ( self , a=False , a=None , a=True , a=True , a=True , a=True , ): snake_case__ : Tuple =self.run_trainer( eval_steps=1 , max_len=1_2 , model_name=lowerCamelCase__ , num_train_epochs=1 , distributed=lowerCamelCase__ , extra_args_str=lowerCamelCase__ , predict_with_generate=lowerCamelCase__ , do_train=lowerCamelCase__ , do_eval=lowerCamelCase__ , do_predict=lowerCamelCase__ , ) snake_case__ : str =TrainerState.load_from_json(os.path.join(lowerCamelCase__ , """trainer_state.json""" ) ).log_history if not do_eval: return snake_case__ : int =[log for log in logs if """eval_loss""" in log.keys()] snake_case__ : List[str] =eval_metrics[0] if predict_with_generate: assert "eval_bleu" in first_step_stats snake_case__ : List[Any] =eval_metrics[-1] assert isinstance(last_step_stats["""eval_bleu"""] , lowerCamelCase__ ) assert not math.isnan(float(last_step_stats["""eval_loss"""] ) ), "eval_loss must not be `nan`" @require_torch_non_multi_gpu def lowercase__ ( self ): self.run_seqaseq_quick() @require_torch_multi_gpu def lowercase__ ( self ): self.run_seqaseq_quick(distributed=lowerCamelCase__ ) @require_torch_multi_gpu def lowercase__ ( self ): self.run_seqaseq_quick(distributed=lowerCamelCase__ ) @unittest.skip("""Requires an update of the env running those tests""" ) @require_torch_multi_gpu @require_fairscale def lowercase__ ( self ): self.run_seqaseq_quick(distributed=lowerCamelCase__ , extra_args_str="""--sharded_ddp simple""" ) @unittest.skip("""Requires an update of the env running those tests""" ) @require_torch_multi_gpu @require_fairscale def lowercase__ ( self ): self.run_seqaseq_quick(distributed=lowerCamelCase__ , extra_args_str="""--sharded_ddp simple --fp16""" ) @unittest.skip("""Requires an update of the env running those tests""" ) @require_torch_multi_gpu @require_fairscale def lowercase__ ( self ): self.run_seqaseq_quick(distributed=lowerCamelCase__ , extra_args_str="""--sharded_ddp zero_dp_2""" , predict_with_generate=lowerCamelCase__ ) @unittest.skip("""Requires an update of the env running those tests""" ) @require_torch_multi_gpu @require_fairscale def lowercase__ ( self ): self.run_seqaseq_quick( distributed=lowerCamelCase__ , extra_args_str="""--sharded_ddp zero_dp_2 --fp16""" , predict_with_generate=lowerCamelCase__ ) @require_apex @require_torch_gpu def lowercase__ ( self ): # XXX: apex breaks the trainer if it's run twice e.g. run_seq2seq.main() from the same # program and it breaks other tests that run from the same pytest worker, therefore until this is # sorted out it must be run only in an external program, that is distributed=True in this # test and only under one or more gpus - if we want cpu will need to make a special test # # specifically to the problem traced it to self.optimizer.step() - if it's run 2nd time via # 2nd main() call it botches the future eval. # self.run_seqaseq_quick(distributed=lowerCamelCase__ , extra_args_str="""--fp16 --fp16_backend=apex""" ) # test 2nd time - was getting eval_loss': nan' # to reproduce the problem set distributed=False self.run_seqaseq_quick(distributed=lowerCamelCase__ , extra_args_str="""--fp16 --fp16_backend=apex""" ) @parameterized.expand(["""base""", """low""", """high""", """mixed"""] ) @require_torch_multi_gpu def lowercase__ ( self , a ): # as each sub-test is slow-ish split into multiple sub-tests to avoid CI timeout snake_case__ : Optional[int] ={ # test with the default log_level - should be info and thus log info once """base""": {"""extra_args_str""": """""", """n_matches""": 1}, # test with low log_level and log_level_replica - should be noisy on all processes # now the info string should appear twice on 2 processes """low""": {"""extra_args_str""": """--log_level debug --log_level_replica debug""", """n_matches""": 2}, # test with high log_level and low log_level_replica # now the info string should appear once only on the replica """high""": {"""extra_args_str""": """--log_level error --log_level_replica debug""", """n_matches""": 1}, # test with high log_level and log_level_replica - should be quiet on all processes """mixed""": {"""extra_args_str""": """--log_level error --log_level_replica error""", """n_matches""": 0}, } snake_case__ : Union[str, Any] =experiments[experiment_id] snake_case__ : int ={"""distributed""": True, """predict_with_generate""": False, """do_eval""": False, """do_predict""": False} snake_case__ : Any ="""Running training""" with CaptureStderr() as cl: self.run_seqaseq_quick(**lowerCamelCase__ , extra_args_str=data["""extra_args_str"""] ) snake_case__ : Any =len(re.findall(lowerCamelCase__ , cl.err ) ) self.assertEqual(lowerCamelCase__ , data["""n_matches"""] ) @slow def lowercase__ ( self ): snake_case__ : List[str] =self.run_trainer( eval_steps=2 , max_len=1_2_8 , model_name=lowerCamelCase__ , learning_rate=3e-4 , num_train_epochs=1_0 , distributed=lowerCamelCase__ , ) # Check metrics snake_case__ : Tuple =TrainerState.load_from_json(os.path.join(lowerCamelCase__ , """trainer_state.json""" ) ).log_history snake_case__ : int =[log for log in logs if """eval_loss""" in log.keys()] snake_case__ : Tuple =eval_metrics[0] snake_case__ : List[Any] =eval_metrics[-1] assert first_step_stats["eval_loss"] > last_step_stats["eval_loss"], "model learned nothing" assert isinstance(last_step_stats["""eval_bleu"""] , lowerCamelCase__ ) # test if do_predict saves generations and metrics snake_case__ : int =os.listdir(lowerCamelCase__ ) snake_case__ : Dict ={os.path.basename(lowerCamelCase__ ) for p in contents} assert "generated_predictions.txt" in contents assert "predict_results.json" in contents @slow @require_bitsandbytes def lowercase__ ( self ): from transformers.training_args import OptimizerNames def train_and_return_metrics(a ) -> Tuple[int, float]: snake_case__ : List[str] ="""--skip_memory_metrics 0""" snake_case__ : Tuple =self.run_trainer( max_len=1_2_8 , model_name=lowerCamelCase__ , learning_rate=3e-4 , num_train_epochs=1 , optim=lowerCamelCase__ , distributed=lowerCamelCase__ , extra_args_str=lowerCamelCase__ , do_eval=lowerCamelCase__ , do_predict=lowerCamelCase__ , n_gpus_to_use=1 , ) # Check metrics snake_case__ : List[Any] =TrainerState.load_from_json(Path(lowerCamelCase__ , """trainer_state.json""" ) ).log_history snake_case__ : List[Any] =int(logs[0]["""train_mem_gpu_peaked_delta"""] / 2**2_0 ) snake_case__ : Tuple =int(logs[0]["""train_mem_gpu_alloc_delta"""] / 2**2_0 ) snake_case__ : Tuple =logs[0]["""train_loss"""] return gpu_peak_mem_mb, gpu_alloc_mem_mb, loss snake_case__ : Tuple =train_and_return_metrics(OptimizerNames.ADAMW_TORCH.value ) snake_case__ : List[Any] =train_and_return_metrics(OptimizerNames.ADAMW_BNB.value ) snake_case__ : Optional[Any] =gpu_alloc_mem_orig - gpu_alloc_mem_bnb snake_case__ : List[str] =gpu_peak_mem_orig + gpu_alloc_mem_orig snake_case__ : str =gpu_peak_mem_bnb + gpu_alloc_mem_bnb snake_case__ : Optional[Any] =gpu_total_mem_orig - gpu_total_mem_bnb # sshleifer/student_marian_en_ro_6_1 has 54M parameter, 29M of which is `nn.Embedding` which # doesn't get quantized and remains in fp32. Therefore we only have 25M parameters quantized # in 2 bytes and the diff in optim memory usage is derived as so: # # - normal 25*8=~200MB (8 bytes per param) # - bnb 25*2= ~50MB (2 bytes per param) # # Thus we should expect ~150MB total memory saved. # # Peak memory should be the same - the total should be different by about that same margin # # After leaving a small margin to accommodate for differences between gpus let's check # that we have at least 120MB in savings snake_case__ : Union[str, Any] =1_2_0 # uncomment the following if this test starts failing - requires py38 for a new print feature # gpu_peak_mem_diff = gpu_peak_mem_orig - gpu_peak_mem_bnb # print(f"{gpu_alloc_mem_orig=}MB {gpu_peak_mem_orig=}MB {gpu_alloc_mem_orig+gpu_peak_mem_orig=}MB") # print(f" {gpu_alloc_mem_bnb=}MB {gpu_peak_mem_bnb=}MB {gpu_alloc_mem_bnb+gpu_peak_mem_bnb=}MB") # print(f"{gpu_alloc_mem_diff=}MB") # print(f"{gpu_peak_mem_diff=}MB") # print(f"{gpu_total_mem_orig=}MB, {gpu_total_mem_bnb=}MB") # print(f"{gpu_total_mem_diff=}MB, {gpu_total_mem_diff=}MB") self.assertGreater( lowerCamelCase__ , lowerCamelCase__ , """should use ~150MB less alloc gpu memory with BNB, compared to without it for this model but got""" F" a difference of {gpu_alloc_mem_diff}MB, with gpu_alloc_mem_orig={gpu_alloc_mem_orig}MB and" F" gpu_alloc_mem_bnb={gpu_alloc_mem_bnb}MB" , ) self.assertGreater( lowerCamelCase__ , lowerCamelCase__ , """should use ~150MB less total gpu memory with BNB, compared to without it for this model but got""" F" a difference of {gpu_total_mem_diff}MB, with gpu_total_mem_orig={gpu_total_mem_orig}MB and" F" gpu_total_mem_bnb={gpu_total_mem_bnb}MB" , ) self.assertEqual( lowerCamelCase__ , lowerCamelCase__ , F"loss should be the same, but got loss_orig={loss_orig}, loss_bnb={loss_bnb}" ) def lowercase__ ( self , a , a , a , a = 3e-3 , a = "adafactor" , a = False , a = None , a = 0 , a = True , a = True , a = True , a = True , a = None , ): snake_case__ : List[Any] =self.test_file_dir / """../fixtures/tests_samples/wmt_en_ro""" snake_case__ : int =self.get_auto_remove_tmp_dir() snake_case__ : List[Any] =F"\n --model_name_or_path {model_name}\n --train_file {data_dir}/train.json\n --validation_file {data_dir}/val.json\n --test_file {data_dir}/test.json\n --output_dir {output_dir}\n --overwrite_output_dir\n --max_train_samples 8\n --max_source_length {max_len}\n --max_target_length {max_len}\n --do_train\n --num_train_epochs {str(lowerCamelCase__ )}\n --per_device_train_batch_size 4\n --learning_rate {learning_rate}\n --warmup_steps 8\n --logging_steps 0\n --logging_strategy no\n --save_steps {str(lowerCamelCase__ )}\n --group_by_length\n --label_smoothing_factor 0.1\n --target_lang ro_RO\n --source_lang en_XX\n ".split() snake_case__ : Optional[Any] =F"\n --do_eval\n --per_device_eval_batch_size 4\n --max_eval_samples 8\n --val_max_target_length {max_len}\n --evaluation_strategy steps\n --eval_steps {str(lowerCamelCase__ )}\n ".split() snake_case__ : Optional[Any] =""" --do_predict """.split() snake_case__ : Union[str, Any] =[] if do_train: args += args_train if do_eval: args += args_eval if do_predict: args += args_predict if predict_with_generate: args += "--predict_with_generate".split() if do_train: if optim == "adafactor": args += "--adafactor".split() else: args += F"--optim {optim}".split() if extra_args_str is not None: args += extra_args_str.split() if distributed: if n_gpus_to_use is None: snake_case__ : List[Any] =get_gpu_count() snake_case__ : int =get_torch_dist_unique_port() snake_case__ : Tuple =F"\n -m torch.distributed.run\n --nproc_per_node={n_gpus_to_use}\n --master_port={master_port}\n {self.examples_dir_str}/pytorch/translation/run_translation.py\n ".split() snake_case__ : Dict =[sys.executable] + distributed_args + args # keep for quick debug # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die execute_subprocess_async(lowerCamelCase__ , env=self.get_env() ) else: snake_case__ : Dict =["""run_translation.py"""] + args with patch.object(lowerCamelCase__ , """argv""" , lowerCamelCase__ ): main() return output_dir
385
def A ( lowercase__ : int , lowercase__ : int ) -> int: return int(input_a == input_a == 0 ) def A ( ) -> None: print("""Truth Table of NOR Gate:""" ) print("""| Input 1 | Input 2 | Output |""" ) print(f"""| 0 | 0 | {nor_gate(0 , 0 )} |""" ) print(f"""| 0 | 1 | {nor_gate(0 , 1 )} |""" ) print(f"""| 1 | 0 | {nor_gate(1 , 0 )} |""" ) print(f"""| 1 | 1 | {nor_gate(1 , 1 )} |""" ) if __name__ == "__main__": import doctest doctest.testmod() main()
45
0
from __future__ import annotations def lowercase_ ( __snake_case : list[int] ) -> int: '''simple docstring''' snake_case__ :Union[str, Any] = len(__snake_case ) // 2 # choose the middle 3 elements snake_case__ :List[str] = lst[m - 1 : m + 2] # if middle element is peak if three[1] > three[0] and three[1] > three[2]: return three[1] # if increasing, recurse on right elif three[0] < three[2]: if len(lst[:m] ) == 2: m -= 1 return peak(lst[m:] ) # decreasing else: if len(lst[:m] ) == 2: m += 1 return peak(lst[:m] ) if __name__ == "__main__": import doctest doctest.testmod()
57
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available __UpperCAmelCase : Tuple = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase : List[Any] = ["BartphoTokenizer"] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bartpho import BartphoTokenizer else: import sys __UpperCAmelCase : Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
57
1
"""simple docstring""" import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler __UpperCamelCase = 16 __UpperCamelCase = 32 def lowercase (SCREAMING_SNAKE_CASE_ : Accelerator , SCREAMING_SNAKE_CASE_ : int = 16 , SCREAMING_SNAKE_CASE_ : str = "bert-base-cased" ) -> Optional[Any]: SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE = load_dataset('glue' , 'mrpc' ) def tokenize_function(SCREAMING_SNAKE_CASE_ : List[Any] ): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset SCREAMING_SNAKE_CASE = datasets.map( SCREAMING_SNAKE_CASE_ , batched=SCREAMING_SNAKE_CASE_ , remove_columns=['idx', 'sentence1', 'sentence2'] , load_from_cache_file=SCREAMING_SNAKE_CASE_ ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library SCREAMING_SNAKE_CASE = tokenized_datasets.rename_column('label' , 'labels' ) def collate_fn(SCREAMING_SNAKE_CASE_ : Union[str, Any] ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(SCREAMING_SNAKE_CASE_ , padding='max_length' , max_length=1_28 , return_tensors='pt' ) return tokenizer.pad(SCREAMING_SNAKE_CASE_ , padding='longest' , return_tensors='pt' ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets['train'] , shuffle=SCREAMING_SNAKE_CASE_ , collate_fn=SCREAMING_SNAKE_CASE_ , batch_size=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets['validation'] , shuffle=SCREAMING_SNAKE_CASE_ , collate_fn=SCREAMING_SNAKE_CASE_ , batch_size=SCREAMING_SNAKE_CASE_ ) return train_dataloader, eval_dataloader def lowercase (SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : List[str] ) -> Dict: model.eval() SCREAMING_SNAKE_CASE = 0 for step, batch in enumerate(SCREAMING_SNAKE_CASE_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): SCREAMING_SNAKE_CASE = model(**SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.gather( (predictions, batch['labels']) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(SCREAMING_SNAKE_CASE_ ) - 1: SCREAMING_SNAKE_CASE = predictions[: len(eval_dataloader.dataset ) - samples_seen] SCREAMING_SNAKE_CASE = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=SCREAMING_SNAKE_CASE_ , references=SCREAMING_SNAKE_CASE_ , ) SCREAMING_SNAKE_CASE = metric.compute() return eval_metric["accuracy"] def lowercase (SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Any ) -> Any: # Initialize accelerator SCREAMING_SNAKE_CASE = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE = config['lr'] SCREAMING_SNAKE_CASE = int(config['num_epochs'] ) SCREAMING_SNAKE_CASE = int(config['seed'] ) SCREAMING_SNAKE_CASE = int(config['batch_size'] ) SCREAMING_SNAKE_CASE = args.model_name_or_path set_seed(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_dataloaders(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained(SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ ) # Instantiate optimizer SCREAMING_SNAKE_CASE = ( AdamW if accelerator.state.deepspeed_plugin is None or 'optimizer' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) SCREAMING_SNAKE_CASE = optimizer_cls(params=model.parameters() , lr=SCREAMING_SNAKE_CASE_ ) if accelerator.state.deepspeed_plugin is not None: SCREAMING_SNAKE_CASE = accelerator.state.deepspeed_plugin.deepspeed_config[ 'gradient_accumulation_steps' ] else: SCREAMING_SNAKE_CASE = 1 SCREAMING_SNAKE_CASE = (len(SCREAMING_SNAKE_CASE_ ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): SCREAMING_SNAKE_CASE = get_linear_schedule_with_warmup( optimizer=SCREAMING_SNAKE_CASE_ , num_warmup_steps=0 , num_training_steps=SCREAMING_SNAKE_CASE_ , ) else: SCREAMING_SNAKE_CASE = DummyScheduler(SCREAMING_SNAKE_CASE_ , total_num_steps=SCREAMING_SNAKE_CASE_ , warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.prepare( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # We need to keep track of how many total steps we have iterated over SCREAMING_SNAKE_CASE = 0 # We also need to keep track of the stating epoch so files are named properly SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = evaluate.load('glue' , 'mrpc' ) SCREAMING_SNAKE_CASE = num_epochs if args.partial_train_epoch is not None: SCREAMING_SNAKE_CASE = args.partial_train_epoch if args.resume_from_checkpoint: accelerator.load_state(args.resume_from_checkpoint ) SCREAMING_SNAKE_CASE = args.resume_from_checkpoint.split('epoch_' )[1] SCREAMING_SNAKE_CASE = '' for char in epoch_string: if char.isdigit(): state_epoch_num += char else: break SCREAMING_SNAKE_CASE = int(SCREAMING_SNAKE_CASE_ ) + 1 SCREAMING_SNAKE_CASE = evaluation_loop(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) accelerator.print('resumed checkpoint performance:' , SCREAMING_SNAKE_CASE_ ) accelerator.print('resumed checkpoint\'s scheduler\'s lr:' , lr_scheduler.get_lr()[0] ) accelerator.print('resumed optimizers\'s lr:' , optimizer.param_groups[0]['lr'] ) with open(os.path.join(args.output_dir , F'state_{starting_epoch-1}.json' ) , 'r' ) as f: SCREAMING_SNAKE_CASE = json.load(SCREAMING_SNAKE_CASE_ ) assert resumed_state["accuracy"] == accuracy, "Accuracy mismatch, loading from checkpoint failed" assert ( resumed_state["lr"] == lr_scheduler.get_lr()[0] ), "Scheduler learning rate mismatch, loading from checkpoint failed" assert ( resumed_state["optimizer_lr"] == optimizer.param_groups[0]["lr"] ), "Optimizer learning rate mismatch, loading from checkpoint failed" assert resumed_state["epoch"] == starting_epoch - 1, "Epoch mismatch, loading from checkpoint failed" return # Now we train the model SCREAMING_SNAKE_CASE = {} for epoch in range(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): model.train() for step, batch in enumerate(SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE = model(**SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE = outputs.loss SCREAMING_SNAKE_CASE = loss / gradient_accumulation_steps accelerator.backward(SCREAMING_SNAKE_CASE_ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 SCREAMING_SNAKE_CASE = F'epoch_{epoch}' SCREAMING_SNAKE_CASE = os.path.join(args.output_dir , SCREAMING_SNAKE_CASE_ ) accelerator.save_state(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE = evaluation_loop(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE = accuracy SCREAMING_SNAKE_CASE = lr_scheduler.get_lr()[0] SCREAMING_SNAKE_CASE = optimizer.param_groups[0]['lr'] SCREAMING_SNAKE_CASE = epoch SCREAMING_SNAKE_CASE = overall_step accelerator.print(F'epoch {epoch}:' , SCREAMING_SNAKE_CASE_ ) accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir , F'state_{epoch}.json' ) , 'w' ) as f: json.dump(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def lowercase () -> Dict: SCREAMING_SNAKE_CASE = argparse.ArgumentParser(description='Simple example of training script tracking peak GPU memory usage.' ) parser.add_argument( '--model_name_or_path' , type=SCREAMING_SNAKE_CASE_ , default='bert-base-cased' , help='Path to pretrained model or model identifier from huggingface.co/models.' , required=SCREAMING_SNAKE_CASE_ , ) parser.add_argument( '--output_dir' , type=SCREAMING_SNAKE_CASE_ , default='.' , help='Optional save directory where all checkpoint folders will be stored. Default is the current working directory.' , ) parser.add_argument( '--resume_from_checkpoint' , type=SCREAMING_SNAKE_CASE_ , default=SCREAMING_SNAKE_CASE_ , help='If the training should continue from a checkpoint folder.' , ) parser.add_argument( '--partial_train_epoch' , type=SCREAMING_SNAKE_CASE_ , default=SCREAMING_SNAKE_CASE_ , help='If passed, the training will stop after this number of epochs.' , ) parser.add_argument( '--num_epochs' , type=SCREAMING_SNAKE_CASE_ , default=2 , help='Number of train epochs.' , ) SCREAMING_SNAKE_CASE = parser.parse_args() SCREAMING_SNAKE_CASE = {'lr': 2E-5, 'num_epochs': args.num_epochs, 'seed': 42, 'batch_size': 16} training_function(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": main()
247
"""simple docstring""" from __future__ import annotations __UpperCamelCase = [-10, -5, 0, 5, 5.1, 11, 13, 21, 3, 4, -21, -10, -5, -1, 0] __UpperCamelCase = [-5, 0, 5, 5.1, 11, 13, 21, -1, 4, -1, -10, -5, -1, 0, -1] def lowercase (SCREAMING_SNAKE_CASE_ : list[float] ) -> list[float]: SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = len(SCREAMING_SNAKE_CASE_ ) for i in range(SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE = -1 for j in range(i + 1 , SCREAMING_SNAKE_CASE_ ): if arr[i] < arr[j]: SCREAMING_SNAKE_CASE = arr[j] break result.append(SCREAMING_SNAKE_CASE_ ) return result def lowercase (SCREAMING_SNAKE_CASE_ : list[float] ) -> list[float]: SCREAMING_SNAKE_CASE = [] for i, outer in enumerate(SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE = -1 for inner in arr[i + 1 :]: if outer < inner: SCREAMING_SNAKE_CASE = inner break result.append(SCREAMING_SNAKE_CASE_ ) return result def lowercase (SCREAMING_SNAKE_CASE_ : list[float] ) -> list[float]: SCREAMING_SNAKE_CASE = len(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = [-1] * arr_size for index in reversed(range(SCREAMING_SNAKE_CASE_ ) ): if stack: while stack[-1] <= arr[index]: stack.pop() if not stack: break if stack: SCREAMING_SNAKE_CASE = stack[-1] stack.append(arr[index] ) return result if __name__ == "__main__": from doctest import testmod from timeit import timeit testmod() print(next_greatest_element_slow(arr)) print(next_greatest_element_fast(arr)) print(next_greatest_element(arr)) __UpperCamelCase = ( '''from __main__ import arr, next_greatest_element_slow, ''' '''next_greatest_element_fast, next_greatest_element''' ) print( '''next_greatest_element_slow():''', timeit('''next_greatest_element_slow(arr)''', setup=setup), ) print( '''next_greatest_element_fast():''', timeit('''next_greatest_element_fast(arr)''', setup=setup), ) print( ''' next_greatest_element():''', timeit('''next_greatest_element(arr)''', setup=setup), )
247
1
from typing import Dict, List, Optional, Tuple, Union import torch from ...models import AutoencoderKL, TransformeraDModel from ...schedulers import KarrasDiffusionSchedulers from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class __SCREAMING_SNAKE_CASE ( UpperCAmelCase__ ): def __init__( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = None , ): super().__init__() self.register_modules(transformer=__lowerCAmelCase , vae=__lowerCAmelCase , scheduler=__lowerCAmelCase ) # create a imagenet -> id dictionary for easier use UpperCamelCase__ = {} if idalabel is not None: for key, value in idalabel.items(): for label in value.split(""",""" ): UpperCamelCase__ = int(__lowerCAmelCase ) UpperCamelCase__ = dict(sorted(self.labels.items() ) ) def _lowerCamelCase ( self , __lowerCAmelCase ): if not isinstance(__lowerCAmelCase , __lowerCAmelCase ): UpperCamelCase__ = list(__lowerCAmelCase ) for l in label: if l not in self.labels: raise ValueError( f"""{l} does not exist. Please make sure to select one of the following labels: \n {self.labels}.""" ) return [self.labels[l] for l in label] @torch.no_grad() def __call__( self , __lowerCAmelCase , __lowerCAmelCase = 4.0 , __lowerCAmelCase = None , __lowerCAmelCase = 50 , __lowerCAmelCase = "pil" , __lowerCAmelCase = True , ): UpperCamelCase__ = len(__lowerCAmelCase ) UpperCamelCase__ = self.transformer.config.sample_size UpperCamelCase__ = self.transformer.config.in_channels UpperCamelCase__ = randn_tensor( shape=(batch_size, latent_channels, latent_size, latent_size) , generator=__lowerCAmelCase , device=self.device , dtype=self.transformer.dtype , ) UpperCamelCase__ = torch.cat([latents] * 2 ) if guidance_scale > 1 else latents UpperCamelCase__ = torch.tensor(__lowerCAmelCase , device=self.device ).reshape(-1 ) UpperCamelCase__ = torch.tensor([1000] * batch_size , device=self.device ) UpperCamelCase__ = torch.cat([class_labels, class_null] , 0 ) if guidance_scale > 1 else class_labels # set step values self.scheduler.set_timesteps(__lowerCAmelCase ) for t in self.progress_bar(self.scheduler.timesteps ): if guidance_scale > 1: UpperCamelCase__ = latent_model_input[: len(__lowerCAmelCase ) // 2] UpperCamelCase__ = torch.cat([half, half] , dim=0 ) UpperCamelCase__ = self.scheduler.scale_model_input(__lowerCAmelCase , __lowerCAmelCase ) UpperCamelCase__ = t if not torch.is_tensor(__lowerCAmelCase ): # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can # This would be a good case for the `match` statement (Python 3.10+) UpperCamelCase__ = latent_model_input.device.type == """mps""" if isinstance(__lowerCAmelCase , __lowerCAmelCase ): UpperCamelCase__ = torch.floataa if is_mps else torch.floataa else: UpperCamelCase__ = torch.intaa if is_mps else torch.intaa UpperCamelCase__ = torch.tensor([timesteps] , dtype=__lowerCAmelCase , device=latent_model_input.device ) elif len(timesteps.shape ) == 0: UpperCamelCase__ = timesteps[None].to(latent_model_input.device ) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML UpperCamelCase__ = timesteps.expand(latent_model_input.shape[0] ) # predict noise model_output UpperCamelCase__ = self.transformer( __lowerCAmelCase , timestep=__lowerCAmelCase , class_labels=__lowerCAmelCase ).sample # perform guidance if guidance_scale > 1: UpperCamelCase__ , UpperCamelCase__ = noise_pred[:, :latent_channels], noise_pred[:, latent_channels:] UpperCamelCase__ , UpperCamelCase__ = torch.split(__lowerCAmelCase , len(__lowerCAmelCase ) // 2 , dim=0 ) UpperCamelCase__ = uncond_eps + guidance_scale * (cond_eps - uncond_eps) UpperCamelCase__ = torch.cat([half_eps, half_eps] , dim=0 ) UpperCamelCase__ = torch.cat([eps, rest] , dim=1 ) # learned sigma if self.transformer.config.out_channels // 2 == latent_channels: UpperCamelCase__ , UpperCamelCase__ = torch.split(__lowerCAmelCase , __lowerCAmelCase , dim=1 ) else: UpperCamelCase__ = noise_pred # compute previous image: x_t -> x_t-1 UpperCamelCase__ = self.scheduler.step(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ).prev_sample if guidance_scale > 1: UpperCamelCase__ , UpperCamelCase__ = latent_model_input.chunk(2 , dim=0 ) else: UpperCamelCase__ = latent_model_input UpperCamelCase__ = 1 / self.vae.config.scaling_factor * latents UpperCamelCase__ = self.vae.decode(__lowerCAmelCase ).sample UpperCamelCase__ = (samples / 2 + 0.5).clamp(0 , 1 ) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 UpperCamelCase__ = samples.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": UpperCamelCase__ = self.numpy_to_pil(__lowerCAmelCase ) if not return_dict: return (samples,) return ImagePipelineOutput(images=__lowerCAmelCase )
710
import argparse import datetime def _UpperCamelCase (a__ :str ): """simple docstring""" UpperCamelCase__ = { """0""": """Sunday""", """1""": """Monday""", """2""": """Tuesday""", """3""": """Wednesday""", """4""": """Thursday""", """5""": """Friday""", """6""": """Saturday""", } UpperCamelCase__ = {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 0} # Validate if not 0 < len(a__ ) < 11: raise ValueError("""Must be 10 characters long""" ) # Get month UpperCamelCase__ = int(date_input[0] + date_input[1] ) # Validate if not 0 < m < 13: raise ValueError("""Month must be between 1 - 12""" ) UpperCamelCase__ = date_input[2] # Validate if sep_a not in ["-", "/"]: raise ValueError("""Date separator must be '-' or '/'""" ) # Get day UpperCamelCase__ = int(date_input[3] + date_input[4] ) # Validate if not 0 < d < 32: raise ValueError("""Date must be between 1 - 31""" ) # Get second separator UpperCamelCase__ = date_input[5] # Validate if sep_a not in ["-", "/"]: raise ValueError("""Date separator must be '-' or '/'""" ) # Get year UpperCamelCase__ = int(date_input[6] + date_input[7] + date_input[8] + date_input[9] ) # Arbitrary year range if not 45 < y < 8500: raise ValueError( """Year out of range. There has to be some sort of limit...right?""" ) # Get datetime obj for validation UpperCamelCase__ = datetime.date(int(a__ ) , int(a__ ) , int(a__ ) ) # Start math if m <= 2: UpperCamelCase__ = y - 1 UpperCamelCase__ = m + 12 # maths var UpperCamelCase__ = int(str(a__ )[:2] ) UpperCamelCase__ = int(str(a__ )[2:] ) UpperCamelCase__ = int(2.6 * m - 5.39 ) UpperCamelCase__ = int(c / 4 ) UpperCamelCase__ = int(k / 4 ) UpperCamelCase__ = int(d + k ) UpperCamelCase__ = int(t + u + v + x ) UpperCamelCase__ = int(z - (2 * c) ) UpperCamelCase__ = round(w % 7 ) # End math # Validate math if f != convert_datetime_days[dt_ck.weekday()]: raise AssertionError("""The date was evaluated incorrectly. Contact developer.""" ) # Response UpperCamelCase__ = f"""Your date {date_input}, is a {days[str(a__ )]}!""" return response if __name__ == "__main__": import doctest doctest.testmod() UpperCamelCase__ = argparse.ArgumentParser( description=( "Find out what day of the week nearly any date is or was. Enter " "date as a string in the mm-dd-yyyy or mm/dd/yyyy format" ) ) parser.add_argument( "date_input", type=str, help="Date as a string (mm-dd-yyyy or mm/dd/yyyy)" ) UpperCamelCase__ = parser.parse_args() zeller(args.date_input)
548
0
"""simple docstring""" def _snake_case ( _snake_case : int = 10_00 ) -> int: '''simple docstring''' _A = 2**power _A = str(_snake_case ) _A = list(_snake_case ) _A = 0 for i in list_num: sum_of_num += int(_snake_case ) return sum_of_num if __name__ == "__main__": a = int(input('''Enter the power of 2: ''').strip()) print('''2 ^ ''', power, ''' = ''', 2**power) a = solution(power) print('''Sum of the digits is: ''', result)
7
import torch from transformers import CamembertForMaskedLM, CamembertTokenizer def lowerCamelCase_ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase=5 ): # Adapted from https://github.com/pytorch/fairseq/blob/master/fairseq/models/roberta/hub_interface.py assert masked_input.count('''<mask>''' ) == 1 A_ = torch.tensor(tokenizer.encode(__UpperCamelCase , add_special_tokens=__UpperCamelCase ) ).unsqueeze(0 ) # Batch size 1 A_ = model(__UpperCamelCase )[0] # The last hidden-state is the first element of the output tuple A_ = (input_ids.squeeze() == tokenizer.mask_token_id).nonzero().item() A_ = logits[0, masked_index, :] A_ = logits.softmax(dim=0 ) A_ , A_ = prob.topk(k=__UpperCamelCase , dim=0 ) A_ = ''' '''.join( [tokenizer.convert_ids_to_tokens(indices[i].item() ) for i in range(len(__UpperCamelCase ) )] ) A_ = tokenizer.mask_token A_ = [] for index, predicted_token_bpe in enumerate(topk_predicted_token_bpe.split(''' ''' ) ): A_ = predicted_token_bpe.replace('''\u2581''' , ''' ''' ) if " {0}".format(__UpperCamelCase ) in masked_input: topk_filled_outputs.append( ( masked_input.replace(''' {0}'''.format(__UpperCamelCase ) , __UpperCamelCase ), values[index].item(), predicted_token, ) ) else: topk_filled_outputs.append( ( masked_input.replace(__UpperCamelCase , __UpperCamelCase ), values[index].item(), predicted_token, ) ) return topk_filled_outputs SCREAMING_SNAKE_CASE : Optional[int] = CamembertTokenizer.from_pretrained("camembert-base") SCREAMING_SNAKE_CASE : Optional[int] = CamembertForMaskedLM.from_pretrained("camembert-base") model.eval() SCREAMING_SNAKE_CASE : List[Any] = "Le camembert est <mask> :)" print(fill_mask(masked_input, model, tokenizer, topk=3))
141
0
"""simple docstring""" import math from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin @dataclass # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->UnCLIP class _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCAmelCase = 42 __UpperCAmelCase = None def __lowerCAmelCase ( __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Tuple=0.999 , __lowerCAmelCase : List[Any]="cosine" , ) -> List[Any]: if alpha_transform_type == "cosine": def alpha_bar_fn(__lowerCAmelCase : List[str] ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(__lowerCAmelCase : Dict ): return math.exp(t * -12.0 ) else: raise ValueError(f"Unsupported alpha_tranform_type: {alpha_transform_type}" ) _UpperCamelCase : List[Any] = [] for i in range(__lowerCAmelCase ): _UpperCamelCase : Any = i / num_diffusion_timesteps _UpperCamelCase : str = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(__lowerCAmelCase ) / alpha_bar_fn(__lowerCAmelCase ) , __lowerCAmelCase ) ) return torch.tensor(__lowerCAmelCase , dtype=torch.floataa ) class _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' @register_to_config def __init__(self , lowerCAmelCase__ = 10_00 , lowerCAmelCase__ = "fixed_small_log" , lowerCAmelCase__ = True , lowerCAmelCase__ = 1.0 , lowerCAmelCase__ = "epsilon" , lowerCAmelCase__ = "squaredcos_cap_v2" , ): '''simple docstring''' if beta_schedule != "squaredcos_cap_v2": raise ValueError("UnCLIPScheduler only supports `beta_schedule`: 'squaredcos_cap_v2'" ) _UpperCamelCase : int = betas_for_alpha_bar(lowerCAmelCase__ ) _UpperCamelCase : str = 1.0 - self.betas _UpperCamelCase : List[Any] = torch.cumprod(self.alphas , dim=0 ) _UpperCamelCase : Tuple = torch.tensor(1.0 ) # standard deviation of the initial noise distribution _UpperCamelCase : List[str] = 1.0 # setable values _UpperCamelCase : str = None _UpperCamelCase : List[str] = torch.from_numpy(np.arange(0 , lowerCAmelCase__ )[::-1].copy() ) _UpperCamelCase : Optional[int] = variance_type def lowercase_ (self , lowerCAmelCase__ , lowerCAmelCase__ = None ): '''simple docstring''' return sample def lowercase_ (self , lowerCAmelCase__ , lowerCAmelCase__ = None ): '''simple docstring''' _UpperCamelCase : Union[str, Any] = num_inference_steps _UpperCamelCase : Optional[Any] = (self.config.num_train_timesteps - 1) / (self.num_inference_steps - 1) _UpperCamelCase : List[Any] = (np.arange(0 , lowerCAmelCase__ ) * step_ratio).round()[::-1].copy().astype(np.intaa ) _UpperCamelCase : Dict = torch.from_numpy(lowerCAmelCase__ ).to(lowerCAmelCase__ ) def lowercase_ (self , lowerCAmelCase__ , lowerCAmelCase__=None , lowerCAmelCase__=None , lowerCAmelCase__=None ): '''simple docstring''' if prev_timestep is None: _UpperCamelCase : List[str] = t - 1 _UpperCamelCase : Union[str, Any] = self.alphas_cumprod[t] _UpperCamelCase : Optional[Any] = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.one _UpperCamelCase : Tuple = 1 - alpha_prod_t _UpperCamelCase : Optional[int] = 1 - alpha_prod_t_prev if prev_timestep == t - 1: _UpperCamelCase : Dict = self.betas[t] else: _UpperCamelCase : List[Any] = 1 - alpha_prod_t / alpha_prod_t_prev # For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf) # and sample from it to get previous sample # x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample _UpperCamelCase : List[Any] = beta_prod_t_prev / beta_prod_t * beta if variance_type is None: _UpperCamelCase : Optional[int] = self.config.variance_type # hacks - were probably added for training stability if variance_type == "fixed_small_log": _UpperCamelCase : str = torch.log(torch.clamp(lowerCAmelCase__ , min=1E-20 ) ) _UpperCamelCase : Dict = torch.exp(0.5 * variance ) elif variance_type == "learned_range": # NOTE difference with DDPM scheduler _UpperCamelCase : Tuple = variance.log() _UpperCamelCase : Optional[int] = beta.log() _UpperCamelCase : Optional[Any] = (predicted_variance + 1) / 2 _UpperCamelCase : List[str] = frac * max_log + (1 - frac) * min_log return variance def lowercase_ (self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = None , lowerCAmelCase__=None , lowerCAmelCase__ = True , ): '''simple docstring''' _UpperCamelCase : Union[str, Any] = timestep if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type == "learned_range": _UpperCamelCase , _UpperCamelCase : List[str] = torch.split(lowerCAmelCase__ , sample.shape[1] , dim=1 ) else: _UpperCamelCase : List[str] = None # 1. compute alphas, betas if prev_timestep is None: _UpperCamelCase : Optional[int] = t - 1 _UpperCamelCase : Union[str, Any] = self.alphas_cumprod[t] _UpperCamelCase : List[str] = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.one _UpperCamelCase : Any = 1 - alpha_prod_t _UpperCamelCase : Tuple = 1 - alpha_prod_t_prev if prev_timestep == t - 1: _UpperCamelCase : Tuple = self.betas[t] _UpperCamelCase : List[Any] = self.alphas[t] else: _UpperCamelCase : Dict = 1 - alpha_prod_t / alpha_prod_t_prev _UpperCamelCase : str = 1 - beta # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if self.config.prediction_type == "epsilon": _UpperCamelCase : Dict = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif self.config.prediction_type == "sample": _UpperCamelCase : str = model_output else: raise ValueError( F"prediction_type given as {self.config.prediction_type} must be one of `epsilon` or `sample`" " for the UnCLIPScheduler." ) # 3. Clip "predicted x_0" if self.config.clip_sample: _UpperCamelCase : List[str] = torch.clamp( lowerCAmelCase__ , -self.config.clip_sample_range , self.config.clip_sample_range ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf _UpperCamelCase : Optional[Any] = (alpha_prod_t_prev ** 0.5 * beta) / beta_prod_t _UpperCamelCase : Optional[int] = alpha ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf _UpperCamelCase : Union[str, Any] = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise _UpperCamelCase : Tuple = 0 if t > 0: _UpperCamelCase : Optional[Any] = randn_tensor( model_output.shape , dtype=model_output.dtype , generator=lowerCAmelCase__ , device=model_output.device ) _UpperCamelCase : Optional[Any] = self._get_variance( lowerCAmelCase__ , predicted_variance=lowerCAmelCase__ , prev_timestep=lowerCAmelCase__ , ) if self.variance_type == "fixed_small_log": _UpperCamelCase : Union[str, Any] = variance elif self.variance_type == "learned_range": _UpperCamelCase : str = (0.5 * variance).exp() else: raise ValueError( F"variance_type given as {self.variance_type} must be one of `fixed_small_log` or `learned_range`" " for the UnCLIPScheduler." ) _UpperCamelCase : int = variance * variance_noise _UpperCamelCase : Union[str, Any] = pred_prev_sample + variance if not return_dict: return (pred_prev_sample,) return UnCLIPSchedulerOutput(prev_sample=lowerCAmelCase__ , pred_original_sample=lowerCAmelCase__ ) def lowercase_ (self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , ): '''simple docstring''' _UpperCamelCase : Optional[Any] = self.alphas_cumprod.to(device=original_samples.device , dtype=original_samples.dtype ) _UpperCamelCase : str = timesteps.to(original_samples.device ) _UpperCamelCase : str = alphas_cumprod[timesteps] ** 0.5 _UpperCamelCase : Optional[int] = sqrt_alpha_prod.flatten() while len(sqrt_alpha_prod.shape ) < len(original_samples.shape ): _UpperCamelCase : Union[str, Any] = sqrt_alpha_prod.unsqueeze(-1 ) _UpperCamelCase : Optional[int] = (1 - alphas_cumprod[timesteps]) ** 0.5 _UpperCamelCase : List[Any] = sqrt_one_minus_alpha_prod.flatten() while len(sqrt_one_minus_alpha_prod.shape ) < len(original_samples.shape ): _UpperCamelCase : Tuple = sqrt_one_minus_alpha_prod.unsqueeze(-1 ) _UpperCamelCase : List[str] = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise return noisy_samples
239
"""simple docstring""" from math import ceil def __lowerCAmelCase ( __lowerCAmelCase : int = 1001 ) -> int: _UpperCamelCase : Tuple = 1 for i in range(1 , int(ceil(n / 2.0 ) ) ): _UpperCamelCase : Tuple = 2 * i + 1 _UpperCamelCase : Optional[Any] = 2 * i _UpperCamelCase : Optional[int] = total + 4 * odd**2 - 6 * even return total if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution()) else: try: _SCREAMING_SNAKE_CASE = int(sys.argv[1]) print(solution(n)) except ValueError: print("""Invalid entry - please enter a number""")
239
1
'''simple docstring''' def a ( __a = 1000000 ) -> int: '''simple docstring''' UpperCamelCase__ :str = set(range(3 , snake_case_ , 2 ) ) primes.add(2 ) for p in range(3 , snake_case_ , 2 ): if p not in primes: continue primes.difference_update(set(range(p * p , snake_case_ , snake_case_ ) ) ) UpperCamelCase__ :str = [float(snake_case_ ) for n in range(limit + 1 )] for p in primes: for n in range(snake_case_ , limit + 1 , snake_case_ ): phi[n] *= 1 - 1 / p return int(sum(phi[2:] ) ) if __name__ == "__main__": print(F"""{solution() = }""")
189
"""simple docstring""" import requests a_ = """https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=""" def __lowercase ( snake_case_ : str ) ->None: '''simple docstring''' __A : str = requests.get(_NEWS_API + bbc_news_api_key ).json() # each article in the list is a dict for i, article in enumerate(bbc_news_page['''articles'''] ,1 ): print(F"""{i}.) {article['title']}""" ) if __name__ == "__main__": fetch_bbc_news(bbc_news_api_key="""<Your BBC News API key goes here>""")
177
0
import argparse import json from collections import OrderedDict import torch from huggingface_hub import cached_download, hf_hub_url from transformers import AutoImageProcessor, CvtConfig, CvtForImageClassification def lowerCamelCase__ ( snake_case_ : Optional[int] ) -> Dict: __snake_case = [] embed.append( ( f"""cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.weight""", f"""stage{idx}.patch_embed.proj.weight""", ) ) embed.append( ( f"""cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.bias""", f"""stage{idx}.patch_embed.proj.bias""", ) ) embed.append( ( f"""cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.weight""", f"""stage{idx}.patch_embed.norm.weight""", ) ) embed.append( ( f"""cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.bias""", f"""stage{idx}.patch_embed.norm.bias""", ) ) return embed def lowerCamelCase__ ( snake_case_ : Union[str, Any] , snake_case_ : int ) -> str: __snake_case = [] attention_weights.append( ( f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.convolution.weight""", f"""stage{idx}.blocks.{cnt}.attn.conv_proj_q.conv.weight""", ) ) attention_weights.append( ( f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.weight""", f"""stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.weight""", ) ) attention_weights.append( ( f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.bias""", f"""stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.bias""", ) ) attention_weights.append( ( f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_mean""", f"""stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_mean""", ) ) attention_weights.append( ( f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_var""", f"""stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_var""", ) ) attention_weights.append( ( f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.num_batches_tracked""", f"""stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.num_batches_tracked""", ) ) attention_weights.append( ( f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.convolution.weight""", f"""stage{idx}.blocks.{cnt}.attn.conv_proj_k.conv.weight""", ) ) attention_weights.append( ( f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.weight""", f"""stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.weight""", ) ) attention_weights.append( ( f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.bias""", f"""stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.bias""", ) ) attention_weights.append( ( f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_mean""", f"""stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_mean""", ) ) attention_weights.append( ( f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_var""", f"""stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_var""", ) ) attention_weights.append( ( f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.num_batches_tracked""", f"""stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.num_batches_tracked""", ) ) attention_weights.append( ( f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.convolution.weight""", f"""stage{idx}.blocks.{cnt}.attn.conv_proj_v.conv.weight""", ) ) attention_weights.append( ( f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.weight""", f"""stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.weight""", ) ) attention_weights.append( ( f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.bias""", f"""stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.bias""", ) ) attention_weights.append( ( f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_mean""", f"""stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_mean""", ) ) attention_weights.append( ( f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_var""", f"""stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_var""", ) ) attention_weights.append( ( f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.num_batches_tracked""", f"""stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.num_batches_tracked""", ) ) attention_weights.append( ( f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.weight""", f"""stage{idx}.blocks.{cnt}.attn.proj_q.weight""", ) ) attention_weights.append( ( f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.bias""", f"""stage{idx}.blocks.{cnt}.attn.proj_q.bias""", ) ) attention_weights.append( ( f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.weight""", f"""stage{idx}.blocks.{cnt}.attn.proj_k.weight""", ) ) attention_weights.append( ( f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.bias""", f"""stage{idx}.blocks.{cnt}.attn.proj_k.bias""", ) ) attention_weights.append( ( f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.weight""", f"""stage{idx}.blocks.{cnt}.attn.proj_v.weight""", ) ) attention_weights.append( ( f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.bias""", f"""stage{idx}.blocks.{cnt}.attn.proj_v.bias""", ) ) attention_weights.append( ( f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.weight""", f"""stage{idx}.blocks.{cnt}.attn.proj.weight""", ) ) attention_weights.append( ( f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.bias""", f"""stage{idx}.blocks.{cnt}.attn.proj.bias""", ) ) attention_weights.append( (f"""cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.weight""", f"""stage{idx}.blocks.{cnt}.mlp.fc1.weight""") ) attention_weights.append( (f"""cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.bias""", f"""stage{idx}.blocks.{cnt}.mlp.fc1.bias""") ) attention_weights.append( (f"""cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.weight""", f"""stage{idx}.blocks.{cnt}.mlp.fc2.weight""") ) attention_weights.append( (f"""cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.bias""", f"""stage{idx}.blocks.{cnt}.mlp.fc2.bias""") ) attention_weights.append( (f"""cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.weight""", f"""stage{idx}.blocks.{cnt}.norm1.weight""") ) attention_weights.append( (f"""cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.bias""", f"""stage{idx}.blocks.{cnt}.norm1.bias""") ) attention_weights.append( (f"""cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.weight""", f"""stage{idx}.blocks.{cnt}.norm2.weight""") ) attention_weights.append( (f"""cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.bias""", f"""stage{idx}.blocks.{cnt}.norm2.bias""") ) return attention_weights def lowerCamelCase__ ( snake_case_ : Tuple ) -> str: __snake_case = [] token.append((f"""cvt.encoder.stages.{idx}.cls_token""", '''stage2.cls_token''') ) return token def lowerCamelCase__ ( ) -> Any: __snake_case = [] head.append(('''layernorm.weight''', '''norm.weight''') ) head.append(('''layernorm.bias''', '''norm.bias''') ) head.append(('''classifier.weight''', '''head.weight''') ) head.append(('''classifier.bias''', '''head.bias''') ) return head def lowerCamelCase__ ( snake_case_ : Union[str, Any] , snake_case_ : Optional[int] , snake_case_ : Any , snake_case_ : Tuple ) -> Optional[Any]: __snake_case = '''imagenet-1k-id2label.json''' __snake_case = 1000 __snake_case = '''huggingface/label-files''' __snake_case = num_labels __snake_case = json.load(open(cached_download(hf_hub_url(__lowerCAmelCase , __lowerCAmelCase , repo_type='''dataset''' ) ) , '''r''' ) ) __snake_case = {int(__lowerCAmelCase ): v for k, v in idalabel.items()} __snake_case = idalabel __snake_case = {v: k for k, v in idalabel.items()} __snake_case = __snake_case = CvtConfig(num_labels=__lowerCAmelCase , idalabel=__lowerCAmelCase , labelaid=__lowerCAmelCase ) # For depth size 13 (13 = 1+2+10) if cvt_model.rsplit('''/''' , 1 )[-1][4:6] == "13": __snake_case = [1, 2, 10] # For depth size 21 (21 = 1+4+16) elif cvt_model.rsplit('''/''' , 1 )[-1][4:6] == "21": __snake_case = [1, 4, 16] # For wide cvt (similar to wide-resnet) depth size 24 (w24 = 2 + 2 20) else: __snake_case = [2, 2, 20] __snake_case = [3, 12, 16] __snake_case = [192, 768, 1024] __snake_case = CvtForImageClassification(__lowerCAmelCase ) __snake_case = AutoImageProcessor.from_pretrained('''facebook/convnext-base-224-22k-1k''' ) __snake_case = image_size __snake_case = torch.load(__lowerCAmelCase , map_location=torch.device('''cpu''' ) ) __snake_case = OrderedDict() __snake_case = [] for idx in range(len(config.depth ) ): if config.cls_token[idx]: __snake_case = list_of_state_dict + cls_token(__lowerCAmelCase ) __snake_case = list_of_state_dict + embeddings(__lowerCAmelCase ) for cnt in range(config.depth[idx] ): __snake_case = list_of_state_dict + attention(__lowerCAmelCase , __lowerCAmelCase ) __snake_case = list_of_state_dict + final() for gg in list_of_state_dict: print(__lowerCAmelCase ) for i in range(len(__lowerCAmelCase ) ): __snake_case = original_weights[list_of_state_dict[i][1]] model.load_state_dict(__lowerCAmelCase ) model.save_pretrained(__lowerCAmelCase ) image_processor.save_pretrained(__lowerCAmelCase ) # Download the weights from zoo: https://1drv.ms/u/s!AhIXJn_J-blW9RzF3rMW7SsLHa8h?e=blQ0Al if __name__ == "__main__": snake_case_ = argparse.ArgumentParser() parser.add_argument( '--cvt_model', default='cvt-w24', type=str, help='Name of the cvt model you\'d like to convert.', ) parser.add_argument( '--image_size', default=384, type=int, help='Input Image Size', ) parser.add_argument( '--cvt_file_name', default=R'cvtmodels\CvT-w24-384x384-IN-22k.pth', type=str, help='Input Image Size', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) snake_case_ = parser.parse_args() convert_cvt_checkpoint(args.cvt_model, args.image_size, args.cvt_file_name, args.pytorch_dump_folder_path)
712
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) snake_case_ = { 'configuration_electra': ['ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ElectraConfig', 'ElectraOnnxConfig'], 'tokenization_electra': ['ElectraTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ = ['ElectraTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ = [ 'ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST', 'ElectraForCausalLM', 'ElectraForMaskedLM', 'ElectraForMultipleChoice', 'ElectraForPreTraining', 'ElectraForQuestionAnswering', 'ElectraForSequenceClassification', 'ElectraForTokenClassification', 'ElectraModel', 'ElectraPreTrainedModel', 'load_tf_weights_in_electra', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ = [ 'TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFElectraForMaskedLM', 'TFElectraForMultipleChoice', 'TFElectraForPreTraining', 'TFElectraForQuestionAnswering', 'TFElectraForSequenceClassification', 'TFElectraForTokenClassification', 'TFElectraModel', 'TFElectraPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ = [ 'FlaxElectraForCausalLM', 'FlaxElectraForMaskedLM', 'FlaxElectraForMultipleChoice', 'FlaxElectraForPreTraining', 'FlaxElectraForQuestionAnswering', 'FlaxElectraForSequenceClassification', 'FlaxElectraForTokenClassification', 'FlaxElectraModel', 'FlaxElectraPreTrainedModel', ] if TYPE_CHECKING: from .configuration_electra import ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ElectraConfig, ElectraOnnxConfig from .tokenization_electra import ElectraTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_electra_fast import ElectraTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_electra import ( ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST, ElectraForCausalLM, ElectraForMaskedLM, ElectraForMultipleChoice, ElectraForPreTraining, ElectraForQuestionAnswering, ElectraForSequenceClassification, ElectraForTokenClassification, ElectraModel, ElectraPreTrainedModel, load_tf_weights_in_electra, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_electra import ( TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST, TFElectraForMaskedLM, TFElectraForMultipleChoice, TFElectraForPreTraining, TFElectraForQuestionAnswering, TFElectraForSequenceClassification, TFElectraForTokenClassification, TFElectraModel, TFElectraPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_electra import ( FlaxElectraForCausalLM, FlaxElectraForMaskedLM, FlaxElectraForMultipleChoice, FlaxElectraForPreTraining, FlaxElectraForQuestionAnswering, FlaxElectraForSequenceClassification, FlaxElectraForTokenClassification, FlaxElectraModel, FlaxElectraPreTrainedModel, ) else: import sys snake_case_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
388
0
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow 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 DetaImageProcessor class _a ( unittest.TestCase ): """simple docstring""" def __init__( self , _snake_case , _snake_case=7 , _snake_case=3 , _snake_case=30 , _snake_case=400 , _snake_case=True , _snake_case=None , _snake_case=True , _snake_case=[0.5, 0.5, 0.5] , _snake_case=[0.5, 0.5, 0.5] , _snake_case=True , _snake_case=1 / 255 , _snake_case=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p _UpperCAmelCase =size if size is not None else {"shortest_edge": 18, "longest_edge": 1333} _UpperCAmelCase =parent _UpperCAmelCase =batch_size _UpperCAmelCase =num_channels _UpperCAmelCase =min_resolution _UpperCAmelCase =max_resolution _UpperCAmelCase =do_resize _UpperCAmelCase =size _UpperCAmelCase =do_normalize _UpperCAmelCase =image_mean _UpperCAmelCase =image_std _UpperCAmelCase =do_rescale _UpperCAmelCase =rescale_factor _UpperCAmelCase =do_pad def SCREAMING_SNAKE_CASE ( self ): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def SCREAMING_SNAKE_CASE ( self , _snake_case , _snake_case=False ): if not batched: _UpperCAmelCase =image_inputs[0] if isinstance(_snake_case , Image.Image ): _UpperCAmelCase , _UpperCAmelCase =image.size else: _UpperCAmelCase , _UpperCAmelCase =image.shape[1], image.shape[2] if w < h: _UpperCAmelCase =int(self.size["shortest_edge"] * h / w ) _UpperCAmelCase =self.size["shortest_edge"] elif w > h: _UpperCAmelCase =self.size["shortest_edge"] _UpperCAmelCase =int(self.size["shortest_edge"] * w / h ) else: _UpperCAmelCase =self.size["shortest_edge"] _UpperCAmelCase =self.size["shortest_edge"] else: _UpperCAmelCase =[] for image in image_inputs: _UpperCAmelCase , _UpperCAmelCase =self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) _UpperCAmelCase =max(_snake_case , key=lambda _snake_case : item[0] )[0] _UpperCAmelCase =max(_snake_case , key=lambda _snake_case : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class _a ( A__ , unittest.TestCase ): """simple docstring""" snake_case =DetaImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE ( self ): _UpperCAmelCase =DetaImageProcessingTester(self ) @property def SCREAMING_SNAKE_CASE ( self ): return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE ( self ): _UpperCAmelCase =self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_snake_case , "image_mean" ) ) self.assertTrue(hasattr(_snake_case , "image_std" ) ) self.assertTrue(hasattr(_snake_case , "do_normalize" ) ) self.assertTrue(hasattr(_snake_case , "do_resize" ) ) self.assertTrue(hasattr(_snake_case , "do_rescale" ) ) self.assertTrue(hasattr(_snake_case , "do_pad" ) ) self.assertTrue(hasattr(_snake_case , "size" ) ) def SCREAMING_SNAKE_CASE ( self ): _UpperCAmelCase =self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"shortest_edge": 18, "longest_edge": 1333} ) self.assertEqual(image_processor.do_pad , _snake_case ) def SCREAMING_SNAKE_CASE ( self ): pass def SCREAMING_SNAKE_CASE ( self ): # Initialize image_processing _UpperCAmelCase =self.image_processing_class(**self.image_processor_dict ) # create random PIL images _UpperCAmelCase =prepare_image_inputs(self.image_processor_tester , equal_resolution=_snake_case ) for image in image_inputs: self.assertIsInstance(_snake_case , Image.Image ) # Test not batched input _UpperCAmelCase =image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values _UpperCAmelCase , _UpperCAmelCase =self.image_processor_tester.get_expected_values(_snake_case ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched _UpperCAmelCase , _UpperCAmelCase =self.image_processor_tester.get_expected_values(_snake_case , batched=_snake_case ) _UpperCAmelCase =image_processing(_snake_case , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE ( self ): # Initialize image_processing _UpperCAmelCase =self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _UpperCAmelCase =prepare_image_inputs(self.image_processor_tester , equal_resolution=_snake_case , numpify=_snake_case ) for image in image_inputs: self.assertIsInstance(_snake_case , np.ndarray ) # Test not batched input _UpperCAmelCase =image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values _UpperCAmelCase , _UpperCAmelCase =self.image_processor_tester.get_expected_values(_snake_case ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched _UpperCAmelCase =image_processing(_snake_case , return_tensors="pt" ).pixel_values _UpperCAmelCase , _UpperCAmelCase =self.image_processor_tester.get_expected_values(_snake_case , batched=_snake_case ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE ( self ): # Initialize image_processing _UpperCAmelCase =self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _UpperCAmelCase =prepare_image_inputs(self.image_processor_tester , equal_resolution=_snake_case , torchify=_snake_case ) for image in image_inputs: self.assertIsInstance(_snake_case , torch.Tensor ) # Test not batched input _UpperCAmelCase =image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values _UpperCAmelCase , _UpperCAmelCase =self.image_processor_tester.get_expected_values(_snake_case ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched _UpperCAmelCase =image_processing(_snake_case , return_tensors="pt" ).pixel_values _UpperCAmelCase , _UpperCAmelCase =self.image_processor_tester.get_expected_values(_snake_case , batched=_snake_case ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def SCREAMING_SNAKE_CASE ( self ): # prepare image and target _UpperCAmelCase =Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_annotations.txt" , "r" ) as f: _UpperCAmelCase =json.loads(f.read() ) _UpperCAmelCase ={"image_id": 3_9769, "annotations": target} # encode them _UpperCAmelCase =DetaImageProcessor() _UpperCAmelCase =image_processing(images=_snake_case , annotations=_snake_case , return_tensors="pt" ) # verify pixel values _UpperCAmelCase =torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding["pixel_values"].shape , _snake_case ) _UpperCAmelCase =torch.tensor([0.2_796, 0.3_138, 0.3_481] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , _snake_case , atol=1E-4 ) ) # verify area _UpperCAmelCase =torch.tensor([5_887.9_600, 11_250.2_061, 489_353.8_438, 837_122.7_500, 147_967.5_156, 165_732.3_438] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , _snake_case ) ) # verify boxes _UpperCAmelCase =torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , _snake_case ) _UpperCAmelCase =torch.tensor([0.5_503, 0.2_765, 0.0_604, 0.2_215] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , _snake_case , atol=1E-3 ) ) # verify image_id _UpperCAmelCase =torch.tensor([3_9769] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , _snake_case ) ) # verify is_crowd _UpperCAmelCase =torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , _snake_case ) ) # verify class_labels _UpperCAmelCase =torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , _snake_case ) ) # verify orig_size _UpperCAmelCase =torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , _snake_case ) ) # verify size _UpperCAmelCase =torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , _snake_case ) ) @slow def SCREAMING_SNAKE_CASE ( self ): # prepare image, target and masks_path _UpperCAmelCase =Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt" , "r" ) as f: _UpperCAmelCase =json.loads(f.read() ) _UpperCAmelCase ={"file_name": "000000039769.png", "image_id": 3_9769, "segments_info": target} _UpperCAmelCase =pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic" ) # encode them _UpperCAmelCase =DetaImageProcessor(format="coco_panoptic" ) _UpperCAmelCase =image_processing(images=_snake_case , annotations=_snake_case , masks_path=_snake_case , return_tensors="pt" ) # verify pixel values _UpperCAmelCase =torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding["pixel_values"].shape , _snake_case ) _UpperCAmelCase =torch.tensor([0.2_796, 0.3_138, 0.3_481] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , _snake_case , atol=1E-4 ) ) # verify area _UpperCAmelCase =torch.tensor([147_979.6_875, 165_527.0_469, 484_638.5_938, 11_292.9_375, 5_879.6_562, 7_634.1_147] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , _snake_case ) ) # verify boxes _UpperCAmelCase =torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , _snake_case ) _UpperCAmelCase =torch.tensor([0.2_625, 0.5_437, 0.4_688, 0.8_625] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , _snake_case , atol=1E-3 ) ) # verify image_id _UpperCAmelCase =torch.tensor([3_9769] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , _snake_case ) ) # verify is_crowd _UpperCAmelCase =torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , _snake_case ) ) # verify class_labels _UpperCAmelCase =torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , _snake_case ) ) # verify masks _UpperCAmelCase =82_2873 self.assertEqual(encoding["labels"][0]["masks"].sum().item() , _snake_case ) # verify orig_size _UpperCAmelCase =torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , _snake_case ) ) # verify size _UpperCAmelCase =torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , _snake_case ) )
408
import argparse import json import os from collections import OrderedDict import torch from transformers import LukeConfig, LukeForMaskedLM, MLukeTokenizer, XLMRobertaTokenizer from transformers.tokenization_utils_base import AddedToken @torch.no_grad() def lowerCamelCase__ ( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) ->Tuple: # Load configuration defined in the metadata file with open(_lowerCamelCase ) as metadata_file: _UpperCAmelCase =json.load(_lowerCamelCase ) _UpperCAmelCase =LukeConfig(use_entity_aware_attention=_lowerCamelCase , **metadata["model_config"] ) # Load in the weights from the checkpoint_path _UpperCAmelCase =torch.load(_lowerCamelCase , map_location="cpu" )["module"] # Load the entity vocab file _UpperCAmelCase =load_original_entity_vocab(_lowerCamelCase ) # add an entry for [MASK2] _UpperCAmelCase =max(entity_vocab.values() ) + 1 config.entity_vocab_size += 1 _UpperCAmelCase =XLMRobertaTokenizer.from_pretrained(metadata["model_config"]["bert_model_name"] ) # Add special tokens to the token vocabulary for downstream tasks _UpperCAmelCase =AddedToken("<ent>" , lstrip=_lowerCamelCase , rstrip=_lowerCamelCase ) _UpperCAmelCase =AddedToken("<ent2>" , lstrip=_lowerCamelCase , rstrip=_lowerCamelCase ) tokenizer.add_special_tokens({"additional_special_tokens": [entity_token_a, entity_token_a]} ) config.vocab_size += 2 print(F"Saving tokenizer to {pytorch_dump_folder_path}" ) tokenizer.save_pretrained(_lowerCamelCase ) with open(os.path.join(_lowerCamelCase , "tokenizer_config.json" ) , "r" ) as f: _UpperCAmelCase =json.load(_lowerCamelCase ) _UpperCAmelCase ="MLukeTokenizer" with open(os.path.join(_lowerCamelCase , "tokenizer_config.json" ) , "w" ) as f: json.dump(_lowerCamelCase , _lowerCamelCase ) with open(os.path.join(_lowerCamelCase , MLukeTokenizer.vocab_files_names["entity_vocab_file"] ) , "w" ) as f: json.dump(_lowerCamelCase , _lowerCamelCase ) _UpperCAmelCase =MLukeTokenizer.from_pretrained(_lowerCamelCase ) # Initialize the embeddings of the special tokens _UpperCAmelCase =tokenizer.convert_tokens_to_ids(["@"] )[0] _UpperCAmelCase =tokenizer.convert_tokens_to_ids(["#"] )[0] _UpperCAmelCase =state_dict["embeddings.word_embeddings.weight"] _UpperCAmelCase =word_emb[ent_init_index].unsqueeze(0 ) _UpperCAmelCase =word_emb[enta_init_index].unsqueeze(0 ) _UpperCAmelCase =torch.cat([word_emb, ent_emb, enta_emb] ) # add special tokens for 'entity_predictions.bias' for bias_name in ["lm_head.decoder.bias", "lm_head.bias"]: _UpperCAmelCase =state_dict[bias_name] _UpperCAmelCase =decoder_bias[ent_init_index].unsqueeze(0 ) _UpperCAmelCase =decoder_bias[enta_init_index].unsqueeze(0 ) _UpperCAmelCase =torch.cat([decoder_bias, ent_decoder_bias, enta_decoder_bias] ) # Initialize the query layers of the entity-aware self-attention mechanism for layer_index in range(config.num_hidden_layers ): for matrix_name in ["query.weight", "query.bias"]: _UpperCAmelCase =F"encoder.layer.{layer_index}.attention.self." _UpperCAmelCase =state_dict[prefix + matrix_name] _UpperCAmelCase =state_dict[prefix + matrix_name] _UpperCAmelCase =state_dict[prefix + matrix_name] # Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks _UpperCAmelCase =state_dict["entity_embeddings.entity_embeddings.weight"] _UpperCAmelCase =entity_emb[entity_vocab["[MASK]"]].unsqueeze(0 ) _UpperCAmelCase =torch.cat([entity_emb, entity_mask_emb] ) # add [MASK2] for 'entity_predictions.bias' _UpperCAmelCase =state_dict["entity_predictions.bias"] _UpperCAmelCase =entity_prediction_bias[entity_vocab["[MASK]"]].unsqueeze(0 ) _UpperCAmelCase =torch.cat([entity_prediction_bias, entity_mask_bias] ) _UpperCAmelCase =LukeForMaskedLM(config=_lowerCamelCase ).eval() state_dict.pop("entity_predictions.decoder.weight" ) state_dict.pop("lm_head.decoder.weight" ) state_dict.pop("lm_head.decoder.bias" ) _UpperCAmelCase =OrderedDict() for key, value in state_dict.items(): if not (key.startswith("lm_head" ) or key.startswith("entity_predictions" )): _UpperCAmelCase =state_dict[key] else: _UpperCAmelCase =state_dict[key] _UpperCAmelCase , _UpperCAmelCase =model.load_state_dict(_lowerCamelCase , strict=_lowerCamelCase ) if set(_lowerCamelCase ) != {"luke.embeddings.position_ids"}: raise ValueError(F"Unexpected unexpected_keys: {unexpected_keys}" ) if set(_lowerCamelCase ) != { "lm_head.decoder.weight", "lm_head.decoder.bias", "entity_predictions.decoder.weight", }: raise ValueError(F"Unexpected missing_keys: {missing_keys}" ) model.tie_weights() assert (model.luke.embeddings.word_embeddings.weight == model.lm_head.decoder.weight).all() assert (model.luke.entity_embeddings.entity_embeddings.weight == model.entity_predictions.decoder.weight).all() # Check outputs _UpperCAmelCase =MLukeTokenizer.from_pretrained(_lowerCamelCase , task="entity_classification" ) _UpperCAmelCase ="ISO 639-3 uses the code fas for the dialects spoken across Iran and アフガニスタン (Afghanistan)." _UpperCAmelCase =(0, 9) _UpperCAmelCase =tokenizer(_lowerCamelCase , entity_spans=[span] , return_tensors="pt" ) _UpperCAmelCase =model(**_lowerCamelCase ) # Verify word hidden states if model_size == "large": raise NotImplementedError else: # base _UpperCAmelCase =torch.Size((1, 33, 768) ) _UpperCAmelCase =torch.tensor([[0.0_892, 0.0_596, -0.2_819], [0.0_134, 0.1_199, 0.0_573], [-0.0_169, 0.0_927, 0.0_644]] ) if not (outputs.last_hidden_state.shape == expected_shape): raise ValueError( F"Outputs.last_hidden_state.shape is {outputs.last_hidden_state.shape}, Expected shape is {expected_shape}" ) if not torch.allclose(outputs.last_hidden_state[0, :3, :3] , _lowerCamelCase , atol=1e-4 ): raise ValueError # Verify entity hidden states if model_size == "large": raise NotImplementedError else: # base _UpperCAmelCase =torch.Size((1, 1, 768) ) _UpperCAmelCase =torch.tensor([[-0.1_482, 0.0_609, 0.0_322]] ) if not (outputs.entity_last_hidden_state.shape == expected_shape): raise ValueError( F"Outputs.entity_last_hidden_state.shape is {outputs.entity_last_hidden_state.shape}, Expected shape is" F" {expected_shape}" ) if not torch.allclose(outputs.entity_last_hidden_state[0, :3, :3] , _lowerCamelCase , atol=1e-4 ): raise ValueError # Verify masked word/entity prediction _UpperCAmelCase =MLukeTokenizer.from_pretrained(_lowerCamelCase ) _UpperCAmelCase ="Tokyo is the capital of <mask>." _UpperCAmelCase =(24, 30) _UpperCAmelCase =tokenizer(_lowerCamelCase , entity_spans=[span] , return_tensors="pt" ) _UpperCAmelCase =model(**_lowerCamelCase ) _UpperCAmelCase =encoding["input_ids"][0].tolist() _UpperCAmelCase =input_ids.index(tokenizer.convert_tokens_to_ids("<mask>" ) ) _UpperCAmelCase =outputs.logits[0][mask_position_id].argmax(dim=-1 ) assert "Japan" == tokenizer.decode(_lowerCamelCase ) _UpperCAmelCase =outputs.entity_logits[0][0].argmax().item() _UpperCAmelCase =[ entity for entity, entity_id in tokenizer.entity_vocab.items() if entity_id == predicted_entity_id ] assert [e for e in multilingual_predicted_entities if e.startswith("en:" )][0] == "en:Japan" # Finally, save our PyTorch model and tokenizer print("Saving PyTorch model to {}".format(_lowerCamelCase ) ) model.save_pretrained(_lowerCamelCase ) def lowerCamelCase__ ( _lowerCamelCase ) ->str: _UpperCAmelCase =["[MASK]", "[PAD]", "[UNK]"] _UpperCAmelCase =[json.loads(_lowerCamelCase ) for line in open(_lowerCamelCase )] _UpperCAmelCase ={} for entry in data: _UpperCAmelCase =entry["id"] for entity_name, language in entry["entities"]: if entity_name in SPECIAL_TOKENS: _UpperCAmelCase =entity_id break _UpperCAmelCase =F"{language}:{entity_name}" _UpperCAmelCase =entity_id return new_mapping if __name__ == "__main__": snake_case__ : Any = argparse.ArgumentParser() # Required parameters parser.add_argument('--checkpoint_path', type=str, help='Path to a pytorch_model.bin file.') parser.add_argument( '--metadata_path', default=None, type=str, help='Path to a metadata.json file, defining the configuration.' ) parser.add_argument( '--entity_vocab_path', default=None, type=str, help='Path to an entity_vocab.tsv file, containing the entity vocabulary.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to where to dump the output PyTorch model.' ) parser.add_argument( '--model_size', default='base', type=str, choices=['base', 'large'], help='Size of the model to be converted.' ) snake_case__ : int = parser.parse_args() convert_luke_checkpoint( args.checkpoint_path, args.metadata_path, args.entity_vocab_path, args.pytorch_dump_folder_path, args.model_size, )
408
1
def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase ): if a < 0 or b < 0: raise ValueError("the value of both inputs must be positive" ) __snake_case : Tuple = str(bin(lowerCamelCase_ ) )[2:] # remove the leading "0b" __snake_case : str = str(bin(lowerCamelCase_ ) )[2:] __snake_case : List[str] = max(len(lowerCamelCase_ ) , len(lowerCamelCase_ ) ) return "0b" + "".join( str(int("1" in (char_a, char_b) ) ) for char_a, char_b in zip(a_binary.zfill(lowerCamelCase_ ) , b_binary.zfill(lowerCamelCase_ ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
706
from sklearn.metrics import fa_score, matthews_corrcoef import datasets from .record_evaluation import evaluate as evaluate_record _snake_case : List[Any] = "\\n@article{wang2019superglue,\n title={SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems},\n author={Wang, Alex and Pruksachatkun, Yada and Nangia, Nikita and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R},\n journal={arXiv preprint arXiv:1905.00537},\n year={2019}\n}\n" _snake_case : Any = "\\nSuperGLUE (https://super.gluebenchmark.com/) is a new benchmark styled after\nGLUE with a new set of more difficult language understanding tasks, improved\nresources, and a new public leaderboard.\n" _snake_case : str = "\nCompute SuperGLUE evaluation metric associated to each SuperGLUE dataset.\nArgs:\n predictions: list of predictions to score. Depending on the SuperGlUE subset:\n - for 'record': list of question-answer dictionaries with the following keys:\n - 'idx': index of the question as specified by the dataset\n - 'prediction_text': the predicted answer text\n - for 'multirc': list of question-answer dictionaries with the following keys:\n - 'idx': index of the question-answer pair as specified by the dataset\n - 'prediction': the predicted answer label\n - otherwise: list of predicted labels\n references: list of reference labels. Depending on the SuperGLUE subset:\n - for 'record': list of question-answers dictionaries with the following keys:\n - 'idx': index of the question as specified by the dataset\n - 'answers': list of possible answers\n - otherwise: list of reference labels\nReturns: depending on the SuperGLUE subset:\n - for 'record':\n - 'exact_match': Exact match between answer and gold answer\n - 'f1': F1 score\n - for 'multirc':\n - 'exact_match': Exact match between answer and gold answer\n - 'f1_m': Per-question macro-F1 score\n - 'f1_a': Average F1 score over all answers\n - for 'axb':\n 'matthews_correlation': Matthew Correlation\n - for 'cb':\n - 'accuracy': Accuracy\n - 'f1': F1 score\n - for all others:\n - 'accuracy': Accuracy\nExamples:\n\n >>> super_glue_metric = datasets.load_metric('super_glue', 'copa') # any of [\"copa\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"boolq\", \"axg\"]\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'accuracy': 1.0}\n\n >>> super_glue_metric = datasets.load_metric('super_glue', 'cb')\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'accuracy': 1.0, 'f1': 1.0}\n\n >>> super_glue_metric = datasets.load_metric('super_glue', 'record')\n >>> predictions = [{'idx': {'passage': 0, 'query': 0}, 'prediction_text': 'answer'}]\n >>> references = [{'idx': {'passage': 0, 'query': 0}, 'answers': ['answer', 'another_answer']}]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'exact_match': 1.0, 'f1': 1.0}\n\n >>> super_glue_metric = datasets.load_metric('super_glue', 'multirc')\n >>> predictions = [{'idx': {'answer': 0, 'paragraph': 0, 'question': 0}, 'prediction': 0}, {'idx': {'answer': 1, 'paragraph': 2, 'question': 3}, 'prediction': 1}]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'exact_match': 1.0, 'f1_m': 1.0, 'f1_a': 1.0}\n\n >>> super_glue_metric = datasets.load_metric('super_glue', 'axb')\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'matthews_correlation': 1.0}\n" def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase ): return float((preds == labels).mean() ) def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase="binary" ): __snake_case : Union[str, Any] = simple_accuracy(__lowerCamelCase , __lowerCamelCase ) __snake_case : List[str] = float(fa_score(y_true=__lowerCamelCase , y_pred=__lowerCamelCase , average=__lowerCamelCase ) ) return { "accuracy": acc, "f1": fa, } def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase ): __snake_case : List[Any] = {} for id_pred, label in zip(__lowerCamelCase , __lowerCamelCase ): __snake_case : int = F'{id_pred["idx"]["paragraph"]}-{id_pred["idx"]["question"]}' __snake_case : str = id_pred["prediction"] if question_id in question_map: question_map[question_id].append((pred, label) ) else: __snake_case : Optional[Any] = [(pred, label)] __snake_case , __snake_case : Dict = [], [] for question, preds_labels in question_map.items(): __snake_case , __snake_case : int = zip(*__lowerCamelCase ) __snake_case : Optional[Any] = fa_score(y_true=__lowerCamelCase , y_pred=__lowerCamelCase , average="macro" ) fas.append(__lowerCamelCase ) __snake_case : Union[str, Any] = int(sum(pred == label for pred, label in preds_labels ) == len(__lowerCamelCase ) ) ems.append(__lowerCamelCase ) __snake_case : Tuple = float(sum(__lowerCamelCase ) / len(__lowerCamelCase ) ) __snake_case : Any = sum(__lowerCamelCase ) / len(__lowerCamelCase ) __snake_case : int = float(fa_score(y_true=__lowerCamelCase , y_pred=[id_pred["prediction"] for id_pred in ids_preds] ) ) return {"exact_match": em, "f1_m": fa_m, "f1_a": fa_a} @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a (datasets.Metric ): """simple docstring""" def __snake_case ( self : List[Any] ) -> Union[str, Any]: if self.config_name not in [ "boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg", ]: raise KeyError( "You should supply a configuration name selected in " "[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]" ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , codebase_urls=[] , reference_urls=[] , format="numpy" if not self.config_name == "record" and not self.config_name == "multirc" else None , ) def __snake_case ( self : Any ) -> int: if self.config_name == "record": return { "predictions": { "idx": { "passage": datasets.Value("int64" ), "query": datasets.Value("int64" ), }, "prediction_text": datasets.Value("string" ), }, "references": { "idx": { "passage": datasets.Value("int64" ), "query": datasets.Value("int64" ), }, "answers": datasets.Sequence(datasets.Value("string" ) ), }, } elif self.config_name == "multirc": return { "predictions": { "idx": { "answer": datasets.Value("int64" ), "paragraph": datasets.Value("int64" ), "question": datasets.Value("int64" ), }, "prediction": datasets.Value("int64" ), }, "references": datasets.Value("int64" ), } else: return { "predictions": datasets.Value("int64" ), "references": datasets.Value("int64" ), } def __snake_case ( self : Optional[Any] , lowerCamelCase : str , lowerCamelCase : Optional[Any] ) -> str: if self.config_name == "axb": return {"matthews_correlation": matthews_corrcoef(lowerCamelCase , lowerCamelCase )} elif self.config_name == "cb": return acc_and_fa(lowerCamelCase , lowerCamelCase , fa_avg="macro" ) elif self.config_name == "record": __snake_case : Tuple = [ { "qas": [ {"id": ref["idx"]["query"], "answers": [{"text": ans} for ans in ref["answers"]]} for ref in references ] } ] __snake_case : List[str] = {pred["idx"]["query"]: pred["prediction_text"] for pred in predictions} return evaluate_record(lowerCamelCase , lowerCamelCase )[0] elif self.config_name == "multirc": return evaluate_multirc(lowerCamelCase , lowerCamelCase ) elif self.config_name in ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]: return {"accuracy": simple_accuracy(lowerCamelCase , lowerCamelCase )} else: raise KeyError( "You should supply a configuration name selected in " "[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]" )
203
0
import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import datasets import datasets.config from .utils import require_beam class lowerCamelCase ( datasets.BeamBasedBuilder ): '''simple docstring''' def A__ ( self ): return datasets.DatasetInfo( features=datasets.Features({"content": datasets.Value("string" )} ) , supervised_keys=lowerCAmelCase , ) def A__ ( self , lowerCAmelCase , lowerCAmelCase ): return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"examples": get_test_dummy_examples()} )] def A__ ( self , lowerCAmelCase , lowerCAmelCase ): import apache_beam as beam return pipeline | "Load Examples" >> beam.Create(lowerCAmelCase ) class lowerCamelCase ( datasets.BeamBasedBuilder ): '''simple docstring''' def A__ ( self ): return datasets.DatasetInfo( features=datasets.Features({"a": datasets.Sequence({"b": datasets.Value("string" )} )} ) , supervised_keys=lowerCAmelCase , ) def A__ ( self , lowerCAmelCase , lowerCAmelCase ): return [ datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"examples": get_test_nested_examples()} ) ] def A__ ( self , lowerCAmelCase , lowerCAmelCase ): import apache_beam as beam return pipeline | "Load Examples" >> beam.Create(lowerCAmelCase ) def snake_case__ ( ) -> Dict: return [(i, {"content": content}) for i, content in enumerate(["foo", "bar", "foobar"] )] def snake_case__ ( ) -> Optional[int]: return [(i, {"a": {"b": [content]}}) for i, content in enumerate(["foo", "bar", "foobar"] )] class lowerCamelCase ( lowercase__ ): '''simple docstring''' @require_beam def A__ ( self ): UpperCAmelCase_ = len(get_test_dummy_examples() ) with tempfile.TemporaryDirectory() as tmp_cache_dir: UpperCAmelCase_ = DummyBeamDataset(cache_dir=lowerCAmelCase , beam_runner="DirectRunner" ) builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join(lowerCAmelCase , builder.name , "default" , "0.0.0" , f'''{builder.name}-train.arrow''' ) ) ) self.assertDictEqual(builder.info.features , datasets.Features({"content": datasets.Value("string" )} ) ) UpperCAmelCase_ = builder.as_dataset() self.assertEqual(dset["train"].num_rows , lowerCAmelCase ) self.assertEqual(dset["train"].info.splits["train"].num_examples , lowerCAmelCase ) self.assertDictEqual(dset["train"][0] , get_test_dummy_examples()[0][1] ) self.assertDictEqual( dset["train"][expected_num_examples - 1] , get_test_dummy_examples()[expected_num_examples - 1][1] ) self.assertTrue( os.path.exists(os.path.join(lowerCAmelCase , builder.name , "default" , "0.0.0" , "dataset_info.json" ) ) ) del dset @require_beam def A__ ( self ): import apache_beam as beam UpperCAmelCase_ = beam.io.parquetio.WriteToParquet UpperCAmelCase_ = len(get_test_dummy_examples() ) with tempfile.TemporaryDirectory() as tmp_cache_dir: UpperCAmelCase_ = DummyBeamDataset(cache_dir=lowerCAmelCase , beam_runner="DirectRunner" ) with patch("apache_beam.io.parquetio.WriteToParquet" ) as write_parquet_mock: UpperCAmelCase_ = partial(lowerCAmelCase , num_shards=2 ) builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join( lowerCAmelCase , builder.name , "default" , "0.0.0" , f'''{builder.name}-train-00000-of-00002.arrow''' ) ) ) self.assertTrue( os.path.exists( os.path.join( lowerCAmelCase , builder.name , "default" , "0.0.0" , f'''{builder.name}-train-00000-of-00002.arrow''' ) ) ) self.assertDictEqual(builder.info.features , datasets.Features({"content": datasets.Value("string" )} ) ) UpperCAmelCase_ = builder.as_dataset() self.assertEqual(dset["train"].num_rows , lowerCAmelCase ) self.assertEqual(dset["train"].info.splits["train"].num_examples , lowerCAmelCase ) # Order is not preserved when sharding, so we just check that all the elements are there self.assertListEqual(sorted(dset["train"]["content"] ) , sorted(["foo", "bar", "foobar"] ) ) self.assertTrue( os.path.exists(os.path.join(lowerCAmelCase , builder.name , "default" , "0.0.0" , "dataset_info.json" ) ) ) del dset @require_beam def A__ ( self ): with tempfile.TemporaryDirectory() as tmp_cache_dir: UpperCAmelCase_ = DummyBeamDataset(cache_dir=lowerCAmelCase ) self.assertRaises(datasets.builder.MissingBeamOptions , builder.download_and_prepare ) @require_beam def A__ ( self ): UpperCAmelCase_ = len(get_test_nested_examples() ) with tempfile.TemporaryDirectory() as tmp_cache_dir: UpperCAmelCase_ = NestedBeamDataset(cache_dir=lowerCAmelCase , beam_runner="DirectRunner" ) builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join(lowerCAmelCase , builder.name , "default" , "0.0.0" , f'''{builder.name}-train.arrow''' ) ) ) self.assertDictEqual( builder.info.features , datasets.Features({"a": datasets.Sequence({"b": datasets.Value("string" )} )} ) ) UpperCAmelCase_ = builder.as_dataset() self.assertEqual(dset["train"].num_rows , lowerCAmelCase ) self.assertEqual(dset["train"].info.splits["train"].num_examples , lowerCAmelCase ) self.assertDictEqual(dset["train"][0] , get_test_nested_examples()[0][1] ) self.assertDictEqual( dset["train"][expected_num_examples - 1] , get_test_nested_examples()[expected_num_examples - 1][1] ) self.assertTrue( os.path.exists(os.path.join(lowerCAmelCase , builder.name , "default" , "0.0.0" , "dataset_info.json" ) ) ) del dset
579
import json import os from collections import Counter import torch import torchvision import torchvision.transforms as transforms from PIL import Image from torch import nn from torch.utils.data import Dataset SCREAMING_SNAKE_CASE = {1: (1, 1), 2: (2, 1), 3: (3, 1), 4: (2, 2), 5: (5, 1), 6: (3, 2), 7: (7, 1), 8: (4, 2), 9: (3, 3)} class lowerCamelCase ( nn.Module ): '''simple docstring''' def __init__( self , lowerCAmelCase ): super().__init__() UpperCAmelCase_ = torchvision.models.resnetaaa(pretrained=lowerCAmelCase ) UpperCAmelCase_ = list(model.children() )[:-2] UpperCAmelCase_ = nn.Sequential(*lowerCAmelCase ) UpperCAmelCase_ = nn.AdaptiveAvgPoolad(POOLING_BREAKDOWN[args.num_image_embeds] ) def A__ ( self , lowerCAmelCase ): # Bx3x224x224 -> Bx2048x7x7 -> Bx2048xN -> BxNx2048 UpperCAmelCase_ = self.pool(self.model(lowerCAmelCase ) ) UpperCAmelCase_ = torch.flatten(lowerCAmelCase , start_dim=2 ) UpperCAmelCase_ = out.transpose(1 , 2 ).contiguous() return out # BxNx2048 class lowerCamelCase ( lowercase__ ): '''simple docstring''' def __init__( self , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ): UpperCAmelCase_ = [json.loads(lowerCAmelCase ) for l in open(lowerCAmelCase )] UpperCAmelCase_ = os.path.dirname(lowerCAmelCase ) UpperCAmelCase_ = tokenizer UpperCAmelCase_ = labels UpperCAmelCase_ = len(lowerCAmelCase ) UpperCAmelCase_ = max_seq_length UpperCAmelCase_ = transforms def __len__( self ): return len(self.data ) def __getitem__( self , lowerCAmelCase ): UpperCAmelCase_ = torch.LongTensor(self.tokenizer.encode(self.data[index]["text"] , add_special_tokens=lowerCAmelCase ) ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = sentence[0], sentence[1:-1], sentence[-1] UpperCAmelCase_ = sentence[: self.max_seq_length] UpperCAmelCase_ = torch.zeros(self.n_classes ) UpperCAmelCase_ = 1 UpperCAmelCase_ = Image.open(os.path.join(self.data_dir , self.data[index]["img"] ) ).convert("RGB" ) UpperCAmelCase_ = self.transforms(lowerCAmelCase ) return { "image_start_token": start_token, "image_end_token": end_token, "sentence": sentence, "image": image, "label": label, } def A__ ( self ): UpperCAmelCase_ = Counter() for row in self.data: label_freqs.update(row["label"] ) return label_freqs def snake_case__ ( __SCREAMING_SNAKE_CASE ) -> int: UpperCAmelCase_ = [len(row["sentence"] ) for row in batch] UpperCAmelCase_ , UpperCAmelCase_ = len(__SCREAMING_SNAKE_CASE ), max(__SCREAMING_SNAKE_CASE ) UpperCAmelCase_ = torch.zeros(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , dtype=torch.long ) UpperCAmelCase_ = torch.zeros(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , dtype=torch.long ) for i_batch, (input_row, length) in enumerate(zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ): UpperCAmelCase_ = input_row["sentence"] UpperCAmelCase_ = 1 UpperCAmelCase_ = torch.stack([row["image"] for row in batch] ) UpperCAmelCase_ = torch.stack([row["label"] for row in batch] ) UpperCAmelCase_ = torch.stack([row["image_start_token"] for row in batch] ) UpperCAmelCase_ = torch.stack([row["image_end_token"] for row in batch] ) return text_tensor, mask_tensor, img_tensor, img_start_token, img_end_token, tgt_tensor def snake_case__ ( ) -> int: return [ "Crime", "Drama", "Thriller", "Action", "Comedy", "Romance", "Documentary", "Short", "Mystery", "History", "Family", "Adventure", "Fantasy", "Sci-Fi", "Western", "Horror", "Sport", "War", "Music", "Musical", "Animation", "Biography", "Film-Noir", ] def snake_case__ ( ) -> Optional[int]: return transforms.Compose( [ transforms.Resize(256 ), transforms.CenterCrop(224 ), transforms.ToTensor(), transforms.Normalize( mean=[0.46_777_044, 0.44_531_429, 0.40_661_017] , std=[0.12_221_994, 0.12_145_835, 0.14_380_469] , ), ] )
579
1
import argparse import pytorch_lightning as pl import torch from torch import nn from transformers import LongformerForQuestionAnswering, LongformerModel class UpperCamelCase__ ( pl.LightningModule ): '''simple docstring''' def __init__( self , UpperCamelCase__ ): super().__init__() A__ = model A__ = 2 A__ = nn.Linear(self.model.config.hidden_size , self.num_labels ) def __snake_case ( self ): pass def SCREAMING_SNAKE_CASE ( __UpperCamelCase : str , __UpperCamelCase : str , __UpperCamelCase : str ) -> Tuple: """simple docstring""" A__ = LongformerModel.from_pretrained(__UpperCamelCase ) A__ = LightningModel(__UpperCamelCase ) A__ = torch.load(__UpperCamelCase , map_location=torch.device('''cpu''' ) ) lightning_model.load_state_dict(ckpt['''state_dict'''] ) # init longformer question answering model A__ = LongformerForQuestionAnswering.from_pretrained(__UpperCamelCase ) # transfer weights longformer_for_qa.longformer.load_state_dict(lightning_model.model.state_dict() ) longformer_for_qa.qa_outputs.load_state_dict(lightning_model.qa_outputs.state_dict() ) longformer_for_qa.eval() # save model longformer_for_qa.save_pretrained(__UpperCamelCase ) print(F"Conversion successful. Model saved under {pytorch_dump_folder_path}" ) if __name__ == "__main__": _SCREAMING_SNAKE_CASE : Dict = argparse.ArgumentParser() # Required parameters parser.add_argument( '--longformer_model', default=None, type=str, required=True, help='model identifier of longformer. Should be either `longformer-base-4096` or `longformer-large-4096`.', ) parser.add_argument( '--longformer_question_answering_ckpt_path', default=None, type=str, required=True, help='Path the official PyTorch Lightning Checkpoint.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) _SCREAMING_SNAKE_CASE : List[str] = parser.parse_args() convert_longformer_qa_checkpoint_to_pytorch( args.longformer_model, args.longformer_question_answering_ckpt_path, args.pytorch_dump_folder_path )
705
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tensorflow_text_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _SCREAMING_SNAKE_CASE : int = { 'configuration_bert': ['BERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BertConfig', 'BertOnnxConfig'], 'tokenization_bert': ['BasicTokenizer', 'BertTokenizer', 'WordpieceTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Optional[Any] = ['BertTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Union[str, Any] = [ 'BERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'BertForMaskedLM', 'BertForMultipleChoice', 'BertForNextSentencePrediction', 'BertForPreTraining', 'BertForQuestionAnswering', 'BertForSequenceClassification', 'BertForTokenClassification', 'BertLayer', 'BertLMHeadModel', 'BertModel', 'BertPreTrainedModel', 'load_tf_weights_in_bert', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Tuple = [ 'TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFBertEmbeddings', 'TFBertForMaskedLM', 'TFBertForMultipleChoice', 'TFBertForNextSentencePrediction', 'TFBertForPreTraining', 'TFBertForQuestionAnswering', 'TFBertForSequenceClassification', 'TFBertForTokenClassification', 'TFBertLMHeadModel', 'TFBertMainLayer', 'TFBertModel', 'TFBertPreTrainedModel', ] try: if not is_tensorflow_text_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Dict = ['TFBertTokenizer'] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Optional[int] = [ 'FlaxBertForCausalLM', 'FlaxBertForMaskedLM', 'FlaxBertForMultipleChoice', 'FlaxBertForNextSentencePrediction', 'FlaxBertForPreTraining', 'FlaxBertForQuestionAnswering', 'FlaxBertForSequenceClassification', 'FlaxBertForTokenClassification', 'FlaxBertModel', 'FlaxBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_bert import BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BertConfig, BertOnnxConfig from .tokenization_bert import BasicTokenizer, BertTokenizer, WordpieceTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bert_fast import BertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bert import ( BERT_PRETRAINED_MODEL_ARCHIVE_LIST, BertForMaskedLM, BertForMultipleChoice, BertForNextSentencePrediction, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, BertForTokenClassification, BertLayer, BertLMHeadModel, BertModel, BertPreTrainedModel, load_tf_weights_in_bert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_bert import ( TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFBertEmbeddings, TFBertForMaskedLM, TFBertForMultipleChoice, TFBertForNextSentencePrediction, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertForTokenClassification, TFBertLMHeadModel, TFBertMainLayer, TFBertModel, TFBertPreTrainedModel, ) try: if not is_tensorflow_text_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bert_tf import TFBertTokenizer try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_bert import ( FlaxBertForCausalLM, FlaxBertForMaskedLM, FlaxBertForMultipleChoice, FlaxBertForNextSentencePrediction, FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification, FlaxBertForTokenClassification, FlaxBertModel, FlaxBertPreTrainedModel, ) else: import sys _SCREAMING_SNAKE_CASE : Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
55
0
import gzip import hashlib import json import multiprocessing import os import re import shutil import time from pathlib import Path import numpy as np from arguments import PreprocessingArguments from datasets import load_dataset from minhash_deduplication import deduplicate_dataset from transformers import AutoTokenizer, HfArgumentParser __A = re.compile(r"\s+") def lowercase__ ( A_: int ) -> Any: """simple docstring""" return {"hash": hashlib.mda(re.sub(A_ , """""" , example["""content"""] ).encode("""utf-8""" ) ).hexdigest()} def lowercase__ ( A_: int ) -> Optional[int]: """simple docstring""" __UpperCAmelCase =[len(A_ ) for line in example["""content"""].splitlines()] return {"line_mean": np.mean(A_ ), "line_max": max(A_ )} def lowercase__ ( A_: Any ) -> int: """simple docstring""" __UpperCAmelCase =np.mean([c.isalnum() for c in example["""content"""]] ) return {"alpha_frac": alpha_frac} def lowercase__ ( A_: List[Any] , A_: Tuple ) -> str: """simple docstring""" if example["hash"] in uniques: uniques.remove(example["""hash"""] ) return True else: return False def lowercase__ ( A_: List[str] , A_: Dict=5 ) -> Optional[Any]: """simple docstring""" __UpperCAmelCase =["""auto-generated""", """autogenerated""", """automatically generated"""] __UpperCAmelCase =example["""content"""].splitlines() for _, line in zip(range(A_ ) , A_ ): for keyword in keywords: if keyword in line.lower(): return {"autogenerated": True} else: return {"autogenerated": False} def lowercase__ ( A_: str , A_: List[Any]=5 , A_: List[Any]=0.0_5 ) -> List[str]: """simple docstring""" __UpperCAmelCase =["""unit tests""", """test file""", """configuration file"""] __UpperCAmelCase =example["""content"""].splitlines() __UpperCAmelCase =0 __UpperCAmelCase =0 # first test for _, line in zip(range(A_ ) , A_ ): for keyword in keywords: if keyword in line.lower(): return {"config_or_test": True} # second test __UpperCAmelCase =example["""content"""].count("""\n""" ) __UpperCAmelCase =int(coeff * nlines ) for line in lines: count_config += line.lower().count("""config""" ) count_test += line.lower().count("""test""" ) if count_config > threshold or count_test > threshold: return {"config_or_test": True} return {"config_or_test": False} def lowercase__ ( A_: Any ) -> Union[str, Any]: """simple docstring""" __UpperCAmelCase =["""def """, """class """, """for """, """while """] __UpperCAmelCase =example["""content"""].splitlines() for line in lines: for keyword in keywords: if keyword in line.lower(): return {"has_no_keywords": False} return {"has_no_keywords": True} def lowercase__ ( A_: Optional[int] , A_: List[Any]=4 ) -> Any: """simple docstring""" __UpperCAmelCase =example["""content"""].splitlines() __UpperCAmelCase =0 for line in lines: counter += line.lower().count("""=""" ) if counter > minimum: return {"has_few_assignments": False} return {"has_few_assignments": True} def lowercase__ ( A_: List[Any] ) -> Union[str, Any]: """simple docstring""" __UpperCAmelCase =tokenizer(example["""content"""] , truncation=A_ )["""input_ids"""] __UpperCAmelCase =len(example["""content"""] ) / len(A_ ) return {"ratio": ratio} def lowercase__ ( A_: int ) -> str: """simple docstring""" __UpperCAmelCase ={} results.update(get_hash(A_ ) ) results.update(line_stats(A_ ) ) results.update(alpha_stats(A_ ) ) results.update(char_token_ratio(A_ ) ) results.update(is_autogenerated(A_ ) ) results.update(is_config_or_test(A_ ) ) results.update(has_no_keywords(A_ ) ) results.update(has_few_assignments(A_ ) ) return results def lowercase__ ( A_: Dict , A_: Any , A_: List[str] ) -> str: """simple docstring""" if not check_uniques(A_ , A_ ): return False elif example["autogenerated"]: return False elif example["line_max"] > args.line_max: return False elif example["line_mean"] > args.line_mean: return False elif example["alpha_frac"] < args.alpha_frac: return False elif example["ratio"] < args.min_token_ratio: return False elif example["config_or_test"] and np.random.rand() <= args.filter_proba: return False elif example["has_no_keywords"] and np.random.rand() <= args.filter_proba: return False elif example["has_few_assignments"]: return False else: return True def lowercase__ ( A_: List[Any] ) -> Tuple: """simple docstring""" with open(A_ , """rb""" ) as f_in: with gzip.open(str(A_ ) + """.gz""" , """wb""" , compresslevel=6 ) as f_out: shutil.copyfileobj(A_ , A_ ) os.unlink(A_ ) # Settings __A = HfArgumentParser(PreprocessingArguments) __A = parser.parse_args() if args.num_workers is None: __A = multiprocessing.cpu_count() __A = AutoTokenizer.from_pretrained(args.tokenizer_dir) # Load dataset __A = time.time() __A = load_dataset(args.dataset_name, split="train") print(F"""Time to load dataset: {time.time()-t_start:.2f}""") # Run preprocessing __A = time.time() __A = ds.map(preprocess, num_proc=args.num_workers) print(F"""Time to preprocess dataset: {time.time()-t_start:.2f}""") # Deduplicate hashes __A = set(ds.unique("hash")) __A = len(uniques) / len(ds) print(F"""Fraction of duplicates: {1-frac:.2%}""") # Deduplicate data and apply heuristics __A = time.time() __A = ds.filter(filter, fn_kwargs={"uniques": uniques, "args": args}) print(F"""Time to filter dataset: {time.time()-t_start:.2f}""") print(F"""Size of filtered dataset: {len(ds_filter)}""") # Deduplicate with minhash and jaccard similarity if args.near_deduplication: __A = time.time() __A , __A = deduplicate_dataset(ds_filter, args.jaccard_threshold) print(F"""Time to deduplicate dataset: {time.time()-t_start:.2f}""") print(F"""Size of deduplicate dataset: {len(ds_filter)}""") # Save data in batches of samples_per_file __A = Path(args.output_dir) output_dir.mkdir(exist_ok=True) # save duplicate_clusters in the output_dir as artifacts # not sure it is the right place the save it if args.near_deduplication: with open(output_dir / "duplicate_clusters.json", "w") as f: json.dump(duplicate_clusters, f) __A = output_dir / "data" data_dir.mkdir(exist_ok=True) __A = time.time() for file_number, index in enumerate(range(0, len(ds_filter), args.samples_per_file)): __A = str(data_dir / F"""file-{file_number+1:012}.json""") __A = min(len(ds_filter), index + args.samples_per_file) ds_filter.select(list(range(index, end_index))).to_json(file_path) compress_file(file_path) print(F"""Time to save dataset: {time.time()-t_start:.2f}""")
68
'''simple docstring''' def lowerCAmelCase (__A , __A): """simple docstring""" if digit_amount > 0: return round(number - int(__A) , __A) return number - int(__A) if __name__ == "__main__": print(decimal_isolate(1.53, 0)) print(decimal_isolate(35.345, 1)) print(decimal_isolate(35.345, 2)) print(decimal_isolate(35.345, 3)) print(decimal_isolate(-14.789, 3)) print(decimal_isolate(0, 2)) print(decimal_isolate(-14.123, 1)) print(decimal_isolate(-14.123, 2)) print(decimal_isolate(-14.123, 3))
11
0
from __future__ import annotations UpperCAmelCase = 10 def __lowerCAmelCase (SCREAMING_SNAKE_CASE )-> Tuple: """simple docstring""" snake_case_ = 1 snake_case_ = max(__lowerCAmelCase ) while placement <= max_digit: # declare and initialize empty buckets snake_case_ = [[] for _ in range(__lowerCAmelCase )] # split list_of_ints between the buckets for i in list_of_ints: snake_case_ = int((i / placement) % RADIX ) buckets[tmp].append(__lowerCAmelCase ) # put each buckets' contents into list_of_ints snake_case_ = 0 for b in range(__lowerCAmelCase ): for i in buckets[b]: snake_case_ = i a += 1 # move to next placement *= RADIX return list_of_ints if __name__ == "__main__": import doctest doctest.testmod()
718
from math import sqrt import numpy as np from sympy import symbols # Coefficient # Speed of light (m/s) UpperCAmelCase = 2_9979_2458 # Symbols UpperCAmelCase, UpperCAmelCase, UpperCAmelCase, UpperCAmelCase = symbols("""ct x y z""") def __lowerCAmelCase (SCREAMING_SNAKE_CASE )-> float: """simple docstring""" if velocity > c: raise ValueError('''Speed must not exceed light speed 299,792,458 [m/s]!''' ) elif velocity < 1: # Usually the speed should be much higher than 1 (c order of magnitude) raise ValueError('''Speed must be greater than or equal to 1!''' ) return velocity / c def __lowerCAmelCase (SCREAMING_SNAKE_CASE )-> float: """simple docstring""" return 1 / sqrt(1 - beta(SCREAMING_SNAKE_CASE ) ** 2 ) def __lowerCAmelCase (SCREAMING_SNAKE_CASE )-> np.ndarray: """simple docstring""" return np.array( [ [gamma(SCREAMING_SNAKE_CASE ), -gamma(SCREAMING_SNAKE_CASE ) * beta(SCREAMING_SNAKE_CASE ), 0, 0], [-gamma(SCREAMING_SNAKE_CASE ) * beta(SCREAMING_SNAKE_CASE ), gamma(SCREAMING_SNAKE_CASE ), 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], ] ) def __lowerCAmelCase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = None )-> np.ndarray: """simple docstring""" if event is None: snake_case_ = np.array([ct, x, y, z] ) # Symbolic four vector else: event[0] *= c # x0 is ct (speed of light * time) return transformation_matrix(SCREAMING_SNAKE_CASE ) @ event if __name__ == "__main__": import doctest doctest.testmod() # Example of symbolic vector: UpperCAmelCase = transform(2997_9245) print("""Example of four vector: """) print(f'''ct\' = {four_vector[0]}''') print(f'''x\' = {four_vector[1]}''') print(f'''y\' = {four_vector[2]}''') print(f'''z\' = {four_vector[3]}''') # Substitute symbols with numerical values UpperCAmelCase = {ct: c, x: 1, y: 1, z: 1} UpperCAmelCase = [four_vector[i].subs(sub_dict) for i in range(4)] print(f'''\n{numerical_vector}''')
531
0
"""simple docstring""" 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 PoolFormerImageProcessor class _lowerCAmelCase ( unittest.TestCase ): def __init__( self , UpperCamelCase__ , UpperCamelCase__=7 , UpperCamelCase__=3 , UpperCamelCase__=30 , UpperCamelCase__=400 , UpperCamelCase__=True , UpperCamelCase__=None , UpperCamelCase__=0.9 , UpperCamelCase__=None , UpperCamelCase__=True , UpperCamelCase__=[0.5, 0.5, 0.5] , UpperCamelCase__=[0.5, 0.5, 0.5] , ) -> Dict: '''simple docstring''' snake_case : Optional[Any] = size if size is not None else {"shortest_edge": 30} snake_case : Optional[int] = crop_size if crop_size is not None else {"height": 30, "width": 30} snake_case : Tuple = parent snake_case : List[str] = batch_size snake_case : Dict = num_channels snake_case : List[Any] = min_resolution snake_case : Dict = max_resolution snake_case : str = do_resize_and_center_crop snake_case : Any = size snake_case : int = crop_pct snake_case : List[Any] = crop_size snake_case : List[Any] = do_normalize snake_case : List[Any] = image_mean snake_case : List[str] = image_std def lowerCamelCase ( self ) -> List[Any]: '''simple docstring''' return { "size": self.size, "do_resize_and_center_crop": self.do_resize_and_center_crop, "crop_pct": self.crop_pct, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, } @require_torch @require_vision class _lowerCAmelCase ( snake_case_ , unittest.TestCase ): __UpperCAmelCase : Optional[int] = PoolFormerImageProcessor if is_vision_available() else None def lowerCamelCase ( self ) -> List[Any]: '''simple docstring''' snake_case : Optional[Any] = PoolFormerImageProcessingTester(self ) @property def lowerCamelCase ( self ) -> List[Any]: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def lowerCamelCase ( self ) -> List[Any]: '''simple docstring''' snake_case : List[str] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(UpperCamelCase__ , "do_resize_and_center_crop" ) ) self.assertTrue(hasattr(UpperCamelCase__ , "size" ) ) self.assertTrue(hasattr(UpperCamelCase__ , "crop_pct" ) ) self.assertTrue(hasattr(UpperCamelCase__ , "do_normalize" ) ) self.assertTrue(hasattr(UpperCamelCase__ , "image_mean" ) ) self.assertTrue(hasattr(UpperCamelCase__ , "image_std" ) ) def lowerCamelCase ( self ) -> Tuple: '''simple docstring''' snake_case : Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"shortest_edge": 30} ) self.assertEqual(image_processor.crop_size , {"height": 30, "width": 30} ) snake_case : int = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {"shortest_edge": 42} ) self.assertEqual(image_processor.crop_size , {"height": 84, "width": 84} ) def lowerCamelCase ( self ) -> List[Any]: '''simple docstring''' pass def lowerCamelCase ( self ) -> Dict: '''simple docstring''' snake_case : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images snake_case : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCamelCase__ ) for image in image_inputs: self.assertIsInstance(UpperCamelCase__ , Image.Image ) # Test not batched input snake_case : List[Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched snake_case : Optional[int] = image_processing(UpperCamelCase__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) def lowerCamelCase ( self ) -> Tuple: '''simple docstring''' snake_case : str = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors snake_case : Optional[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCamelCase__ , numpify=UpperCamelCase__ ) for image in image_inputs: self.assertIsInstance(UpperCamelCase__ , np.ndarray ) # Test not batched input snake_case : str = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched snake_case : Optional[int] = image_processing(UpperCamelCase__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) def lowerCamelCase ( self ) -> Any: '''simple docstring''' snake_case : Any = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors snake_case : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCamelCase__ , torchify=UpperCamelCase__ ) for image in image_inputs: self.assertIsInstance(UpperCamelCase__ , torch.Tensor ) # Test not batched input snake_case : Optional[int] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched snake_case : Tuple = image_processing(UpperCamelCase__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , )
178
"""simple docstring""" from manim import * class _lowerCAmelCase ( snake_case_ ): def lowerCamelCase ( self ) -> Any: '''simple docstring''' snake_case : List[str] = Rectangle(height=0.5 , width=0.5 ) snake_case : Dict = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 ) snake_case : Tuple = [mem.copy() for i in range(6 )] snake_case : Any = [mem.copy() for i in range(6 )] snake_case : Tuple = VGroup(*UpperCamelCase__ ).arrange(UpperCamelCase__ , buff=0 ) snake_case : Optional[Any] = VGroup(*UpperCamelCase__ ).arrange(UpperCamelCase__ , buff=0 ) snake_case : Optional[Any] = VGroup(UpperCamelCase__ , UpperCamelCase__ ).arrange(UpperCamelCase__ , buff=0 ) snake_case : Optional[Any] = Text("CPU" , font_size=24 ) snake_case : Optional[int] = Group(UpperCamelCase__ , UpperCamelCase__ ).arrange(UpperCamelCase__ , buff=0.5 , aligned_edge=UpperCamelCase__ ) cpu.move_to([-2.5, -0.5, 0] ) self.add(UpperCamelCase__ ) snake_case : Optional[Any] = [mem.copy() for i in range(1 )] snake_case : List[str] = VGroup(*UpperCamelCase__ ).arrange(UpperCamelCase__ , buff=0 ) snake_case : Optional[int] = Text("GPU" , font_size=24 ) snake_case : Tuple = Group(UpperCamelCase__ , UpperCamelCase__ ).arrange(UpperCamelCase__ , buff=0.5 , aligned_edge=UpperCamelCase__ ) gpu.align_to(UpperCamelCase__ , UpperCamelCase__ ) gpu.set_x(gpu.get_x() - 1 ) self.add(UpperCamelCase__ ) snake_case : Any = [mem.copy() for i in range(6 )] snake_case : Any = VGroup(*UpperCamelCase__ ).arrange(UpperCamelCase__ , buff=0 ) snake_case : Dict = Text("Model" , font_size=24 ) snake_case : Optional[Any] = Group(UpperCamelCase__ , UpperCamelCase__ ).arrange(UpperCamelCase__ , buff=0.5 , aligned_edge=UpperCamelCase__ ) model.move_to([3, -1.0, 0] ) self.play( Create(UpperCamelCase__ , run_time=1 ) , Create(UpperCamelCase__ , run_time=1 ) , Create(UpperCamelCase__ , run_time=1 ) , ) snake_case : Optional[Any] = MarkupText( F'First, an empty model skeleton is loaded\ninto <span fgcolor=\'{YELLOW}\'>memory</span> without using much RAM.' , font_size=24 , ) snake_case : Any = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) snake_case : Any = MarkupText( F'<b>Key:</b>\n\n<span fgcolor=\'{YELLOW}\'>●</span> Empty Model' , font_size=18 , ) key_text.move_to([-5, 2.4, 0] ) step_a.move_to([2, 2, 0] ) self.play(Write(UpperCamelCase__ , run_time=2.5 ) , Write(UpperCamelCase__ ) , Write(UpperCamelCase__ ) ) self.add(UpperCamelCase__ ) snake_case : Optional[Any] = [] snake_case : Dict = [] snake_case : Union[str, Any] = [] for i, rect in enumerate(UpperCamelCase__ ): snake_case : Any = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0.0 ).set_fill(UpperCamelCase__ , opacity=0.7 ) cpu_target.move_to(UpperCamelCase__ ) cpu_target.generate_target() snake_case : Optional[int] = 0.46 / 4 snake_case : Any = 0.46 / 3 if i == 0: cpu_target.target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.02 , direction=UpperCamelCase__ ) cpu_target.target.set_x(cpu_target.target.get_x() + 0.1 ) elif i == 3: cpu_target.target.next_to(cpu_targs[0].target , direction=UpperCamelCase__ , buff=0.0 ) else: cpu_target.target.next_to(cpu_targs[i - 1].target , direction=UpperCamelCase__ , buff=0.0 ) cpu_targs.append(UpperCamelCase__ ) first_animations.append(rect.animate(run_time=0.5 ).set_stroke(UpperCamelCase__ ) ) second_animations.append(MoveToTarget(UpperCamelCase__ , run_time=1.5 ) ) self.play(*UpperCamelCase__ ) self.play(*UpperCamelCase__ ) self.wait()
178
1
'''simple docstring''' from typing import Any class _UpperCamelCase : '''simple docstring''' def __init__( self : List[str] , lowerCAmelCase__ : Any ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[Any] = data __SCREAMING_SNAKE_CASE : int = None def __repr__( self : Tuple ): """simple docstring""" return F"Node({self.data})" class _UpperCamelCase : '''simple docstring''' def __init__( self : Any ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = None def __iter__( self : Any ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = self.head while node: yield node.data __SCREAMING_SNAKE_CASE : Union[str, Any] = node.next def __len__( self : int ): """simple docstring""" return sum(1 for _ in self ) def __repr__( self : Union[str, Any] ): """simple docstring""" return "->".join([str(lowerCAmelCase__ ) for item in self] ) def __getitem__( self : Union[str, Any] , lowerCAmelCase__ : 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 : Optional[Any] , lowerCAmelCase__ : int , lowerCAmelCase__ : Any ): """simple docstring""" if not 0 <= index < len(self ): raise ValueError("""list index out of range.""" ) __SCREAMING_SNAKE_CASE : Optional[int] = self.head for _ in range(lowerCAmelCase__ ): __SCREAMING_SNAKE_CASE : str = current.next __SCREAMING_SNAKE_CASE : Union[str, Any] = data def UpperCamelCase__ ( self : Tuple , lowerCAmelCase__ : Any ): """simple docstring""" self.insert_nth(len(self ) , lowerCAmelCase__ ) def UpperCamelCase__ ( self : List[str] , lowerCAmelCase__ : Any ): """simple docstring""" self.insert_nth(0 , lowerCAmelCase__ ) def UpperCamelCase__ ( self : int , lowerCAmelCase__ : int , lowerCAmelCase__ : Any ): """simple docstring""" if not 0 <= index <= len(self ): raise IndexError("""list index out of range""" ) __SCREAMING_SNAKE_CASE : str = Node(lowerCAmelCase__ ) if self.head is None: __SCREAMING_SNAKE_CASE : Dict = new_node elif index == 0: __SCREAMING_SNAKE_CASE : str = self.head # link new_node to head __SCREAMING_SNAKE_CASE : List[Any] = new_node else: __SCREAMING_SNAKE_CASE : List[str] = self.head for _ in range(index - 1 ): __SCREAMING_SNAKE_CASE : Any = temp.next __SCREAMING_SNAKE_CASE : List[str] = temp.next __SCREAMING_SNAKE_CASE : Optional[Any] = new_node def UpperCamelCase__ ( self : Optional[int] ): # print every node data """simple docstring""" print(self ) def UpperCamelCase__ ( self : str ): """simple docstring""" return self.delete_nth(0 ) def UpperCamelCase__ ( self : List[str] ): # delete from tail """simple docstring""" return self.delete_nth(len(self ) - 1 ) def UpperCamelCase__ ( self : Optional[int] , lowerCAmelCase__ : 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 : Optional[int] = self.head # default first node if index == 0: __SCREAMING_SNAKE_CASE : Optional[int] = self.head.next else: __SCREAMING_SNAKE_CASE : Tuple = self.head for _ in range(index - 1 ): __SCREAMING_SNAKE_CASE : int = temp.next __SCREAMING_SNAKE_CASE : Union[str, Any] = temp.next __SCREAMING_SNAKE_CASE : str = temp.next.next return delete_node.data def UpperCamelCase__ ( self : List[Any] ): """simple docstring""" return self.head is None def UpperCamelCase__ ( self : Any ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = None __SCREAMING_SNAKE_CASE : Dict = self.head while current: # Store the current node's next node. __SCREAMING_SNAKE_CASE : Optional[Any] = current.next # Make the current node's next point backwards __SCREAMING_SNAKE_CASE : Dict = prev # Make the previous node be the current node __SCREAMING_SNAKE_CASE : Dict = current # Make the current node the next node (to progress iteration) __SCREAMING_SNAKE_CASE : Any = next_node # Return prev in order to put the head at the end __SCREAMING_SNAKE_CASE : Dict = prev def lowerCAmelCase_ ( ): __SCREAMING_SNAKE_CASE : str = LinkedList() assert linked_list.is_empty() is True assert str(_lowerCamelCase ) == "" 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(_lowerCamelCase ) == i linked_list.insert_nth(_lowerCamelCase , i + 1 ) assert str(_lowerCamelCase ) == "->".join(str(_lowerCamelCase ) for i in range(1 , 11 ) ) linked_list.insert_head(0 ) linked_list.insert_tail(11 ) assert str(_lowerCamelCase ) == "->".join(str(_lowerCamelCase ) 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(_lowerCamelCase ) == 9 assert str(_lowerCamelCase ) == "->".join(str(_lowerCamelCase ) 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 : Any = -i assert all(linked_list[i] == -i for i in range(0 , 9 ) ) is True linked_list.reverse() assert str(_lowerCamelCase ) == "->".join(str(_lowerCamelCase ) for i in range(-8 , 1 ) ) def lowerCAmelCase_ ( ): __SCREAMING_SNAKE_CASE : str = [ -9, 1_00, Node(77_34_51_12 ), """dlrow olleH""", 7, 55_55, 0, -1_92.5_55_55, """Hello, world!""", 77.9, Node(10 ), None, None, 12.20, ] __SCREAMING_SNAKE_CASE : int = LinkedList() for i in test_input: linked_list.insert_tail(_lowerCamelCase ) # Check if it's empty or not assert linked_list.is_empty() is False assert ( str(_lowerCamelCase ) == "-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 : Optional[Any] = linked_list.delete_head() assert result == -9 assert ( str(_lowerCamelCase ) == "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 : Dict = linked_list.delete_tail() assert result == 12.2 assert ( str(_lowerCamelCase ) == "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(_lowerCamelCase ) == "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(_lowerCamelCase ) == "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(_lowerCamelCase ) assert ( str(_lowerCamelCase ) == "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(_lowerCamelCase ) == "None->None->Node(10)->77.9->Hello, world!->-192.55555->0->5555->" "7->dlrow olleH->Node(77345112)->100->Node(Hello again, world!)" ) def lowerCAmelCase_ ( ): from doctest import testmod testmod() __SCREAMING_SNAKE_CASE : Union[str, Any] = 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(_lowerCamelCase ) print("""\nReading/changing Node data using indexing:""" ) print(F"Element at Position 1: {linked_list[1]}" ) __SCREAMING_SNAKE_CASE : Union[str, Any] = input("""Enter New Value: """ ).strip() print("""New list:""" ) print(_lowerCamelCase ) print(F"length of linked_list is : {len(_lowerCamelCase )}" ) if __name__ == "__main__": main()
178
'''simple docstring''' import qiskit def lowerCAmelCase_ ( _lowerCamelCase: int = 2 ): __SCREAMING_SNAKE_CASE : Dict = qubits # Using Aer's simulator __SCREAMING_SNAKE_CASE : Optional[Any] = qiskit.Aer.get_backend("""aer_simulator""" ) # Creating a Quantum Circuit acting on the q register __SCREAMING_SNAKE_CASE : str = qiskit.QuantumCircuit(_lowerCamelCase , _lowerCamelCase ) # Adding a H gate on qubit 0 (now q0 in superposition) circuit.h(0 ) for i in range(1 , _lowerCamelCase ): # Adding CX (CNOT) gate circuit.cx(i - 1 , _lowerCamelCase ) # Mapping the quantum measurement to the classical bits circuit.measure(list(range(_lowerCamelCase ) ) , list(range(_lowerCamelCase ) ) ) # Now measuring any one qubit would affect other qubits to collapse # their super position and have same state as the measured one. # Executing the circuit on the simulator __SCREAMING_SNAKE_CASE : str = qiskit.execute(_lowerCamelCase , _lowerCamelCase , shots=10_00 ) return job.result().get_counts(_lowerCamelCase ) if __name__ == "__main__": print(f"Total count for various states are: {quantum_entanglement(3)}")
178
1
'''simple docstring''' from __future__ import annotations from PIL import Image # Define glider example UpperCAmelCase_ : Optional[int] = [ [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [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], ] # Define blinker example UpperCAmelCase_ : str = [[0, 1, 0], [0, 1, 0], [0, 1, 0]] def _UpperCamelCase (_lowerCamelCase : list[list[int]] )-> list[list[int]]: '''simple docstring''' __snake_case = [] for i in range(len(_lowerCamelCase ) ): __snake_case = [] for j in range(len(cells[i] ) ): # Get the number of live neighbours __snake_case = 0 if i > 0 and j > 0: neighbour_count += cells[i - 1][j - 1] if i > 0: neighbour_count += cells[i - 1][j] if i > 0 and j < len(cells[i] ) - 1: neighbour_count += cells[i - 1][j + 1] if j > 0: neighbour_count += cells[i][j - 1] if j < len(cells[i] ) - 1: neighbour_count += cells[i][j + 1] if i < len(_lowerCamelCase ) - 1 and j > 0: neighbour_count += cells[i + 1][j - 1] if i < len(_lowerCamelCase ) - 1: neighbour_count += cells[i + 1][j] if i < len(_lowerCamelCase ) - 1 and j < len(cells[i] ) - 1: neighbour_count += cells[i + 1][j + 1] # Rules of the game of life (excerpt from Wikipedia): # 1. Any live cell with two or three live neighbours survives. # 2. Any dead cell with three live neighbours becomes a live cell. # 3. All other live cells die in the next generation. # Similarly, all other dead cells stay dead. __snake_case = cells[i][j] == 1 if ( (alive and 2 <= neighbour_count <= 3) or not alive and neighbour_count == 3 ): next_generation_row.append(1 ) else: next_generation_row.append(0 ) next_generation.append(_lowerCamelCase ) return next_generation def _UpperCamelCase (_lowerCamelCase : list[list[int]] , _lowerCamelCase : int )-> list[Image.Image]: '''simple docstring''' __snake_case = [] for _ in range(_lowerCamelCase ): # Create output image __snake_case = Image.new('''RGB''' , (len(cells[0] ), len(_lowerCamelCase )) ) __snake_case = img.load() # Save cells to image for x in range(len(_lowerCamelCase ) ): for y in range(len(cells[0] ) ): __snake_case = 2_55 - cells[y][x] * 2_55 __snake_case = (colour, colour, colour) # Save image images.append(_lowerCamelCase ) __snake_case = new_generation(_lowerCamelCase ) return images if __name__ == "__main__": UpperCAmelCase_ : Dict = generate_images(GLIDER, 1_6) images[0].save('''out.gif''', save_all=True, append_images=images[1:])
24
'''simple docstring''' from collections import UserDict from typing import List, Union from ..utils import ( add_end_docstrings, is_tf_available, is_torch_available, is_vision_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING from ..tf_utils import stable_softmax UpperCAmelCase_ : str = logging.get_logger(__name__) @add_end_docstrings(__lowerCAmelCase) class lowerCAmelCase ( __lowerCAmelCase): def __init__( self , **__SCREAMING_SNAKE_CASE ) -> Optional[int]: '''simple docstring''' super().__init__(**__SCREAMING_SNAKE_CASE ) requires_backends(self , '''vision''' ) self.check_model_type( TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING if self.framework == '''tf''' else MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING ) def __call__( self , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) -> List[Any]: '''simple docstring''' return super().__call__(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def lowerCAmelCase ( self , **__SCREAMING_SNAKE_CASE ) -> Tuple: '''simple docstring''' __snake_case = {} if "candidate_labels" in kwargs: __snake_case = kwargs['''candidate_labels'''] if "hypothesis_template" in kwargs: __snake_case = kwargs['''hypothesis_template'''] return preprocess_params, {}, {} def lowerCAmelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE="This is a photo of {}." ) -> Optional[Any]: '''simple docstring''' __snake_case = load_image(__SCREAMING_SNAKE_CASE ) __snake_case = self.image_processor(images=[image] , return_tensors=self.framework ) __snake_case = candidate_labels __snake_case = [hypothesis_template.format(__SCREAMING_SNAKE_CASE ) for x in candidate_labels] __snake_case = self.tokenizer(__SCREAMING_SNAKE_CASE , return_tensors=self.framework , padding=__SCREAMING_SNAKE_CASE ) __snake_case = [text_inputs] return inputs def lowerCAmelCase ( self , __SCREAMING_SNAKE_CASE ) -> Dict: '''simple docstring''' __snake_case = model_inputs.pop('''candidate_labels''' ) __snake_case = model_inputs.pop('''text_inputs''' ) if isinstance(text_inputs[0] , __SCREAMING_SNAKE_CASE ): __snake_case = text_inputs[0] else: # Batching case. __snake_case = text_inputs[0][0] __snake_case = self.model(**__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __snake_case = { '''candidate_labels''': candidate_labels, '''logits''': outputs.logits_per_image, } return model_outputs def lowerCAmelCase ( self , __SCREAMING_SNAKE_CASE ) -> str: '''simple docstring''' __snake_case = model_outputs.pop('''candidate_labels''' ) __snake_case = model_outputs['''logits'''][0] if self.framework == "pt": __snake_case = logits.softmax(dim=-1 ).squeeze(-1 ) __snake_case = probs.tolist() if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): __snake_case = [scores] elif self.framework == "tf": __snake_case = stable_softmax(__SCREAMING_SNAKE_CASE , axis=-1 ) __snake_case = probs.numpy().tolist() else: raise ValueError(F'''Unsupported framework: {self.framework}''' ) __snake_case = [ {'''score''': score, '''label''': candidate_label} for score, candidate_label in sorted(zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , key=lambda __SCREAMING_SNAKE_CASE : -x[0] ) ] return result
24
1
'''simple docstring''' from math import factorial def _A ( __magic_name__ = 20 ): lowercase__ = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1, # 2, 3,... lowercase__ = n // 2 return int(factorial(lowerCAmelCase__ ) / (factorial(lowerCAmelCase__ ) * factorial(n - k )) ) if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution(20)) else: try: _snake_case = int(sys.argv[1]) print(solution(n)) except ValueError: print("""Invalid entry - please enter a number.""")
709
import argparse import numpy as np import torch from transformers import SpeechTaHifiGan, SpeechTaHifiGanConfig, logging logging.set_verbosity_info() _snake_case = logging.get_logger("""transformers.models.speecht5""") def _A ( __magic_name__ , __magic_name__ , __magic_name__ ): hf_model.apply_weight_norm() lowercase__ = checkpoint["input_conv.weight_g"] lowercase__ = checkpoint["input_conv.weight_v"] lowercase__ = checkpoint["input_conv.bias"] for i in range(len(config.upsample_rates ) ): lowercase__ = checkpoint[f'''upsamples.{i}.1.weight_g'''] lowercase__ = checkpoint[f'''upsamples.{i}.1.weight_v'''] lowercase__ = checkpoint[f'''upsamples.{i}.1.bias'''] for i in range(len(config.upsample_rates ) * len(config.resblock_kernel_sizes ) ): for j in range(len(config.resblock_dilation_sizes ) ): lowercase__ = checkpoint[f'''blocks.{i}.convs1.{j}.1.weight_g'''] lowercase__ = checkpoint[f'''blocks.{i}.convs1.{j}.1.weight_v'''] lowercase__ = checkpoint[f'''blocks.{i}.convs1.{j}.1.bias'''] lowercase__ = checkpoint[f'''blocks.{i}.convs2.{j}.1.weight_g'''] lowercase__ = checkpoint[f'''blocks.{i}.convs2.{j}.1.weight_v'''] lowercase__ = checkpoint[f'''blocks.{i}.convs2.{j}.1.bias'''] lowercase__ = checkpoint["output_conv.1.weight_g"] lowercase__ = checkpoint["output_conv.1.weight_v"] lowercase__ = checkpoint["output_conv.1.bias"] hf_model.remove_weight_norm() @torch.no_grad() def _A ( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__=None , __magic_name__=None , ): if config_path is not None: lowercase__ = SpeechTaHifiGanConfig.from_pretrained(__magic_name__ ) else: lowercase__ = SpeechTaHifiGanConfig() lowercase__ = SpeechTaHifiGan(__magic_name__ ) lowercase__ = torch.load(__magic_name__ ) load_weights(orig_checkpoint["model"]["generator"] , __magic_name__ , __magic_name__ ) lowercase__ = np.load(__magic_name__ ) lowercase__ = stats[0].reshape(-1 ) lowercase__ = stats[1].reshape(-1 ) lowercase__ = torch.from_numpy(__magic_name__ ).float() lowercase__ = torch.from_numpy(__magic_name__ ).float() model.save_pretrained(__magic_name__ ) if repo_id: print("Pushing to the hub..." ) model.push_to_hub(__magic_name__ ) if __name__ == "__main__": _snake_case = argparse.ArgumentParser() parser.add_argument("""--checkpoint_path""", required=True, default=None, type=str, help="""Path to original checkpoint""") parser.add_argument("""--stats_path""", required=True, default=None, type=str, help="""Path to stats.npy file""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") parser.add_argument( """--pytorch_dump_folder_path""", required=True, default=None, type=str, help="""Path to the output PyTorch model.""" ) parser.add_argument( """--push_to_hub""", default=None, type=str, help="""Where to upload the converted model on the 🤗 hub.""" ) _snake_case = parser.parse_args() convert_hifigan_checkpoint( args.checkpoint_path, args.stats_path, args.pytorch_dump_folder_path, args.config_path, args.push_to_hub, )
611
0
from dataclasses import dataclass, field from typing import Tuple from ..utils import cached_property, is_tf_available, logging, requires_backends from .benchmark_args_utils import BenchmarkArguments if is_tf_available(): import tensorflow as tf __snake_case : int = logging.get_logger(__name__) @dataclass class A__(_UpperCamelCase ): """simple docstring""" _A : Union[str, Any] = [ """no_inference""", """no_cuda""", """no_tpu""", """no_speed""", """no_memory""", """no_env_print""", """no_multi_process""", ] def __init__( self , **_lowercase ) -> Tuple: for deprecated_arg in self.deprecated_args: if deprecated_arg in kwargs: a_ : Tuple = deprecated_arg[3:] a_ : int = not kwargs.pop(_lowercase ) logger.warning( F'''{deprecated_arg} is depreciated. Please use --no-{positive_arg} or''' F''' {positive_arg}={kwargs[positive_arg]}''' ) a_ : Optional[int] = kwargs.pop("""tpu_name""" , self.tpu_name ) a_ : Optional[int] = kwargs.pop("""device_idx""" , self.device_idx ) a_ : str = kwargs.pop("""eager_mode""" , self.eager_mode ) a_ : Optional[Any] = kwargs.pop("""use_xla""" , self.use_xla ) super().__init__(**_lowercase ) _A : str = field( default=_UpperCamelCase, metadata={'''help''': '''Name of TPU'''}, ) _A : int = field( default=0, metadata={'''help''': '''CPU / GPU device index. Defaults to 0.'''}, ) _A : bool = field(default=_UpperCamelCase, metadata={'''help''': '''Benchmark models in eager model.'''} ) _A : bool = field( default=_UpperCamelCase, metadata={ '''help''': '''Benchmark models using XLA JIT compilation. Note that `eager_model` has to be set to `False`.''' }, ) @cached_property def UpperCamelCase__ ( self ) -> Tuple["tf.distribute.cluster_resolver.TPUClusterResolver"]: requires_backends(self , ["""tf"""] ) a_ : int = None if self.tpu: try: if self.tpu_name: a_ : Optional[Any] = tf.distribute.cluster_resolver.TPUClusterResolver(self.tpu_name ) else: a_ : Union[str, Any] = tf.distribute.cluster_resolver.TPUClusterResolver() except ValueError: a_ : Dict = None return tpu @cached_property def UpperCamelCase__ ( self ) -> Tuple["tf.distribute.Strategy", "tf.distribute.cluster_resolver.TPUClusterResolver"]: requires_backends(self , ["""tf"""] ) if self.is_tpu: tf.config.experimental_connect_to_cluster(self._setup_tpu ) tf.tpu.experimental.initialize_tpu_system(self._setup_tpu ) a_ : Dict = tf.distribute.TPUStrategy(self._setup_tpu ) else: # currently no multi gpu is allowed if self.is_gpu: # TODO: Currently only single GPU is supported tf.config.set_visible_devices(self.gpu_list[self.device_idx] , """GPU""" ) a_ : int = tf.distribute.OneDeviceStrategy(device=F'''/gpu:{self.device_idx}''' ) else: tf.config.set_visible_devices([] , """GPU""" ) # disable GPU a_ : Optional[Any] = tf.distribute.OneDeviceStrategy(device=F'''/cpu:{self.device_idx}''' ) return strategy @property def UpperCamelCase__ ( self ) -> bool: requires_backends(self , ["""tf"""] ) return self._setup_tpu is not None @property def UpperCamelCase__ ( self ) -> "tf.distribute.Strategy": requires_backends(self , ["""tf"""] ) return self._setup_strategy @property def UpperCamelCase__ ( self ) -> Optional[int]: requires_backends(self , ["""tf"""] ) return tf.config.list_physical_devices("""GPU""" ) @property def UpperCamelCase__ ( self ) -> int: requires_backends(self , ["""tf"""] ) if self.cuda: return len(self.gpu_list ) return 0 @property def UpperCamelCase__ ( self ) -> bool: return self.n_gpu > 0
540
import sacrebleu as scb from packaging import version from sacrebleu import TER import datasets SCREAMING_SNAKE_CASE__ : List[Any] = """\ @inproceedings{snover-etal-2006-study, title = \"A Study of Translation Edit Rate with Targeted Human Annotation\", author = \"Snover, Matthew and Dorr, Bonnie and Schwartz, Rich and Micciulla, Linnea and Makhoul, John\", booktitle = \"Proceedings of the 7th Conference of the Association for Machine Translation in the Americas: Technical Papers\", month = aug # \" 8-12\", year = \"2006\", address = \"Cambridge, Massachusetts, USA\", publisher = \"Association for Machine Translation in the Americas\", url = \"https://aclanthology.org/2006.amta-papers.25\", pages = \"223--231\", } @inproceedings{post-2018-call, title = \"A Call for Clarity in Reporting {BLEU} Scores\", author = \"Post, Matt\", booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\", month = oct, year = \"2018\", address = \"Belgium, Brussels\", publisher = \"Association for Computational Linguistics\", url = \"https://www.aclweb.org/anthology/W18-6319\", pages = \"186--191\", } """ SCREAMING_SNAKE_CASE__ : Optional[Any] = """\ TER (Translation Edit Rate, also called Translation Error Rate) is a metric to quantify the edit operations that a hypothesis requires to match a reference translation. We use the implementation that is already present in sacrebleu (https://github.com/mjpost/sacreBLEU#ter), which in turn is inspired by the TERCOM implementation, which can be found here: https://github.com/jhclark/tercom. The implementation here is slightly different from sacrebleu in terms of the required input format. The length of the references and hypotheses lists need to be the same, so you may need to transpose your references compared to sacrebleu's required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534 See the README.md file at https://github.com/mjpost/sacreBLEU#ter for more information. """ SCREAMING_SNAKE_CASE__ : int = """ Produces TER scores alongside the number of edits and reference length. Args: predictions (list of str): The system stream (a sequence of segments). references (list of list of str): A list of one or more reference streams (each a sequence of segments). normalized (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`. ignore_punct (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`. support_zh_ja_chars (boolean): If `True`, tokenization/normalization supports processing of Chinese characters, as well as Japanese Kanji, Hiragana, Katakana, and Phonetic Extensions of Katakana. Only applies if `normalized = True`. Defaults to `False`. case_sensitive (boolean): If `False`, makes all predictions and references lowercase to ignore differences in case. Defaults to `False`. Returns: 'score' (float): TER score (num_edits / sum_ref_lengths * 100) 'num_edits' (int): The cumulative number of edits 'ref_length' (float): The cumulative average reference length Examples: Example 1: >>> predictions = [\"does this sentence match??\", ... \"what about this sentence?\", ... \"What did the TER metric user say to the developer?\"] >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"], ... [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"], ... [\"Your jokes are...\", \"...TERrible\"]] >>> ter = datasets.load_metric(\"ter\") >>> results = ter.compute(predictions=predictions, ... references=references, ... case_sensitive=True) >>> print(results) {'score': 150.0, 'num_edits': 15, 'ref_length': 10.0} Example 2: >>> predictions = [\"does this sentence match??\", ... \"what about this sentence?\"] >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"], ... [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]] >>> ter = datasets.load_metric(\"ter\") >>> results = ter.compute(predictions=predictions, ... references=references, ... case_sensitive=True) >>> print(results) {'score': 62.5, 'num_edits': 5, 'ref_length': 8.0} Example 3: >>> predictions = [\"does this sentence match??\", ... \"what about this sentence?\"] >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"], ... [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]] >>> ter = datasets.load_metric(\"ter\") >>> results = ter.compute(predictions=predictions, ... references=references, ... normalized=True, ... case_sensitive=True) >>> print(results) {'score': 57.14285714285714, 'num_edits': 6, 'ref_length': 10.5} Example 4: >>> predictions = [\"does this sentence match??\", ... \"what about this sentence?\"] >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"], ... [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]] >>> ter = datasets.load_metric(\"ter\") >>> results = ter.compute(predictions=predictions, ... references=references, ... ignore_punct=True, ... case_sensitive=False) >>> print(results) {'score': 0.0, 'num_edits': 0, 'ref_length': 8.0} Example 5: >>> predictions = [\"does this sentence match??\", ... \"what about this sentence?\", ... \"What did the TER metric user say to the developer?\"] >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"], ... [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"], ... [\"Your jokes are...\", \"...TERrible\"]] >>> ter = datasets.load_metric(\"ter\") >>> results = ter.compute(predictions=predictions, ... references=references, ... ignore_punct=True, ... case_sensitive=False) >>> print(results) {'score': 100.0, 'num_edits': 10, 'ref_length': 10.0} """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION ,_KWARGS_DESCRIPTION ) class __lowerCAmelCase ( datasets.Metric ): def _snake_case ( self ) -> Optional[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 _snake_case ( self , snake_case , snake_case , snake_case = False , snake_case = False , snake_case = False , snake_case = False , ) -> Optional[Any]: """simple docstring""" a__ : int = len(references[0] ) if any(len(snake_case ) != references_per_prediction for refs in references ): raise ValueError("Sacrebleu requires the same number of references for each prediction" ) a__ : int = [[refs[i] for refs in references] for i in range(snake_case )] a__ : Optional[Any] = TER( normalized=snake_case , no_punct=snake_case , asian_support=snake_case , case_sensitive=snake_case , ) a__ : Union[str, Any] = sb_ter.corpus_score(snake_case , snake_case ) return {"score": output.score, "num_edits": output.num_edits, "ref_length": output.ref_length}
112
0
"""simple docstring""" from transformers import HfArgumentParser, TensorFlowBenchmark, TensorFlowBenchmarkArguments def UpperCAmelCase ( ): """simple docstring""" A__ = HfArgumentParser(UpperCamelCase__ ) A__ = parser.parse_args_into_dataclasses()[0] A__ = TensorFlowBenchmark(args=UpperCamelCase__ ) try: A__ = parser.parse_args_into_dataclasses()[0] except ValueError as e: A__ = 'Arg --no_{0} is no longer used, please use --no-{0} instead.' A__ = ' '.join(str(UpperCamelCase__ ).split(' ' )[:-1] ) A__ = '' A__ = eval(str(UpperCamelCase__ ).split(' ' )[-1] ) A__ = [] for arg in depreciated_args: # arg[2:] removes '--' if arg[2:] in TensorFlowBenchmark.deprecated_args: # arg[5:] removes '--no_' full_error_msg += arg_error_msg.format(arg[5:] ) else: wrong_args.append(UpperCamelCase__ ) if len(UpperCamelCase__ ) > 0: A__ = full_error_msg + begin_error_msg + str(UpperCamelCase__ ) raise ValueError(UpperCamelCase__ ) benchmark.run() if __name__ == "__main__": main()
536
"""simple docstring""" import unittest import numpy as np from diffusers import OnnxStableDiffusionInpaintPipelineLegacy from diffusers.utils.testing_utils import ( is_onnx_available, load_image, load_numpy, nightly, require_onnxruntime, require_torch_gpu, ) if is_onnx_available(): import onnxruntime as ort @nightly @require_onnxruntime @require_torch_gpu class UpperCamelCase__( unittest.TestCase ): @property def snake_case__ ( self ) -> int: return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def snake_case__ ( self ) -> Union[str, Any]: A__ = ort.SessionOptions() A__ = False return options def snake_case__ ( self ) -> str: A__ = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/in_paint/overture-creations-5sI6fQgYIuo.png' ) A__ = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/in_paint/overture-creations-5sI6fQgYIuo_mask.png' ) A__ = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/in_paint/red_cat_sitting_on_a_park_bench_onnx.npy' ) # using the PNDM scheduler by default A__ = OnnxStableDiffusionInpaintPipelineLegacy.from_pretrained( 'CompVis/stable-diffusion-v1-4' ,revision='onnx' ,safety_checker=__UpperCAmelCase ,feature_extractor=__UpperCAmelCase ,provider=self.gpu_provider ,sess_options=self.gpu_options ,) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) A__ = 'A red cat sitting on a park bench' A__ = np.random.RandomState(0 ) A__ = pipe( prompt=__UpperCAmelCase ,image=__UpperCAmelCase ,mask_image=__UpperCAmelCase ,strength=0.7_5 ,guidance_scale=7.5 ,num_inference_steps=15 ,generator=__UpperCAmelCase ,output_type='np' ,) A__ = output.images[0] assert image.shape == (5_12, 5_12, 3) assert np.abs(expected_image - image ).max() < 1e-2
536
1
'''simple docstring''' import re from flax.core.frozen_dict import freeze from flax.traverse_util import flatten_dict, unflatten_dict from jax.experimental import PartitionSpec as P # Sentinels __lowerCAmelCase =object() # For specifying empty leaf dict `{}` __lowerCAmelCase =object() def a ( _UpperCAmelCase , _UpperCAmelCase ) -> str: """simple docstring""" a_ = tuple((re.compile(x + '$' ) for x in qs) ) for i in range(len(_UpperCAmelCase ) - len(_UpperCAmelCase ) + 1 ): a_ = [x.match(_UpperCAmelCase ) for x, y in zip(_UpperCAmelCase , ks[i:] )] if matches and all(_UpperCAmelCase ): return True return False def a ( _UpperCAmelCase ) -> List[Any]: """simple docstring""" def replace(_UpperCAmelCase , _UpperCAmelCase ): for rule, replacement in rules: if _match(_UpperCAmelCase , _UpperCAmelCase ): return replacement return val return replace def a ( ) -> Optional[int]: """simple docstring""" return [ # embeddings (("transformer", "wpe", "embedding"), P('mp' , _UpperCAmelCase )), (("transformer", "wte", "embedding"), P('mp' , _UpperCAmelCase )), # atention (("attention", "(q_proj|k_proj|v_proj)", "kernel"), P(_UpperCAmelCase , 'mp' )), (("attention", "out_proj", "kernel"), P('mp' , _UpperCAmelCase )), (("attention", "out_proj", "bias"), None), # mlp (("mlp", "c_fc", "kernel"), P(_UpperCAmelCase , 'mp' )), (("mlp", "c_fc", "bias"), P('mp' )), (("mlp", "c_proj", "kernel"), P('mp' , _UpperCAmelCase )), (("mlp", "c_proj", "bias"), None), # layer norms ((r"ln_\d+", "bias"), None), ((r"\d+", r"ln_\d+", "scale"), None), (("ln_f", "bias"), None), (("ln_f", "scale"), None), ] def a ( _UpperCAmelCase ) -> Dict: """simple docstring""" a_ = _get_partition_rules() a_ = _replacement_rules(_UpperCAmelCase ) a_ = {k: _unmatched for k in flatten_dict(_UpperCAmelCase )} a_ = {k: replace(_UpperCAmelCase , _UpperCAmelCase ) for k, v in initd.items()} assert _unmatched not in result.values(), "Incomplete partition spec." return freeze(unflatten_dict(_UpperCAmelCase ) )
697
'''simple docstring''' from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __lowerCAmelCase ={"configuration_focalnet": ["FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "FocalNetConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase =[ "FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST", "FocalNetForImageClassification", "FocalNetForMaskedImageModeling", "FocalNetBackbone", "FocalNetModel", "FocalNetPreTrainedModel", ] if TYPE_CHECKING: from .configuration_focalnet import FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FocalNetConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_focalnet import ( FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST, FocalNetBackbone, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetModel, FocalNetPreTrainedModel, ) else: import sys __lowerCAmelCase =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
697
1
"""simple docstring""" import inspect import unittest from transformers import MobileViTConfig 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 MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel from transformers.models.mobilevit.modeling_mobilevit import MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class snake_case ( __a ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Optional[int] ): '''simple docstring''' __A = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(a_, '''hidden_sizes''' ) ) self.parent.assertTrue(hasattr(a_, '''neck_hidden_sizes''' ) ) self.parent.assertTrue(hasattr(a_, '''num_attention_heads''' ) ) class snake_case : '''simple docstring''' def __init__( self : Dict, _lowerCamelCase : str, _lowerCamelCase : Tuple=13, _lowerCamelCase : List[str]=32, _lowerCamelCase : Dict=2, _lowerCamelCase : Optional[int]=3, _lowerCamelCase : Union[str, Any]=6_40, _lowerCamelCase : Tuple=4, _lowerCamelCase : Optional[Any]="silu", _lowerCamelCase : Tuple=3, _lowerCamelCase : str=32, _lowerCamelCase : Optional[Any]=0.1, _lowerCamelCase : Any=0.1, _lowerCamelCase : Optional[Any]=0.1, _lowerCamelCase : int=0.02, _lowerCamelCase : int=True, _lowerCamelCase : int=True, _lowerCamelCase : Union[str, Any]=10, _lowerCamelCase : Optional[Any]=None, ): '''simple docstring''' __A = parent __A = batch_size __A = image_size __A = patch_size __A = num_channels __A = last_hidden_size __A = num_attention_heads __A = hidden_act __A = conv_kernel_size __A = output_stride __A = hidden_dropout_prob __A = attention_probs_dropout_prob __A = classifier_dropout_prob __A = use_labels __A = is_training __A = num_labels __A = initializer_range __A = scope def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' __A = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __A = None __A = None if self.use_labels: __A = ids_tensor([self.batch_size], self.num_labels ) __A = ids_tensor([self.batch_size, self.image_size, self.image_size], self.num_labels ) __A = self.get_config() return config, pixel_values, labels, pixel_labels def _SCREAMING_SNAKE_CASE ( self : Any ): '''simple docstring''' return MobileViTConfig( image_size=self.image_size, patch_size=self.patch_size, num_channels=self.num_channels, num_attention_heads=self.num_attention_heads, hidden_act=self.hidden_act, conv_kernel_size=self.conv_kernel_size, output_stride=self.output_stride, hidden_dropout_prob=self.hidden_dropout_prob, attention_probs_dropout_prob=self.attention_probs_dropout_prob, classifier_dropout_prob=self.classifier_dropout_prob, initializer_range=self.initializer_range, ) def _SCREAMING_SNAKE_CASE ( self : List[str], _lowerCamelCase : Any, _lowerCamelCase : Optional[int], _lowerCamelCase : Dict, _lowerCamelCase : Any ): '''simple docstring''' __A = MobileViTModel(config=a_ ) model.to(a_ ) model.eval() __A = model(a_ ) 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 _SCREAMING_SNAKE_CASE ( self : Dict, _lowerCamelCase : Optional[int], _lowerCamelCase : Tuple, _lowerCamelCase : List[str], _lowerCamelCase : List[Any] ): '''simple docstring''' __A = self.num_labels __A = MobileViTForImageClassification(a_ ) model.to(a_ ) model.eval() __A = model(a_, labels=a_ ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels) ) def _SCREAMING_SNAKE_CASE ( self : str, _lowerCamelCase : Any, _lowerCamelCase : Union[str, Any], _lowerCamelCase : Tuple, _lowerCamelCase : int ): '''simple docstring''' __A = self.num_labels __A = MobileViTForSemanticSegmentation(a_ ) model.to(a_ ) model.eval() __A = model(a_ ) self.parent.assertEqual( result.logits.shape, ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ), ) __A = model(a_, labels=a_ ) self.parent.assertEqual( result.logits.shape, ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ), ) def _SCREAMING_SNAKE_CASE ( self : List[str] ): '''simple docstring''' __A = self.prepare_config_and_inputs() __A = config_and_inputs __A = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class snake_case ( __a , __a , unittest.TestCase ): '''simple docstring''' A_ : Tuple = ( (MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation) if is_torch_available() else () ) A_ : Optional[int] = ( { "feature-extraction": MobileViTModel, "image-classification": MobileViTForImageClassification, "image-segmentation": MobileViTForSemanticSegmentation, } if is_torch_available() else {} ) A_ : Optional[int] = False A_ : Dict = False A_ : List[str] = False A_ : Optional[int] = False def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = MobileViTModelTester(self ) __A = MobileViTConfigTester(self, config_class=a_, has_text_modality=a_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ): '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason='''MobileViT does not use inputs_embeds''' ) def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' pass @unittest.skip(reason='''MobileViT does not support input and output embeddings''' ) def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' pass @unittest.skip(reason='''MobileViT does not output attentions''' ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' __A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __A = model_class(a_ ) __A = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __A = [*signature.parameters.keys()] __A = ["""pixel_values"""] self.assertListEqual(arg_names[:1], a_ ) @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : Optional[int] ): '''simple docstring''' __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' def check_hidden_states_output(_lowerCamelCase : Union[str, Any], _lowerCamelCase : int, _lowerCamelCase : int ): __A = model_class(a_ ) model.to(a_ ) model.eval() with torch.no_grad(): __A = model(**self._prepare_for_class(a_, a_ ) ) __A = outputs.hidden_states __A = 5 self.assertEqual(len(a_ ), a_ ) # MobileViT's feature maps are of shape (batch_size, num_channels, height, width) # with the width and height being successively divided by 2. __A = 2 for i in range(len(a_ ) ): self.assertListEqual( list(hidden_states[i].shape[-2:] ), [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor], ) divisor *= 2 self.assertEqual(self.model_tester.output_stride, divisor // 2 ) __A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __A = True check_hidden_states_output(a_, a_, a_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __A = True check_hidden_states_output(a_, a_, a_ ) def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a_ ) def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*a_ ) @slow def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __A = MobileViTModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def lowerCAmelCase ( ): """simple docstring""" __A = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class snake_case ( unittest.TestCase ): '''simple docstring''' @cached_property def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' return MobileViTImageProcessor.from_pretrained('''apple/mobilevit-xx-small''' ) if is_vision_available() else None @slow def _SCREAMING_SNAKE_CASE ( self : Optional[int] ): '''simple docstring''' __A = MobileViTForImageClassification.from_pretrained('''apple/mobilevit-xx-small''' ).to(a_ ) __A = self.default_image_processor __A = prepare_img() __A = image_processor(images=a_, return_tensors='''pt''' ).to(a_ ) # forward pass with torch.no_grad(): __A = model(**a_ ) # verify the logits __A = torch.Size((1, 10_00) ) self.assertEqual(outputs.logits.shape, a_ ) __A = torch.tensor([-1.93_64, -1.23_27, -0.46_53] ).to(a_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3], a_, atol=1e-4 ) ) @slow def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = MobileViTForSemanticSegmentation.from_pretrained('''apple/deeplabv3-mobilevit-xx-small''' ) __A = model.to(a_ ) __A = MobileViTImageProcessor.from_pretrained('''apple/deeplabv3-mobilevit-xx-small''' ) __A = prepare_img() __A = image_processor(images=a_, return_tensors='''pt''' ).to(a_ ) # forward pass with torch.no_grad(): __A = model(**a_ ) __A = outputs.logits # verify the logits __A = torch.Size((1, 21, 32, 32) ) self.assertEqual(logits.shape, a_ ) __A = torch.tensor( [ [[6.97_13, 6.97_86, 7.24_22], [7.28_93, 7.28_25, 7.44_46], [7.65_80, 7.87_97, 7.94_20]], [[-10.68_69, -10.32_50, -10.34_71], [-10.42_28, -9.98_68, -9.71_32], [-11.04_05, -11.02_21, -10.73_18]], [[-3.30_89, -2.85_39, -2.67_40], [-3.27_06, -2.56_21, -2.51_08], [-3.25_34, -2.66_15, -2.66_51]], ], device=a_, ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3], a_, atol=1e-4 ) ) @slow def _SCREAMING_SNAKE_CASE ( self : str ): '''simple docstring''' __A = MobileViTForSemanticSegmentation.from_pretrained('''apple/deeplabv3-mobilevit-xx-small''' ) __A = model.to(a_ ) __A = MobileViTImageProcessor.from_pretrained('''apple/deeplabv3-mobilevit-xx-small''' ) __A = prepare_img() __A = image_processor(images=a_, return_tensors='''pt''' ).to(a_ ) # forward pass with torch.no_grad(): __A = model(**a_ ) __A = outputs.logits.detach().cpu() __A = image_processor.post_process_semantic_segmentation(outputs=a_, target_sizes=[(50, 60)] ) __A = torch.Size((50, 60) ) self.assertEqual(segmentation[0].shape, a_ ) __A = image_processor.post_process_semantic_segmentation(outputs=a_ ) __A = torch.Size((32, 32) ) self.assertEqual(segmentation[0].shape, a_ )
706
"""simple docstring""" from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('>=', '4.25.0')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import UnCLIPImageVariationPipeline, UnCLIPPipeline else: from .pipeline_unclip import UnCLIPPipeline from .pipeline_unclip_image_variation import UnCLIPImageVariationPipeline from .text_proj import UnCLIPTextProjModel
215
0
"""simple docstring""" import importlib.metadata import operator import re import sys from typing import Optional from packaging import version lowerCamelCase_ = { '''<''': operator.lt, '''<=''': operator.le, '''==''': operator.eq, '''!=''': operator.ne, '''>=''': operator.ge, '''>''': operator.gt, } def snake_case ( A__ ,A__ ,A__ ,A__ ,A__ ,A__ ): if got_ver is None or want_ver is None: raise ValueError( F"""Unable to compare versions for {requirement}: need={want_ver} found={got_ver}. This is unusual. Consider""" F""" reinstalling {pkg}.""" ) if not ops[op](version.parse(A__ ) ,version.parse(A__ ) ): raise ImportError( F"""{requirement} is required for a normal functioning of this module, but found {pkg}=={got_ver}.{hint}""" ) def snake_case ( A__ ,A__ = None ): UpperCAmelCase_ : int = F"""\n{hint}""" if hint is not None else "" # non-versioned check if re.match(r"^[\w_\-\d]+$" ,A__ ): UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : Optional[Any] = requirement, None, None else: UpperCAmelCase_ : Optional[int] = re.findall(r"^([^!=<>\s]+)([\s!=<>]{1,2}.+)" ,A__ ) if not match: raise ValueError( "requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23, but" F""" got {requirement}""" ) UpperCAmelCase_ , UpperCAmelCase_ : List[str] = match[0] UpperCAmelCase_ : Optional[Any] = want_full.split("," ) # there could be multiple requirements UpperCAmelCase_ : int = {} for w in want_range: UpperCAmelCase_ : str = re.findall(r"^([\s!=<>]{1,2})(.+)" ,A__ ) if not match: raise ValueError( "requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23," F""" but got {requirement}""" ) UpperCAmelCase_ , UpperCAmelCase_ : Any = match[0] UpperCAmelCase_ : Union[str, Any] = want_ver if op not in ops: raise ValueError(F"""{requirement}: need one of {list(ops.keys() )}, but got {op}""" ) # special case if pkg == "python": UpperCAmelCase_ : List[Any] = ".".join([str(A__ ) for x in sys.version_info[:3]] ) for op, want_ver in wanted.items(): _compare_versions(A__ ,A__ ,A__ ,A__ ,A__ ,A__ ) return # check if any version is installed try: UpperCAmelCase_ : str = importlib.metadata.version(A__ ) except importlib.metadata.PackageNotFoundError: raise importlib.metadata.PackageNotFoundError( F"""The '{requirement}' distribution was not found and is required by this application. {hint}""" ) # check that the right version is installed if version number or a range was provided if want_ver is not None: for op, want_ver in wanted.items(): _compare_versions(A__ ,A__ ,A__ ,A__ ,A__ ,A__ ) def snake_case ( A__ ): UpperCAmelCase_ : Any = "Try: pip install transformers -U or pip install -e '.[dev]' if you're working with git main" return require_version(A__ ,A__ )
95
import copy import os from collections import OrderedDict from typing import TYPE_CHECKING, Any, Dict, Mapping, Optional, Union if TYPE_CHECKING: from ...processing_utils import ProcessorMixin from ...utils import TensorType from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging SCREAMING_SNAKE_CASE : Dict = logging.get_logger(__name__) SCREAMING_SNAKE_CASE : Tuple = { """google/owlvit-base-patch32""": """https://huggingface.co/google/owlvit-base-patch32/resolve/main/config.json""", """google/owlvit-base-patch16""": """https://huggingface.co/google/owlvit-base-patch16/resolve/main/config.json""", """google/owlvit-large-patch14""": """https://huggingface.co/google/owlvit-large-patch14/resolve/main/config.json""", } class A_ ( a_ ): _SCREAMING_SNAKE_CASE = """owlvit_text_model""" def __init__( self : List[str] , __SCREAMING_SNAKE_CASE : Union[str, Any]=4_94_08 , __SCREAMING_SNAKE_CASE : List[Any]=5_12 , __SCREAMING_SNAKE_CASE : Optional[Any]=20_48 , __SCREAMING_SNAKE_CASE : Optional[int]=12 , __SCREAMING_SNAKE_CASE : Tuple=8 , __SCREAMING_SNAKE_CASE : Optional[Any]=16 , __SCREAMING_SNAKE_CASE : Tuple="quick_gelu" , __SCREAMING_SNAKE_CASE : Union[str, Any]=1E-5 , __SCREAMING_SNAKE_CASE : Any=0.0 , __SCREAMING_SNAKE_CASE : List[str]=0.02 , __SCREAMING_SNAKE_CASE : int=1.0 , __SCREAMING_SNAKE_CASE : int=0 , __SCREAMING_SNAKE_CASE : Optional[Any]=4_94_06 , __SCREAMING_SNAKE_CASE : Optional[Any]=4_94_07 , **__SCREAMING_SNAKE_CASE : Union[str, Any] , ): super().__init__(pad_token_id=__SCREAMING_SNAKE_CASE , bos_token_id=__SCREAMING_SNAKE_CASE , eos_token_id=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __a = vocab_size __a = hidden_size __a = intermediate_size __a = num_hidden_layers __a = num_attention_heads __a = max_position_embeddings __a = hidden_act __a = layer_norm_eps __a = attention_dropout __a = initializer_range __a = initializer_factor @classmethod def _UpperCAmelCase ( cls : int , __SCREAMING_SNAKE_CASE : Union[str, os.PathLike] , **__SCREAMING_SNAKE_CASE : Optional[int] ): cls._set_token_in_kwargs(__SCREAMING_SNAKE_CASE ) __a , __a = cls.get_config_dict(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) # get the text config dict if we are loading from OwlViTConfig if config_dict.get("model_type" ) == "owlvit": __a = config_dict["text_config"] if "model_type" in config_dict and hasattr(cls , "model_type" ) and config_dict["model_type"] != cls.model_type: logger.warning( f"""You are using a model of type {config_dict["model_type"]} to instantiate a model of type """ f"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" ) return cls.from_dict(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) class A_ ( a_ ): _SCREAMING_SNAKE_CASE = """owlvit_vision_model""" def __init__( self : List[str] , __SCREAMING_SNAKE_CASE : Optional[Any]=7_68 , __SCREAMING_SNAKE_CASE : Any=30_72 , __SCREAMING_SNAKE_CASE : str=12 , __SCREAMING_SNAKE_CASE : int=12 , __SCREAMING_SNAKE_CASE : str=3 , __SCREAMING_SNAKE_CASE : Optional[Any]=7_68 , __SCREAMING_SNAKE_CASE : List[Any]=32 , __SCREAMING_SNAKE_CASE : Dict="quick_gelu" , __SCREAMING_SNAKE_CASE : List[Any]=1E-5 , __SCREAMING_SNAKE_CASE : int=0.0 , __SCREAMING_SNAKE_CASE : Optional[Any]=0.02 , __SCREAMING_SNAKE_CASE : Dict=1.0 , **__SCREAMING_SNAKE_CASE : Optional[int] , ): super().__init__(**__SCREAMING_SNAKE_CASE ) __a = hidden_size __a = intermediate_size __a = num_hidden_layers __a = num_attention_heads __a = num_channels __a = image_size __a = patch_size __a = hidden_act __a = layer_norm_eps __a = attention_dropout __a = initializer_range __a = initializer_factor @classmethod def _UpperCAmelCase ( cls : List[str] , __SCREAMING_SNAKE_CASE : Union[str, os.PathLike] , **__SCREAMING_SNAKE_CASE : Tuple ): cls._set_token_in_kwargs(__SCREAMING_SNAKE_CASE ) __a , __a = cls.get_config_dict(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) # get the vision config dict if we are loading from OwlViTConfig if config_dict.get("model_type" ) == "owlvit": __a = config_dict["vision_config"] if "model_type" in config_dict and hasattr(cls , "model_type" ) and config_dict["model_type"] != cls.model_type: logger.warning( f"""You are using a model of type {config_dict["model_type"]} to instantiate a model of type """ f"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" ) return cls.from_dict(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) class A_ ( a_ ): _SCREAMING_SNAKE_CASE = """owlvit""" _SCREAMING_SNAKE_CASE = True def __init__( self : Dict , __SCREAMING_SNAKE_CASE : Optional[int]=None , __SCREAMING_SNAKE_CASE : Tuple=None , __SCREAMING_SNAKE_CASE : str=5_12 , __SCREAMING_SNAKE_CASE : List[Any]=2.65_92 , __SCREAMING_SNAKE_CASE : Dict=True , **__SCREAMING_SNAKE_CASE : List[Any] , ): super().__init__(**__SCREAMING_SNAKE_CASE ) if text_config is None: __a = {} logger.info("text_config is None. Initializing the OwlViTTextConfig with default values." ) if vision_config is None: __a = {} logger.info("vision_config is None. initializing the OwlViTVisionConfig with default values." ) __a = OwlViTTextConfig(**__SCREAMING_SNAKE_CASE ) __a = OwlViTVisionConfig(**__SCREAMING_SNAKE_CASE ) __a = projection_dim __a = logit_scale_init_value __a = return_dict __a = 1.0 @classmethod def _UpperCAmelCase ( cls : Tuple , __SCREAMING_SNAKE_CASE : Union[str, os.PathLike] , **__SCREAMING_SNAKE_CASE : List[str] ): cls._set_token_in_kwargs(__SCREAMING_SNAKE_CASE ) __a , __a = cls.get_config_dict(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) if "model_type" in config_dict and hasattr(cls , "model_type" ) and config_dict["model_type"] != cls.model_type: logger.warning( f"""You are using a model of type {config_dict["model_type"]} to instantiate a model of type """ f"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" ) return cls.from_dict(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) @classmethod def _UpperCAmelCase ( cls : List[Any] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Dict , **__SCREAMING_SNAKE_CASE : Optional[Any] ): __a = {} __a = text_config __a = vision_config return cls.from_dict(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def _UpperCAmelCase ( self : Optional[Any] ): __a = copy.deepcopy(self.__dict__ ) __a = self.text_config.to_dict() __a = self.vision_config.to_dict() __a = self.__class__.model_type return output class A_ ( a_ ): @property def _UpperCAmelCase ( self : Any ): return OrderedDict( [ ("input_ids", {0: "batch", 1: "sequence"}), ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ("attention_mask", {0: "batch", 1: "sequence"}), ] ) @property def _UpperCAmelCase ( self : Union[str, Any] ): return OrderedDict( [ ("logits_per_image", {0: "batch"}), ("logits_per_text", {0: "batch"}), ("text_embeds", {0: "batch"}), ("image_embeds", {0: "batch"}), ] ) @property def _UpperCAmelCase ( self : str ): return 1E-4 def _UpperCAmelCase ( self : Any , __SCREAMING_SNAKE_CASE : "ProcessorMixin" , __SCREAMING_SNAKE_CASE : int = -1 , __SCREAMING_SNAKE_CASE : int = -1 , __SCREAMING_SNAKE_CASE : Optional["TensorType"] = None , ): __a = super().generate_dummy_inputs( processor.tokenizer , batch_size=__SCREAMING_SNAKE_CASE , seq_length=__SCREAMING_SNAKE_CASE , framework=__SCREAMING_SNAKE_CASE ) __a = super().generate_dummy_inputs( processor.image_processor , batch_size=__SCREAMING_SNAKE_CASE , framework=__SCREAMING_SNAKE_CASE ) return {**text_input_dict, **image_input_dict} @property def _UpperCAmelCase ( self : Optional[int] ): return 14
197
0
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionInstructPixaPixPipeline, UNetaDConditionModel, ) from diffusers.image_processor import VaeImageProcessor from diffusers.utils import floats_tensor, load_image, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class UpperCAmelCase__ ( _A , _A , _A , unittest.TestCase ): lowerCAmelCase_ = StableDiffusionInstructPixaPixPipeline lowerCAmelCase_ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'height', 'width', 'cross_attention_kwargs'} lowerCAmelCase_ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS lowerCAmelCase_ = IMAGE_TO_IMAGE_IMAGE_PARAMS lowerCAmelCase_ = IMAGE_TO_IMAGE_IMAGE_PARAMS def lowerCamelCase_ ( self : Any ): torch.manual_seed(0 ) _lowerCamelCase : Optional[int] = UNetaDConditionModel( block_out_channels=(3_2, 6_4),layers_per_block=2,sample_size=3_2,in_channels=8,out_channels=4,down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),cross_attention_dim=3_2,) _lowerCamelCase : Union[str, Any] = PNDMScheduler(skip_prk_steps=__A ) torch.manual_seed(0 ) _lowerCamelCase : Optional[Any] = AutoencoderKL( block_out_channels=[3_2, 6_4],in_channels=3,out_channels=3,down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],latent_channels=4,) torch.manual_seed(0 ) _lowerCamelCase : Optional[int] = CLIPTextConfig( bos_token_id=0,eos_token_id=2,hidden_size=3_2,intermediate_size=3_7,layer_norm_eps=1e-05,num_attention_heads=4,num_hidden_layers=5,pad_token_id=1,vocab_size=1_0_0_0,) _lowerCamelCase : Optional[Any] = CLIPTextModel(__A ) _lowerCamelCase : Optional[int] = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) _lowerCamelCase : Optional[Any] = { "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "safety_checker": None, "feature_extractor": None, } return components def lowerCamelCase_ ( self : Dict,__A : int,__A : Any=0 ): _lowerCamelCase : Tuple = floats_tensor((1, 3, 3_2, 3_2),rng=random.Random(__A ) ).to(__A ) _lowerCamelCase : Tuple = image.cpu().permute(0,2,3,1 )[0] _lowerCamelCase : Union[str, Any] = Image.fromarray(np.uinta(__A ) ).convert("RGB" ) if str(__A ).startswith("mps" ): _lowerCamelCase : Dict = torch.manual_seed(__A ) else: _lowerCamelCase : List[Any] = torch.Generator(device=__A ).manual_seed(__A ) _lowerCamelCase : Tuple = { "prompt": "A painting of a squirrel eating a burger", "image": image, "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, "image_guidance_scale": 1, "output_type": "numpy", } return inputs def lowerCamelCase_ ( self : Optional[Any] ): _lowerCamelCase : List[Any] = "cpu" # ensure determinism for the device-dependent torch.Generator _lowerCamelCase : Union[str, Any] = self.get_dummy_components() _lowerCamelCase : List[Any] = StableDiffusionInstructPixaPixPipeline(**__A ) _lowerCamelCase : int = sd_pipe.to(__A ) sd_pipe.set_progress_bar_config(disable=__A ) _lowerCamelCase : Dict = self.get_dummy_inputs(__A ) _lowerCamelCase : Optional[Any] = sd_pipe(**__A ).images _lowerCamelCase : Optional[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 3_2, 3_2, 3) _lowerCamelCase : Union[str, Any] = np.array([0.7526, 0.3750, 0.4547, 0.6117, 0.5866, 0.5016, 0.4327, 0.5642, 0.4815] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def lowerCamelCase_ ( self : Tuple ): _lowerCamelCase : Tuple = "cpu" # ensure determinism for the device-dependent torch.Generator _lowerCamelCase : Any = self.get_dummy_components() _lowerCamelCase : List[Any] = StableDiffusionInstructPixaPixPipeline(**__A ) _lowerCamelCase : Optional[Any] = sd_pipe.to(__A ) sd_pipe.set_progress_bar_config(disable=__A ) _lowerCamelCase : Optional[int] = self.get_dummy_inputs(__A ) _lowerCamelCase : List[str] = "french fries" _lowerCamelCase : int = sd_pipe(**__A,negative_prompt=__A ) _lowerCamelCase : Optional[int] = output.images _lowerCamelCase : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 3_2, 3_2, 3) _lowerCamelCase : Optional[int] = np.array([0.7511, 0.3642, 0.4553, 0.6236, 0.5797, 0.5013, 0.4343, 0.5611, 0.4831] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def lowerCamelCase_ ( self : Any ): _lowerCamelCase : Optional[Any] = "cpu" # ensure determinism for the device-dependent torch.Generator _lowerCamelCase : List[Any] = self.get_dummy_components() _lowerCamelCase : Optional[int] = StableDiffusionInstructPixaPixPipeline(**__A ) _lowerCamelCase : List[Any] = sd_pipe.to(__A ) sd_pipe.set_progress_bar_config(disable=__A ) _lowerCamelCase : Tuple = self.get_dummy_inputs(__A ) _lowerCamelCase : int = [inputs["prompt"]] * 2 _lowerCamelCase : Optional[Any] = np.array(inputs["image"] ).astype(np.floataa ) / 255.0 _lowerCamelCase : Union[str, Any] = torch.from_numpy(__A ).unsqueeze(0 ).to(__A ) _lowerCamelCase : Tuple = image / 2 + 0.5 _lowerCamelCase : Tuple = image.permute(0,3,1,2 ) _lowerCamelCase : Dict = image.repeat(2,1,1,1 ) _lowerCamelCase : List[Any] = sd_pipe(**__A ).images _lowerCamelCase : Tuple = image[-1, -3:, -3:, -1] assert image.shape == (2, 3_2, 3_2, 3) _lowerCamelCase : str = np.array([0.5812, 0.5748, 0.5222, 0.5908, 0.5695, 0.7174, 0.6804, 0.5523, 0.5579] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def lowerCamelCase_ ( self : Optional[int] ): _lowerCamelCase : int = "cpu" # ensure determinism for the device-dependent torch.Generator _lowerCamelCase : Dict = self.get_dummy_components() _lowerCamelCase : Any = EulerAncestralDiscreteScheduler( beta_start=0.00085,beta_end=0.012,beta_schedule="scaled_linear" ) _lowerCamelCase : Tuple = StableDiffusionInstructPixaPixPipeline(**__A ) _lowerCamelCase : str = sd_pipe.to(__A ) sd_pipe.set_progress_bar_config(disable=__A ) _lowerCamelCase : Dict = self.get_dummy_inputs(__A ) _lowerCamelCase : Dict = sd_pipe(**__A ).images _lowerCamelCase : int = image[0, -3:, -3:, -1] _lowerCamelCase : Optional[int] = [round(__A,4 ) for x in image_slice.flatten().tolist()] print(",".join([str(__A ) for x in slice] ) ) assert image.shape == (1, 3_2, 3_2, 3) _lowerCamelCase : str = np.array([0.7417, 0.3842, 0.4732, 0.5776, 0.5891, 0.5139, 0.4052, 0.5673, 0.4986] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def lowerCamelCase_ ( self : Union[str, Any] ): super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) def lowerCamelCase_ ( self : Dict ): _lowerCamelCase : Optional[Any] = self.get_dummy_components() _lowerCamelCase : List[Any] = StableDiffusionInstructPixaPixPipeline(**__A ) _lowerCamelCase : List[Any] = VaeImageProcessor(do_resize=__A,do_normalize=__A ) _lowerCamelCase : Any = pipe.to(__A ) pipe.set_progress_bar_config(disable=__A ) _lowerCamelCase : Union[str, Any] = pipe(**self.get_dummy_inputs_by_type(__A,input_image_type="pt" ) )[0] _lowerCamelCase : Dict = components["vae"] _lowerCamelCase : Optional[Any] = self.get_dummy_inputs_by_type(__A,input_image_type="pt" ) for image_param in self.image_latents_params: if image_param in inputs.keys(): _lowerCamelCase : List[str] = vae.encode(inputs[image_param] ).latent_dist.mode() _lowerCamelCase : Dict = pipe(**__A )[0] _lowerCamelCase : str = np.abs(out - out_latents_inputs ).max() self.assertLess(__A,1e-4,"passing latents as image input generate different result from passing image" ) @slow @require_torch_gpu class UpperCAmelCase__ ( unittest.TestCase ): def lowerCamelCase_ ( self : Dict ): super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCamelCase_ ( self : int,__A : Union[str, Any]=0 ): _lowerCamelCase : List[Any] = torch.manual_seed(__A ) _lowerCamelCase : Union[str, Any] = load_image( "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_pix2pix/example.jpg" ) _lowerCamelCase : List[Any] = { "prompt": "turn him into a cyborg", "image": image, "generator": generator, "num_inference_steps": 3, "guidance_scale": 7.5, "image_guidance_scale": 1.0, "output_type": "numpy", } return inputs def lowerCamelCase_ ( self : Tuple ): _lowerCamelCase : Optional[Any] = StableDiffusionInstructPixaPixPipeline.from_pretrained( "timbrooks/instruct-pix2pix",safety_checker=__A ) pipe.to(__A ) pipe.set_progress_bar_config(disable=__A ) pipe.enable_attention_slicing() _lowerCamelCase : int = self.get_inputs() _lowerCamelCase : List[str] = pipe(**__A ).images _lowerCamelCase : Dict = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_1_2, 5_1_2, 3) _lowerCamelCase : Dict = np.array([0.5902, 0.6015, 0.6027, 0.5983, 0.6092, 0.6061, 0.5765, 0.5785, 0.5555] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def lowerCamelCase_ ( self : Optional[int] ): _lowerCamelCase : List[str] = StableDiffusionInstructPixaPixPipeline.from_pretrained( "timbrooks/instruct-pix2pix",safety_checker=__A ) _lowerCamelCase : List[str] = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.to(__A ) pipe.set_progress_bar_config(disable=__A ) pipe.enable_attention_slicing() _lowerCamelCase : Optional[Any] = self.get_inputs() _lowerCamelCase : Dict = pipe(**__A ).images _lowerCamelCase : Any = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_1_2, 5_1_2, 3) _lowerCamelCase : Optional[Any] = np.array([0.6578, 0.6817, 0.6972, 0.6761, 0.6856, 0.6916, 0.6428, 0.6516, 0.6301] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def lowerCamelCase_ ( self : Dict ): _lowerCamelCase : str = StableDiffusionInstructPixaPixPipeline.from_pretrained( "timbrooks/instruct-pix2pix",safety_checker=__A ) _lowerCamelCase : Any = DDIMScheduler.from_config(pipe.scheduler.config ) pipe.to(__A ) pipe.set_progress_bar_config(disable=__A ) pipe.enable_attention_slicing() _lowerCamelCase : Tuple = self.get_inputs() _lowerCamelCase : str = pipe(**__A ).images _lowerCamelCase : Union[str, Any] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_1_2, 5_1_2, 3) _lowerCamelCase : List[Any] = np.array([0.3828, 0.3834, 0.3818, 0.3792, 0.3865, 0.3752, 0.3792, 0.3847, 0.3753] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def lowerCamelCase_ ( self : Union[str, Any] ): _lowerCamelCase : str = 0 def callback_fn(__A : List[Any],__A : Optional[Any],__A : Dict ) -> None: _lowerCamelCase : Union[str, Any] = True nonlocal number_of_steps number_of_steps += 1 if step == 1: _lowerCamelCase : Optional[int] = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 6_4, 6_4) _lowerCamelCase : Any = latents[0, -3:, -3:, -1] _lowerCamelCase : Optional[Any] = np.array([-0.2463, -0.4644, -0.9756, 1.5176, 1.4414, 0.7866, 0.9897, 0.8521, 0.7983] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 elif step == 2: _lowerCamelCase : Tuple = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 6_4, 6_4) _lowerCamelCase : List[str] = latents[0, -3:, -3:, -1] _lowerCamelCase : Tuple = np.array([-0.2644, -0.4626, -0.9653, 1.5176, 1.4551, 0.7686, 0.9805, 0.8452, 0.8115] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 _lowerCamelCase : Any = False _lowerCamelCase : Tuple = StableDiffusionInstructPixaPixPipeline.from_pretrained( "timbrooks/instruct-pix2pix",safety_checker=__A,torch_dtype=torch.floataa ) _lowerCamelCase : Optional[Any] = pipe.to(__A ) pipe.set_progress_bar_config(disable=__A ) pipe.enable_attention_slicing() _lowerCamelCase : Dict = self.get_inputs() pipe(**__A,callback=__A,callback_steps=1 ) assert callback_fn.has_been_called assert number_of_steps == 3 def lowerCamelCase_ ( self : Optional[int] ): torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() _lowerCamelCase : int = StableDiffusionInstructPixaPixPipeline.from_pretrained( "timbrooks/instruct-pix2pix",safety_checker=__A,torch_dtype=torch.floataa ) _lowerCamelCase : int = pipe.to(__A ) pipe.set_progress_bar_config(disable=__A ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() _lowerCamelCase : Any = self.get_inputs() _lowerCamelCase : int = pipe(**__A ) _lowerCamelCase : Dict = torch.cuda.max_memory_allocated() # make sure that less than 2.2 GB is allocated assert mem_bytes < 2.2 * 1_0**9 def lowerCamelCase_ ( self : List[str] ): _lowerCamelCase : Any = self.get_inputs() # resize to resolution that is divisible by 8 but not 16 or 32 _lowerCamelCase : Optional[int] = inputs["image"].resize((5_0_4, 5_0_4) ) _lowerCamelCase : List[Any] = "timbrooks/instruct-pix2pix" _lowerCamelCase : List[str] = StableDiffusionInstructPixaPixPipeline.from_pretrained( __A,safety_checker=__A,) pipe.to(__A ) pipe.set_progress_bar_config(disable=__A ) pipe.enable_attention_slicing() _lowerCamelCase : Optional[int] = pipe(**__A ) _lowerCamelCase : Any = output.images[0] _lowerCamelCase : Union[str, Any] = image[2_5_5:2_5_8, 3_8_3:3_8_6, -1] assert image.shape == (5_0_4, 5_0_4, 3) _lowerCamelCase : Optional[int] = np.array([0.2726, 0.2529, 0.2664, 0.2655, 0.2641, 0.2642, 0.2591, 0.2649, 0.2590] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-3
712
'''simple docstring''' import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_blenderbot import BlenderbotTokenizer if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation UpperCAmelCase_ : Any = logging.get_logger(__name__) UpperCAmelCase_ : Any = { 'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_config_file': 'tokenizer_config.json', } UpperCAmelCase_ : List[str] = { 'vocab_file': {'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/vocab.json'}, 'merges_file': {'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/merges.txt'}, 'tokenizer_config_file': { 'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/tokenizer_config.json' }, } UpperCAmelCase_ : List[Any] = {'facebook/blenderbot-3B': 128} class UpperCAmelCase__ ( A ): lowerCAmelCase_ = VOCAB_FILES_NAMES lowerCAmelCase_ = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase_ = ['input_ids', 'attention_mask'] lowerCAmelCase_ = BlenderbotTokenizer def __init__( self : Dict,__A : Optional[Any]=None,__A : List[str]=None,__A : Optional[Any]=None,__A : List[Any]="replace",__A : List[Any]="<s>",__A : str="</s>",__A : List[str]="</s>",__A : List[Any]="<s>",__A : Union[str, Any]="<unk>",__A : Optional[Any]="<pad>",__A : Dict="<mask>",__A : Any=False,__A : Tuple=True,**__A : Dict,): super().__init__( __A,__A,tokenizer_file=__A,errors=__A,bos_token=__A,eos_token=__A,sep_token=__A,cls_token=__A,unk_token=__A,pad_token=__A,mask_token=__A,add_prefix_space=__A,trim_offsets=__A,**__A,) _lowerCamelCase : Tuple = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("add_prefix_space",__A ) != add_prefix_space: _lowerCamelCase : Optional[Any] = getattr(__A,pre_tok_state.pop("type" ) ) _lowerCamelCase : List[Any] = add_prefix_space _lowerCamelCase : Optional[Any] = pre_tok_class(**__A ) _lowerCamelCase : Any = add_prefix_space _lowerCamelCase : Any = "post_processor" _lowerCamelCase : Optional[Any] = getattr(self.backend_tokenizer,__A,__A ) if tokenizer_component_instance: _lowerCamelCase : Tuple = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: _lowerCamelCase : List[Any] = tuple(state["sep"] ) if "cls" in state: _lowerCamelCase : Optional[int] = tuple(state["cls"] ) _lowerCamelCase : List[str] = False if state.get("add_prefix_space",__A ) != add_prefix_space: _lowerCamelCase : List[str] = add_prefix_space _lowerCamelCase : int = True if state.get("trim_offsets",__A ) != trim_offsets: _lowerCamelCase : List[str] = trim_offsets _lowerCamelCase : Dict = True if changes_to_apply: _lowerCamelCase : Tuple = getattr(__A,state.pop("type" ) ) _lowerCamelCase : Union[str, Any] = component_class(**__A ) setattr(self.backend_tokenizer,__A,__A ) @property # Copied from transformers.models.roberta.tokenization_roberta_fast.RobertaTokenizerFast.mask_token with Roberta->Blenderbot, RoBERTa->Blenderbot def lowerCamelCase_ ( self : Optional[int] ): if self._mask_token is None: if self.verbose: logger.error("Using mask_token, but it is not set yet." ) return None return str(self._mask_token ) @mask_token.setter def lowerCamelCase_ ( self : Optional[Any],__A : List[Any] ): _lowerCamelCase : Any = AddedToken(__A,lstrip=__A,rstrip=__A ) if isinstance(__A,__A ) else value _lowerCamelCase : List[str] = value def lowerCamelCase_ ( self : Optional[int],*__A : Optional[Any],**__A : List[str] ): _lowerCamelCase : int = kwargs.get("is_split_into_words",__A ) assert self.add_prefix_space or not is_split_into_words, ( f'You need to instantiate {self.__class__.__name__} with add_prefix_space=True ' "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*__A,**__A ) def lowerCamelCase_ ( self : str,*__A : Union[str, Any],**__A : List[Any] ): _lowerCamelCase : Optional[int] = kwargs.get("is_split_into_words",__A ) assert self.add_prefix_space or not is_split_into_words, ( f'You need to instantiate {self.__class__.__name__} with add_prefix_space=True ' "to use it with pretokenized inputs." ) return super()._encode_plus(*__A,**__A ) def lowerCamelCase_ ( self : str,__A : str,__A : Optional[str] = None ): _lowerCamelCase : Optional[int] = self._tokenizer.model.save(__A,name=__A ) return tuple(__A ) def lowerCamelCase_ ( self : Optional[int],__A : List[int],__A : Optional[List[int]] = None ): _lowerCamelCase : int = [self.sep_token_id] _lowerCamelCase : str = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def lowerCamelCase_ ( self : Dict,__A : List[int],__A : Optional[List[int]] = None ): return token_ids_a + [self.eos_token_id] def lowerCamelCase_ ( self : List[str],__A : "Conversation" ): _lowerCamelCase : Dict = [] for is_user, text in conversation.iter_texts(): if is_user: # We need to space prefix as it's being done within blenderbot inputs.append(" " + text ) else: # Generated responses should contain them already. inputs.append(__A ) _lowerCamelCase : List[Any] = " ".join(__A ) _lowerCamelCase : List[str] = self.encode(__A ) if len(__A ) > self.model_max_length: _lowerCamelCase : Tuple = input_ids[-self.model_max_length :] logger.warning(f'Trimmed input from conversation as it was longer than {self.model_max_length} tokens.' ) return input_ids
11
0
"""simple docstring""" import os import textwrap import pyarrow as pa import pytest from datasets import ClassLabel, Features, Image from datasets.packaged_modules.csv.csv import Csv from ..utils import require_pil @pytest.fixture def lowerCamelCase ( _UpperCamelCase : str ) -> Optional[Any]: '''simple docstring''' __UpperCAmelCase : List[Any] = tmp_path / """file.csv""" __UpperCAmelCase : Dict = textwrap.dedent( """\ header1,header2 1,2 10,20 """ ) with open(_UpperCamelCase , """w""" ) as f: f.write(_UpperCamelCase ) return str(_UpperCamelCase ) @pytest.fixture def lowerCamelCase ( _UpperCamelCase : Dict ) -> str: '''simple docstring''' __UpperCAmelCase : int = tmp_path / """malformed_file.csv""" __UpperCAmelCase : Dict = textwrap.dedent( """\ header1,header2 1,2 10,20, """ ) with open(_UpperCamelCase , """w""" ) as f: f.write(_UpperCamelCase ) return str(_UpperCamelCase ) @pytest.fixture def lowerCamelCase ( _UpperCamelCase : Tuple , _UpperCamelCase : List[str] ) -> Union[str, Any]: '''simple docstring''' __UpperCAmelCase : Dict = tmp_path / """csv_with_image.csv""" __UpperCAmelCase : List[Any] = textwrap.dedent( f'''\ image {image_file} ''' ) with open(_UpperCamelCase , """w""" ) as f: f.write(_UpperCamelCase ) return str(_UpperCamelCase ) @pytest.fixture def lowerCamelCase ( _UpperCamelCase : str ) -> str: '''simple docstring''' __UpperCAmelCase : Optional[int] = tmp_path / """csv_with_label.csv""" __UpperCAmelCase : List[str] = textwrap.dedent( """\ label good bad good """ ) with open(_UpperCamelCase , """w""" ) as f: f.write(_UpperCamelCase ) return str(_UpperCamelCase ) @pytest.fixture def lowerCamelCase ( _UpperCamelCase : Optional[int] ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : List[str] = tmp_path / """csv_with_int_list.csv""" __UpperCAmelCase : Optional[Any] = textwrap.dedent( """\ int_list 1 2 3 4 5 6 7 8 9 """ ) with open(_UpperCamelCase , """w""" ) as f: f.write(_UpperCamelCase ) return str(_UpperCamelCase ) def lowerCamelCase ( _UpperCamelCase : Optional[Any] , _UpperCamelCase : Union[str, Any] , _UpperCamelCase : List[str] ) -> str: '''simple docstring''' __UpperCAmelCase : List[Any] = Csv() __UpperCAmelCase : str = csv._generate_tables([[csv_file, malformed_csv_file]] ) with pytest.raises(_UpperCamelCase , match="""Error tokenizing data""" ): for _ in generator: pass assert any( record.levelname == """ERROR""" and """Failed to read file""" in record.message and os.path.basename(_UpperCamelCase ) in record.message for record in caplog.records ) @require_pil def lowerCamelCase ( _UpperCamelCase : int ) -> Optional[int]: '''simple docstring''' with open(_UpperCamelCase , encoding="""utf-8""" ) as f: __UpperCAmelCase : Optional[int] = f.read().splitlines()[1] __UpperCAmelCase : Tuple = Csv(encoding="""utf-8""" , features=Features({"""image""": Image()} ) ) __UpperCAmelCase : List[str] = csv._generate_tables([[csv_file_with_image]] ) __UpperCAmelCase : Union[str, Any] = pa.concat_tables([table for _, table in generator] ) assert pa_table.schema.field("""image""" ).type == Image()() __UpperCAmelCase : str = pa_table.to_pydict()["""image"""] assert generated_content == [{"path": image_file, "bytes": None}] def lowerCamelCase ( _UpperCamelCase : Optional[Any] ) -> int: '''simple docstring''' with open(_UpperCamelCase , encoding="""utf-8""" ) as f: __UpperCAmelCase : Union[str, Any] = f.read().splitlines()[1:] __UpperCAmelCase : Any = Csv(encoding="""utf-8""" , features=Features({"""label""": ClassLabel(names=["""good""", """bad"""] )} ) ) __UpperCAmelCase : Dict = csv._generate_tables([[csv_file_with_label]] ) __UpperCAmelCase : Optional[Any] = pa.concat_tables([table for _, table in generator] ) assert pa_table.schema.field("""label""" ).type == ClassLabel(names=["""good""", """bad"""] )() __UpperCAmelCase : Dict = pa_table.to_pydict()["""label"""] assert generated_content == [ClassLabel(names=["""good""", """bad"""] ).straint(_UpperCamelCase ) for label in labels] def lowerCamelCase ( _UpperCamelCase : Union[str, Any] ) -> List[Any]: '''simple docstring''' __UpperCAmelCase : Tuple = Csv(encoding="""utf-8""" , sep=""",""" , converters={"""int_list""": lambda _UpperCamelCase : [int(_UpperCamelCase ) for i in x.split()]} ) __UpperCAmelCase : str = csv._generate_tables([[csv_file_with_int_list]] ) __UpperCAmelCase : int = pa.concat_tables([table for _, table in generator] ) assert pa.types.is_list(pa_table.schema.field("""int_list""" ).type ) __UpperCAmelCase : Tuple = pa_table.to_pydict()["""int_list"""] assert generated_content == [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
139
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bart import BartTokenizer UpperCAmelCase : str = logging.get_logger(__name__) UpperCAmelCase : Union[str, Any] = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'} # See all BART models at https://huggingface.co/models?filter=bart UpperCAmelCase : Tuple = { 'vocab_file': { 'facebook/bart-base': 'https://huggingface.co/facebook/bart-base/resolve/main/vocab.json', 'facebook/bart-large': 'https://huggingface.co/facebook/bart-large/resolve/main/vocab.json', 'facebook/bart-large-mnli': 'https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json', 'facebook/bart-large-cnn': 'https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json', 'facebook/bart-large-xsum': 'https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json', 'yjernite/bart_eli5': 'https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json', }, 'merges_file': { 'facebook/bart-base': 'https://huggingface.co/facebook/bart-base/resolve/main/merges.txt', 'facebook/bart-large': 'https://huggingface.co/facebook/bart-large/resolve/main/merges.txt', 'facebook/bart-large-mnli': 'https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt', 'facebook/bart-large-cnn': 'https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt', 'facebook/bart-large-xsum': 'https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt', 'yjernite/bart_eli5': 'https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt', }, 'tokenizer_file': { 'facebook/bart-base': 'https://huggingface.co/facebook/bart-base/resolve/main/tokenizer.json', 'facebook/bart-large': 'https://huggingface.co/facebook/bart-large/resolve/main/tokenizer.json', 'facebook/bart-large-mnli': 'https://huggingface.co/facebook/bart-large-mnli/resolve/main/tokenizer.json', 'facebook/bart-large-cnn': 'https://huggingface.co/facebook/bart-large-cnn/resolve/main/tokenizer.json', 'facebook/bart-large-xsum': 'https://huggingface.co/facebook/bart-large-xsum/resolve/main/tokenizer.json', 'yjernite/bart_eli5': 'https://huggingface.co/yjernite/bart_eli5/resolve/main/tokenizer.json', }, } UpperCAmelCase : List[Any] = { 'facebook/bart-base': 1024, 'facebook/bart-large': 1024, 'facebook/bart-large-mnli': 1024, 'facebook/bart-large-cnn': 1024, 'facebook/bart-large-xsum': 1024, 'yjernite/bart_eli5': 1024, } class lowerCamelCase__ ( A ): """simple docstring""" __a = VOCAB_FILES_NAMES __a = PRETRAINED_VOCAB_FILES_MAP __a = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __a = ["""input_ids""", """attention_mask"""] __a = BartTokenizer def __init__( self : int , UpperCamelCase : List[Any]=None , UpperCamelCase : Optional[int]=None , UpperCamelCase : List[str]=None , UpperCamelCase : Tuple="replace" , UpperCamelCase : Optional[int]="<s>" , UpperCamelCase : str="</s>" , UpperCamelCase : str="</s>" , UpperCamelCase : Optional[Any]="<s>" , UpperCamelCase : Optional[int]="<unk>" , UpperCamelCase : Dict="<pad>" , UpperCamelCase : Any="<mask>" , UpperCamelCase : Optional[Any]=False , UpperCamelCase : Tuple=True , **UpperCamelCase : Any , ): '''simple docstring''' super().__init__( UpperCamelCase , UpperCamelCase , tokenizer_file=UpperCamelCase , errors=UpperCamelCase , bos_token=UpperCamelCase , eos_token=UpperCamelCase , sep_token=UpperCamelCase , cls_token=UpperCamelCase , unk_token=UpperCamelCase , pad_token=UpperCamelCase , mask_token=UpperCamelCase , add_prefix_space=UpperCamelCase , trim_offsets=UpperCamelCase , **UpperCamelCase , ) __UpperCAmelCase : Dict = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("""add_prefix_space""" , UpperCamelCase ) != add_prefix_space: __UpperCAmelCase : List[str] = getattr(UpperCamelCase , pre_tok_state.pop("""type""" ) ) __UpperCAmelCase : int = add_prefix_space __UpperCAmelCase : List[Any] = pre_tok_class(**UpperCamelCase ) __UpperCAmelCase : Optional[int] = add_prefix_space # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__` __UpperCAmelCase : Union[str, Any] = """post_processor""" __UpperCAmelCase : Union[str, Any] = getattr(self.backend_tokenizer , UpperCamelCase , UpperCamelCase ) if tokenizer_component_instance: __UpperCAmelCase : List[Any] = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: __UpperCAmelCase : int = tuple(state["""sep"""] ) if "cls" in state: __UpperCAmelCase : Optional[int] = tuple(state["""cls"""] ) __UpperCAmelCase : int = False if state.get("""add_prefix_space""" , UpperCamelCase ) != add_prefix_space: __UpperCAmelCase : Dict = add_prefix_space __UpperCAmelCase : Optional[int] = True if state.get("""trim_offsets""" , UpperCamelCase ) != trim_offsets: __UpperCAmelCase : str = trim_offsets __UpperCAmelCase : int = True if changes_to_apply: __UpperCAmelCase : List[str] = getattr(UpperCamelCase , state.pop("""type""" ) ) __UpperCAmelCase : Tuple = component_class(**UpperCamelCase ) setattr(self.backend_tokenizer , UpperCamelCase , UpperCamelCase ) @property def lowerCamelCase__ ( self : Dict ): '''simple docstring''' if self._mask_token is None: if self.verbose: logger.error("""Using mask_token, but it is not set yet.""" ) return None return str(self._mask_token ) @mask_token.setter def lowerCamelCase__ ( self : Union[str, Any] , UpperCamelCase : str ): '''simple docstring''' __UpperCAmelCase : Dict = AddedToken(UpperCamelCase , lstrip=UpperCamelCase , rstrip=UpperCamelCase ) if isinstance(UpperCamelCase , UpperCamelCase ) else value __UpperCAmelCase : Any = value def lowerCamelCase__ ( self : Optional[Any] , *UpperCamelCase : int , **UpperCamelCase : int ): '''simple docstring''' __UpperCAmelCase : str = kwargs.get("""is_split_into_words""" , UpperCamelCase ) if is_split_into_words and not self.add_prefix_space: raise ValueError( f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True ''' """to use it with pretokenized inputs.""" ) return super()._batch_encode_plus(*UpperCamelCase , **UpperCamelCase ) def lowerCamelCase__ ( self : Optional[Any] , *UpperCamelCase : Any , **UpperCamelCase : Union[str, Any] ): '''simple docstring''' __UpperCAmelCase : Any = kwargs.get("""is_split_into_words""" , UpperCamelCase ) if is_split_into_words and not self.add_prefix_space: raise ValueError( f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True ''' """to use it with pretokenized inputs.""" ) return super()._encode_plus(*UpperCamelCase , **UpperCamelCase ) def lowerCamelCase__ ( self : int , UpperCamelCase : str , UpperCamelCase : Optional[str] = None ): '''simple docstring''' __UpperCAmelCase : List[Any] = self._tokenizer.model.save(UpperCamelCase , name=UpperCamelCase ) return tuple(UpperCamelCase ) def lowerCamelCase__ ( self : Tuple , UpperCamelCase : int , UpperCamelCase : Dict=None ): '''simple docstring''' __UpperCAmelCase : str = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def lowerCamelCase__ ( self : Tuple , UpperCamelCase : List[int] , UpperCamelCase : Optional[List[int]] = None ): '''simple docstring''' __UpperCAmelCase : Optional[Any] = [self.sep_token_id] __UpperCAmelCase : List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
139
1
'''simple docstring''' 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 CLIPImageProcessor, CLIPProcessor @require_vision class snake_case (unittest.TestCase ): def _a ( self ) -> Union[str, Any]: lowercase__ = tempfile.mkdtemp() # fmt: off lowercase__ = ["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 lowercase__ = dict(zip(UpperCAmelCase_ ,range(len(UpperCAmelCase_ ) ) ) ) lowercase__ = ["#version: 0.2", "l o", "lo w</w>", "e r</w>", ""] lowercase__ = {"unk_token": "<unk>"} lowercase__ = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES["vocab_file"] ) lowercase__ = 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(UpperCAmelCase_ ) + "\n" ) with open(self.merges_file ,"w" ,encoding="utf-8" ) as fp: fp.write("\n".join(UpperCAmelCase_ ) ) lowercase__ = { "do_resize": True, "size": 20, "do_center_crop": True, "crop_size": 18, "do_normalize": True, "image_mean": [0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73], "image_std": [0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11], } lowercase__ = os.path.join(self.tmpdirname ,UpperCAmelCase_ ) with open(self.image_processor_file ,"w" ,encoding="utf-8" ) as fp: json.dump(UpperCAmelCase_ ,UpperCAmelCase_ ) def _a ( self ,**UpperCAmelCase_ ) -> Optional[Any]: return CLIPTokenizer.from_pretrained(self.tmpdirname ,**UpperCAmelCase_ ) def _a ( self ,**UpperCAmelCase_ ) -> Union[str, Any]: return CLIPTokenizerFast.from_pretrained(self.tmpdirname ,**UpperCAmelCase_ ) def _a ( self ,**UpperCAmelCase_ ) -> str: return CLIPImageProcessor.from_pretrained(self.tmpdirname ,**UpperCAmelCase_ ) def _a ( self ) -> Optional[int]: shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Any: lowercase__ = [np.random.randint(255 ,size=(3, 30, 400) ,dtype=np.uinta )] lowercase__ = [Image.fromarray(np.moveaxis(UpperCAmelCase_ ,0 ,-1 ) ) for x in image_inputs] return image_inputs def _a ( self ) -> List[str]: lowercase__ = self.get_tokenizer() lowercase__ = self.get_rust_tokenizer() lowercase__ = self.get_image_processor() lowercase__ = CLIPProcessor(tokenizer=UpperCAmelCase_ ,image_processor=UpperCAmelCase_ ) processor_slow.save_pretrained(self.tmpdirname ) lowercase__ = CLIPProcessor.from_pretrained(self.tmpdirname ,use_fast=UpperCAmelCase_ ) lowercase__ = CLIPProcessor(tokenizer=UpperCAmelCase_ ,image_processor=UpperCAmelCase_ ) processor_fast.save_pretrained(self.tmpdirname ) lowercase__ = CLIPProcessor.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 ,UpperCAmelCase_ ) self.assertIsInstance(processor_fast.tokenizer ,UpperCAmelCase_ ) 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 ,UpperCAmelCase_ ) self.assertIsInstance(processor_fast.image_processor ,UpperCAmelCase_ ) def _a ( self ) -> List[Any]: lowercase__ = CLIPProcessor(tokenizer=self.get_tokenizer() ,image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) lowercase__ = self.get_tokenizer(bos_token="(BOS)" ,eos_token="(EOS)" ) lowercase__ = self.get_image_processor(do_normalize=UpperCAmelCase_ ,padding_value=1.0 ) lowercase__ = CLIPProcessor.from_pretrained( self.tmpdirname ,bos_token="(BOS)" ,eos_token="(EOS)" ,do_normalize=UpperCAmelCase_ ,padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() ,tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer ,UpperCAmelCase_ ) self.assertEqual(processor.image_processor.to_json_string() ,image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor ,UpperCAmelCase_ ) def _a ( self ) -> Dict: lowercase__ = self.get_image_processor() lowercase__ = self.get_tokenizer() lowercase__ = CLIPProcessor(tokenizer=UpperCAmelCase_ ,image_processor=UpperCAmelCase_ ) lowercase__ = self.prepare_image_inputs() lowercase__ = image_processor(UpperCAmelCase_ ,return_tensors="np" ) lowercase__ = processor(images=UpperCAmelCase_ ,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 ) -> Dict: lowercase__ = self.get_image_processor() lowercase__ = self.get_tokenizer() lowercase__ = CLIPProcessor(tokenizer=UpperCAmelCase_ ,image_processor=UpperCAmelCase_ ) lowercase__ = "lower newer" lowercase__ = processor(text=UpperCAmelCase_ ) lowercase__ = tokenizer(UpperCAmelCase_ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] ,encoded_processor[key] ) def _a ( self ) -> Optional[Any]: lowercase__ = self.get_image_processor() lowercase__ = self.get_tokenizer() lowercase__ = CLIPProcessor(tokenizer=UpperCAmelCase_ ,image_processor=UpperCAmelCase_ ) lowercase__ = "lower newer" lowercase__ = self.prepare_image_inputs() lowercase__ = processor(text=UpperCAmelCase_ ,images=UpperCAmelCase_ ) self.assertListEqual(list(inputs.keys() ) ,["input_ids", "attention_mask", "pixel_values"] ) # test if it raises when no input is passed with pytest.raises(UpperCAmelCase_ ): processor() def _a ( self ) -> List[Any]: lowercase__ = self.get_image_processor() lowercase__ = self.get_tokenizer() lowercase__ = CLIPProcessor(tokenizer=UpperCAmelCase_ ,image_processor=UpperCAmelCase_ ) lowercase__ = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] lowercase__ = processor.batch_decode(UpperCAmelCase_ ) lowercase__ = tokenizer.batch_decode(UpperCAmelCase_ ) self.assertListEqual(UpperCAmelCase_ ,UpperCAmelCase_ ) def _a ( self ) -> Dict: lowercase__ = self.get_image_processor() lowercase__ = self.get_tokenizer() lowercase__ = CLIPProcessor(tokenizer=UpperCAmelCase_ ,image_processor=UpperCAmelCase_ ) lowercase__ = "lower newer" lowercase__ = self.prepare_image_inputs() lowercase__ = processor(text=UpperCAmelCase_ ,images=UpperCAmelCase_ ) self.assertListEqual(list(inputs.keys() ) ,processor.model_input_names )
539
'''simple docstring''' import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DPMSolverMultistepScheduler, TextToVideoSDPipeline, UNetaDConditionModel, ) from diffusers.utils import is_xformers_available, load_numpy, skip_mps, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class snake_case (UpperCamelCase , unittest.TestCase ): lowerCAmelCase__ :int = TextToVideoSDPipeline lowerCAmelCase__ :Union[str, Any] = TEXT_TO_IMAGE_PARAMS lowerCAmelCase__ :List[str] = TEXT_TO_IMAGE_BATCH_PARAMS # No `output_type`. lowerCAmelCase__ :Optional[Any] = frozenset( [ "num_inference_steps", "generator", "latents", "return_dict", "callback", "callback_steps", ] ) def _a ( self ) -> Optional[int]: torch.manual_seed(0 ) lowercase__ = UNetaDConditionModel( block_out_channels=(32, 64, 64, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=4 ,out_channels=4 ,down_block_types=("CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "DownBlock3D") ,up_block_types=("UpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D") ,cross_attention_dim=32 ,attention_head_dim=4 ,) lowercase__ = DDIMScheduler( beta_start=0.0_00_85 ,beta_end=0.0_12 ,beta_schedule="scaled_linear" ,clip_sample=UpperCAmelCase_ ,set_alpha_to_one=UpperCAmelCase_ ,) torch.manual_seed(0 ) lowercase__ = 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 ) lowercase__ = CLIPTextConfig( bos_token_id=0 ,eos_token_id=2 ,hidden_size=32 ,intermediate_size=37 ,layer_norm_eps=1E-0_5 ,num_attention_heads=4 ,num_hidden_layers=5 ,pad_token_id=1 ,vocab_size=1_000 ,hidden_act="gelu" ,projection_dim=512 ,) lowercase__ = CLIPTextModel(UpperCAmelCase_ ) lowercase__ = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) lowercase__ = { "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, } return components def _a ( self ,UpperCAmelCase_ ,UpperCAmelCase_=0 ) -> int: if str(UpperCAmelCase_ ).startswith("mps" ): lowercase__ = torch.manual_seed(UpperCAmelCase_ ) else: lowercase__ = torch.Generator(device=UpperCAmelCase_ ).manual_seed(UpperCAmelCase_ ) lowercase__ = { "prompt": "A painting of a squirrel eating a burger", "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, "output_type": "pt", } return inputs def _a ( self ) -> Tuple: lowercase__ = "cpu" # ensure determinism for the device-dependent torch.Generator lowercase__ = self.get_dummy_components() lowercase__ = TextToVideoSDPipeline(**UpperCAmelCase_ ) lowercase__ = sd_pipe.to(UpperCAmelCase_ ) sd_pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) lowercase__ = self.get_dummy_inputs(UpperCAmelCase_ ) lowercase__ = "np" lowercase__ = sd_pipe(**UpperCAmelCase_ ).frames lowercase__ = frames[0][-3:, -3:, -1] assert frames[0].shape == (64, 64, 3) lowercase__ = np.array([1_58.0, 1_60.0, 1_53.0, 1_25.0, 1_00.0, 1_21.0, 1_11.0, 93.0, 1_13.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _a ( self ) -> List[Any]: self._test_attention_slicing_forward_pass(test_mean_pixel_difference=UpperCAmelCase_ ,expected_max_diff=3E-3 ) @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() ,reason="XFormers attention is only available with CUDA and `xformers` installed" ,) def _a ( self ) -> Dict: self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=UpperCAmelCase_ ,expected_max_diff=1E-2 ) @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." ) def _a ( self ) -> Union[str, Any]: pass @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." ) def _a ( self ) -> Union[str, Any]: pass @unittest.skip(reason="`num_images_per_prompt` argument is not supported for this pipeline." ) def _a ( self ) -> Union[str, Any]: pass def _a ( self ) -> str: return super().test_progress_bar() @slow @skip_mps class snake_case (unittest.TestCase ): def _a ( self ) -> Optional[int]: lowercase__ = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video.npy" ) lowercase__ = TextToVideoSDPipeline.from_pretrained("damo-vilab/text-to-video-ms-1.7b" ) lowercase__ = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) lowercase__ = pipe.to("cuda" ) lowercase__ = "Spiderman is surfing" lowercase__ = torch.Generator(device="cpu" ).manual_seed(0 ) lowercase__ = pipe(UpperCAmelCase_ ,generator=UpperCAmelCase_ ,num_inference_steps=25 ,output_type="pt" ).frames lowercase__ = video_frames.cpu().numpy() assert np.abs(expected_video - video ).mean() < 5E-2 def _a ( self ) -> Optional[int]: lowercase__ = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video_2step.npy" ) lowercase__ = TextToVideoSDPipeline.from_pretrained("damo-vilab/text-to-video-ms-1.7b" ) lowercase__ = pipe.to("cuda" ) lowercase__ = "Spiderman is surfing" lowercase__ = torch.Generator(device="cpu" ).manual_seed(0 ) lowercase__ = pipe(UpperCAmelCase_ ,generator=UpperCAmelCase_ ,num_inference_steps=2 ,output_type="pt" ).frames lowercase__ = video_frames.cpu().numpy() assert np.abs(expected_video - video ).mean() < 5E-2
539
1