code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
"""simple docstring""" from typing import List, Optional, Union import torch from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) __lowercase = logging.get_logger(__name__) # pylint: disable=invalid-name __lowercase = """ Examples: ```py >>> from diffusers import KandinskyV22Pipeline, KandinskyV22PriorPipeline >>> import torch >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\"kandinsky-community/kandinsky-2-2-prior\") >>> pipe_prior.to(\"cuda\") >>> prompt = \"red cat, 4k photo\" >>> out = pipe_prior(prompt) >>> image_emb = out.image_embeds >>> zero_image_emb = out.negative_image_embeds >>> pipe = KandinskyV22Pipeline.from_pretrained(\"kandinsky-community/kandinsky-2-2-decoder\") >>> pipe.to(\"cuda\") >>> image = pipe( ... image_embeds=image_emb, ... negative_image_embeds=zero_image_emb, ... height=768, ... width=768, ... num_inference_steps=50, ... ).images >>> image[0].save(\"cat.png\") ``` """ def lowercase ( A_ , A_ , A_=8 )-> List[Any]: '''simple docstring''' a : int = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 a : List[str] = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor class _A ( _a ): """simple docstring""" def __init__( self : Tuple , __UpperCAmelCase : UNetaDConditionModel , __UpperCAmelCase : DDPMScheduler , __UpperCAmelCase : VQModel , ): super().__init__() self.register_modules( unet=__UpperCAmelCase , scheduler=__UpperCAmelCase , movq=__UpperCAmelCase , ) a : int = 2 ** (len(self.movq.config.block_out_channels) - 1) def __snake_case ( self : Optional[Any] , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Any , __UpperCAmelCase : List[str] , __UpperCAmelCase : List[str]): if latents is None: a : Any = randn_tensor(__UpperCAmelCase , generator=__UpperCAmelCase , device=__UpperCAmelCase , dtype=__UpperCAmelCase) else: if latents.shape != shape: raise ValueError(f'''Unexpected latents shape, got {latents.shape}, expected {shape}''') a : Dict = latents.to(__UpperCAmelCase) a : Dict = latents * scheduler.init_noise_sigma return latents def __snake_case ( self : Any , __UpperCAmelCase : List[Any]=0): if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("Please install accelerate via `pip install accelerate`") a : Dict = torch.device(f'''cuda:{gpu_id}''') a : Any = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(__UpperCAmelCase , __UpperCAmelCase) def __snake_case ( self : List[Any] , __UpperCAmelCase : Union[str, Any]=0): 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.") a : List[Any] = torch.device(f'''cuda:{gpu_id}''') if self.device.type != "cpu": self.to("cpu" , silence_dtype_warnings=__UpperCAmelCase) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) a : Any = None for cpu_offloaded_model in [self.unet, self.movq]: a , a : Tuple = cpu_offload_with_hook(__UpperCAmelCase , __UpperCAmelCase , prev_module_hook=__UpperCAmelCase) # We'll offload the last model manually. a : Dict = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def __snake_case ( self : Optional[int]): if not hasattr(self.unet , "_hf_hook"): return self.device for module in self.unet.modules(): if ( hasattr(__UpperCAmelCase , "_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(__UpperCAmelCase) def __call__( self : Optional[Any] , __UpperCAmelCase : Union[torch.FloatTensor, List[torch.FloatTensor]] , __UpperCAmelCase : Union[torch.FloatTensor, List[torch.FloatTensor]] , __UpperCAmelCase : int = 512 , __UpperCAmelCase : int = 512 , __UpperCAmelCase : int = 100 , __UpperCAmelCase : float = 4.0 , __UpperCAmelCase : int = 1 , __UpperCAmelCase : Optional[Union[torch.Generator, List[torch.Generator]]] = None , __UpperCAmelCase : Optional[torch.FloatTensor] = None , __UpperCAmelCase : Optional[str] = "pil" , __UpperCAmelCase : bool = True , ): a : Optional[int] = self._execution_device a : int = guidance_scale > 1.0 if isinstance(__UpperCAmelCase , __UpperCAmelCase): a : Union[str, Any] = torch.cat(__UpperCAmelCase , dim=0) a : int = image_embeds.shape[0] * num_images_per_prompt if isinstance(__UpperCAmelCase , __UpperCAmelCase): a : List[str] = torch.cat(__UpperCAmelCase , dim=0) if do_classifier_free_guidance: a : Union[str, Any] = image_embeds.repeat_interleave(__UpperCAmelCase , dim=0) a : Tuple = negative_image_embeds.repeat_interleave(__UpperCAmelCase , dim=0) a : Union[str, Any] = torch.cat([negative_image_embeds, image_embeds] , dim=0).to(dtype=self.unet.dtype , device=__UpperCAmelCase) self.scheduler.set_timesteps(__UpperCAmelCase , device=__UpperCAmelCase) a : Union[str, Any] = self.scheduler.timesteps a : Any = self.unet.config.in_channels a , a : str = downscale_height_and_width(__UpperCAmelCase , __UpperCAmelCase , self.movq_scale_factor) # create initial latent a : Any = self.prepare_latents( (batch_size, num_channels_latents, height, width) , image_embeds.dtype , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , self.scheduler , ) for i, t in enumerate(self.progress_bar(__UpperCAmelCase)): # expand the latents if we are doing classifier free guidance a : str = torch.cat([latents] * 2) if do_classifier_free_guidance else latents a : Dict = {"image_embeds": image_embeds} a : Tuple = self.unet( sample=__UpperCAmelCase , timestep=__UpperCAmelCase , encoder_hidden_states=__UpperCAmelCase , added_cond_kwargs=__UpperCAmelCase , return_dict=__UpperCAmelCase , )[0] if do_classifier_free_guidance: a , a : int = noise_pred.split(latents.shape[1] , dim=1) a , a : Any = noise_pred.chunk(2) a , a : int = variance_pred.chunk(2) a : Any = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) a : str = 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"] ): a , a : Union[str, Any] = noise_pred.split(latents.shape[1] , dim=1) # compute the previous noisy sample x_t -> x_t-1 a : Any = self.scheduler.step( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , generator=__UpperCAmelCase , )[0] # post-processing a : Tuple = self.movq.decode(__UpperCAmelCase , force_not_quantize=__UpperCAmelCase)["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"]: a : Optional[Any] = image * 0.5 + 0.5 a : Union[str, Any] = image.clamp(0 , 1) a : Union[str, Any] = image.cpu().permute(0 , 2 , 3 , 1).float().numpy() if output_type == "pil": a : Optional[int] = self.numpy_to_pil(__UpperCAmelCase) if not return_dict: return (image,) return ImagePipelineOutput(images=__UpperCAmelCase)
40
"""simple docstring""" import math import sys def __lowerCAmelCase (_UpperCamelCase ): if number != int(_UpperCamelCase ): raise ValueError('the value of input must be a natural number' ) if number < 0: raise ValueError('the value of input must not be a negative number' ) if number == 0: return 1 __lowerCAmelCase : Any = [-1] * (number + 1) __lowerCAmelCase : List[Any] = 0 for i in range(1 , number + 1 ): __lowerCAmelCase : List[Any] = sys.maxsize __lowerCAmelCase : Optional[int] = int(math.sqrt(_UpperCamelCase ) ) for j in range(1 , root + 1 ): __lowerCAmelCase : Optional[Any] = 1 + answers[i - (j**2)] __lowerCAmelCase : Any = min(_UpperCamelCase , _UpperCamelCase ) __lowerCAmelCase : List[str] = answer return answers[number] if __name__ == "__main__": import doctest doctest.testmod()
86
0
'''simple docstring''' import argparse import io import requests import torch from omegaconf import OmegaConf from diffusers import AutoencoderKL from diffusers.pipelines.stable_diffusion.convert_from_ckpt import ( assign_to_checkpoint, conv_attn_to_linear, create_vae_diffusers_config, renew_vae_attention_paths, renew_vae_resnet_paths, ) def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> Union[str, Any]: lowerCamelCase__ : Optional[Any] = checkpoint lowerCamelCase__ : Optional[Any] = {} lowerCamelCase__ : Dict = vae_state_dict["""encoder.conv_in.weight"""] lowerCamelCase__ : List[str] = vae_state_dict["""encoder.conv_in.bias"""] lowerCamelCase__ : str = vae_state_dict["""encoder.conv_out.weight"""] lowerCamelCase__ : Union[str, Any] = vae_state_dict["""encoder.conv_out.bias"""] lowerCamelCase__ : Dict = vae_state_dict["""encoder.norm_out.weight"""] lowerCamelCase__ : Dict = vae_state_dict["""encoder.norm_out.bias"""] lowerCamelCase__ : Dict = vae_state_dict["""decoder.conv_in.weight"""] lowerCamelCase__ : Dict = vae_state_dict["""decoder.conv_in.bias"""] lowerCamelCase__ : int = vae_state_dict["""decoder.conv_out.weight"""] lowerCamelCase__ : int = vae_state_dict["""decoder.conv_out.bias"""] lowerCamelCase__ : Optional[int] = vae_state_dict["""decoder.norm_out.weight"""] lowerCamelCase__ : Tuple = vae_state_dict["""decoder.norm_out.bias"""] lowerCamelCase__ : Optional[int] = vae_state_dict["""quant_conv.weight"""] lowerCamelCase__ : Optional[Any] = vae_state_dict["""quant_conv.bias"""] lowerCamelCase__ : str = vae_state_dict["""post_quant_conv.weight"""] lowerCamelCase__ : List[str] = vae_state_dict["""post_quant_conv.bias"""] # Retrieves the keys for the encoder down blocks only lowerCamelCase__ : int = len({""".""".join(layer.split(""".""" )[:3] ) for layer in vae_state_dict if """encoder.down""" in layer} ) lowerCamelCase__ : Any = { layer_id: [key for key in vae_state_dict if f'''down.{layer_id}''' in key] for layer_id in range(UpperCamelCase ) } # Retrieves the keys for the decoder up blocks only lowerCamelCase__ : Tuple = len({""".""".join(layer.split(""".""" )[:3] ) for layer in vae_state_dict if """decoder.up""" in layer} ) lowerCamelCase__ : List[str] = { layer_id: [key for key in vae_state_dict if f'''up.{layer_id}''' in key] for layer_id in range(UpperCamelCase ) } for i in range(UpperCamelCase ): lowerCamelCase__ : Tuple = [key for key in down_blocks[i] if f'''down.{i}''' in key and f'''down.{i}.downsample''' not in key] if f'''encoder.down.{i}.downsample.conv.weight''' in vae_state_dict: lowerCamelCase__ : List[str] = vae_state_dict.pop( f'''encoder.down.{i}.downsample.conv.weight''' ) lowerCamelCase__ : Dict = vae_state_dict.pop( f'''encoder.down.{i}.downsample.conv.bias''' ) lowerCamelCase__ : List[Any] = renew_vae_resnet_paths(UpperCamelCase ) lowerCamelCase__ : Optional[int] = {"""old""": f'''down.{i}.block''', """new""": f'''down_blocks.{i}.resnets'''} assign_to_checkpoint(UpperCamelCase , UpperCamelCase , UpperCamelCase , additional_replacements=[meta_path] , config=UpperCamelCase ) lowerCamelCase__ : Tuple = [key for key in vae_state_dict if """encoder.mid.block""" in key] lowerCamelCase__ : Optional[int] = 2 for i in range(1 , num_mid_res_blocks + 1 ): lowerCamelCase__ : List[Any] = [key for key in mid_resnets if f'''encoder.mid.block_{i}''' in key] lowerCamelCase__ : Union[str, Any] = renew_vae_resnet_paths(UpperCamelCase ) lowerCamelCase__ : int = {"""old""": f'''mid.block_{i}''', """new""": f'''mid_block.resnets.{i - 1}'''} assign_to_checkpoint(UpperCamelCase , UpperCamelCase , UpperCamelCase , additional_replacements=[meta_path] , config=UpperCamelCase ) lowerCamelCase__ : Tuple = [key for key in vae_state_dict if """encoder.mid.attn""" in key] lowerCamelCase__ : List[str] = renew_vae_attention_paths(UpperCamelCase ) lowerCamelCase__ : Any = {"""old""": """mid.attn_1""", """new""": """mid_block.attentions.0"""} assign_to_checkpoint(UpperCamelCase , UpperCamelCase , UpperCamelCase , additional_replacements=[meta_path] , config=UpperCamelCase ) conv_attn_to_linear(UpperCamelCase ) for i in range(UpperCamelCase ): lowerCamelCase__ : Union[str, Any] = num_up_blocks - 1 - i lowerCamelCase__ : List[str] = [ key for key in up_blocks[block_id] if f'''up.{block_id}''' in key and f'''up.{block_id}.upsample''' not in key ] if f'''decoder.up.{block_id}.upsample.conv.weight''' in vae_state_dict: lowerCamelCase__ : Dict = vae_state_dict[ f'''decoder.up.{block_id}.upsample.conv.weight''' ] lowerCamelCase__ : Any = vae_state_dict[ f'''decoder.up.{block_id}.upsample.conv.bias''' ] lowerCamelCase__ : Optional[Any] = renew_vae_resnet_paths(UpperCamelCase ) lowerCamelCase__ : Dict = {"""old""": f'''up.{block_id}.block''', """new""": f'''up_blocks.{i}.resnets'''} assign_to_checkpoint(UpperCamelCase , UpperCamelCase , UpperCamelCase , additional_replacements=[meta_path] , config=UpperCamelCase ) lowerCamelCase__ : Optional[int] = [key for key in vae_state_dict if """decoder.mid.block""" in key] lowerCamelCase__ : Optional[Any] = 2 for i in range(1 , num_mid_res_blocks + 1 ): lowerCamelCase__ : Tuple = [key for key in mid_resnets if f'''decoder.mid.block_{i}''' in key] lowerCamelCase__ : Tuple = renew_vae_resnet_paths(UpperCamelCase ) lowerCamelCase__ : str = {"""old""": f'''mid.block_{i}''', """new""": f'''mid_block.resnets.{i - 1}'''} assign_to_checkpoint(UpperCamelCase , UpperCamelCase , UpperCamelCase , additional_replacements=[meta_path] , config=UpperCamelCase ) lowerCamelCase__ : List[Any] = [key for key in vae_state_dict if """decoder.mid.attn""" in key] lowerCamelCase__ : Optional[int] = renew_vae_attention_paths(UpperCamelCase ) lowerCamelCase__ : List[str] = {"""old""": """mid.attn_1""", """new""": """mid_block.attentions.0"""} assign_to_checkpoint(UpperCamelCase , UpperCamelCase , UpperCamelCase , additional_replacements=[meta_path] , config=UpperCamelCase ) conv_attn_to_linear(UpperCamelCase ) return new_checkpoint def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , ) -> Tuple: # Only support V1 lowerCamelCase__ : Any = requests.get( """ https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml""" ) lowerCamelCase__ : Tuple = io.BytesIO(r.content ) lowerCamelCase__ : Union[str, Any] = OmegaConf.load(UpperCamelCase ) lowerCamelCase__ : List[Any] = 512 lowerCamelCase__ : List[str] = """cuda""" if torch.cuda.is_available() else """cpu""" if checkpoint_path.endswith("""safetensors""" ): from safetensors import safe_open lowerCamelCase__ : Optional[int] = {} with safe_open(UpperCamelCase , framework="""pt""" , device="""cpu""" ) as f: for key in f.keys(): lowerCamelCase__ : Any = f.get_tensor(UpperCamelCase ) else: lowerCamelCase__ : Any = torch.load(UpperCamelCase , map_location=UpperCamelCase )["""state_dict"""] # Convert the VAE model. lowerCamelCase__ : List[Any] = create_vae_diffusers_config(UpperCamelCase , image_size=UpperCamelCase ) lowerCamelCase__ : Union[str, Any] = custom_convert_ldm_vae_checkpoint(UpperCamelCase , UpperCamelCase ) lowerCamelCase__ : Tuple = AutoencoderKL(**UpperCamelCase ) vae.load_state_dict(UpperCamelCase ) vae.save_pretrained(UpperCamelCase ) if __name__ == "__main__": _A : Tuple =argparse.ArgumentParser() parser.add_argument('''--vae_pt_path''', default=None, type=str, required=True, help='''Path to the VAE.pt to convert.''') parser.add_argument('''--dump_path''', default=None, type=str, required=True, help='''Path to the VAE.pt to convert.''') _A : Union[str, Any] =parser.parse_args() vae_pt_to_vae_diffuser(args.vae_pt_path, args.dump_path)
41
"""simple docstring""" import tempfile import unittest import numpy as np import transformers from transformers import GPTaTokenizer, GPTJConfig, is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax, tooslow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax import jax.numpy as jnp from transformers.modeling_flax_pytorch_utils import ( convert_pytorch_state_dict_to_flax, load_flax_weights_in_pytorch_model, ) from transformers.models.gptj.modeling_flax_gptj import FlaxGPTJForCausalLM, FlaxGPTJModel if is_torch_available(): import torch class A__ : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=14 , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=99 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=37 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=5_12 , _SCREAMING_SNAKE_CASE=0.02 , ): __lowerCAmelCase : Union[str, Any] = parent __lowerCAmelCase : Any = batch_size __lowerCAmelCase : Any = seq_length __lowerCAmelCase : Optional[Any] = is_training __lowerCAmelCase : Any = use_input_mask __lowerCAmelCase : Any = use_token_type_ids __lowerCAmelCase : Tuple = use_labels __lowerCAmelCase : Optional[Any] = vocab_size __lowerCAmelCase : Tuple = hidden_size __lowerCAmelCase : str = rotary_dim __lowerCAmelCase : Union[str, Any] = num_hidden_layers __lowerCAmelCase : Union[str, Any] = num_attention_heads __lowerCAmelCase : int = intermediate_size __lowerCAmelCase : List[str] = hidden_act __lowerCAmelCase : int = hidden_dropout_prob __lowerCAmelCase : Any = attention_probs_dropout_prob __lowerCAmelCase : List[Any] = max_position_embeddings __lowerCAmelCase : Optional[Any] = initializer_range __lowerCAmelCase : Tuple = None __lowerCAmelCase : int = vocab_size - 1 __lowerCAmelCase : Dict = vocab_size - 1 __lowerCAmelCase : int = vocab_size - 1 def __lowerCamelCase ( self ): __lowerCAmelCase : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __lowerCAmelCase : List[str] = None if self.use_input_mask: __lowerCAmelCase : Dict = random_attention_mask([self.batch_size, self.seq_length] ) __lowerCAmelCase : Optional[int] = GPTJConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , use_cache=_SCREAMING_SNAKE_CASE , bos_token_id=self.bos_token_id , eos_token_id=self.eos_token_id , pad_token_id=self.pad_token_id , rotary_dim=self.rotary_dim , ) return (config, input_ids, input_mask) def __lowerCamelCase ( self ): __lowerCAmelCase : Optional[int] = self.prepare_config_and_inputs() __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase : Any = config_and_inputs __lowerCAmelCase : Dict = {'input_ids': input_ids, 'attention_mask': attention_mask} return config, inputs_dict def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : List[str] = 20 __lowerCAmelCase : List[str] = model_class_name(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = model.init_cache(input_ids.shape[0] , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = jnp.ones((input_ids.shape[0], max_decoder_length) , dtype='i4' ) __lowerCAmelCase : Optional[Any] = jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1 )[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1) ) __lowerCAmelCase : Any = model( input_ids[:, :-1] , attention_mask=_SCREAMING_SNAKE_CASE , past_key_values=_SCREAMING_SNAKE_CASE , position_ids=_SCREAMING_SNAKE_CASE , ) __lowerCAmelCase : Any = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype='i4' ) __lowerCAmelCase : int = model( input_ids[:, -1:] , attention_mask=_SCREAMING_SNAKE_CASE , past_key_values=outputs_cache.past_key_values , position_ids=_SCREAMING_SNAKE_CASE , ) __lowerCAmelCase : Any = model(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=f"Max diff is {diff}" ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Tuple = 20 __lowerCAmelCase : List[str] = model_class_name(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Union[str, Any] = jnp.concatenate( [attention_mask, jnp.zeros((attention_mask.shape[0], max_decoder_length - attention_mask.shape[1]) )] , axis=-1 , ) __lowerCAmelCase : List[str] = model.init_cache(input_ids.shape[0] , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : str = jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1 )[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1) ) __lowerCAmelCase : Optional[Any] = model( input_ids[:, :-1] , attention_mask=_SCREAMING_SNAKE_CASE , past_key_values=_SCREAMING_SNAKE_CASE , position_ids=_SCREAMING_SNAKE_CASE , ) __lowerCAmelCase : str = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype='i4' ) __lowerCAmelCase : Tuple = model( input_ids[:, -1:] , past_key_values=outputs_cache.past_key_values , attention_mask=_SCREAMING_SNAKE_CASE , position_ids=_SCREAMING_SNAKE_CASE , ) __lowerCAmelCase : Union[str, Any] = model(_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=f"Max diff is {diff}" ) @require_flax class A__ ( _lowerCamelCase , _lowerCamelCase , unittest.TestCase): A_ : Tuple = (FlaxGPTJModel, FlaxGPTJForCausalLM) if is_flax_available() else () A_ : str = (FlaxGPTJForCausalLM,) if is_flax_available() else () def __lowerCamelCase ( self ): __lowerCAmelCase : int = FlaxGPTJModelTester(self ) def __lowerCamelCase ( self ): for model_class_name in self.all_model_classes: __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): for model_class_name in self.all_model_classes: __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward_with_attn_mask( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @tooslow def __lowerCamelCase ( self ): __lowerCAmelCase : Tuple = GPTaTokenizer.from_pretrained('gpt2' , pad_token='<|endoftext|>' , padding_side='left' ) __lowerCAmelCase : Optional[int] = tokenizer(['Hello this is a long string', 'Hey'] , return_tensors='np' , padding=_SCREAMING_SNAKE_CASE , truncation=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : int = FlaxGPTJForCausalLM.from_pretrained('EleutherAI/gpt-j-6B' ) __lowerCAmelCase : Any = False __lowerCAmelCase : Any = model.config.eos_token_id __lowerCAmelCase : Union[str, Any] = jax.jit(model.generate ) __lowerCAmelCase : Optional[Any] = jit_generate( inputs['input_ids'] , attention_mask=inputs['attention_mask'] , pad_token_id=tokenizer.pad_token_id ).sequences __lowerCAmelCase : str = tokenizer.batch_decode(_SCREAMING_SNAKE_CASE , skip_special_tokens=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = [ 'Hello this is a long string of text.\n\nI\'m trying to get the text of the', 'Hey, I\'m a little late to the party. I\'m going to', ] self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @is_pt_flax_cross_test def __lowerCamelCase ( self ): __lowerCAmelCase , __lowerCAmelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): # prepare inputs __lowerCAmelCase : str = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Union[str, Any] = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class __lowerCAmelCase : Dict = model_class.__name__[4:] # Skip the "Flax" at the beginning __lowerCAmelCase : Optional[int] = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase , __lowerCAmelCase : List[Any] = pt_inputs['input_ids'].shape __lowerCAmelCase : int = np.random.randint(0 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(_SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Tuple = 0 __lowerCAmelCase : Tuple = 1 __lowerCAmelCase : List[str] = 0 __lowerCAmelCase : Any = 1 __lowerCAmelCase : Optional[Any] = pt_model_class(_SCREAMING_SNAKE_CASE ).eval() __lowerCAmelCase : Any = model_class(_SCREAMING_SNAKE_CASE , dtype=jnp.floataa ) __lowerCAmelCase : int = convert_pytorch_state_dict_to_flax(pt_model.state_dict() , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : str = fx_state with torch.no_grad(): __lowerCAmelCase : Union[str, Any] = pt_model(**_SCREAMING_SNAKE_CASE ).to_tuple() __lowerCAmelCase : str = fx_model(**_SCREAMING_SNAKE_CASE ).to_tuple() self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , len(_SCREAMING_SNAKE_CASE ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output, pt_output in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) with tempfile.TemporaryDirectory() as tmpdirname: pt_model.save_pretrained(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Tuple = model_class.from_pretrained(_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = fx_model_loaded(**_SCREAMING_SNAKE_CASE ).to_tuple() self.assertEqual( len(_SCREAMING_SNAKE_CASE ) , len(_SCREAMING_SNAKE_CASE ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output_loaded, pt_output in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): self.assert_almost_equals(fx_output_loaded[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) @is_pt_flax_cross_test def __lowerCamelCase ( self ): __lowerCAmelCase , __lowerCAmelCase : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): # prepare inputs __lowerCAmelCase : List[str] = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class __lowerCAmelCase : Dict = model_class.__name__[4:] # Skip the "Flax" at the beginning __lowerCAmelCase : str = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = pt_model_class(_SCREAMING_SNAKE_CASE ).eval() __lowerCAmelCase : Tuple = model_class(_SCREAMING_SNAKE_CASE , dtype=jnp.floataa ) __lowerCAmelCase : List[str] = load_flax_weights_in_pytorch_model(_SCREAMING_SNAKE_CASE , fx_model.params ) __lowerCAmelCase , __lowerCAmelCase : int = pt_inputs['input_ids'].shape __lowerCAmelCase : List[str] = np.random.randint(0 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(_SCREAMING_SNAKE_CASE ): __lowerCAmelCase : str = 0 __lowerCAmelCase : Optional[Any] = 1 __lowerCAmelCase : Optional[int] = 0 __lowerCAmelCase : Optional[Any] = 1 # make sure weights are tied in PyTorch pt_model.tie_weights() with torch.no_grad(): __lowerCAmelCase : List[str] = pt_model(**_SCREAMING_SNAKE_CASE ).to_tuple() __lowerCAmelCase : Optional[int] = fx_model(**_SCREAMING_SNAKE_CASE ).to_tuple() self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , len(_SCREAMING_SNAKE_CASE ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output, pt_output in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) with tempfile.TemporaryDirectory() as tmpdirname: fx_model.save_pretrained(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = pt_model_class.from_pretrained(_SCREAMING_SNAKE_CASE , from_flax=_SCREAMING_SNAKE_CASE ) with torch.no_grad(): __lowerCAmelCase : Any = pt_model_loaded(**_SCREAMING_SNAKE_CASE ).to_tuple() self.assertEqual( len(_SCREAMING_SNAKE_CASE ) , len(_SCREAMING_SNAKE_CASE ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output, pt_output in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) @tooslow def __lowerCamelCase ( self ): for model_class_name in self.all_model_classes: __lowerCAmelCase : Optional[int] = model_class_name.from_pretrained('EleutherAI/gpt-j-6B' ) __lowerCAmelCase : List[Any] = model(np.ones((1, 1) ) ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE )
86
0
'''simple docstring''' from __future__ import annotations def SCREAMING_SNAKE_CASE__ ( __A , __A , __A ) -> tuple[float, list[float]]: _snake_case = list(range(len(__A ) ) ) _snake_case = [v / w for v, w in zip(__A , __A )] index.sort(key=lambda __A : ratio[i] , reverse=__A ) _snake_case = 0 _snake_case = [0] * len(__A ) for i in index: if weight[i] <= capacity: _snake_case = 1 max_value += value[i] capacity -= weight[i] else: _snake_case = capacity / weight[i] max_value += value[i] * capacity / weight[i] break return max_value, fractions if __name__ == "__main__": import doctest doctest.testmod()
42
"""simple docstring""" 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 , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=13 , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=99 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=37 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=5_12 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=None , ): __lowerCAmelCase : Tuple = parent __lowerCAmelCase : Optional[int] = 13 __lowerCAmelCase : List[Any] = 7 __lowerCAmelCase : int = True __lowerCAmelCase : Optional[int] = True __lowerCAmelCase : List[Any] = True __lowerCAmelCase : Optional[int] = True __lowerCAmelCase : Optional[Any] = 99 __lowerCAmelCase : int = 3_84 __lowerCAmelCase : Union[str, Any] = 2 __lowerCAmelCase : Tuple = 4 __lowerCAmelCase : str = 37 __lowerCAmelCase : Any = 'gelu' __lowerCAmelCase : List[str] = 0.1 __lowerCAmelCase : Any = 0.1 __lowerCAmelCase : Union[str, Any] = 5_12 __lowerCAmelCase : int = 16 __lowerCAmelCase : Union[str, Any] = 2 __lowerCAmelCase : int = 0.02 __lowerCAmelCase : Dict = 3 __lowerCAmelCase : Tuple = 4 __lowerCAmelCase : Tuple = 1_28 __lowerCAmelCase : Optional[int] = 2 __lowerCAmelCase : List[str] = 9 __lowerCAmelCase : int = 1 __lowerCAmelCase : int = None def __lowerCamelCase ( self ): __lowerCAmelCase : Any = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __lowerCAmelCase : Optional[int] = None if self.use_input_mask: __lowerCAmelCase : str = random_attention_mask([self.batch_size, self.seq_length] ) __lowerCAmelCase : Tuple = None if self.use_token_type_ids: __lowerCAmelCase : Dict = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __lowerCAmelCase : Optional[Any] = None __lowerCAmelCase : Dict = None __lowerCAmelCase : Union[str, Any] = None if self.use_labels: __lowerCAmelCase : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCAmelCase : Dict = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __lowerCAmelCase : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) __lowerCAmelCase : Union[str, 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=_SCREAMING_SNAKE_CASE , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Optional[int] = TFConvBertModel(config=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids} __lowerCAmelCase : Tuple = [input_ids, input_mask] __lowerCAmelCase : Any = model(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Any = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Any = TFConvBertForMaskedLM(config=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } __lowerCAmelCase : Optional[Any] = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Tuple = self.num_labels __lowerCAmelCase : Optional[Any] = TFConvBertForSequenceClassification(config=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : int = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } __lowerCAmelCase : Union[str, Any] = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : int = self.num_choices __lowerCAmelCase : List[str] = TFConvBertForMultipleChoice(config=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = tf.tile(tf.expand_dims(_SCREAMING_SNAKE_CASE , 1 ) , (1, self.num_choices, 1) ) __lowerCAmelCase : Dict = tf.tile(tf.expand_dims(_SCREAMING_SNAKE_CASE , 1 ) , (1, self.num_choices, 1) ) __lowerCAmelCase : Union[str, Any] = tf.tile(tf.expand_dims(_SCREAMING_SNAKE_CASE , 1 ) , (1, self.num_choices, 1) ) __lowerCAmelCase : Tuple = { 'input_ids': multiple_choice_inputs_ids, 'attention_mask': multiple_choice_input_mask, 'token_type_ids': multiple_choice_token_type_ids, } __lowerCAmelCase : str = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : str = self.num_labels __lowerCAmelCase : Any = TFConvBertForTokenClassification(config=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } __lowerCAmelCase : Union[str, Any] = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : str = TFConvBertForQuestionAnswering(config=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Union[str, Any] = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } __lowerCAmelCase : Optional[int] = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __lowerCamelCase ( self ): __lowerCAmelCase : Union[str, Any] = self.prepare_config_and_inputs() ( ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ) : List[str] = config_and_inputs __lowerCAmelCase : Any = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_tf class A__ ( _lowerCamelCase , _lowerCamelCase , unittest.TestCase): A_ : List[str] = ( ( TFConvBertModel, TFConvBertForMaskedLM, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertForMultipleChoice, ) if is_tf_available() else () ) A_ : str = ( { 'feature-extraction': TFConvBertModel, 'fill-mask': TFConvBertForMaskedLM, 'question-answering': TFConvBertForQuestionAnswering, 'text-classification': TFConvBertForSequenceClassification, 'token-classification': TFConvBertForTokenClassification, 'zero-shot': TFConvBertForSequenceClassification, } if is_tf_available() else {} ) A_ : List[Any] = False A_ : str = False A_ : List[Any] = False def __lowerCamelCase ( self ): __lowerCAmelCase : Dict = TFConvBertModelTester(self ) __lowerCAmelCase : Any = ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , hidden_size=37 ) def __lowerCamelCase ( self ): self.config_tester.run_common_tests() def __lowerCamelCase ( self ): __lowerCAmelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_SCREAMING_SNAKE_CASE ) @slow def __lowerCamelCase ( self ): __lowerCAmelCase , __lowerCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() __lowerCAmelCase : Any = True __lowerCAmelCase : Dict = True if hasattr(_SCREAMING_SNAKE_CASE , 'use_cache' ): __lowerCAmelCase : int = True __lowerCAmelCase : List[str] = getattr(self.model_tester , 'encoder_seq_length' , self.model_tester.seq_length ) __lowerCAmelCase : str = getattr(self.model_tester , 'key_length' , _SCREAMING_SNAKE_CASE ) for model_class in self.all_model_classes: __lowerCAmelCase : str = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : str = model_class(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = len(model(_SCREAMING_SNAKE_CASE ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(_SCREAMING_SNAKE_CASE , saved_model=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = os.path.join(_SCREAMING_SNAKE_CASE , 'saved_model' , '1' ) __lowerCAmelCase : int = tf.keras.models.load_model(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = model(_SCREAMING_SNAKE_CASE ) if self.is_encoder_decoder: __lowerCAmelCase : List[str] = outputs['encoder_hidden_states'] __lowerCAmelCase : Tuple = outputs['encoder_attentions'] else: __lowerCAmelCase : Optional[int] = outputs['hidden_states'] __lowerCAmelCase : Tuple = outputs['attentions'] self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Union[str, Any] = getattr( self.model_tester , 'expected_num_hidden_layers' , self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) self.assertListEqual( list(output_hidden_states[0].shape[-2:] ) , [self.model_tester.seq_length, self.model_tester.hidden_size] , ) self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , 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 __lowerCamelCase ( self ): __lowerCAmelCase : Tuple = TFConvBertModel.from_pretrained('YituTech/conv-bert-base' ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase , __lowerCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs_for_common() __lowerCAmelCase : Optional[Any] = True __lowerCAmelCase : List[Any] = getattr(self.model_tester , 'decoder_seq_length' , self.model_tester.seq_length ) __lowerCAmelCase : str = getattr(self.model_tester , 'encoder_seq_length' , self.model_tester.seq_length ) __lowerCAmelCase : Tuple = getattr(self.model_tester , 'key_length' , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = getattr(self.model_tester , 'key_length' , _SCREAMING_SNAKE_CASE ) def check_decoder_attentions_output(_SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Union[str, Any] = len(_SCREAMING_SNAKE_CASE ) self.assertEqual(out_len % 2 , 0 ) __lowerCAmelCase : Optional[Any] = outputs.decoder_attentions self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , 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(_SCREAMING_SNAKE_CASE ): __lowerCAmelCase : str = [ t.numpy() for t in (outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions) ] self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , 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: __lowerCAmelCase : List[str] = True __lowerCAmelCase : Optional[int] = False __lowerCAmelCase : List[Any] = model_class(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = model(self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) __lowerCAmelCase : Tuple = len(_SCREAMING_SNAKE_CASE ) self.assertEqual(config.output_hidden_states , _SCREAMING_SNAKE_CASE ) check_encoder_attentions_output(_SCREAMING_SNAKE_CASE ) if self.is_encoder_decoder: __lowerCAmelCase : Any = model_class(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = model(self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) self.assertEqual(config.output_hidden_states , _SCREAMING_SNAKE_CASE ) check_decoder_attentions_output(_SCREAMING_SNAKE_CASE ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] __lowerCAmelCase : Optional[Any] = True __lowerCAmelCase : str = model_class(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = model(self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) self.assertEqual(config.output_hidden_states , _SCREAMING_SNAKE_CASE ) check_encoder_attentions_output(_SCREAMING_SNAKE_CASE ) # Check attention is always last and order is fine __lowerCAmelCase : Dict = True __lowerCAmelCase : Optional[Any] = True __lowerCAmelCase : List[Any] = model_class(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = model(self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(_SCREAMING_SNAKE_CASE ) ) self.assertEqual(model.config.output_hidden_states , _SCREAMING_SNAKE_CASE ) check_encoder_attentions_output(_SCREAMING_SNAKE_CASE ) @require_tf class A__ ( unittest.TestCase): @slow def __lowerCamelCase ( self ): __lowerCAmelCase : Dict = TFConvBertModel.from_pretrained('YituTech/conv-bert-base' ) __lowerCAmelCase : int = tf.constant([[0, 1, 2, 3, 4, 5]] ) __lowerCAmelCase : Tuple = model(_SCREAMING_SNAKE_CASE )[0] __lowerCAmelCase : Tuple = [1, 6, 7_68] self.assertEqual(output.shape , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = tf.constant( [ [ [-0.0347_5493, -0.468_6034, -0.3063_8832], [0.2263_7248, -0.2698_8646, -0.742_3424], [0.1032_4868, -0.4501_3508, -0.5828_0784], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 )
86
0
import argparse import json import logging import os import shutil import sys import tempfile import unittest from unittest import mock import torch from accelerate.utils import write_basic_config from transformers.testing_utils import TestCasePlus, get_gpu_count, run_command, slow, torch_device from transformers.utils import is_apex_available logging.basicConfig(level=logging.DEBUG) __lowercase = logging.getLogger() def lowerCamelCase ( ): '''simple docstring''' __UpperCamelCase :List[Any] = argparse.ArgumentParser() parser.add_argument('''-f''' ) __UpperCamelCase :Any = parser.parse_args() return args.f def lowerCamelCase ( SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCamelCase :Union[str, Any] = {} __UpperCamelCase :str = os.path.join(SCREAMING_SNAKE_CASE , '''all_results.json''' ) if os.path.exists(SCREAMING_SNAKE_CASE ): with open(SCREAMING_SNAKE_CASE , '''r''' ) as f: __UpperCamelCase :Optional[Any] = json.load(SCREAMING_SNAKE_CASE ) else: raise ValueError(f"""can't find {path}""" ) return results def lowerCamelCase ( ): '''simple docstring''' __UpperCamelCase :Optional[Any] = torch.cuda.is_available() and torch_device == '''cuda''' return is_using_cuda and is_apex_available() __lowercase = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class lowerCamelCase_ ( UpperCAmelCase_ ): '''simple docstring''' @classmethod def UpperCamelCase__ ( cls) -> int: # Write Accelerate config, will pick up on CPU, GPU, and multi-GPU __UpperCamelCase :List[Any] = tempfile.mkdtemp() __UpperCamelCase :List[Any] = os.path.join(cls.tmpdir , '''default_config.yml''') write_basic_config(save_location=cls.configPath) __UpperCamelCase :int = ['''accelerate''', '''launch''', '''--config_file''', cls.configPath] @classmethod def UpperCamelCase__ ( cls) -> Union[str, Any]: shutil.rmtree(cls.tmpdir) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''}) def UpperCamelCase__ ( self) -> Union[str, Any]: __UpperCamelCase :List[str] = self.get_auto_remove_tmp_dir() __UpperCamelCase :Any = f""" {self.examples_dir}/pytorch/text-classification/run_glue_no_trainer.py --model_name_or_path distilbert-base-uncased --output_dir {tmp_dir} --train_file ./tests/fixtures/tests_samples/MRPC/train.csv --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --learning_rate=1e-4 --seed=42 --checkpointing_steps epoch --with_tracking """.split() if is_cuda_and_apex_available(): testargs.append('''--fp16''') run_command(self._launch_args + testargs) __UpperCamelCase :Optional[Any] = get_results(__lowercase) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75) self.assertTrue(os.path.exists(os.path.join(__lowercase , '''epoch_0'''))) self.assertTrue(os.path.exists(os.path.join(__lowercase , '''glue_no_trainer'''))) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''}) def UpperCamelCase__ ( self) -> int: __UpperCamelCase :Any = self.get_auto_remove_tmp_dir() __UpperCamelCase :List[str] = f""" {self.examples_dir}/pytorch/language-modeling/run_clm_no_trainer.py --model_name_or_path distilgpt2 --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --block_size 128 --per_device_train_batch_size 5 --per_device_eval_batch_size 5 --num_train_epochs 2 --output_dir {tmp_dir} --checkpointing_steps epoch --with_tracking """.split() if torch.cuda.device_count() > 1: # Skipping because there are not enough batches to train the model + would need a drop_last to work. return run_command(self._launch_args + testargs) __UpperCamelCase :Dict = get_results(__lowercase) self.assertLess(result['''perplexity'''] , 100) self.assertTrue(os.path.exists(os.path.join(__lowercase , '''epoch_0'''))) self.assertTrue(os.path.exists(os.path.join(__lowercase , '''clm_no_trainer'''))) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''}) def UpperCamelCase__ ( self) -> Any: __UpperCamelCase :List[Any] = self.get_auto_remove_tmp_dir() __UpperCamelCase :List[Any] = f""" {self.examples_dir}/pytorch/language-modeling/run_mlm_no_trainer.py --model_name_or_path distilroberta-base --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --output_dir {tmp_dir} --num_train_epochs=1 --checkpointing_steps epoch --with_tracking """.split() run_command(self._launch_args + testargs) __UpperCamelCase :Union[str, Any] = get_results(__lowercase) self.assertLess(result['''perplexity'''] , 42) self.assertTrue(os.path.exists(os.path.join(__lowercase , '''epoch_0'''))) self.assertTrue(os.path.exists(os.path.join(__lowercase , '''mlm_no_trainer'''))) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''}) def UpperCamelCase__ ( self) -> Tuple: # with so little data distributed training needs more epochs to get the score on par with 0/1 gpu __UpperCamelCase :Union[str, Any] = 7 if get_gpu_count() > 1 else 2 __UpperCamelCase :List[Any] = self.get_auto_remove_tmp_dir() __UpperCamelCase :List[Any] = f""" {self.examples_dir}/pytorch/token-classification/run_ner_no_trainer.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/conll/sample.json --validation_file tests/fixtures/tests_samples/conll/sample.json --output_dir {tmp_dir} --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=2 --num_train_epochs={epochs} --seed 7 --checkpointing_steps epoch --with_tracking """.split() run_command(self._launch_args + testargs) __UpperCamelCase :Optional[Any] = get_results(__lowercase) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75) self.assertLess(result['''train_loss'''] , 0.5) self.assertTrue(os.path.exists(os.path.join(__lowercase , '''epoch_0'''))) self.assertTrue(os.path.exists(os.path.join(__lowercase , '''ner_no_trainer'''))) @unittest.skip(reason='''Fix me @muellerzr''') @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''}) def UpperCamelCase__ ( self) -> Union[str, Any]: __UpperCamelCase :Union[str, Any] = self.get_auto_remove_tmp_dir() __UpperCamelCase :int = f""" {self.examples_dir}/pytorch/question-answering/run_qa_no_trainer.py --model_name_or_path bert-base-uncased --version_2_with_negative --train_file tests/fixtures/tests_samples/SQUAD/sample.json --validation_file tests/fixtures/tests_samples/SQUAD/sample.json --output_dir {tmp_dir} --seed=42 --max_train_steps=10 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch --with_tracking """.split() run_command(self._launch_args + testargs) __UpperCamelCase :Any = get_results(__lowercase) # Because we use --version_2_with_negative the testing script uses SQuAD v2 metrics. self.assertGreaterEqual(result['''eval_f1'''] , 28) self.assertGreaterEqual(result['''eval_exact'''] , 28) self.assertTrue(os.path.exists(os.path.join(__lowercase , '''epoch_0'''))) self.assertTrue(os.path.exists(os.path.join(__lowercase , '''qa_no_trainer'''))) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''}) def UpperCamelCase__ ( self) -> Union[str, Any]: __UpperCamelCase :int = self.get_auto_remove_tmp_dir() __UpperCamelCase :int = f""" {self.examples_dir}/pytorch/multiple-choice/run_swag_no_trainer.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/swag/sample.json --validation_file tests/fixtures/tests_samples/swag/sample.json --output_dir {tmp_dir} --max_train_steps=20 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --with_tracking """.split() run_command(self._launch_args + testargs) __UpperCamelCase :Dict = get_results(__lowercase) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.8) self.assertTrue(os.path.exists(os.path.join(__lowercase , '''swag_no_trainer'''))) @slow @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''}) def UpperCamelCase__ ( self) -> str: __UpperCamelCase :str = self.get_auto_remove_tmp_dir() __UpperCamelCase :Dict = f""" {self.examples_dir}/pytorch/summarization/run_summarization_no_trainer.py --model_name_or_path t5-small --train_file tests/fixtures/tests_samples/xsum/sample.json --validation_file tests/fixtures/tests_samples/xsum/sample.json --output_dir {tmp_dir} --max_train_steps=50 --num_warmup_steps=8 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch --with_tracking """.split() run_command(self._launch_args + testargs) __UpperCamelCase :Tuple = get_results(__lowercase) self.assertGreaterEqual(result['''eval_rouge1'''] , 10) self.assertGreaterEqual(result['''eval_rouge2'''] , 2) self.assertGreaterEqual(result['''eval_rougeL'''] , 7) self.assertGreaterEqual(result['''eval_rougeLsum'''] , 7) self.assertTrue(os.path.exists(os.path.join(__lowercase , '''epoch_0'''))) self.assertTrue(os.path.exists(os.path.join(__lowercase , '''summarization_no_trainer'''))) @slow @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''}) def UpperCamelCase__ ( self) -> str: __UpperCamelCase :Optional[int] = self.get_auto_remove_tmp_dir() __UpperCamelCase :Dict = f""" {self.examples_dir}/pytorch/translation/run_translation_no_trainer.py --model_name_or_path sshleifer/student_marian_en_ro_6_1 --source_lang en --target_lang ro --train_file tests/fixtures/tests_samples/wmt16/sample.json --validation_file tests/fixtures/tests_samples/wmt16/sample.json --output_dir {tmp_dir} --max_train_steps=50 --num_warmup_steps=8 --num_beams=6 --learning_rate=3e-3 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --source_lang en_XX --target_lang ro_RO --checkpointing_steps epoch --with_tracking """.split() run_command(self._launch_args + testargs) __UpperCamelCase :Optional[int] = get_results(__lowercase) self.assertGreaterEqual(result['''eval_bleu'''] , 30) self.assertTrue(os.path.exists(os.path.join(__lowercase , '''epoch_0'''))) self.assertTrue(os.path.exists(os.path.join(__lowercase , '''translation_no_trainer'''))) @slow def UpperCamelCase__ ( self) -> Tuple: __UpperCamelCase :Tuple = logging.StreamHandler(sys.stdout) logger.addHandler(__lowercase) __UpperCamelCase :int = self.get_auto_remove_tmp_dir() __UpperCamelCase :Any = f""" {self.examples_dir}/pytorch/semantic-segmentation/run_semantic_segmentation_no_trainer.py --dataset_name huggingface/semantic-segmentation-test-sample --output_dir {tmp_dir} --max_train_steps=10 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch """.split() run_command(self._launch_args + testargs) __UpperCamelCase :List[str] = get_results(__lowercase) self.assertGreaterEqual(result['''eval_overall_accuracy'''] , 0.10) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''}) def UpperCamelCase__ ( self) -> Optional[int]: __UpperCamelCase :Union[str, Any] = self.get_auto_remove_tmp_dir() __UpperCamelCase :Optional[Any] = f""" {self.examples_dir}/pytorch/image-classification/run_image_classification_no_trainer.py --model_name_or_path google/vit-base-patch16-224-in21k --dataset_name hf-internal-testing/cats_vs_dogs_sample --learning_rate 1e-4 --per_device_train_batch_size 2 --per_device_eval_batch_size 1 --max_train_steps 2 --train_val_split 0.1 --seed 42 --output_dir {tmp_dir} --with_tracking --checkpointing_steps 1 """.split() if is_cuda_and_apex_available(): testargs.append('''--fp16''') run_command(self._launch_args + testargs) __UpperCamelCase :Optional[Any] = get_results(__lowercase) # The base model scores a 25% self.assertGreaterEqual(result['''eval_accuracy'''] , 0.6) self.assertTrue(os.path.exists(os.path.join(__lowercase , '''step_1'''))) self.assertTrue(os.path.exists(os.path.join(__lowercase , '''image_classification_no_trainer''')))
43
"""simple docstring""" 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 DetrImageProcessor class A__ ( unittest.TestCase): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=30 , _SCREAMING_SNAKE_CASE=4_00 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=1 / 2_55 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , _SCREAMING_SNAKE_CASE=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __lowerCAmelCase : Any = size if size is not None else {'shortest_edge': 18, 'longest_edge': 13_33} __lowerCAmelCase : Optional[int] = parent __lowerCAmelCase : int = batch_size __lowerCAmelCase : str = num_channels __lowerCAmelCase : Optional[int] = min_resolution __lowerCAmelCase : List[Any] = max_resolution __lowerCAmelCase : Union[str, Any] = do_resize __lowerCAmelCase : Optional[Any] = size __lowerCAmelCase : Dict = do_rescale __lowerCAmelCase : Optional[Any] = rescale_factor __lowerCAmelCase : Any = do_normalize __lowerCAmelCase : List[str] = image_mean __lowerCAmelCase : Union[str, Any] = image_std __lowerCAmelCase : Optional[int] = do_pad def __lowerCamelCase ( self ): return { "do_resize": self.do_resize, "size": self.size, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_pad": self.do_pad, } def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ): if not batched: __lowerCAmelCase : str = image_inputs[0] if isinstance(_SCREAMING_SNAKE_CASE , Image.Image ): __lowerCAmelCase , __lowerCAmelCase : Optional[int] = image.size else: __lowerCAmelCase , __lowerCAmelCase : Union[str, Any] = image.shape[1], image.shape[2] if w < h: __lowerCAmelCase : str = int(self.size['shortest_edge'] * h / w ) __lowerCAmelCase : Optional[int] = self.size['shortest_edge'] elif w > h: __lowerCAmelCase : str = self.size['shortest_edge'] __lowerCAmelCase : Union[str, Any] = int(self.size['shortest_edge'] * w / h ) else: __lowerCAmelCase : str = self.size['shortest_edge'] __lowerCAmelCase : Optional[Any] = self.size['shortest_edge'] else: __lowerCAmelCase : str = [] for image in image_inputs: __lowerCAmelCase , __lowerCAmelCase : List[Any] = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __lowerCAmelCase : Any = max(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : item[0] )[0] __lowerCAmelCase : Dict = max(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class A__ ( _lowerCamelCase , unittest.TestCase): A_ : List[str] = DetrImageProcessor if is_vision_available() else None def __lowerCamelCase ( self ): __lowerCAmelCase : List[Any] = DetrImageProcessingTester(self ) @property def __lowerCamelCase ( self ): return self.image_processor_tester.prepare_image_processor_dict() def __lowerCamelCase ( self ): __lowerCAmelCase : Dict = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'image_mean' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'image_std' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_normalize' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_rescale' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'rescale_factor' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_resize' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'size' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_pad' ) ) def __lowerCamelCase ( self ): __lowerCAmelCase : Optional[Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'shortest_edge': 18, 'longest_edge': 13_33} ) self.assertEqual(image_processor.do_pad , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=_SCREAMING_SNAKE_CASE ) self.assertEqual(image_processor.size , {'shortest_edge': 42, 'longest_edge': 84} ) self.assertEqual(image_processor.do_pad , _SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): pass def __lowerCamelCase ( self ): # Initialize image_processing __lowerCAmelCase : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __lowerCAmelCase : str = 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 __lowerCAmelCase : int = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values __lowerCAmelCase , __lowerCAmelCase : List[Any] = self.image_processor_tester.get_expected_values(_SCREAMING_SNAKE_CASE ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __lowerCAmelCase , __lowerCAmelCase : int = self.image_processor_tester.get_expected_values(_SCREAMING_SNAKE_CASE , batched=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Union[str, Any] = image_processing(_SCREAMING_SNAKE_CASE , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __lowerCamelCase ( self ): # Initialize image_processing __lowerCAmelCase : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __lowerCAmelCase : str = 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 __lowerCAmelCase : Tuple = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values __lowerCAmelCase , __lowerCAmelCase : Tuple = self.image_processor_tester.get_expected_values(_SCREAMING_SNAKE_CASE ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __lowerCAmelCase : Union[str, Any] = image_processing(_SCREAMING_SNAKE_CASE , return_tensors='pt' ).pixel_values __lowerCAmelCase , __lowerCAmelCase : List[Any] = self.image_processor_tester.get_expected_values(_SCREAMING_SNAKE_CASE , batched=_SCREAMING_SNAKE_CASE ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __lowerCamelCase ( self ): # Initialize image_processing __lowerCAmelCase : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __lowerCAmelCase : int = 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 __lowerCAmelCase : Any = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values __lowerCAmelCase , __lowerCAmelCase : Dict = self.image_processor_tester.get_expected_values(_SCREAMING_SNAKE_CASE ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __lowerCAmelCase : Tuple = image_processing(_SCREAMING_SNAKE_CASE , return_tensors='pt' ).pixel_values __lowerCAmelCase , __lowerCAmelCase : Any = self.image_processor_tester.get_expected_values(_SCREAMING_SNAKE_CASE , batched=_SCREAMING_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 __lowerCamelCase ( self ): # prepare image and target __lowerCAmelCase : Union[str, Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' , 'r' ) as f: __lowerCAmelCase : Any = json.loads(f.read() ) __lowerCAmelCase : Tuple = {'image_id': 3_97_69, 'annotations': target} # encode them __lowerCAmelCase : Dict = DetrImageProcessor.from_pretrained('facebook/detr-resnet-50' ) __lowerCAmelCase : int = image_processing(images=_SCREAMING_SNAKE_CASE , annotations=_SCREAMING_SNAKE_CASE , return_tensors='pt' ) # verify pixel values __lowerCAmelCase : str = torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding['pixel_values'].shape , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : int = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 ) ) # verify area __lowerCAmelCase : List[str] = torch.tensor([5887.9600, 1_1250.2061, 48_9353.8438, 83_7122.7500, 14_7967.5156, 16_5732.3438] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , _SCREAMING_SNAKE_CASE ) ) # verify boxes __lowerCAmelCase : Tuple = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : str = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , _SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # verify image_id __lowerCAmelCase : Dict = torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , _SCREAMING_SNAKE_CASE ) ) # verify is_crowd __lowerCAmelCase : Optional[int] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , _SCREAMING_SNAKE_CASE ) ) # verify class_labels __lowerCAmelCase : Union[str, Any] = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , _SCREAMING_SNAKE_CASE ) ) # verify orig_size __lowerCAmelCase : int = torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , _SCREAMING_SNAKE_CASE ) ) # verify size __lowerCAmelCase : List[Any] = torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , _SCREAMING_SNAKE_CASE ) ) @slow def __lowerCamelCase ( self ): # prepare image, target and masks_path __lowerCAmelCase : Optional[int] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' , 'r' ) as f: __lowerCAmelCase : Optional[int] = json.loads(f.read() ) __lowerCAmelCase : Optional[int] = {'file_name': '000000039769.png', 'image_id': 3_97_69, 'segments_info': target} __lowerCAmelCase : Union[str, Any] = pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic' ) # encode them __lowerCAmelCase : Optional[int] = DetrImageProcessor.from_pretrained('facebook/detr-resnet-50-panoptic' ) __lowerCAmelCase : Optional[Any] = image_processing(images=_SCREAMING_SNAKE_CASE , annotations=_SCREAMING_SNAKE_CASE , masks_path=_SCREAMING_SNAKE_CASE , return_tensors='pt' ) # verify pixel values __lowerCAmelCase : str = torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding['pixel_values'].shape , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 ) ) # verify area __lowerCAmelCase : int = torch.tensor([14_7979.6875, 16_5527.0469, 48_4638.5938, 1_1292.9375, 5879.6562, 7634.1147] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , _SCREAMING_SNAKE_CASE ) ) # verify boxes __lowerCAmelCase : Optional[int] = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , _SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # verify image_id __lowerCAmelCase : str = torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , _SCREAMING_SNAKE_CASE ) ) # verify is_crowd __lowerCAmelCase : Optional[int] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , _SCREAMING_SNAKE_CASE ) ) # verify class_labels __lowerCAmelCase : str = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , _SCREAMING_SNAKE_CASE ) ) # verify masks __lowerCAmelCase : Dict = 82_28_73 self.assertEqual(encoding['labels'][0]['masks'].sum().item() , _SCREAMING_SNAKE_CASE ) # verify orig_size __lowerCAmelCase : str = torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , _SCREAMING_SNAKE_CASE ) ) # verify size __lowerCAmelCase : List[Any] = torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , _SCREAMING_SNAKE_CASE ) )
86
0
"""simple docstring""" import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Image from .base import TaskTemplate @dataclass(frozen=SCREAMING_SNAKE_CASE_ ) class __A ( SCREAMING_SNAKE_CASE_ ): _UpperCamelCase : str = field(default="image-classification" , metadata={"include_in_asdict_even_if_is_default": True} ) _UpperCamelCase : ClassVar[Features] = Features({"image": Image()} ) _UpperCamelCase : ClassVar[Features] = Features({"labels": ClassLabel} ) _UpperCamelCase : str = "image" _UpperCamelCase : str = "labels" def __A ( self , a__ ): if self.label_column not in features: raise ValueError(F"Column {self.label_column} is not present in features." ) if not isinstance(features[self.label_column] , a__ ): raise ValueError(F"Column {self.label_column} is not a ClassLabel." ) _lowerCAmelCase : str = copy.deepcopy(self ) _lowerCAmelCase : Dict = self.label_schema.copy() _lowerCAmelCase : str = features[self.label_column] _lowerCAmelCase : Optional[Any] = label_schema return task_template @property def __A ( self ): return { self.image_column: "image", self.label_column: "labels", }
44
"""simple docstring""" import numpy as np def __lowerCAmelCase (_UpperCamelCase ): return 1 / (1 + np.exp(-vector )) def __lowerCAmelCase (_UpperCamelCase ): return vector * sigmoid(_UpperCamelCase ) if __name__ == "__main__": import doctest doctest.testmod()
86
0
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool lowercase_ = { "Acehnese Arabic": "ace_Arab", "Acehnese Latin": "ace_Latn", "Mesopotamian Arabic": "acm_Arab", "Ta'izzi-Adeni Arabic": "acq_Arab", "Tunisian Arabic": "aeb_Arab", "Afrikaans": "afr_Latn", "South Levantine Arabic": "ajp_Arab", "Akan": "aka_Latn", "Amharic": "amh_Ethi", "North Levantine Arabic": "apc_Arab", "Modern Standard Arabic": "arb_Arab", "Modern Standard Arabic Romanized": "arb_Latn", "Najdi Arabic": "ars_Arab", "Moroccan Arabic": "ary_Arab", "Egyptian Arabic": "arz_Arab", "Assamese": "asm_Beng", "Asturian": "ast_Latn", "Awadhi": "awa_Deva", "Central Aymara": "ayr_Latn", "South Azerbaijani": "azb_Arab", "North Azerbaijani": "azj_Latn", "Bashkir": "bak_Cyrl", "Bambara": "bam_Latn", "Balinese": "ban_Latn", "Belarusian": "bel_Cyrl", "Bemba": "bem_Latn", "Bengali": "ben_Beng", "Bhojpuri": "bho_Deva", "Banjar Arabic": "bjn_Arab", "Banjar Latin": "bjn_Latn", "Standard Tibetan": "bod_Tibt", "Bosnian": "bos_Latn", "Buginese": "bug_Latn", "Bulgarian": "bul_Cyrl", "Catalan": "cat_Latn", "Cebuano": "ceb_Latn", "Czech": "ces_Latn", "Chokwe": "cjk_Latn", "Central Kurdish": "ckb_Arab", "Crimean Tatar": "crh_Latn", "Welsh": "cym_Latn", "Danish": "dan_Latn", "German": "deu_Latn", "Southwestern Dinka": "dik_Latn", "Dyula": "dyu_Latn", "Dzongkha": "dzo_Tibt", "Greek": "ell_Grek", "English": "eng_Latn", "Esperanto": "epo_Latn", "Estonian": "est_Latn", "Basque": "eus_Latn", "Ewe": "ewe_Latn", "Faroese": "fao_Latn", "Fijian": "fij_Latn", "Finnish": "fin_Latn", "Fon": "fon_Latn", "French": "fra_Latn", "Friulian": "fur_Latn", "Nigerian Fulfulde": "fuv_Latn", "Scottish Gaelic": "gla_Latn", "Irish": "gle_Latn", "Galician": "glg_Latn", "Guarani": "grn_Latn", "Gujarati": "guj_Gujr", "Haitian Creole": "hat_Latn", "Hausa": "hau_Latn", "Hebrew": "heb_Hebr", "Hindi": "hin_Deva", "Chhattisgarhi": "hne_Deva", "Croatian": "hrv_Latn", "Hungarian": "hun_Latn", "Armenian": "hye_Armn", "Igbo": "ibo_Latn", "Ilocano": "ilo_Latn", "Indonesian": "ind_Latn", "Icelandic": "isl_Latn", "Italian": "ita_Latn", "Javanese": "jav_Latn", "Japanese": "jpn_Jpan", "Kabyle": "kab_Latn", "Jingpho": "kac_Latn", "Kamba": "kam_Latn", "Kannada": "kan_Knda", "Kashmiri Arabic": "kas_Arab", "Kashmiri Devanagari": "kas_Deva", "Georgian": "kat_Geor", "Central Kanuri Arabic": "knc_Arab", "Central Kanuri Latin": "knc_Latn", "Kazakh": "kaz_Cyrl", "Kabiyè": "kbp_Latn", "Kabuverdianu": "kea_Latn", "Khmer": "khm_Khmr", "Kikuyu": "kik_Latn", "Kinyarwanda": "kin_Latn", "Kyrgyz": "kir_Cyrl", "Kimbundu": "kmb_Latn", "Northern Kurdish": "kmr_Latn", "Kikongo": "kon_Latn", "Korean": "kor_Hang", "Lao": "lao_Laoo", "Ligurian": "lij_Latn", "Limburgish": "lim_Latn", "Lingala": "lin_Latn", "Lithuanian": "lit_Latn", "Lombard": "lmo_Latn", "Latgalian": "ltg_Latn", "Luxembourgish": "ltz_Latn", "Luba-Kasai": "lua_Latn", "Ganda": "lug_Latn", "Luo": "luo_Latn", "Mizo": "lus_Latn", "Standard Latvian": "lvs_Latn", "Magahi": "mag_Deva", "Maithili": "mai_Deva", "Malayalam": "mal_Mlym", "Marathi": "mar_Deva", "Minangkabau Arabic ": "min_Arab", "Minangkabau Latin": "min_Latn", "Macedonian": "mkd_Cyrl", "Plateau Malagasy": "plt_Latn", "Maltese": "mlt_Latn", "Meitei Bengali": "mni_Beng", "Halh Mongolian": "khk_Cyrl", "Mossi": "mos_Latn", "Maori": "mri_Latn", "Burmese": "mya_Mymr", "Dutch": "nld_Latn", "Norwegian Nynorsk": "nno_Latn", "Norwegian Bokmål": "nob_Latn", "Nepali": "npi_Deva", "Northern Sotho": "nso_Latn", "Nuer": "nus_Latn", "Nyanja": "nya_Latn", "Occitan": "oci_Latn", "West Central Oromo": "gaz_Latn", "Odia": "ory_Orya", "Pangasinan": "pag_Latn", "Eastern Panjabi": "pan_Guru", "Papiamento": "pap_Latn", "Western Persian": "pes_Arab", "Polish": "pol_Latn", "Portuguese": "por_Latn", "Dari": "prs_Arab", "Southern Pashto": "pbt_Arab", "Ayacucho Quechua": "quy_Latn", "Romanian": "ron_Latn", "Rundi": "run_Latn", "Russian": "rus_Cyrl", "Sango": "sag_Latn", "Sanskrit": "san_Deva", "Santali": "sat_Olck", "Sicilian": "scn_Latn", "Shan": "shn_Mymr", "Sinhala": "sin_Sinh", "Slovak": "slk_Latn", "Slovenian": "slv_Latn", "Samoan": "smo_Latn", "Shona": "sna_Latn", "Sindhi": "snd_Arab", "Somali": "som_Latn", "Southern Sotho": "sot_Latn", "Spanish": "spa_Latn", "Tosk Albanian": "als_Latn", "Sardinian": "srd_Latn", "Serbian": "srp_Cyrl", "Swati": "ssw_Latn", "Sundanese": "sun_Latn", "Swedish": "swe_Latn", "Swahili": "swh_Latn", "Silesian": "szl_Latn", "Tamil": "tam_Taml", "Tatar": "tat_Cyrl", "Telugu": "tel_Telu", "Tajik": "tgk_Cyrl", "Tagalog": "tgl_Latn", "Thai": "tha_Thai", "Tigrinya": "tir_Ethi", "Tamasheq Latin": "taq_Latn", "Tamasheq Tifinagh": "taq_Tfng", "Tok Pisin": "tpi_Latn", "Tswana": "tsn_Latn", "Tsonga": "tso_Latn", "Turkmen": "tuk_Latn", "Tumbuka": "tum_Latn", "Turkish": "tur_Latn", "Twi": "twi_Latn", "Central Atlas Tamazight": "tzm_Tfng", "Uyghur": "uig_Arab", "Ukrainian": "ukr_Cyrl", "Umbundu": "umb_Latn", "Urdu": "urd_Arab", "Northern Uzbek": "uzn_Latn", "Venetian": "vec_Latn", "Vietnamese": "vie_Latn", "Waray": "war_Latn", "Wolof": "wol_Latn", "Xhosa": "xho_Latn", "Eastern Yiddish": "ydd_Hebr", "Yoruba": "yor_Latn", "Yue Chinese": "yue_Hant", "Chinese Simplified": "zho_Hans", "Chinese Traditional": "zho_Hant", "Standard Malay": "zsm_Latn", "Zulu": "zul_Latn", } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : List[str] = 'facebook/nllb-200-distilled-600M' __UpperCAmelCase : int = ( 'This is a tool that translates text from a language to another. It takes three inputs: `text`, which should ' 'be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, ' 'which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in ' 'plain English, such as \'Romanian\', or \'Albanian\'. It returns the text translated in `tgt_lang`.' ) __UpperCAmelCase : Tuple = 'translator' __UpperCAmelCase : int = AutoTokenizer __UpperCAmelCase : Dict = AutoModelForSeqaSeqLM __UpperCAmelCase : List[str] = LANGUAGE_CODES __UpperCAmelCase : Dict = ['text', 'text', 'text'] __UpperCAmelCase : Dict = ['text'] def __UpperCAmelCase ( self , _a , _a , _a ): if src_lang not in self.lang_to_code: raise ValueError(f'''{src_lang} is not a supported language.''' ) if tgt_lang not in self.lang_to_code: raise ValueError(f'''{tgt_lang} is not a supported language.''' ) __a = self.lang_to_code[src_lang] __a = self.lang_to_code[tgt_lang] return self.pre_processor._build_translation_inputs( _a , return_tensors='''pt''' , src_lang=_a , tgt_lang=_a ) def __UpperCAmelCase ( self , _a ): return self.model.generate(**_a ) def __UpperCAmelCase ( self , _a ): return self.post_processor.decode(outputs[0].tolist() , skip_special_tokens=_a )
45
"""simple docstring""" import unittest from transformers import MobileBertConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, MobileBertForMaskedLM, MobileBertForMultipleChoice, MobileBertForNextSentencePrediction, MobileBertForPreTraining, MobileBertForQuestionAnswering, MobileBertForSequenceClassification, MobileBertForTokenClassification, MobileBertModel, ) class A__ : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=13 , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=99 , _SCREAMING_SNAKE_CASE=64 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=37 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=5_12 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=None , ): __lowerCAmelCase : Optional[int] = parent __lowerCAmelCase : Union[str, Any] = batch_size __lowerCAmelCase : Dict = seq_length __lowerCAmelCase : Dict = is_training __lowerCAmelCase : List[str] = use_input_mask __lowerCAmelCase : int = use_token_type_ids __lowerCAmelCase : Optional[int] = use_labels __lowerCAmelCase : List[Any] = vocab_size __lowerCAmelCase : Dict = hidden_size __lowerCAmelCase : Tuple = embedding_size __lowerCAmelCase : List[Any] = num_hidden_layers __lowerCAmelCase : Tuple = num_attention_heads __lowerCAmelCase : Union[str, Any] = intermediate_size __lowerCAmelCase : Optional[Any] = hidden_act __lowerCAmelCase : Optional[int] = hidden_dropout_prob __lowerCAmelCase : Dict = attention_probs_dropout_prob __lowerCAmelCase : Any = max_position_embeddings __lowerCAmelCase : Any = type_vocab_size __lowerCAmelCase : Union[str, Any] = type_sequence_label_size __lowerCAmelCase : List[str] = initializer_range __lowerCAmelCase : str = num_labels __lowerCAmelCase : int = num_choices __lowerCAmelCase : Union[str, Any] = scope def __lowerCamelCase ( self ): __lowerCAmelCase : Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __lowerCAmelCase : Optional[int] = None if self.use_input_mask: __lowerCAmelCase : Optional[int] = random_attention_mask([self.batch_size, self.seq_length] ) __lowerCAmelCase : str = None if self.use_token_type_ids: __lowerCAmelCase : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __lowerCAmelCase : Union[str, Any] = None __lowerCAmelCase : Optional[int] = None __lowerCAmelCase : Union[str, Any] = None if self.use_labels: __lowerCAmelCase : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCAmelCase : Dict = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __lowerCAmelCase : Dict = ids_tensor([self.batch_size] , self.num_choices ) __lowerCAmelCase : str = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowerCamelCase ( self ): return MobileBertConfig( 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 , embedding_size=self.embedding_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=_SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : str = MobileBertModel(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() __lowerCAmelCase : Optional[Any] = model(_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = model(_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : int = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Union[str, Any] = MobileBertForMaskedLM(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() __lowerCAmelCase : Any = model(_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Optional[Any] = MobileBertForNextSentencePrediction(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() __lowerCAmelCase : Dict = model( _SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : List[Any] = MobileBertForPreTraining(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() __lowerCAmelCase : List[Any] = model( _SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE , next_sentence_label=_SCREAMING_SNAKE_CASE , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Optional[int] = MobileBertForQuestionAnswering(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() __lowerCAmelCase : List[str] = model( _SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_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 __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Optional[int] = self.num_labels __lowerCAmelCase : Tuple = MobileBertForSequenceClassification(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() __lowerCAmelCase : str = model(_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Optional[Any] = self.num_labels __lowerCAmelCase : int = MobileBertForTokenClassification(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() __lowerCAmelCase : Optional[Any] = model(_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Optional[int] = self.num_choices __lowerCAmelCase : List[str] = MobileBertForMultipleChoice(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() __lowerCAmelCase : str = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __lowerCAmelCase : List[Any] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __lowerCAmelCase : List[Any] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __lowerCAmelCase : List[str] = model( _SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __lowerCamelCase ( self ): __lowerCAmelCase : Optional[Any] = self.prepare_config_and_inputs() ( ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ) : Optional[Any] = config_and_inputs __lowerCAmelCase : List[str] = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class A__ ( _lowerCamelCase , _lowerCamelCase , unittest.TestCase): A_ : str = ( ( MobileBertModel, MobileBertForMaskedLM, MobileBertForMultipleChoice, MobileBertForNextSentencePrediction, MobileBertForPreTraining, MobileBertForQuestionAnswering, MobileBertForSequenceClassification, MobileBertForTokenClassification, ) if is_torch_available() else () ) A_ : List[str] = ( { 'feature-extraction': MobileBertModel, 'fill-mask': MobileBertForMaskedLM, 'question-answering': MobileBertForQuestionAnswering, 'text-classification': MobileBertForSequenceClassification, 'token-classification': MobileBertForTokenClassification, 'zero-shot': MobileBertForSequenceClassification, } if is_torch_available() else {} ) A_ : Dict = True def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ): __lowerCAmelCase : List[str] = super()._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) if return_labels: if model_class in get_values(_SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Tuple = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=_SCREAMING_SNAKE_CASE ) return inputs_dict def __lowerCamelCase ( self ): __lowerCAmelCase : Optional[Any] = MobileBertModelTester(self ) __lowerCAmelCase : str = ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , hidden_size=37 ) def __lowerCamelCase ( self ): self.config_tester.run_common_tests() def __lowerCamelCase ( self ): __lowerCAmelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_model(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_masked_lm(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_multiple_choice(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_next_sequence_prediction(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_pretraining(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_question_answering(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_sequence_classification(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_token_classification(*_SCREAMING_SNAKE_CASE ) def __lowerCAmelCase (_UpperCamelCase ): return torch.tensor( _UpperCamelCase , dtype=torch.long , device=_UpperCamelCase , ) lowerCamelCase__ = 1E-3 @require_torch @require_sentencepiece @require_tokenizers class A__ ( unittest.TestCase): @slow def __lowerCamelCase ( self ): __lowerCAmelCase : Union[str, Any] = MobileBertModel.from_pretrained('google/mobilebert-uncased' ).to(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = _long_tensor([[1_01, 71_10, 10_05, 10_56, 20_23, 1_13_33, 1_74_13, 10_29, 1_02]] ) with torch.no_grad(): __lowerCAmelCase : int = model(_SCREAMING_SNAKE_CASE )[0] __lowerCAmelCase : Dict = torch.Size((1, 9, 5_12) ) self.assertEqual(output.shape , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = torch.tensor( [ [ [-2.4_73_65_26E07, 8.2_69_16_56E04, 1.6_52_18_38E05], [-5.7_54_17_04E-01, 3.9_05_60_22E00, 4.4_01_15_07E00], [2.6_04_73_59E00, 1.5_67_76_52E00, -1.7_32_41_88E-01], ] ] , device=_SCREAMING_SNAKE_CASE , ) # MobileBERT results range from 10e0 to 10e8. Even a 0.0000001% difference with a value of 10e8 results in a # ~1 difference, it's therefore not a good idea to measure using addition. # Here, we instead divide the expected result with the result in order to obtain ~1. We then check that the # result is held between bounds: 1 - TOLERANCE < expected_result / result < 1 + TOLERANCE __lowerCAmelCase : Tuple = torch.all((expected_slice / output[..., :3, :3]) >= 1 - TOLERANCE ) __lowerCAmelCase : Union[str, Any] = torch.all((expected_slice / output[..., :3, :3]) <= 1 + TOLERANCE ) self.assertTrue(lower_bound and upper_bound )
86
0
"""simple docstring""" def UpperCAmelCase__ ( SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : int ): '''simple docstring''' while b: lowerCAmelCase , lowerCAmelCase = b, a % b return a def UpperCAmelCase__ ( SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : int ): '''simple docstring''' return a if b == 0 else euclidean_gcd_recursive(SCREAMING_SNAKE_CASE , a % b ) def UpperCAmelCase__ ( ): '''simple docstring''' print(F'euclidean_gcd(3, 5) = {euclidean_gcd(3 , 5 )}' ) print(F'euclidean_gcd(5, 3) = {euclidean_gcd(5 , 3 )}' ) print(F'euclidean_gcd(1, 3) = {euclidean_gcd(1 , 3 )}' ) print(F'euclidean_gcd(3, 6) = {euclidean_gcd(3 , 6 )}' ) print(F'euclidean_gcd(6, 3) = {euclidean_gcd(6 , 3 )}' ) print(F'euclidean_gcd_recursive(3, 5) = {euclidean_gcd_recursive(3 , 5 )}' ) print(F'euclidean_gcd_recursive(5, 3) = {euclidean_gcd_recursive(5 , 3 )}' ) print(F'euclidean_gcd_recursive(1, 3) = {euclidean_gcd_recursive(1 , 3 )}' ) print(F'euclidean_gcd_recursive(3, 6) = {euclidean_gcd_recursive(3 , 6 )}' ) print(F'euclidean_gcd_recursive(6, 3) = {euclidean_gcd_recursive(6 , 3 )}' ) if __name__ == "__main__": main()
46
"""simple docstring""" import re import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class A__ ( _lowerCamelCase): A_ : Any = ['image_processor', 'tokenizer'] A_ : Optional[Any] = 'AutoImageProcessor' A_ : str = 'AutoTokenizer' def __init__( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Union[str, Any] = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , _SCREAMING_SNAKE_CASE , ) __lowerCAmelCase : Any = kwargs.pop('feature_extractor' ) __lowerCAmelCase : str = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.' ) if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.' ) super().__init__(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Any = self.image_processor __lowerCAmelCase : Tuple = False def __call__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = kwargs.pop('images' , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Any = kwargs.pop('text' , _SCREAMING_SNAKE_CASE ) if len(_SCREAMING_SNAKE_CASE ) > 0: __lowerCAmelCase : Dict = args[0] __lowerCAmelCase : Union[str, Any] = args[1:] if images is None and text is None: raise ValueError('You need to specify either an `images` or `text` input to process.' ) if images is not None: __lowerCAmelCase : Union[str, Any] = self.image_processor(_SCREAMING_SNAKE_CASE , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) if text is not None: __lowerCAmelCase : Dict = self.tokenizer(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) if text is None: return inputs elif images is None: return encodings else: __lowerCAmelCase : Union[str, Any] = encodings['input_ids'] return inputs def __lowerCamelCase ( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ): return self.tokenizer.batch_decode(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ): return self.tokenizer.decode(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @contextmanager def __lowerCamelCase ( self ): 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 images inputs, or in a separate call.' ) __lowerCAmelCase : Any = True __lowerCAmelCase : Dict = self.tokenizer yield __lowerCAmelCase : Optional[int] = self.image_processor __lowerCAmelCase : Optional[Any] = False def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=None ): if added_vocab is None: __lowerCAmelCase : str = self.tokenizer.get_added_vocab() __lowerCAmelCase : List[Any] = {} while tokens: __lowerCAmelCase : int = re.search(R'<s_(.*?)>' , _SCREAMING_SNAKE_CASE , re.IGNORECASE ) if start_token is None: break __lowerCAmelCase : Union[str, Any] = start_token.group(1 ) __lowerCAmelCase : Tuple = re.search(Rf"</s_{key}>" , _SCREAMING_SNAKE_CASE , re.IGNORECASE ) __lowerCAmelCase : str = start_token.group() if end_token is None: __lowerCAmelCase : Optional[int] = tokens.replace(_SCREAMING_SNAKE_CASE , '' ) else: __lowerCAmelCase : Optional[Any] = end_token.group() __lowerCAmelCase : Tuple = re.escape(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Tuple = re.escape(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = re.search(f"{start_token_escaped}(.*?){end_token_escaped}" , _SCREAMING_SNAKE_CASE , re.IGNORECASE ) if content is not None: __lowerCAmelCase : List[str] = content.group(1 ).strip() if r"<s_" in content and r"</s_" in content: # non-leaf node __lowerCAmelCase : int = self.tokenajson(_SCREAMING_SNAKE_CASE , is_inner_value=_SCREAMING_SNAKE_CASE , added_vocab=_SCREAMING_SNAKE_CASE ) if value: if len(_SCREAMING_SNAKE_CASE ) == 1: __lowerCAmelCase : Tuple = value[0] __lowerCAmelCase : Tuple = value else: # leaf nodes __lowerCAmelCase : Any = [] for leaf in content.split(R'<sep/>' ): __lowerCAmelCase : List[Any] = leaf.strip() if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>": __lowerCAmelCase : Dict = leaf[1:-2] # for categorical special tokens output[key].append(_SCREAMING_SNAKE_CASE ) if len(output[key] ) == 1: __lowerCAmelCase : str = output[key][0] __lowerCAmelCase : Dict = tokens[tokens.find(_SCREAMING_SNAKE_CASE ) + len(_SCREAMING_SNAKE_CASE ) :].strip() if tokens[:6] == r"<sep/>": # non-leaf nodes return [output] + self.tokenajson(tokens[6:] , is_inner_value=_SCREAMING_SNAKE_CASE , added_vocab=_SCREAMING_SNAKE_CASE ) if len(_SCREAMING_SNAKE_CASE ): return [output] if is_inner_value else output else: return [] if is_inner_value else {"text_sequence": tokens} @property def __lowerCamelCase ( self ): warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , _SCREAMING_SNAKE_CASE , ) return self.image_processor_class @property def __lowerCamelCase ( self ): warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , _SCREAMING_SNAKE_CASE , ) return self.image_processor
86
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase : Optional[int] = { "configuration_roformer": ["ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "RoFormerConfig", "RoFormerOnnxConfig"], "tokenization_roformer": ["RoFormerTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : List[str] = ["RoFormerTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Optional[Any] = [ "ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "RoFormerForCausalLM", "RoFormerForMaskedLM", "RoFormerForMultipleChoice", "RoFormerForQuestionAnswering", "RoFormerForSequenceClassification", "RoFormerForTokenClassification", "RoFormerLayer", "RoFormerModel", "RoFormerPreTrainedModel", "load_tf_weights_in_roformer", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : str = [ "TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TFRoFormerForCausalLM", "TFRoFormerForMaskedLM", "TFRoFormerForMultipleChoice", "TFRoFormerForQuestionAnswering", "TFRoFormerForSequenceClassification", "TFRoFormerForTokenClassification", "TFRoFormerLayer", "TFRoFormerModel", "TFRoFormerPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Optional[Any] = [ "FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "FlaxRoFormerForMaskedLM", "FlaxRoFormerForMultipleChoice", "FlaxRoFormerForQuestionAnswering", "FlaxRoFormerForSequenceClassification", "FlaxRoFormerForTokenClassification", "FlaxRoFormerModel", "FlaxRoFormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_roformer import ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, RoFormerConfig, RoFormerOnnxConfig from .tokenization_roformer import RoFormerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roformer_fast import RoFormerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roformer import ( ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, RoFormerForCausalLM, RoFormerForMaskedLM, RoFormerForMultipleChoice, RoFormerForQuestionAnswering, RoFormerForSequenceClassification, RoFormerForTokenClassification, RoFormerLayer, RoFormerModel, RoFormerPreTrainedModel, load_tf_weights_in_roformer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roformer import ( TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerLayer, TFRoFormerModel, TFRoFormerPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roformer import ( FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, FlaxRoFormerPreTrainedModel, ) else: import sys lowerCamelCase : List[str] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
47
"""simple docstring""" def __lowerCAmelCase (_UpperCamelCase ): __lowerCAmelCase : Tuple = 0 while num > 0: digit_sum += num % 10 num //= 10 return digit_sum def __lowerCAmelCase (_UpperCamelCase = 100 ): __lowerCAmelCase : Optional[int] = 1 __lowerCAmelCase : Optional[Any] = 2 for i in range(2 , max_n + 1 ): __lowerCAmelCase : Any = pre_numerator __lowerCAmelCase : Union[str, Any] = 2 * i // 3 if i % 3 == 0 else 1 __lowerCAmelCase : int = cur_numerator __lowerCAmelCase : Dict = e_cont * pre_numerator + temp return sum_digits(_UpperCamelCase ) if __name__ == "__main__": print(f'{solution() = }')
86
0
def A ( _SCREAMING_SNAKE_CASE ) -> int: if a < 0: raise ValueError("Input value must be a positive integer" ) elif isinstance(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ): raise TypeError("Input value must be a 'int' type" ) return bin(_SCREAMING_SNAKE_CASE ).count("1" ) if __name__ == "__main__": import doctest doctest.testmod()
48
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { """microsoft/markuplm-base""": """https://huggingface.co/microsoft/markuplm-base/resolve/main/config.json""", """microsoft/markuplm-large""": """https://huggingface.co/microsoft/markuplm-large/resolve/main/config.json""", } class A__ ( _lowerCamelCase): A_ : List[Any] = 'markuplm' def __init__( self , _SCREAMING_SNAKE_CASE=3_05_22 , _SCREAMING_SNAKE_CASE=7_68 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=30_72 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=5_12 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE=1E-12 , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=2_56 , _SCREAMING_SNAKE_CASE=10_24 , _SCREAMING_SNAKE_CASE=2_16 , _SCREAMING_SNAKE_CASE=10_01 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=50 , _SCREAMING_SNAKE_CASE="absolute" , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE , ): super().__init__( pad_token_id=_SCREAMING_SNAKE_CASE , bos_token_id=_SCREAMING_SNAKE_CASE , eos_token_id=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) __lowerCAmelCase : Union[str, Any] = vocab_size __lowerCAmelCase : Any = hidden_size __lowerCAmelCase : List[Any] = num_hidden_layers __lowerCAmelCase : Tuple = num_attention_heads __lowerCAmelCase : Union[str, Any] = hidden_act __lowerCAmelCase : List[Any] = intermediate_size __lowerCAmelCase : List[str] = hidden_dropout_prob __lowerCAmelCase : List[str] = attention_probs_dropout_prob __lowerCAmelCase : Optional[int] = max_position_embeddings __lowerCAmelCase : int = type_vocab_size __lowerCAmelCase : Tuple = initializer_range __lowerCAmelCase : int = layer_norm_eps __lowerCAmelCase : List[str] = position_embedding_type __lowerCAmelCase : List[Any] = use_cache __lowerCAmelCase : Optional[Any] = classifier_dropout # additional properties __lowerCAmelCase : Optional[int] = max_depth __lowerCAmelCase : List[str] = max_xpath_tag_unit_embeddings __lowerCAmelCase : Optional[Any] = max_xpath_subs_unit_embeddings __lowerCAmelCase : Any = tag_pad_id __lowerCAmelCase : Union[str, Any] = subs_pad_id __lowerCAmelCase : int = xpath_unit_hidden_size
86
0
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool class _A ( __UpperCAmelCase ): UpperCamelCase__ : Union[str, Any] = '''philschmid/bart-large-cnn-samsum''' UpperCamelCase__ : Optional[int] = ( '''This is a tool that summarizes an English text. It takes an input `text` containing the text to summarize, ''' '''and returns a summary of the text.''' ) UpperCamelCase__ : Optional[int] = '''summarizer''' UpperCamelCase__ : Optional[int] = AutoTokenizer UpperCamelCase__ : Optional[Any] = AutoModelForSeqaSeqLM UpperCamelCase__ : Optional[Any] = ['''text'''] UpperCamelCase__ : List[Any] = ['''text'''] def _lowerCamelCase ( self : str , __SCREAMING_SNAKE_CASE : List[Any]): '''simple docstring''' return self.pre_processor(__SCREAMING_SNAKE_CASE , return_tensors='''pt''' , truncation=__SCREAMING_SNAKE_CASE) def _lowerCamelCase ( self : str , __SCREAMING_SNAKE_CASE : str): '''simple docstring''' return self.model.generate(**__SCREAMING_SNAKE_CASE)[0] def _lowerCamelCase ( self : Tuple , __SCREAMING_SNAKE_CASE : Tuple): '''simple docstring''' return self.pre_processor.decode(__SCREAMING_SNAKE_CASE , skip_special_tokens=__SCREAMING_SNAKE_CASE , clean_up_tokenization_spaces=__SCREAMING_SNAKE_CASE)
49
"""simple docstring""" import argparse import torch # Step 1. clone https://github.com/microsoft/unilm # Step 2. git checkout to https://github.com/microsoft/unilm/commit/b94ec76c36f02fb2b0bf0dcb0b8554a2185173cd # Step 3. cd unilm # Step 4. ln -s $(realpath wavlm/modules.py) ./ # create simlink # import classes from unilm.wavlm.WavLM import WavLM as WavLMOrig from unilm.wavlm.WavLM import WavLMConfig as WavLMConfigOrig from transformers import WavLMConfig, WavLMModel, logging logging.set_verbosity_info() lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { """post_extract_proj""": """feature_projection.projection""", """encoder.pos_conv.0""": """encoder.pos_conv_embed.conv""", """self_attn.k_proj""": """encoder.layers.*.attention.k_proj""", """self_attn.v_proj""": """encoder.layers.*.attention.v_proj""", """self_attn.q_proj""": """encoder.layers.*.attention.q_proj""", """self_attn.out_proj""": """encoder.layers.*.attention.out_proj""", """self_attn.grep_linear""": """encoder.layers.*.attention.gru_rel_pos_linear""", """self_attn.relative_attention_bias""": """encoder.layers.*.attention.rel_attn_embed""", """self_attn.grep_a""": """encoder.layers.*.attention.gru_rel_pos_const""", """self_attn_layer_norm""": """encoder.layers.*.layer_norm""", """fc1""": """encoder.layers.*.feed_forward.intermediate_dense""", """fc2""": """encoder.layers.*.feed_forward.output_dense""", """final_layer_norm""": """encoder.layers.*.final_layer_norm""", """encoder.layer_norm""": """encoder.layer_norm""", """w2v_model.layer_norm""": """feature_projection.layer_norm""", """quantizer.weight_proj""": """quantizer.weight_proj""", """quantizer.vars""": """quantizer.codevectors""", """project_q""": """project_q""", """final_proj""": """project_hid""", """w2v_encoder.proj""": """ctc_proj""", """mask_emb""": """masked_spec_embed""", } lowerCamelCase__ = [ """ctc_proj""", """quantizer.weight_proj""", """quantizer.codevectors""", """project_q""", """project_hid""", ] def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): for attribute in key.split('.' ): __lowerCAmelCase : str = getattr(_UpperCamelCase , _UpperCamelCase ) if weight_type is not None: __lowerCAmelCase : Tuple = getattr(_UpperCamelCase , _UpperCamelCase ).shape else: __lowerCAmelCase : Dict = hf_pointer.shape assert hf_shape == value.shape, ( F"Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be" F" {value.shape} for {full_name}" ) if weight_type == "weight": __lowerCAmelCase : Union[str, Any] = value elif weight_type == "weight_g": __lowerCAmelCase : List[Any] = value elif weight_type == "weight_v": __lowerCAmelCase : Any = value elif weight_type == "bias": __lowerCAmelCase : List[str] = value else: __lowerCAmelCase : List[Any] = value logger.info(F"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}." ) def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase ): __lowerCAmelCase : Any = [] __lowerCAmelCase : Optional[int] = fairseq_model.state_dict() __lowerCAmelCase : Union[str, Any] = hf_model.feature_extractor for name, value in fairseq_dict.items(): __lowerCAmelCase : Union[str, Any] = False if "conv_layers" in name: load_conv_layer( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , hf_model.config.feat_extract_norm == 'group' , ) __lowerCAmelCase : str = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]: __lowerCAmelCase : int = True if "*" in mapped_key: __lowerCAmelCase : List[str] = name.split(_UpperCamelCase )[0].split('.' )[-2] __lowerCAmelCase : Optional[Any] = mapped_key.replace('*' , _UpperCamelCase ) if "weight_g" in name: __lowerCAmelCase : Union[str, Any] = 'weight_g' elif "weight_v" in name: __lowerCAmelCase : int = 'weight_v' elif "bias" in name and "relative_attention_bias" not in name: __lowerCAmelCase : Optional[Any] = 'bias' elif "weight" in name: # TODO: don't match quantizer.weight_proj __lowerCAmelCase : List[str] = 'weight' else: __lowerCAmelCase : Optional[Any] = None set_recursively(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) continue if not is_used: unused_weights.append(_UpperCamelCase ) logger.warning(F"Unused weights: {unused_weights}" ) def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): __lowerCAmelCase : List[Any] = full_name.split('conv_layers.' )[-1] __lowerCAmelCase : Any = name.split('.' ) __lowerCAmelCase : List[Any] = int(items[0] ) __lowerCAmelCase : Tuple = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( F"{full_name} has size {value.shape}, but" F" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found." ) __lowerCAmelCase : Tuple = value logger.info(F"Feat extract conv layer {layer_id} was initialized from {full_name}." ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( F"{full_name} has size {value.shape}, but" F" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found." ) __lowerCAmelCase : int = value logger.info(F"Feat extract conv layer {layer_id} was initialized from {full_name}." ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( F"{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was" " found." ) __lowerCAmelCase : Optional[Any] = value logger.info(F"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( F"{full_name} has size {value.shape}, but" F" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found." ) __lowerCAmelCase : Any = value logger.info(F"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) else: unused_weights.append(_UpperCamelCase ) @torch.no_grad() def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase=None ): # load the pre-trained checkpoints __lowerCAmelCase : Any = torch.load(_UpperCamelCase ) __lowerCAmelCase : List[str] = WavLMConfigOrig(checkpoint['cfg'] ) __lowerCAmelCase : Optional[Any] = WavLMOrig(_UpperCamelCase ) model.load_state_dict(checkpoint['model'] ) model.eval() if config_path is not None: __lowerCAmelCase : Dict = WavLMConfig.from_pretrained(_UpperCamelCase ) else: __lowerCAmelCase : List[str] = WavLMConfig() __lowerCAmelCase : List[str] = WavLMModel(_UpperCamelCase ) recursively_load_weights(_UpperCamelCase , _UpperCamelCase ) hf_wavlm.save_pretrained(_UpperCamelCase ) if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to fairseq checkpoint""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") lowerCamelCase__ = parser.parse_args() convert_wavlm_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
86
0
from scipy.stats import pearsonr import datasets _UpperCAmelCase : str = """ Pearson correlation coefficient and p-value for testing non-correlation. The Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases. The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. """ _UpperCAmelCase : Union[str, Any] = """ Args: predictions (`list` of `int`): Predicted class labels, as returned by a model. references (`list` of `int`): Ground truth labels. return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`. Returns: pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation. p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities. Examples: Example 1-A simple example using only predictions and references. >>> pearsonr_metric = datasets.load_metric(\"pearsonr\") >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5]) >>> print(round(results['pearsonr'], 2)) -0.74 Example 2-The same as Example 1, but that also returns the `p-value`. >>> pearsonr_metric = datasets.load_metric(\"pearsonr\") >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True) >>> print(sorted(list(results.keys()))) ['p-value', 'pearsonr'] >>> print(round(results['pearsonr'], 2)) -0.74 >>> print(round(results['p-value'], 2)) 0.15 """ _UpperCAmelCase : List[Any] = """ @article{2020SciPy-NMeth, author = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and Haberland, Matt and Reddy, Tyler and Cournapeau, David and Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and Bright, Jonathan and {van der Walt}, St{\'e}fan J. and Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and Kern, Robert and Larson, Eric and Carey, C J and Polat, Ilhan and Feng, Yu and Moore, Eric W. and {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and Harris, Charles R. and Archibald, Anne M. and Ribeiro, Antonio H. and Pedregosa, Fabian and {van Mulbregt}, Paul and {SciPy 1.0 Contributors}}, title = {{{SciPy} 1.0: Fundamental Algorithms for Scientific Computing in Python}}, journal = {Nature Methods}, year = {2020}, volume = {17}, pages = {261--272}, adsurl = {https://rdcu.be/b08Wh}, doi = {10.1038/s41592-019-0686-2}, } """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION ) class lowerCAmelCase ( datasets.Metric ): def A_ ( self : Any ) -> List[Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('float' ), 'references': datasets.Value('float' ), } ) , reference_urls=['https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html'] , ) def A_ ( self : int , UpperCAmelCase : str , UpperCAmelCase : List[Any] , UpperCAmelCase : Any=False ) -> str: if return_pvalue: lowerCamelCase__ : int = pearsonr(UpperCAmelCase , UpperCAmelCase ) return {"pearsonr": results[0], "p-value": results[1]} else: return {"pearsonr": float(pearsonr(UpperCAmelCase , UpperCAmelCase )[0] )}
50
"""simple docstring""" import os import pytest from attr import dataclass lowerCamelCase__ = """us-east-1""" # defaults region @dataclass class A__ : A_ : str A_ : Union[str, Any] = 'arn:aws:iam::558105141721:role/sagemaker_execution_role' A_ : Optional[int] = { 'task_name': 'mnli', 'per_device_train_batch_size': 1_6, 'per_device_eval_batch_size': 1_6, 'do_train': True, 'do_eval': True, 'do_predict': True, 'output_dir': '/opt/ml/model', 'overwrite_output_dir': True, 'max_steps': 5_0_0, 'save_steps': 5_5_0_0, } A_ : List[Any] = {**hyperparameters, 'max_steps': 1_0_0_0} @property def __lowerCamelCase ( self ): if self.framework == "pytorch": return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"eval_accuracy.*=\D*(.*?)$"}, {"Name": "eval_loss", "Regex": r"eval_loss.*=\D*(.*?)$"}, ] else: return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"loss.*=\D*(.*?)]?$"}, {"Name": "eval_loss", "Regex": r"sparse_categorical_accuracy.*=\D*(.*?)]?$"}, ] @property def __lowerCamelCase ( self ): return f"{self.framework}-transfromers-test" @property def __lowerCamelCase ( self ): return f"./tests/sagemaker/scripts/{self.framework}" @property def __lowerCamelCase ( self ): if self.framework == "pytorch": return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-pytorch-training:1.7.1-transformers4.6.1-gpu-py36-cu110-ubuntu18.04" else: return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-tensorflow-training:2.4.1-transformers4.6.1-gpu-py37-cu110-ubuntu18.04" @pytest.fixture(scope='class' ) def __lowerCAmelCase (_UpperCamelCase ): __lowerCAmelCase : str = SageMakerTestEnvironment(framework=request.cls.framework )
86
0
import unittest import torch from diffusers import VQModel from diffusers.utils import floats_tensor, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class __snake_case ( a , a , unittest.TestCase ): UpperCAmelCase__ : List[str] = VQModel UpperCAmelCase__ : Optional[Any] = '''sample''' @property def lowerCamelCase ( self : Optional[int] , _snake_case : List[str]=(32, 32)): """simple docstring""" UpperCAmelCase_ = 4 UpperCAmelCase_ = 3 UpperCAmelCase_ = floats_tensor((batch_size, num_channels) + sizes).to(_snake_case) return {"sample": image} @property def lowerCamelCase ( self : Optional[int]): """simple docstring""" return (3, 32, 32) @property def lowerCamelCase ( self : Dict): """simple docstring""" return (3, 32, 32) def lowerCamelCase ( self : Optional[Any]): """simple docstring""" UpperCAmelCase_ = { '''block_out_channels''': [32, 64], '''in_channels''': 3, '''out_channels''': 3, '''down_block_types''': ['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''], '''up_block_types''': ['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''], '''latent_channels''': 3, } UpperCAmelCase_ = self.dummy_input return init_dict, inputs_dict def lowerCamelCase ( self : List[str]): """simple docstring""" pass def lowerCamelCase ( self : Optional[int]): """simple docstring""" pass def lowerCamelCase ( self : str): """simple docstring""" UpperCAmelCase_ , UpperCAmelCase_ = VQModel.from_pretrained('''fusing/vqgan-dummy''' , output_loading_info=_snake_case) self.assertIsNotNone(_snake_case) self.assertEqual(len(loading_info['''missing_keys''']) , 0) model.to(_snake_case) UpperCAmelCase_ = model(**self.dummy_input) assert image is not None, "Make sure output is not None" def lowerCamelCase ( self : Optional[int]): """simple docstring""" UpperCAmelCase_ = VQModel.from_pretrained('''fusing/vqgan-dummy''') model.to(_snake_case).eval() torch.manual_seed(0) if torch.cuda.is_available(): torch.cuda.manual_seed_all(0) UpperCAmelCase_ = torch.randn(1 , model.config.in_channels , model.config.sample_size , model.config.sample_size) UpperCAmelCase_ = image.to(_snake_case) with torch.no_grad(): UpperCAmelCase_ = model(_snake_case).sample UpperCAmelCase_ = output[0, -1, -3:, -3:].flatten().cpu() # fmt: off UpperCAmelCase_ = torch.tensor([-0.0_1_5_3, -0.4_0_4_4, -0.1_8_8_0, -0.5_1_6_1, -0.2_4_1_8, -0.4_0_7_2, -0.1_6_1_2, -0.0_6_3_3, -0.0_1_4_3]) # fmt: on self.assertTrue(torch.allclose(_snake_case , _snake_case , atol=1e-3))
51
"""simple docstring""" from __future__ import annotations lowerCamelCase__ = list[tuple[int, int]] lowerCamelCase__ = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] lowerCamelCase__ = ([-1, 0], [0, -1], [1, 0], [0, 1]) # up, left, down, right class A__ : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , ): __lowerCAmelCase : int = pos_x __lowerCAmelCase : Optional[Any] = pos_y __lowerCAmelCase : Optional[int] = (pos_y, pos_x) __lowerCAmelCase : Union[str, Any] = goal_x __lowerCAmelCase : Any = goal_y __lowerCAmelCase : Optional[Any] = g_cost __lowerCAmelCase : Any = parent __lowerCAmelCase : Union[str, Any] = self.calculate_heuristic() def __lowerCamelCase ( self ): __lowerCAmelCase : str = abs(self.pos_x - self.goal_x ) __lowerCAmelCase : str = abs(self.pos_y - self.goal_y ) return dx + dy def __lt__( self , _SCREAMING_SNAKE_CASE ): return self.f_cost < other.f_cost class A__ : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Optional[int] = Node(start[1] , start[0] , goal[1] , goal[0] , 0 , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Any = Node(goal[1] , goal[0] , goal[1] , goal[0] , 9_99_99 , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Tuple = [self.start] __lowerCAmelCase : list[Node] = [] __lowerCAmelCase : str = False def __lowerCamelCase ( self ): while self.open_nodes: # Open Nodes are sorted using __lt__ self.open_nodes.sort() __lowerCAmelCase : Optional[int] = self.open_nodes.pop(0 ) if current_node.pos == self.target.pos: __lowerCAmelCase : Union[str, Any] = True return self.retrace_path(_SCREAMING_SNAKE_CASE ) self.closed_nodes.append(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = self.get_successors(_SCREAMING_SNAKE_CASE ) for child_node in successors: if child_node in self.closed_nodes: continue if child_node not in self.open_nodes: self.open_nodes.append(_SCREAMING_SNAKE_CASE ) else: # retrieve the best current path __lowerCAmelCase : Optional[Any] = self.open_nodes.pop(self.open_nodes.index(_SCREAMING_SNAKE_CASE ) ) if child_node.g_cost < better_node.g_cost: self.open_nodes.append(_SCREAMING_SNAKE_CASE ) else: self.open_nodes.append(_SCREAMING_SNAKE_CASE ) if not self.reached: return [self.start.pos] return None def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Dict = [] for action in delta: __lowerCAmelCase : Optional[int] = parent.pos_x + action[1] __lowerCAmelCase : Union[str, Any] = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(_SCREAMING_SNAKE_CASE ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , self.target.pos_y , self.target.pos_x , parent.g_cost + 1 , _SCREAMING_SNAKE_CASE , ) ) return successors def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Union[str, Any] = node __lowerCAmelCase : Optional[int] = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) __lowerCAmelCase : int = current_node.parent path.reverse() return path if __name__ == "__main__": lowerCamelCase__ = (0, 0) lowerCamelCase__ = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) print("""------""") lowerCamelCase__ = GreedyBestFirst(init, goal) lowerCamelCase__ = greedy_bf.search() if path: for pos_x, pos_y in path: lowerCamelCase__ = 2 for elem in grid: print(elem)
86
0
import pickle import numpy as np from matplotlib import pyplot as plt class A__ : def __init__( self , A_ , A_ , A_ , A_ , A_ , A_=0.2 , A_=0.2 ): '''simple docstring''' UpperCamelCase : int = bp_numa UpperCamelCase : int = bp_numa UpperCamelCase : List[Any] = bp_numa UpperCamelCase : Optional[int] = conva_get[:2] UpperCamelCase : Optional[Any] = conva_get[2] UpperCamelCase : Dict = size_pa UpperCamelCase : Union[str, Any] = rate_w UpperCamelCase : Dict = rate_t UpperCamelCase : Union[str, Any] = [ np.mat(-1 * np.random.rand(self.conva[0] , self.conva[0] ) + 0.5 ) for i in range(self.conva[1] ) ] UpperCamelCase : Any = np.mat(-1 * np.random.rand(self.num_bpa , self.num_bpa ) + 0.5 ) UpperCamelCase : List[Any] = np.mat(-1 * np.random.rand(self.num_bpa , self.num_bpa ) + 0.5 ) UpperCamelCase : Optional[Any] = -2 * np.random.rand(self.conva[1] ) + 1 UpperCamelCase : Any = -2 * np.random.rand(self.num_bpa ) + 1 UpperCamelCase : int = -2 * np.random.rand(self.num_bpa ) + 1 def __UpperCamelCase( self , A_ ): '''simple docstring''' UpperCamelCase : Optional[int] = { "num_bp1": self.num_bpa, "num_bp2": self.num_bpa, "num_bp3": self.num_bpa, "conv1": self.conva, "step_conv1": self.step_conva, "size_pooling1": self.size_poolinga, "rate_weight": self.rate_weight, "rate_thre": self.rate_thre, "w_conv1": self.w_conva, "wkj": self.wkj, "vji": self.vji, "thre_conv1": self.thre_conva, "thre_bp2": self.thre_bpa, "thre_bp3": self.thre_bpa, } with open(A_ , "wb" ) as f: pickle.dump(A_ , A_ ) print(F"""Model saved: {save_path}""" ) @classmethod def __UpperCamelCase( cls , A_ ): '''simple docstring''' with open(A_ , "rb" ) as f: UpperCamelCase : Optional[Any] = pickle.load(A_ ) # noqa: S301 UpperCamelCase : List[Any] = model_dic.get("conv1" ) conv_get.append(model_dic.get("step_conv1" ) ) UpperCamelCase : Union[str, Any] = model_dic.get("size_pooling1" ) UpperCamelCase : List[Any] = model_dic.get("num_bp1" ) UpperCamelCase : Dict = model_dic.get("num_bp2" ) UpperCamelCase : Dict = model_dic.get("num_bp3" ) UpperCamelCase : Dict = model_dic.get("rate_weight" ) UpperCamelCase : str = model_dic.get("rate_thre" ) # create model instance UpperCamelCase : Any = CNN(A_ , A_ , A_ , A_ , A_ , A_ , A_ ) # modify model parameter UpperCamelCase : str = model_dic.get("w_conv1" ) UpperCamelCase : Optional[Any] = model_dic.get("wkj" ) UpperCamelCase : int = model_dic.get("vji" ) UpperCamelCase : Any = model_dic.get("thre_conv1" ) UpperCamelCase : Optional[int] = model_dic.get("thre_bp2" ) UpperCamelCase : Union[str, Any] = model_dic.get("thre_bp3" ) return conv_ins def __UpperCamelCase( self , A_ ): '''simple docstring''' return 1 / (1 + np.exp(-1 * x )) def __UpperCamelCase( self , A_ ): '''simple docstring''' return round(A_ , 3 ) def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ ): '''simple docstring''' UpperCamelCase : str = convs[0] UpperCamelCase : Optional[Any] = convs[1] UpperCamelCase : Optional[Any] = np.shape(A_ )[0] # get the data slice of original image data, data_focus UpperCamelCase : List[str] = [] for i_focus in range(0 , size_data - size_conv + 1 , A_ ): for j_focus in range(0 , size_data - size_conv + 1 , A_ ): UpperCamelCase : Union[str, Any] = data[ i_focus : i_focus + size_conv, j_focus : j_focus + size_conv ] data_focus.append(A_ ) # calculate the feature map of every single kernel, and saved as list of matrix UpperCamelCase : int = [] UpperCamelCase : Optional[Any] = int((size_data - size_conv) / conv_step + 1 ) for i_map in range(A_ ): UpperCamelCase : str = [] for i_focus in range(len(A_ ) ): UpperCamelCase : List[Any] = ( np.sum(np.multiply(data_focus[i_focus] , w_convs[i_map] ) ) - thre_convs[i_map] ) featuremap.append(self.sig(A_ ) ) UpperCamelCase : Optional[int] = np.asmatrix(A_ ).reshape( A_ , A_ ) data_featuremap.append(A_ ) # expanding the data slice to One dimenssion UpperCamelCase : List[Any] = [] for each_focus in data_focus: focusa_list.extend(self.Expand_Mat(A_ ) ) UpperCamelCase : Tuple = np.asarray(A_ ) return focus_list, data_featuremap def __UpperCamelCase( self , A_ , A_ , A_="average_pool" ): '''simple docstring''' UpperCamelCase : Any = len(featuremaps[0] ) UpperCamelCase : str = int(size_map / size_pooling ) UpperCamelCase : Optional[int] = [] for i_map in range(len(A_ ) ): UpperCamelCase : Tuple = featuremaps[i_map] UpperCamelCase : Any = [] for i_focus in range(0 , A_ , A_ ): for j_focus in range(0 , A_ , A_ ): UpperCamelCase : int = feature_map[ i_focus : i_focus + size_pooling, j_focus : j_focus + size_pooling, ] if pooling_type == "average_pool": # average pooling map_pooled.append(np.average(A_ ) ) elif pooling_type == "max_pooling": # max pooling map_pooled.append(np.max(A_ ) ) UpperCamelCase : Optional[Any] = np.asmatrix(A_ ).reshape(A_ , A_ ) featuremap_pooled.append(A_ ) return featuremap_pooled def __UpperCamelCase( self , A_ ): '''simple docstring''' UpperCamelCase : List[Any] = [] for i in range(len(A_ ) ): UpperCamelCase : List[Any] = np.shape(data[i] ) UpperCamelCase : str = data[i].reshape(1 , shapes[0] * shapes[1] ) UpperCamelCase : Optional[int] = data_listed.getA().tolist()[0] data_expanded.extend(A_ ) UpperCamelCase : Any = np.asarray(A_ ) return data_expanded def __UpperCamelCase( self , A_ ): '''simple docstring''' UpperCamelCase : List[Any] = np.asarray(A_ ) UpperCamelCase : List[Any] = np.shape(A_ ) UpperCamelCase : Any = data_mat.reshape(1 , shapes[0] * shapes[1] ) return data_expanded def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ ): '''simple docstring''' UpperCamelCase : int = [] UpperCamelCase : Optional[int] = 0 for i_map in range(A_ ): UpperCamelCase : int = np.ones((size_map, size_map) ) for i in range(0 , A_ , A_ ): for j in range(0 , A_ , A_ ): UpperCamelCase : str = pd_pool[ i_pool ] UpperCamelCase : str = i_pool + 1 UpperCamelCase : str = np.multiply( A_ , np.multiply(out_map[i_map] , (1 - out_map[i_map]) ) ) pd_all.append(A_ ) return pd_all def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ , A_=bool ): '''simple docstring''' print("----------------------Start Training-------------------------" ) print((" - - Shape: Train_Data ", np.shape(A_ )) ) print((" - - Shape: Teach_Data ", np.shape(A_ )) ) UpperCamelCase : List[str] = 0 UpperCamelCase : Union[str, Any] = [] UpperCamelCase : int = 1_0000 while rp < n_repeat and mse >= error_accuracy: UpperCamelCase : Tuple = 0 print(F"""-------------Learning Time {rp}--------------""" ) for p in range(len(A_ ) ): # print('------------Learning Image: %d--------------'%p) UpperCamelCase : Any = np.asmatrix(datas_train[p] ) UpperCamelCase : List[str] = np.asarray(datas_teach[p] ) UpperCamelCase , UpperCamelCase : Dict = self.convolute( A_ , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , ) UpperCamelCase : Tuple = self.pooling(A_ , self.size_poolinga ) UpperCamelCase : int = np.shape(A_ ) UpperCamelCase : List[str] = self._expand(A_ ) UpperCamelCase : Optional[int] = data_bp_input UpperCamelCase : str = np.dot(A_ , self.vji.T ) - self.thre_bpa UpperCamelCase : Optional[int] = self.sig(A_ ) UpperCamelCase : List[Any] = np.dot(A_ , self.wkj.T ) - self.thre_bpa UpperCamelCase : Dict = self.sig(A_ ) # --------------Model Leaning ------------------------ # calculate error and gradient--------------- UpperCamelCase : List[Any] = np.multiply( (data_teach - bp_outa) , np.multiply(A_ , (1 - bp_outa) ) ) UpperCamelCase : str = np.multiply( np.dot(A_ , self.wkj ) , np.multiply(A_ , (1 - bp_outa) ) ) UpperCamelCase : Any = np.dot(A_ , self.vji ) UpperCamelCase : Dict = pd_i_all / (self.size_poolinga * self.size_poolinga) UpperCamelCase : List[Any] = pd_conva_pooled.T.getA().tolist() UpperCamelCase : List[Any] = self._calculate_gradient_from_pool( A_ , A_ , shape_featuremapa[0] , shape_featuremapa[1] , self.size_poolinga , ) # weight and threshold learning process--------- # convolution layer for k_conv in range(self.conva[1] ): UpperCamelCase : List[Any] = self._expand_mat(pd_conva_all[k_conv] ) UpperCamelCase : List[Any] = self.rate_weight * np.dot(A_ , A_ ) UpperCamelCase : str = self.w_conva[k_conv] + delta_w.reshape( (self.conva[0], self.conva[0]) ) UpperCamelCase : Dict = ( self.thre_conva[k_conv] - np.sum(pd_conva_all[k_conv] ) * self.rate_thre ) # all connected layer UpperCamelCase : Optional[Any] = self.wkj + pd_k_all.T * bp_outa * self.rate_weight UpperCamelCase : List[Any] = self.vji + pd_j_all.T * bp_outa * self.rate_weight UpperCamelCase : Optional[Any] = self.thre_bpa - pd_k_all * self.rate_thre UpperCamelCase : List[str] = self.thre_bpa - pd_j_all * self.rate_thre # calculate the sum error of all single image UpperCamelCase : List[Any] = np.sum(abs(data_teach - bp_outa ) ) error_count += errors # print(' ----Teach ',data_teach) # print(' ----BP_output ',bp_out3) UpperCamelCase : Any = rp + 1 UpperCamelCase : Union[str, Any] = error_count / patterns all_mse.append(A_ ) def draw_error(): UpperCamelCase : Tuple = [error_accuracy for i in range(int(n_repeat * 1.2 ) )] plt.plot(A_ , "+-" ) plt.plot(A_ , "r--" ) plt.xlabel("Learning Times" ) plt.ylabel("All_mse" ) plt.grid(A_ , alpha=0.5 ) plt.show() print("------------------Training Complished---------------------" ) print((" - - Training epoch: ", rp, F""" - - Mse: {mse:.6f}""") ) if draw_e: draw_error() return mse def __UpperCamelCase( self , A_ ): '''simple docstring''' UpperCamelCase : Optional[Any] = [] print("-------------------Start Testing-------------------------" ) print((" - - Shape: Test_Data ", np.shape(A_ )) ) for p in range(len(A_ ) ): UpperCamelCase : int = np.asmatrix(datas_test[p] ) UpperCamelCase , UpperCamelCase : Any = self.convolute( A_ , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , ) UpperCamelCase : List[str] = self.pooling(A_ , self.size_poolinga ) UpperCamelCase : Dict = self._expand(A_ ) UpperCamelCase : List[Any] = data_bp_input UpperCamelCase : Any = bp_outa * self.vji.T - self.thre_bpa UpperCamelCase : List[Any] = self.sig(A_ ) UpperCamelCase : int = bp_outa * self.wkj.T - self.thre_bpa UpperCamelCase : Optional[int] = self.sig(A_ ) produce_out.extend(bp_outa.getA().tolist() ) UpperCamelCase : List[str] = [list(map(self.do_round , A_ ) ) for each in produce_out] return np.asarray(A_ ) def __UpperCamelCase( self , A_ ): '''simple docstring''' UpperCamelCase : Union[str, Any] = np.asmatrix(A_ ) UpperCamelCase , UpperCamelCase : List[Any] = self.convolute( A_ , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , ) UpperCamelCase : str = self.pooling(A_ , self.size_poolinga ) return data_conveda, data_pooleda if __name__ == "__main__": pass
52
"""simple docstring""" def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): return round(float(moles / volume ) * nfactor ) def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): return round(float((moles * 0.0821 * temperature) / (volume) ) ) def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): return round(float((moles * 0.0821 * temperature) / (pressure) ) ) def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): return round(float((pressure * volume) / (0.0821 * moles) ) ) if __name__ == "__main__": import doctest doctest.testmod()
86
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import _LazyModule a__ : List[str] ={'''tokenization_wav2vec2_phoneme''': ['''Wav2Vec2PhonemeCTCTokenizer''']} if TYPE_CHECKING: from .tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizer else: import sys a__ : Dict =_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
53
"""simple docstring""" import enum import warnings from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING from ..utils import add_end_docstrings, is_tf_available from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf class A__ ( enum.Enum): A_ : List[Any] = 0 A_ : Dict = 1 A_ : Union[str, Any] = 2 @add_end_docstrings(_lowerCamelCase) class A__ ( _lowerCamelCase): A_ : str = '\n In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The\n voice of Nicholas\'s young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western\n Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision\n and denounces one of the men as a horse thief. Although his father initially slaps him for making such an\n accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of\n the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop,\n begging for his blessing. <eod> </s> <eos>\n ' def __init__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ): super().__init__(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) self.check_model_type( TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == 'tf' else MODEL_FOR_CAUSAL_LM_MAPPING ) if "prefix" not in self._preprocess_params: # This is very specific. The logic is quite complex and needs to be done # as a "default". # It also defines both some preprocess_kwargs and generate_kwargs # which is why we cannot put them in their respective methods. __lowerCAmelCase : Any = None if self.model.config.prefix is not None: __lowerCAmelCase : str = self.model.config.prefix if prefix is None and self.model.__class__.__name__ in [ "XLNetLMHeadModel", "TransfoXLLMHeadModel", "TFXLNetLMHeadModel", "TFTransfoXLLMHeadModel", ]: # For XLNet and TransformerXL we add an article to the prompt to give more state to the model. __lowerCAmelCase : Tuple = self.XL_PREFIX if prefix is not None: # Recalculate some generate_kwargs linked to prefix. __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase : Union[str, Any] = self._sanitize_parameters(prefix=_SCREAMING_SNAKE_CASE , **self._forward_params ) __lowerCAmelCase : List[str] = {**self._preprocess_params, **preprocess_params} __lowerCAmelCase : List[str] = {**self._forward_params, **forward_params} def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE , ): __lowerCAmelCase : Optional[int] = {} if prefix is not None: __lowerCAmelCase : Union[str, Any] = prefix if prefix: __lowerCAmelCase : Dict = self.tokenizer( _SCREAMING_SNAKE_CASE , padding=_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE , return_tensors=self.framework ) __lowerCAmelCase : List[Any] = prefix_inputs['input_ids'].shape[-1] if handle_long_generation is not None: if handle_long_generation not in {"hole"}: raise ValueError( f"{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected" ' [None, \'hole\']' ) __lowerCAmelCase : int = handle_long_generation preprocess_params.update(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : int = generate_kwargs __lowerCAmelCase : List[Any] = {} if return_full_text is not None and return_type is None: if return_text is not None: raise ValueError('`return_text` is mutually exclusive with `return_full_text`' ) if return_tensors is not None: raise ValueError('`return_full_text` is mutually exclusive with `return_tensors`' ) __lowerCAmelCase : Optional[Any] = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT if return_tensors is not None and return_type is None: if return_text is not None: raise ValueError('`return_text` is mutually exclusive with `return_tensors`' ) __lowerCAmelCase : List[Any] = ReturnType.TENSORS if return_type is not None: __lowerCAmelCase : Optional[Any] = return_type if clean_up_tokenization_spaces is not None: __lowerCAmelCase : Tuple = clean_up_tokenization_spaces if stop_sequence is not None: __lowerCAmelCase : Union[str, Any] = self.tokenizer.encode(_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE ) if len(_SCREAMING_SNAKE_CASE ) > 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.' ) __lowerCAmelCase : Optional[Any] = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def __lowerCamelCase ( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ): # Parse arguments if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]: kwargs.update({'add_space_before_punct_symbol': True} ) return super()._parse_and_tokenize(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def __call__( self , _SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ): return super().__call__(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE="" , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Any = self.tokenizer( prefix + prompt_text , padding=_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE , return_tensors=self.framework ) __lowerCAmelCase : Optional[Any] = prompt_text if handle_long_generation == "hole": __lowerCAmelCase : str = inputs['input_ids'].shape[-1] if "max_new_tokens" in generate_kwargs: __lowerCAmelCase : Union[str, Any] = generate_kwargs['max_new_tokens'] else: __lowerCAmelCase : Any = generate_kwargs.get('max_length' , self.model.config.max_length ) - cur_len if new_tokens < 0: raise ValueError('We cannot infer how many new tokens are expected' ) if cur_len + new_tokens > self.tokenizer.model_max_length: __lowerCAmelCase : Any = self.tokenizer.model_max_length - new_tokens if keep_length <= 0: raise ValueError( 'We cannot use `hole` to handle this generation the number of desired tokens exceeds the' ' models max length' ) __lowerCAmelCase : int = inputs['input_ids'][:, -keep_length:] if "attention_mask" in inputs: __lowerCAmelCase : List[Any] = inputs['attention_mask'][:, -keep_length:] return inputs def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ): __lowerCAmelCase : str = model_inputs['input_ids'] __lowerCAmelCase : List[Any] = model_inputs.get('attention_mask' , _SCREAMING_SNAKE_CASE ) # Allow empty prompts if input_ids.shape[1] == 0: __lowerCAmelCase : Dict = None __lowerCAmelCase : str = None __lowerCAmelCase : Tuple = 1 else: __lowerCAmelCase : Any = input_ids.shape[0] __lowerCAmelCase : Union[str, Any] = model_inputs.pop('prompt_text' ) # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline. __lowerCAmelCase : Optional[int] = generate_kwargs.pop('prefix_length' , 0 ) if prefix_length > 0: __lowerCAmelCase : Any = 'max_new_tokens' in generate_kwargs or ( 'generation_config' in generate_kwargs and generate_kwargs['generation_config'].max_new_tokens is not None ) if not has_max_new_tokens: __lowerCAmelCase : List[str] = generate_kwargs.get('max_length' ) or self.model.config.max_length generate_kwargs["max_length"] += prefix_length __lowerCAmelCase : Dict = 'min_new_tokens' in generate_kwargs or ( 'generation_config' in generate_kwargs and generate_kwargs['generation_config'].min_new_tokens is not None ) if not has_min_new_tokens and "min_length" in generate_kwargs: generate_kwargs["min_length"] += prefix_length # BS x SL __lowerCAmelCase : Optional[int] = self.model.generate(input_ids=_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = generated_sequence.shape[0] if self.framework == "pt": __lowerCAmelCase : Dict = generated_sequence.reshape(_SCREAMING_SNAKE_CASE , out_b // in_b , *generated_sequence.shape[1:] ) elif self.framework == "tf": __lowerCAmelCase : Any = tf.reshape(_SCREAMING_SNAKE_CASE , (in_b, out_b // in_b, *generated_sequence.shape[1:]) ) return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text} def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=ReturnType.FULL_TEXT , _SCREAMING_SNAKE_CASE=True ): __lowerCAmelCase : Any = model_outputs['generated_sequence'][0] __lowerCAmelCase : Tuple = model_outputs['input_ids'] __lowerCAmelCase : Any = model_outputs['prompt_text'] __lowerCAmelCase : int = generated_sequence.numpy().tolist() __lowerCAmelCase : Union[str, Any] = [] for sequence in generated_sequence: if return_type == ReturnType.TENSORS: __lowerCAmelCase : int = {'generated_token_ids': sequence} elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}: # Decode text __lowerCAmelCase : Any = self.tokenizer.decode( _SCREAMING_SNAKE_CASE , skip_special_tokens=_SCREAMING_SNAKE_CASE , clean_up_tokenization_spaces=_SCREAMING_SNAKE_CASE , ) # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used if input_ids is None: __lowerCAmelCase : Optional[Any] = 0 else: __lowerCAmelCase : Any = len( self.tokenizer.decode( input_ids[0] , skip_special_tokens=_SCREAMING_SNAKE_CASE , clean_up_tokenization_spaces=_SCREAMING_SNAKE_CASE , ) ) if return_type == ReturnType.FULL_TEXT: __lowerCAmelCase : Union[str, Any] = prompt_text + text[prompt_length:] else: __lowerCAmelCase : int = text[prompt_length:] __lowerCAmelCase : Dict = {'generated_text': all_text} records.append(_SCREAMING_SNAKE_CASE ) return records
86
0
"""simple docstring""" import os import unittest from transformers.models.bartpho.tokenization_bartpho import VOCAB_FILES_NAMES, BartphoTokenizer from transformers.testing_utils import get_tests_dir from ...test_tokenization_common import TokenizerTesterMixin a__ : Optional[int] = get_tests_dir('''fixtures/test_sentencepiece_bpe.model''') class UpperCamelCase_ ( UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : Optional[int] = BartphoTokenizer snake_case__ : Union[str, Any] = False snake_case__ : Optional[int] = True def UpperCAmelCase_ ( self : List[str] ) -> int: super().setUp() __SCREAMING_SNAKE_CASE = ["▁This", "▁is", "▁a", "▁t", "est"] __SCREAMING_SNAKE_CASE = dict(zip(UpperCAmelCase__ , range(len(UpperCAmelCase__ ) ) ) ) __SCREAMING_SNAKE_CASE = {"unk_token": "<unk>"} __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["monolingual_vocab_file"] ) with open(self.monolingual_vocab_file , "w" , encoding="utf-8" ) as fp: for token in vocab_tokens: fp.write(F"""{token} {vocab_tokens[token]}\n""" ) __SCREAMING_SNAKE_CASE = BartphoTokenizer(UpperCAmelCase__ , self.monolingual_vocab_file , **self.special_tokens_map ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCAmelCase_ ( self : str , **UpperCAmelCase__ : int ) -> int: kwargs.update(self.special_tokens_map ) return BartphoTokenizer.from_pretrained(self.tmpdirname , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : Union[str, Any] ) -> List[Any]: __SCREAMING_SNAKE_CASE = "This is a là test" __SCREAMING_SNAKE_CASE = "This is a<unk><unk> test" return input_text, output_text def UpperCAmelCase_ ( self : List[str] ) -> str: __SCREAMING_SNAKE_CASE = BartphoTokenizer(UpperCAmelCase__ , self.monolingual_vocab_file , **self.special_tokens_map ) __SCREAMING_SNAKE_CASE = "This is a là test" __SCREAMING_SNAKE_CASE = "▁This ▁is ▁a ▁l à ▁t est".split() __SCREAMING_SNAKE_CASE = tokenizer.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokens + [tokenizer.unk_token] __SCREAMING_SNAKE_CASE = [4, 5, 6, 3, 3, 7, 8, 3] self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) , UpperCAmelCase__ )
54
"""simple docstring""" from __future__ import annotations import bisect def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase = 0 , _UpperCamelCase = -1 ): if hi < 0: __lowerCAmelCase : Tuple = len(_UpperCamelCase ) while lo < hi: __lowerCAmelCase : Optional[int] = lo + (hi - lo) // 2 if sorted_collection[mid] < item: __lowerCAmelCase : int = mid + 1 else: __lowerCAmelCase : List[str] = mid return lo def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase = 0 , _UpperCamelCase = -1 ): if hi < 0: __lowerCAmelCase : List[Any] = len(_UpperCamelCase ) while lo < hi: __lowerCAmelCase : Union[str, Any] = lo + (hi - lo) // 2 if sorted_collection[mid] <= item: __lowerCAmelCase : Dict = mid + 1 else: __lowerCAmelCase : str = mid return lo def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase = 0 , _UpperCamelCase = -1 ): sorted_collection.insert(bisect_left(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) , _UpperCamelCase ) def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase = 0 , _UpperCamelCase = -1 ): sorted_collection.insert(bisect_right(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) , _UpperCamelCase ) def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase ): __lowerCAmelCase : List[Any] = 0 __lowerCAmelCase : int = len(_UpperCamelCase ) - 1 while left <= right: __lowerCAmelCase : List[Any] = left + (right - left) // 2 __lowerCAmelCase : Union[str, Any] = sorted_collection[midpoint] if current_item == item: return midpoint elif item < current_item: __lowerCAmelCase : Tuple = midpoint - 1 else: __lowerCAmelCase : str = midpoint + 1 return None def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase ): __lowerCAmelCase : Union[str, Any] = bisect.bisect_left(_UpperCamelCase , _UpperCamelCase ) if index != len(_UpperCamelCase ) and sorted_collection[index] == item: return index return None def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): if right < left: return None __lowerCAmelCase : List[str] = left + (right - left) // 2 if sorted_collection[midpoint] == item: return midpoint elif sorted_collection[midpoint] > item: return binary_search_by_recursion(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , midpoint - 1 ) else: return binary_search_by_recursion(_UpperCamelCase , _UpperCamelCase , midpoint + 1 , _UpperCamelCase ) if __name__ == "__main__": lowerCamelCase__ = input("""Enter numbers separated by comma:\n""").strip() lowerCamelCase__ = sorted(int(item) for item in user_input.split(""",""")) lowerCamelCase__ = int(input("""Enter a single number to be found in the list:\n""")) lowerCamelCase__ = binary_search(collection, target) if result is None: print(f'{target} was not found in {collection}.') else: print(f'{target} was found at position {result} in {collection}.')
86
0
'''simple docstring''' def __snake_case ( UpperCAmelCase_ : int , UpperCAmelCase_ : float , UpperCAmelCase_ : float ): return round(float(moles / volume ) * nfactor ) def __snake_case ( UpperCAmelCase_ : float , UpperCAmelCase_ : float , UpperCAmelCase_ : float ): return round(float((moles * 0.0821 * temperature) / (volume) ) ) def __snake_case ( UpperCAmelCase_ : float , UpperCAmelCase_ : float , UpperCAmelCase_ : float ): return round(float((moles * 0.0821 * temperature) / (pressure) ) ) def __snake_case ( UpperCAmelCase_ : float , UpperCAmelCase_ : float , UpperCAmelCase_ : float ): return round(float((pressure * volume) / (0.0821 * moles) ) ) if __name__ == "__main__": import doctest doctest.testmod()
55
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available, is_torch_available from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, is_pt_tf_cross_test, slow if is_tf_available(): from transformers import ( AutoConfig, BertConfig, GPTaConfig, TaConfig, TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSeqaSeqLM, TFAutoModelForSequenceClassification, TFAutoModelWithLMHead, TFBertForMaskedLM, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertModel, TFGPTaLMHeadModel, TFRobertaForMaskedLM, TFTaForConditionalGeneration, ) from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST if is_torch_available(): from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForPreTraining, AutoModelForQuestionAnswering, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoModelWithLMHead, BertForMaskedLM, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, BertModel, GPTaLMHeadModel, RobertaForMaskedLM, TaForConditionalGeneration, ) @is_pt_tf_cross_test class A__ ( unittest.TestCase): @slow def __lowerCamelCase ( self ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __lowerCAmelCase : Tuple = AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = TFAutoModel.from_pretrained(_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = AutoModel.from_pretrained(_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @slow def __lowerCamelCase ( self ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __lowerCAmelCase : int = AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Tuple = TFAutoModelForPreTraining.from_pretrained(_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : str = AutoModelForPreTraining.from_pretrained(_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @slow def __lowerCamelCase ( self ): for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCAmelCase : Dict = AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = TFAutoModelForCausalLM.from_pretrained(_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase , __lowerCAmelCase : List[str] = TFAutoModelForCausalLM.from_pretrained( _SCREAMING_SNAKE_CASE , output_loading_info=_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Any = AutoModelForCausalLM.from_pretrained(_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase , __lowerCAmelCase : List[Any] = AutoModelForCausalLM.from_pretrained( _SCREAMING_SNAKE_CASE , output_loading_info=_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @slow def __lowerCamelCase ( self ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCAmelCase : Dict = AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : int = TFAutoModelWithLMHead.from_pretrained(_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = AutoModelWithLMHead.from_pretrained(_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @slow def __lowerCamelCase ( self ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCAmelCase : Optional[Any] = AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = TFAutoModelForMaskedLM.from_pretrained(_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase , __lowerCAmelCase : int = TFAutoModelForMaskedLM.from_pretrained( _SCREAMING_SNAKE_CASE , output_loading_info=_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Union[str, Any] = AutoModelForMaskedLM.from_pretrained(_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase , __lowerCAmelCase : str = AutoModelForMaskedLM.from_pretrained( _SCREAMING_SNAKE_CASE , output_loading_info=_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @slow def __lowerCamelCase ( self ): for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCAmelCase : Optional[int] = AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Tuple = TFAutoModelForSeqaSeqLM.from_pretrained(_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase , __lowerCAmelCase : Tuple = TFAutoModelForSeqaSeqLM.from_pretrained( _SCREAMING_SNAKE_CASE , output_loading_info=_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : int = AutoModelForSeqaSeqLM.from_pretrained(_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase , __lowerCAmelCase : Dict = AutoModelForSeqaSeqLM.from_pretrained( _SCREAMING_SNAKE_CASE , output_loading_info=_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @slow def __lowerCamelCase ( self ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __lowerCAmelCase : Dict = AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = TFAutoModelForSequenceClassification.from_pretrained(_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Union[str, Any] = AutoModelForSequenceClassification.from_pretrained(_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @slow def __lowerCamelCase ( self ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __lowerCAmelCase : Union[str, Any] = AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = TFAutoModelForQuestionAnswering.from_pretrained(_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Union[str, Any] = AutoModelForQuestionAnswering.from_pretrained(_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : List[Any] = TFAutoModelWithLMHead.from_pretrained(_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) self.assertEqual(model.num_parameters() , 1_44_10 ) self.assertEqual(model.num_parameters(only_trainable=_SCREAMING_SNAKE_CASE ) , 1_44_10 ) __lowerCAmelCase : Tuple = AutoModelWithLMHead.from_pretrained(_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) self.assertEqual(model.num_parameters() , 1_44_10 ) self.assertEqual(model.num_parameters(only_trainable=_SCREAMING_SNAKE_CASE ) , 1_44_10 ) def __lowerCamelCase ( self ): __lowerCAmelCase : int = TFAutoModelWithLMHead.from_pretrained(_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) self.assertEqual(model.num_parameters() , 1_44_10 ) self.assertEqual(model.num_parameters(only_trainable=_SCREAMING_SNAKE_CASE ) , 1_44_10 ) __lowerCAmelCase : Tuple = AutoModelWithLMHead.from_pretrained(_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) self.assertEqual(model.num_parameters() , 1_44_10 ) self.assertEqual(model.num_parameters(only_trainable=_SCREAMING_SNAKE_CASE ) , 1_44_10 )
86
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available a : str = { 'configuration_rag': ['RagConfig'], 'retrieval_rag': ['RagRetriever'], 'tokenization_rag': ['RagTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a : List[Any] = [ 'RagModel', 'RagPreTrainedModel', 'RagSequenceForGeneration', 'RagTokenForGeneration', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a : Any = [ 'TFRagModel', 'TFRagPreTrainedModel', 'TFRagSequenceForGeneration', 'TFRagTokenForGeneration', ] if TYPE_CHECKING: from .configuration_rag import RagConfig from .retrieval_rag import RagRetriever from .tokenization_rag import RagTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rag import ( TFRagModel, TFRagPreTrainedModel, TFRagSequenceForGeneration, TFRagTokenForGeneration, ) else: import sys a : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
56
"""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 lowerCamelCase__ = logging.get_logger(__name__) # pylint: disable=invalid-name lowerCamelCase__ = """ 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 (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase=8 ): __lowerCAmelCase : Dict = h // scale_factor**2 if h % scale_factor**2 != 0: new_h += 1 __lowerCAmelCase : List[str] = w // scale_factor**2 if w % scale_factor**2 != 0: new_w += 1 return new_h * scale_factor, new_w * scale_factor class A__ ( _lowerCamelCase): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , ): super().__init__() self.register_modules( text_encoder=_SCREAMING_SNAKE_CASE , tokenizer=_SCREAMING_SNAKE_CASE , unet=_SCREAMING_SNAKE_CASE , scheduler=_SCREAMING_SNAKE_CASE , movq=_SCREAMING_SNAKE_CASE , ) __lowerCAmelCase : Dict = 2 ** (len(self.movq.config.block_out_channels ) - 1) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): if latents is None: __lowerCAmelCase : Tuple = randn_tensor(_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , device=_SCREAMING_SNAKE_CASE , dtype=_SCREAMING_SNAKE_CASE ) else: if latents.shape != shape: raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}" ) __lowerCAmelCase : Any = latents.to(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = latents * scheduler.init_noise_sigma return latents def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , ): __lowerCAmelCase : Tuple = len(_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else 1 # get prompt text embeddings __lowerCAmelCase : Dict = self.tokenizer( _SCREAMING_SNAKE_CASE , padding='max_length' , truncation=_SCREAMING_SNAKE_CASE , max_length=77 , return_attention_mask=_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE , return_tensors='pt' , ) __lowerCAmelCase : Tuple = text_inputs.input_ids __lowerCAmelCase : Union[str, Any] = self.tokenizer(_SCREAMING_SNAKE_CASE , padding='longest' , return_tensors='pt' ).input_ids if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : List[Any] = 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}" ) __lowerCAmelCase : Dict = text_input_ids.to(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = text_inputs.attention_mask.to(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase , __lowerCAmelCase : str = self.text_encoder( input_ids=_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Any = prompt_embeds.repeat_interleave(_SCREAMING_SNAKE_CASE , dim=0 ) __lowerCAmelCase : Dict = text_encoder_hidden_states.repeat_interleave(_SCREAMING_SNAKE_CASE , dim=0 ) __lowerCAmelCase : Optional[int] = text_mask.repeat_interleave(_SCREAMING_SNAKE_CASE , dim=0 ) if do_classifier_free_guidance: __lowerCAmelCase : List[str] if negative_prompt is None: __lowerCAmelCase : Union[str, Any] = [''] * batch_size elif type(_SCREAMING_SNAKE_CASE ) is not type(_SCREAMING_SNAKE_CASE ): raise TypeError( f"`negative_prompt` should be the same type to `prompt`, but got {type(_SCREAMING_SNAKE_CASE )} !=" f" {type(_SCREAMING_SNAKE_CASE )}." ) elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Optional[int] = [negative_prompt] elif batch_size != len(_SCREAMING_SNAKE_CASE ): raise ValueError( f"`negative_prompt`: {negative_prompt} has batch size {len(_SCREAMING_SNAKE_CASE )}, but `prompt`:" f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" ' the batch size of `prompt`.' ) else: __lowerCAmelCase : Optional[int] = negative_prompt __lowerCAmelCase : Tuple = self.tokenizer( _SCREAMING_SNAKE_CASE , padding='max_length' , max_length=77 , truncation=_SCREAMING_SNAKE_CASE , return_attention_mask=_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE , return_tensors='pt' , ) __lowerCAmelCase : Union[str, Any] = uncond_input.input_ids.to(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = uncond_input.attention_mask.to(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase , __lowerCAmelCase : Any = self.text_encoder( input_ids=_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE ) # duplicate unconditional embeddings for each generation per prompt, using mps friendly method __lowerCAmelCase : List[str] = negative_prompt_embeds.shape[1] __lowerCAmelCase : Any = negative_prompt_embeds.repeat(1 , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = negative_prompt_embeds.view(batch_size * num_images_per_prompt , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : int = uncond_text_encoder_hidden_states.shape[1] __lowerCAmelCase : List[Any] = uncond_text_encoder_hidden_states.repeat(1 , _SCREAMING_SNAKE_CASE , 1 ) __lowerCAmelCase : Optional[int] = uncond_text_encoder_hidden_states.view( batch_size * num_images_per_prompt , _SCREAMING_SNAKE_CASE , -1 ) __lowerCAmelCase : Optional[Any] = uncond_text_mask.repeat_interleave(_SCREAMING_SNAKE_CASE , 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 __lowerCAmelCase : Tuple = torch.cat([negative_prompt_embeds, prompt_embeds] ) __lowerCAmelCase : Tuple = torch.cat([uncond_text_encoder_hidden_states, text_encoder_hidden_states] ) __lowerCAmelCase : int = torch.cat([uncond_text_mask, text_mask] ) return prompt_embeds, text_encoder_hidden_states, text_mask def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE=0 ): if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('Please install accelerate via `pip install accelerate`' ) __lowerCAmelCase : Union[str, Any] = torch.device(f"cuda:{gpu_id}" ) __lowerCAmelCase : List[Any] = [ self.unet, self.text_encoder, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE=0 ): 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.' ) __lowerCAmelCase : str = torch.device(f"cuda:{gpu_id}" ) if self.device.type != "cpu": self.to('cpu' , silence_dtype_warnings=_SCREAMING_SNAKE_CASE ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) __lowerCAmelCase : Any = None for cpu_offloaded_model in [self.text_encoder, self.unet, self.movq]: __lowerCAmelCase , __lowerCAmelCase : Any = cpu_offload_with_hook(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , prev_module_hook=_SCREAMING_SNAKE_CASE ) if self.safety_checker is not None: __lowerCAmelCase , __lowerCAmelCase : Dict = cpu_offload_with_hook(self.safety_checker , _SCREAMING_SNAKE_CASE , prev_module_hook=_SCREAMING_SNAKE_CASE ) # We'll offload the last model manually. __lowerCAmelCase : Optional[Any] = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def __lowerCamelCase ( self ): if not hasattr(self.unet , '_hf_hook' ): return self.device for module in self.unet.modules(): if ( hasattr(_SCREAMING_SNAKE_CASE , '_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(_SCREAMING_SNAKE_CASE ) def __call__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 5_12 , _SCREAMING_SNAKE_CASE = 5_12 , _SCREAMING_SNAKE_CASE = 1_00 , _SCREAMING_SNAKE_CASE = 4.0 , _SCREAMING_SNAKE_CASE = 1 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = "pil" , _SCREAMING_SNAKE_CASE = True , ): if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : List[str] = 1 elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Optional[int] = len(_SCREAMING_SNAKE_CASE ) else: raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(_SCREAMING_SNAKE_CASE )}" ) __lowerCAmelCase : Dict = self._execution_device __lowerCAmelCase : Optional[Any] = batch_size * num_images_per_prompt __lowerCAmelCase : Optional[int] = guidance_scale > 1.0 __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase : int = self._encode_prompt( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : int = torch.cat(_SCREAMING_SNAKE_CASE , dim=0 ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Dict = torch.cat(_SCREAMING_SNAKE_CASE , dim=0 ) if do_classifier_free_guidance: __lowerCAmelCase : Optional[Any] = image_embeds.repeat_interleave(_SCREAMING_SNAKE_CASE , dim=0 ) __lowerCAmelCase : int = negative_image_embeds.repeat_interleave(_SCREAMING_SNAKE_CASE , dim=0 ) __lowerCAmelCase : Any = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to( dtype=prompt_embeds.dtype , device=_SCREAMING_SNAKE_CASE ) self.scheduler.set_timesteps(_SCREAMING_SNAKE_CASE , device=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = self.scheduler.timesteps __lowerCAmelCase : int = self.unet.config.in_channels __lowerCAmelCase , __lowerCAmelCase : Any = get_new_h_w(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , self.movq_scale_factor ) # create initial latent __lowerCAmelCase : str = self.prepare_latents( (batch_size, num_channels_latents, height, width) , text_encoder_hidden_states.dtype , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , self.scheduler , ) for i, t in enumerate(self.progress_bar(_SCREAMING_SNAKE_CASE ) ): # expand the latents if we are doing classifier free guidance __lowerCAmelCase : List[str] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents __lowerCAmelCase : Union[str, Any] = {'text_embeds': prompt_embeds, 'image_embeds': image_embeds} __lowerCAmelCase : Optional[Any] = self.unet( sample=_SCREAMING_SNAKE_CASE , timestep=_SCREAMING_SNAKE_CASE , encoder_hidden_states=_SCREAMING_SNAKE_CASE , added_cond_kwargs=_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , )[0] if do_classifier_free_guidance: __lowerCAmelCase , __lowerCAmelCase : Dict = noise_pred.split(latents.shape[1] , dim=1 ) __lowerCAmelCase , __lowerCAmelCase : Optional[Any] = noise_pred.chunk(2 ) __lowerCAmelCase , __lowerCAmelCase : int = variance_pred.chunk(2 ) __lowerCAmelCase : Dict = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) __lowerCAmelCase : 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"] ): __lowerCAmelCase , __lowerCAmelCase : Union[str, Any] = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 __lowerCAmelCase : List[str] = self.scheduler.step( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , ).prev_sample # post-processing __lowerCAmelCase : Tuple = self.movq.decode(_SCREAMING_SNAKE_CASE , force_not_quantize=_SCREAMING_SNAKE_CASE )['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"]: __lowerCAmelCase : List[str] = image * 0.5 + 0.5 __lowerCAmelCase : Dict = image.clamp(0 , 1 ) __lowerCAmelCase : Dict = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": __lowerCAmelCase : Union[str, Any] = self.numpy_to_pil(_SCREAMING_SNAKE_CASE ) if not return_dict: return (image,) return ImagePipelineOutput(images=_SCREAMING_SNAKE_CASE )
86
0
"""simple docstring""" from __future__ import annotations def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = 0.00 __lowerCAmelCase = 0 for resistor in resistors: if resistor <= 0: __lowerCAmelCase = f"Resistor at index {index} has a negative or zero value!" raise ValueError(_UpperCamelCase ) first_sum += 1 / float(_UpperCamelCase ) index += 1 return 1 / first_sum def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = 0.00 __lowerCAmelCase = 0 for resistor in resistors: sum_r += resistor if resistor < 0: __lowerCAmelCase = f"Resistor at index {index} has a negative value!" raise ValueError(_UpperCamelCase ) index += 1 return sum_r if __name__ == "__main__": import doctest doctest.testmod()
57
"""simple docstring""" import unittest from transformers import BarthezTokenizer, BarthezTokenizerFast, BatchEncoding from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers @require_sentencepiece @slow # see https://github.com/huggingface/transformers/issues/11457 class A__ ( _lowerCamelCase , unittest.TestCase): A_ : Union[str, Any] = BarthezTokenizer A_ : Tuple = BarthezTokenizerFast A_ : Dict = True A_ : List[str] = True def __lowerCamelCase ( self ): super().setUp() __lowerCAmelCase : str = BarthezTokenizerFast.from_pretrained('moussaKam/mbarthez' ) tokenizer.save_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname , legacy_format=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Any = tokenizer def __lowerCamelCase ( self ): __lowerCAmelCase : Optional[Any] = '<pad>' __lowerCAmelCase : Union[str, Any] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : List[Any] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<s>' ) self.assertEqual(vocab_keys[1] , '<pad>' ) self.assertEqual(vocab_keys[-1] , '<mask>' ) self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , 10_11_22 ) def __lowerCamelCase ( self ): self.assertEqual(self.get_tokenizer().vocab_size , 10_11_22 ) @require_torch def __lowerCamelCase ( self ): __lowerCAmelCase : List[str] = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] __lowerCAmelCase : Optional[Any] = [0, 57, 30_18, 7_03_07, 91, 2] __lowerCAmelCase : Optional[int] = self.tokenizer( _SCREAMING_SNAKE_CASE , max_length=len(_SCREAMING_SNAKE_CASE ) , padding=_SCREAMING_SNAKE_CASE , truncation=_SCREAMING_SNAKE_CASE , return_tensors='pt' ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) self.assertEqual((2, 6) , batch.input_ids.shape ) self.assertEqual((2, 6) , batch.attention_mask.shape ) __lowerCAmelCase : List[str] = batch.input_ids.tolist()[0] self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): if not self.test_rust_tokenizer: return __lowerCAmelCase : Tuple = self.get_tokenizer() __lowerCAmelCase : Optional[int] = self.get_rust_tokenizer() __lowerCAmelCase : List[str] = 'I was born in 92000, and this is falsé.' __lowerCAmelCase : Optional[int] = tokenizer.tokenize(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Union[str, Any] = rust_tokenizer.tokenize(_SCREAMING_SNAKE_CASE ) self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = tokenizer.encode(_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = rust_tokenizer.encode(_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE ) self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = self.get_rust_tokenizer() __lowerCAmelCase : List[Any] = tokenizer.encode(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = rust_tokenizer.encode(_SCREAMING_SNAKE_CASE ) self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @slow def __lowerCamelCase ( self ): # fmt: off __lowerCAmelCase : str = {'input_ids': [[0, 4_90, 1_43_28, 45_07, 3_54, 47, 4_36_69, 95, 25, 7_81_17, 2_02_15, 1_97_79, 1_90, 22, 4_00, 4, 3_53_43, 8_03_10, 6_03, 86, 2_49_37, 1_05, 3_34_38, 9_47_62, 1_96, 3_96_42, 7, 15, 1_59_33, 1_73, 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], [0, 1_05_34, 87, 25, 66, 33_58, 1_96, 5_52_89, 8, 8_29_61, 81, 22_04, 7_52_03, 7, 15, 7_63, 1_29_56, 2_16, 1_78, 1_43_28, 95_95, 13_77, 6_96_93, 7, 4_48, 7_10_21, 1_96, 1_81_06, 14_37, 1_39_74, 1_08, 90_83, 4, 4_93_15, 7, 39, 86, 13_26, 27_93, 4_63_33, 4, 4_48, 1_96, 7_45_88, 7, 4_93_15, 7, 39, 21, 8_22, 3_84_70, 74, 21, 6_67_23, 6_24_80, 8, 2_20_50, 5, 2]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on # moussaKam/mbarthez is a french model. So we also use french texts. __lowerCAmelCase : Union[str, Any] = [ 'Le transformeur est un modèle d\'apprentissage profond introduit en 2017, ' 'utilisé principalement dans le domaine du traitement automatique des langues (TAL).', 'À l\'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus ' 'pour gérer des données séquentielles, telles que le langage naturel, pour des tâches ' 'telles que la traduction et la synthèse de texte.', ] self.tokenizer_integration_test_util( expected_encoding=_SCREAMING_SNAKE_CASE , model_name='moussaKam/mbarthez' , revision='c2e4ecbca5e3cd2c37fe1ac285ca4fbdf1366fb6' , sequences=_SCREAMING_SNAKE_CASE , )
86
0
'''simple docstring''' import argparse import torch from torch import nn from transformers import SpeechaTextConfig, SpeechaTextForConditionalGeneration def lowerCamelCase ( __lowerCamelCase : List[str] ) ->List[str]: _SCREAMING_SNAKE_CASE = [ """encoder.version""", """decoder.version""", """model.encoder.version""", """model.decoder.version""", """decoder.output_projection.weight""", """_float_tensor""", """encoder.embed_positions._float_tensor""", """decoder.embed_positions._float_tensor""", ] for k in ignore_keys: state_dict.pop(__lowerCamelCase , __lowerCamelCase ) def lowerCamelCase ( __lowerCamelCase : int ) ->Union[str, Any]: _SCREAMING_SNAKE_CASE = list(s_dict.keys() ) for key in keys: if "transformer_layers" in key: _SCREAMING_SNAKE_CASE = s_dict.pop(__lowerCamelCase ) elif "subsample" in key: _SCREAMING_SNAKE_CASE = s_dict.pop(__lowerCamelCase ) def lowerCamelCase ( __lowerCamelCase : List[str] ) ->List[Any]: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = emb.weight.shape _SCREAMING_SNAKE_CASE = nn.Linear(__lowerCamelCase , __lowerCamelCase , bias=__lowerCamelCase ) _SCREAMING_SNAKE_CASE = emb.weight.data return lin_layer def lowerCamelCase ( __lowerCamelCase : Optional[Any] , __lowerCamelCase : List[str] ) ->int: _SCREAMING_SNAKE_CASE = torch.load(__lowerCamelCase , map_location="""cpu""" ) _SCREAMING_SNAKE_CASE = mam_aaa["""args"""] _SCREAMING_SNAKE_CASE = mam_aaa["""model"""] _SCREAMING_SNAKE_CASE = state_dict["""decoder.output_projection.weight"""] remove_ignore_keys_(__lowerCamelCase ) rename_keys(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = state_dict["""decoder.embed_tokens.weight"""].shape[0] _SCREAMING_SNAKE_CASE = args.share_decoder_input_output_embed _SCREAMING_SNAKE_CASE = [int(__lowerCamelCase ) for i in args.conv_kernel_sizes.split(""",""" )] _SCREAMING_SNAKE_CASE = SpeechaTextConfig( vocab_size=__lowerCamelCase , max_source_positions=args.max_source_positions , max_target_positions=args.max_target_positions , encoder_layers=args.encoder_layers , decoder_layers=args.decoder_layers , encoder_attention_heads=args.encoder_attention_heads , decoder_attention_heads=args.decoder_attention_heads , encoder_ffn_dim=args.encoder_ffn_embed_dim , decoder_ffn_dim=args.decoder_ffn_embed_dim , d_model=args.encoder_embed_dim , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function="""relu""" , num_conv_layers=len(__lowerCamelCase ) , conv_channels=args.conv_channels , conv_kernel_sizes=__lowerCamelCase , input_feat_per_channel=args.input_feat_per_channel , input_channels=args.input_channels , tie_word_embeddings=__lowerCamelCase , num_beams=5 , max_length=200 , use_cache=__lowerCamelCase , decoder_start_token_id=2 , early_stopping=__lowerCamelCase , ) _SCREAMING_SNAKE_CASE = SpeechaTextForConditionalGeneration(__lowerCamelCase ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = model.model.load_state_dict(__lowerCamelCase , strict=__lowerCamelCase ) if len(__lowerCamelCase ) > 0 and not set(__lowerCamelCase ) <= { "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: _SCREAMING_SNAKE_CASE = make_linear_from_emb(model.model.decoder.embed_tokens ) else: _SCREAMING_SNAKE_CASE = lm_head_weights model.save_pretrained(__lowerCamelCase ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument("""--fairseq_path""", type=str, help="""Path to the fairseq model (.pt) file.""") parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") lowercase_ = parser.parse_args() convert_fairseq_sat_checkpoint_to_tfms(args.fairseq_path, args.pytorch_dump_folder_path)
58
"""simple docstring""" 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__ = { """sail/poolformer_s12""": """https://huggingface.co/sail/poolformer_s12/resolve/main/config.json""", # See all PoolFormer models at https://huggingface.co/models?filter=poolformer } class A__ ( _lowerCamelCase): A_ : Optional[int] = 'poolformer' def __init__( self , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=4.0 , _SCREAMING_SNAKE_CASE=[2, 2, 6, 2] , _SCREAMING_SNAKE_CASE=[64, 1_28, 3_20, 5_12] , _SCREAMING_SNAKE_CASE=[7, 3, 3, 3] , _SCREAMING_SNAKE_CASE=[4, 2, 2, 2] , _SCREAMING_SNAKE_CASE=[2, 1, 1, 1] , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=1E-5 , _SCREAMING_SNAKE_CASE=0.02 , **_SCREAMING_SNAKE_CASE , ): __lowerCAmelCase : int = num_channels __lowerCAmelCase : str = patch_size __lowerCAmelCase : Optional[Any] = stride __lowerCAmelCase : Optional[int] = padding __lowerCAmelCase : List[Any] = pool_size __lowerCAmelCase : int = hidden_sizes __lowerCAmelCase : str = mlp_ratio __lowerCAmelCase : Optional[int] = depths __lowerCAmelCase : str = patch_sizes __lowerCAmelCase : str = strides __lowerCAmelCase : Optional[int] = num_encoder_blocks __lowerCAmelCase : Any = drop_path_rate __lowerCAmelCase : Any = hidden_act __lowerCAmelCase : Dict = use_layer_scale __lowerCAmelCase : Union[str, Any] = layer_scale_init_value __lowerCAmelCase : Dict = initializer_range super().__init__(**_SCREAMING_SNAKE_CASE ) class A__ ( _lowerCamelCase): A_ : List[str] = version.parse('1.11') @property def __lowerCamelCase ( self ): return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def __lowerCamelCase ( self ): return 2E-3
86
0
import argparse import logging import sys from unittest.mock import patch import run_glue_deebert from transformers.testing_utils import TestCasePlus, get_gpu_count, require_torch_non_multi_gpu, slow logging.basicConfig(level=logging.DEBUG) __lowerCamelCase = logging.getLogger() def UpperCamelCase ( ): snake_case : Any = argparse.ArgumentParser() parser.add_argument("-f" ) snake_case : Tuple = parser.parse_args() return args.f class UpperCAmelCase ( A_ ): def _SCREAMING_SNAKE_CASE (self : str ) -> None: '''simple docstring''' snake_case : int = logging.StreamHandler(sys.stdout ) logger.addHandler(snake_case__ ) def _SCREAMING_SNAKE_CASE (self : int , snake_case__ : Optional[int] ) -> str: '''simple docstring''' snake_case : int = get_gpu_count() if n_gpu > 1: pass # XXX: doesn't quite work with n_gpu > 1 https://github.com/huggingface/transformers/issues/10560 # script = f"{self.examples_dir_str}/research_projects/deebert/run_glue_deebert.py" # distributed_args = f"-m torch.distributed.launch --nproc_per_node={n_gpu} {script}".split() # cmd = [sys.executable] + distributed_args + args # execute_subprocess_async(cmd, env=self.get_env()) # XXX: test the results - need to save them first into .json file else: args.insert(0 , "run_glue_deebert.py" ) with patch.object(snake_case__ , "argv" , snake_case__ ): snake_case : List[Any] = run_glue_deebert.main() for value in result.values(): self.assertGreaterEqual(snake_case__ , 0.666 ) @slow @require_torch_non_multi_gpu def _SCREAMING_SNAKE_CASE (self : Any ) -> List[Any]: '''simple docstring''' snake_case : Optional[Any] = "\n --model_type roberta\n --model_name_or_path roberta-base\n --task_name MRPC\n --do_train\n --do_eval\n --do_lower_case\n --data_dir ./tests/fixtures/tests_samples/MRPC/\n --max_seq_length 128\n --per_gpu_eval_batch_size=1\n --per_gpu_train_batch_size=8\n --learning_rate 2e-4\n --num_train_epochs 3\n --overwrite_output_dir\n --seed 42\n --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage\n --plot_data_dir ./examples/deebert/results/\n --save_steps 0\n --overwrite_cache\n --eval_after_first_stage\n ".split() self.run_and_check(snake_case__ ) snake_case : int = "\n --model_type roberta\n --model_name_or_path ./examples/deebert/saved_models/roberta-base/MRPC/two_stage\n --task_name MRPC\n --do_eval\n --do_lower_case\n --data_dir ./tests/fixtures/tests_samples/MRPC/\n --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage\n --plot_data_dir ./examples/deebert/results/\n --max_seq_length 128\n --eval_each_highway\n --eval_highway\n --overwrite_cache\n --per_gpu_eval_batch_size=1\n ".split() self.run_and_check(snake_case__ ) snake_case : int = "\n --model_type roberta\n --model_name_or_path ./examples/deebert/saved_models/roberta-base/MRPC/two_stage\n --task_name MRPC\n --do_eval\n --do_lower_case\n --data_dir ./tests/fixtures/tests_samples/MRPC/\n --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage\n --plot_data_dir ./examples/deebert/results/\n --max_seq_length 128\n --early_exit_entropy 0.1\n --eval_highway\n --overwrite_cache\n --per_gpu_eval_batch_size=1\n ".split() self.run_and_check(snake_case__ )
59
"""simple docstring""" import gc import unittest import numpy as np import torch from diffusers import AutoencoderKL, DDIMScheduler, DiTPipeline, DPMSolverMultistepScheduler, TransformeraDModel from diffusers.utils import is_xformers_available, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS, CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class A__ ( _lowerCamelCase , unittest.TestCase): A_ : Union[str, Any] = DiTPipeline A_ : Union[str, Any] = CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS A_ : List[Any] = PipelineTesterMixin.required_optional_params - { 'latents', 'num_images_per_prompt', 'callback', 'callback_steps', } A_ : Optional[Any] = CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS A_ : Tuple = False def __lowerCamelCase ( self ): torch.manual_seed(0 ) __lowerCAmelCase : List[str] = TransformeraDModel( sample_size=16 , num_layers=2 , patch_size=4 , attention_head_dim=8 , num_attention_heads=2 , in_channels=4 , out_channels=8 , attention_bias=_SCREAMING_SNAKE_CASE , activation_fn='gelu-approximate' , num_embeds_ada_norm=10_00 , norm_type='ada_norm_zero' , norm_elementwise_affine=_SCREAMING_SNAKE_CASE , ) __lowerCAmelCase : str = AutoencoderKL() __lowerCAmelCase : Union[str, Any] = DDIMScheduler() __lowerCAmelCase : Dict = {'transformer': transformer.eval(), 'vae': vae.eval(), 'scheduler': scheduler} return components def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=0 ): if str(_SCREAMING_SNAKE_CASE ).startswith('mps' ): __lowerCAmelCase : List[str] = torch.manual_seed(_SCREAMING_SNAKE_CASE ) else: __lowerCAmelCase : List[str] = torch.Generator(device=_SCREAMING_SNAKE_CASE ).manual_seed(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Any = { 'class_labels': [1], 'generator': generator, 'num_inference_steps': 2, 'output_type': 'numpy', } return inputs def __lowerCamelCase ( self ): __lowerCAmelCase : List[str] = 'cpu' __lowerCAmelCase : Any = self.get_dummy_components() __lowerCAmelCase : Union[str, Any] = self.pipeline_class(**_SCREAMING_SNAKE_CASE ) pipe.to(_SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Tuple = self.get_dummy_inputs(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = pipe(**_SCREAMING_SNAKE_CASE ).images __lowerCAmelCase : List[str] = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 16, 16, 3) ) __lowerCAmelCase : Optional[int] = np.array([0.2946, 0.6601, 0.4329, 0.3296, 0.4144, 0.5319, 0.7273, 0.5013, 0.4457] ) __lowerCAmelCase : List[Any] = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(_SCREAMING_SNAKE_CASE , 1E-3 ) def __lowerCamelCase ( self ): self._test_inference_batch_single_identical(relax_max_difference=_SCREAMING_SNAKE_CASE , expected_max_diff=1E-3 ) @unittest.skipIf( torch_device != 'cuda' or not is_xformers_available() , reason='XFormers attention is only available with CUDA and `xformers` installed' , ) def __lowerCamelCase ( self ): self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 ) @require_torch_gpu @slow class A__ ( unittest.TestCase): def __lowerCamelCase ( self ): super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCamelCase ( self ): __lowerCAmelCase : Dict = torch.manual_seed(0 ) __lowerCAmelCase : int = DiTPipeline.from_pretrained('facebook/DiT-XL-2-256' ) pipe.to('cuda' ) __lowerCAmelCase : Optional[Any] = ['vase', 'umbrella', 'white shark', 'white wolf'] __lowerCAmelCase : Optional[Any] = pipe.get_label_ids(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = pipe(_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , num_inference_steps=40 , output_type='np' ).images for word, image in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Tuple = load_numpy( f"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/dit/{word}.npy" ) assert np.abs((expected_image - image).max() ) < 1E-2 def __lowerCamelCase ( self ): __lowerCAmelCase : Any = DiTPipeline.from_pretrained('facebook/DiT-XL-2-512' ) __lowerCAmelCase : Union[str, Any] = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.to('cuda' ) __lowerCAmelCase : Dict = ['vase', 'umbrella'] __lowerCAmelCase : List[str] = pipe.get_label_ids(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Any = torch.manual_seed(0 ) __lowerCAmelCase : Optional[Any] = pipe(_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , num_inference_steps=25 , output_type='np' ).images for word, image in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Dict = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' f"/dit/{word}_512.npy" ) assert np.abs((expected_image - image).max() ) < 1E-1
86
0
"""simple docstring""" from __future__ import annotations def _snake_case ( _snake_case : list[float] , _snake_case : Optional[Any] ): print(f'''Vertex\tShortest Distance from vertex {src}''' ) for i, d in enumerate(_snake_case ): print(f'''{i}\t\t{d}''' ) def _snake_case ( _snake_case : list[dict[str, int]] , _snake_case : list[float] , _snake_case : int ): for j in range(_snake_case ): lowerCAmelCase, lowerCAmelCase, lowerCAmelCase : Union[str, Any] = (graph[j][k] for k in ['''src''', '''dst''', '''weight''']) if distance[u] != float('''inf''' ) and distance[u] + w < distance[v]: return True return False def _snake_case ( _snake_case : list[dict[str, int]] , _snake_case : int , _snake_case : int , _snake_case : int ): lowerCAmelCase : Optional[Any] = [float('''inf''' )] * vertex_count lowerCAmelCase : Tuple = 0.0 for _ in range(vertex_count - 1 ): for j in range(_snake_case ): lowerCAmelCase, lowerCAmelCase, lowerCAmelCase : str = (graph[j][k] for k in ['''src''', '''dst''', '''weight''']) if distance[u] != float('''inf''' ) and distance[u] + w < distance[v]: lowerCAmelCase : Any = distance[u] + w lowerCAmelCase : Dict = check_negative_cycle(_snake_case , _snake_case , _snake_case ) if negative_cycle_exists: raise Exception('''Negative cycle found''' ) return distance if __name__ == "__main__": import doctest doctest.testmod() snake_case__ : List[Any] = int(input('''Enter number of vertices: ''').strip()) snake_case__ : int = int(input('''Enter number of edges: ''').strip()) snake_case__ : list[dict[str, int]] = [{} for _ in range(E)] for i in range(E): print('''Edge ''', i + 1) snake_case__ , snake_case__ , snake_case__ : str = ( int(x) for x in input('''Enter source, destination, weight: ''').strip().split(''' ''') ) snake_case__ : int = {'''src''': src, '''dst''': dest, '''weight''': weight} snake_case__ : str = int(input('''\nEnter shortest path source:''').strip()) snake_case__ : Optional[int] = bellman_ford(graph, V, E, source) print_distance(shortest_distance, 0)
60
"""simple docstring""" import gc import random import unittest import numpy as np import torch from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import floats_tensor, load_image, load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class A__ ( _lowerCamelCase , unittest.TestCase): A_ : str = ShapEImgaImgPipeline A_ : str = ['image'] A_ : int = ['image'] A_ : Tuple = [ 'num_images_per_prompt', 'num_inference_steps', 'generator', 'latents', 'guidance_scale', 'frame_size', 'output_type', 'return_dict', ] A_ : Tuple = False @property def __lowerCamelCase ( self ): return 32 @property def __lowerCamelCase ( self ): return 32 @property def __lowerCamelCase ( self ): return self.time_input_dim * 4 @property def __lowerCamelCase ( self ): return 8 @property def __lowerCamelCase ( self ): torch.manual_seed(0 ) __lowerCAmelCase : Any = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=64 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=1 , ) __lowerCAmelCase : Tuple = CLIPVisionModel(_SCREAMING_SNAKE_CASE ) return model @property def __lowerCamelCase ( self ): __lowerCAmelCase : Any = CLIPImageProcessor( crop_size=2_24 , do_center_crop=_SCREAMING_SNAKE_CASE , do_normalize=_SCREAMING_SNAKE_CASE , do_resize=_SCREAMING_SNAKE_CASE , image_mean=[0.4814_5466, 0.457_8275, 0.4082_1073] , image_std=[0.2686_2954, 0.2613_0258, 0.2757_7711] , resample=3 , size=2_24 , ) return image_processor @property def __lowerCamelCase ( self ): torch.manual_seed(0 ) __lowerCAmelCase : Optional[Any] = { 'num_attention_heads': 2, 'attention_head_dim': 16, 'embedding_dim': self.time_input_dim, 'num_embeddings': 32, 'embedding_proj_dim': self.text_embedder_hidden_size, 'time_embed_dim': self.time_embed_dim, 'num_layers': 1, 'clip_embed_dim': self.time_input_dim * 2, 'additional_embeddings': 0, 'time_embed_act_fn': 'gelu', 'norm_in_type': 'layer', 'embedding_proj_norm_type': 'layer', 'encoder_hid_proj_type': None, 'added_emb_type': None, } __lowerCAmelCase : List[Any] = PriorTransformer(**_SCREAMING_SNAKE_CASE ) return model @property def __lowerCamelCase ( self ): torch.manual_seed(0 ) __lowerCAmelCase : Dict = { 'param_shapes': ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), 'd_latent': self.time_input_dim, 'd_hidden': self.renderer_dim, 'n_output': 12, 'background': ( 0.1, 0.1, 0.1, ), } __lowerCAmelCase : int = ShapERenderer(**_SCREAMING_SNAKE_CASE ) return model def __lowerCamelCase ( self ): __lowerCAmelCase : Any = self.dummy_prior __lowerCAmelCase : List[Any] = self.dummy_image_encoder __lowerCAmelCase : int = self.dummy_image_processor __lowerCAmelCase : Any = self.dummy_renderer __lowerCAmelCase : Any = HeunDiscreteScheduler( beta_schedule='exp' , num_train_timesteps=10_24 , prediction_type='sample' , use_karras_sigmas=_SCREAMING_SNAKE_CASE , clip_sample=_SCREAMING_SNAKE_CASE , clip_sample_range=1.0 , ) __lowerCAmelCase : Tuple = { 'prior': prior, 'image_encoder': image_encoder, 'image_processor': image_processor, 'renderer': renderer, 'scheduler': scheduler, } return components def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=0 ): __lowerCAmelCase : Optional[Any] = floats_tensor((1, 3, 64, 64) , rng=random.Random(_SCREAMING_SNAKE_CASE ) ).to(_SCREAMING_SNAKE_CASE ) if str(_SCREAMING_SNAKE_CASE ).startswith('mps' ): __lowerCAmelCase : int = torch.manual_seed(_SCREAMING_SNAKE_CASE ) else: __lowerCAmelCase : str = torch.Generator(device=_SCREAMING_SNAKE_CASE ).manual_seed(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = { 'image': input_image, 'generator': generator, 'num_inference_steps': 1, 'frame_size': 32, 'output_type': 'np', } return inputs def __lowerCamelCase ( self ): __lowerCAmelCase : str = 'cpu' __lowerCAmelCase : Dict = self.get_dummy_components() __lowerCAmelCase : Optional[int] = self.pipeline_class(**_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = pipe.to(_SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = pipe(**self.get_dummy_inputs(_SCREAMING_SNAKE_CASE ) ) __lowerCAmelCase : Any = output.images[0] __lowerCAmelCase : Optional[Any] = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) __lowerCAmelCase : List[Any] = np.array( [ 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def __lowerCamelCase ( self ): # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def __lowerCamelCase ( self ): __lowerCAmelCase : str = torch_device == 'cpu' __lowerCAmelCase : Optional[Any] = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=_SCREAMING_SNAKE_CASE , relax_max_difference=_SCREAMING_SNAKE_CASE , ) def __lowerCamelCase ( self ): __lowerCAmelCase : str = self.get_dummy_components() __lowerCAmelCase : List[str] = self.pipeline_class(**_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = pipe.to(_SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = 1 __lowerCAmelCase : List[str] = 2 __lowerCAmelCase : Union[str, Any] = self.get_dummy_inputs(_SCREAMING_SNAKE_CASE ) for key in inputs.keys(): if key in self.batch_params: __lowerCAmelCase : Optional[Any] = batch_size * [inputs[key]] __lowerCAmelCase : List[str] = pipe(**_SCREAMING_SNAKE_CASE , num_images_per_prompt=_SCREAMING_SNAKE_CASE )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class A__ ( unittest.TestCase): def __lowerCamelCase ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCamelCase ( self ): __lowerCAmelCase : int = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/shap_e/corgi.png' ) __lowerCAmelCase : Any = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/shap_e/test_shap_e_img2img_out.npy' ) __lowerCAmelCase : Union[str, Any] = ShapEImgaImgPipeline.from_pretrained('openai/shap-e-img2img' ) __lowerCAmelCase : Dict = pipe.to(_SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Tuple = torch.Generator(device=_SCREAMING_SNAKE_CASE ).manual_seed(0 ) __lowerCAmelCase : int = pipe( _SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , guidance_scale=3.0 , num_inference_steps=64 , frame_size=64 , output_type='np' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
86
0
"""simple docstring""" import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( HubertConfig, HubertForCTC, HubertModel, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() _a = logging.get_logger(__name__) _a = { 'post_extract_proj': 'feature_projection.projection', 'encoder.pos_conv.0': 'encoder.pos_conv_embed.conv', 'self_attn.k_proj': 'encoder.layers.*.attention.k_proj', 'self_attn.v_proj': 'encoder.layers.*.attention.v_proj', 'self_attn.q_proj': 'encoder.layers.*.attention.q_proj', 'self_attn.out_proj': 'encoder.layers.*.attention.out_proj', 'self_attn_layer_norm': 'encoder.layers.*.layer_norm', 'fc1': 'encoder.layers.*.feed_forward.intermediate_dense', 'fc2': 'encoder.layers.*.feed_forward.output_dense', 'final_layer_norm': 'encoder.layers.*.final_layer_norm', 'encoder.layer_norm': 'encoder.layer_norm', 'w2v_model.layer_norm': 'feature_projection.layer_norm', 'w2v_encoder.proj': 'lm_head', 'mask_emb': 'masked_spec_embed', } def __a ( __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ): for attribute in key.split("." ): UpperCAmelCase_ : List[str] = getattr(__lowerCamelCase, __lowerCamelCase ) if weight_type is not None: UpperCAmelCase_ : List[str] = getattr(__lowerCamelCase, __lowerCamelCase ).shape else: UpperCAmelCase_ : Optional[Any] = hf_pointer.shape assert hf_shape == value.shape, ( f"""Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be""" f""" {value.shape} for {full_name}""" ) if weight_type == "weight": UpperCAmelCase_ : List[str] = value elif weight_type == "weight_g": UpperCAmelCase_ : List[str] = value elif weight_type == "weight_v": UpperCAmelCase_ : int = value elif weight_type == "bias": UpperCAmelCase_ : int = value else: UpperCAmelCase_ : Optional[int] = value logger.info(f"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def __a ( __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ): UpperCAmelCase_ : str = [] UpperCAmelCase_ : int = fairseq_model.state_dict() UpperCAmelCase_ : int = hf_model.hubert.feature_extractor if is_finetuned else hf_model.feature_extractor for name, value in fairseq_dict.items(): UpperCAmelCase_ : int = False if "conv_layers" in name: load_conv_layer( __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, hf_model.config.feat_extract_norm == "group", ) UpperCAmelCase_ : int = True else: for key, mapped_key in MAPPING.items(): UpperCAmelCase_ : List[str] = "hubert." + mapped_key if (is_finetuned and mapped_key != "lm_head") else mapped_key if key in name or (key.split("w2v_model." )[-1] == name.split("." )[0] and not is_finetuned): UpperCAmelCase_ : Union[str, Any] = True if "*" in mapped_key: UpperCAmelCase_ : Tuple = name.split(__lowerCamelCase )[0].split("." )[-2] UpperCAmelCase_ : List[Any] = mapped_key.replace("*", __lowerCamelCase ) if "weight_g" in name: UpperCAmelCase_ : Optional[Any] = "weight_g" elif "weight_v" in name: UpperCAmelCase_ : int = "weight_v" elif "weight" in name: UpperCAmelCase_ : List[Any] = "weight" elif "bias" in name: UpperCAmelCase_ : Union[str, Any] = "bias" else: UpperCAmelCase_ : Optional[int] = None set_recursively(__lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ) continue if not is_used: unused_weights.append(__lowerCamelCase ) logger.warning(f"""Unused weights: {unused_weights}""" ) def __a ( __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ): UpperCAmelCase_ : Optional[Any] = full_name.split("conv_layers." )[-1] UpperCAmelCase_ : Tuple = name.split("." ) UpperCAmelCase_ : int = int(items[0] ) UpperCAmelCase_ : Optional[int] = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) UpperCAmelCase_ : int = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) UpperCAmelCase_ : Optional[Any] = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( f"""{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was""" " found." ) UpperCAmelCase_ : Optional[int] = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.""" ) UpperCAmelCase_ : Any = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(__lowerCamelCase ) @torch.no_grad() def __a ( __lowerCamelCase, __lowerCamelCase, __lowerCamelCase=None, __lowerCamelCase=None, __lowerCamelCase=True ): if config_path is not None: UpperCAmelCase_ : Any = HubertConfig.from_pretrained(__lowerCamelCase ) else: UpperCAmelCase_ : Dict = HubertConfig() if is_finetuned: if dict_path: UpperCAmelCase_ : str = Dictionary.load(__lowerCamelCase ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq UpperCAmelCase_ : str = target_dict.pad_index UpperCAmelCase_ : int = target_dict.bos_index UpperCAmelCase_ : List[str] = target_dict.eos_index UpperCAmelCase_ : Optional[Any] = len(target_dict.symbols ) UpperCAmelCase_ : int = os.path.join(__lowerCamelCase, "vocab.json" ) if not os.path.isdir(__lowerCamelCase ): logger.error("--pytorch_dump_folder_path ({}) should be a directory".format(__lowerCamelCase ) ) return os.makedirs(__lowerCamelCase, exist_ok=__lowerCamelCase ) with open(__lowerCamelCase, "w", encoding="utf-8" ) as vocab_handle: json.dump(target_dict.indices, __lowerCamelCase ) UpperCAmelCase_ : List[Any] = WavaVecaCTCTokenizer( __lowerCamelCase, unk_token=target_dict.unk_word, pad_token=target_dict.pad_word, bos_token=target_dict.bos_word, eos_token=target_dict.eos_word, word_delimiter_token="|", do_lower_case=__lowerCamelCase, ) UpperCAmelCase_ : int = True if config.feat_extract_norm == "layer" else False UpperCAmelCase_ : Dict = WavaVecaFeatureExtractor( feature_size=1, sampling_rate=1_6000, padding_value=0, do_normalize=__lowerCamelCase, return_attention_mask=__lowerCamelCase, ) UpperCAmelCase_ : Tuple = WavaVecaProcessor(feature_extractor=__lowerCamelCase, tokenizer=__lowerCamelCase ) processor.save_pretrained(__lowerCamelCase ) UpperCAmelCase_ : List[Any] = HubertForCTC(__lowerCamelCase ) else: UpperCAmelCase_ : str = HubertModel(__lowerCamelCase ) if is_finetuned: UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : Tuple = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path], arg_overrides={"data": "/".join(dict_path.split("/" )[:-1] )} ) else: UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : str = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ) UpperCAmelCase_ : int = model[0].eval() recursively_load_weights(__lowerCamelCase, __lowerCamelCase, __lowerCamelCase ) hf_wavavec.save_pretrained(__lowerCamelCase ) if __name__ == "__main__": _a = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint') parser.add_argument('--dict_path', default=None, type=str, help='Path to dict of fine-tuned model') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') parser.add_argument( '--not_finetuned', action='store_true', help='Whether the model to convert is a fine-tuned model or not' ) _a = parser.parse_args() convert_hubert_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
61
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase__ = {"""configuration_fnet""": ["""FNET_PRETRAINED_CONFIG_ARCHIVE_MAP""", """FNetConfig"""]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = ["""FNetTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = ["""FNetTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ """FNET_PRETRAINED_MODEL_ARCHIVE_LIST""", """FNetForMaskedLM""", """FNetForMultipleChoice""", """FNetForNextSentencePrediction""", """FNetForPreTraining""", """FNetForQuestionAnswering""", """FNetForSequenceClassification""", """FNetForTokenClassification""", """FNetLayer""", """FNetModel""", """FNetPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_fnet import FNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet import FNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet_fast import FNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_fnet import ( FNET_PRETRAINED_MODEL_ARCHIVE_LIST, FNetForMaskedLM, FNetForMultipleChoice, FNetForNextSentencePrediction, FNetForPreTraining, FNetForQuestionAnswering, FNetForSequenceClassification, FNetForTokenClassification, FNetLayer, FNetModel, FNetPreTrainedModel, ) else: import sys lowerCamelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
86
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) _A = { 'configuration_lxmert': ['LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LxmertConfig'], 'tokenization_lxmert': ['LxmertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = ['LxmertTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'LxmertEncoder', 'LxmertForPreTraining', 'LxmertForQuestionAnswering', 'LxmertModel', 'LxmertPreTrainedModel', 'LxmertVisualFeatureEncoder', 'LxmertXLayer', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'TF_LXMERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFLxmertForPreTraining', 'TFLxmertMainLayer', 'TFLxmertModel', 'TFLxmertPreTrainedModel', 'TFLxmertVisualFeatureEncoder', ] if TYPE_CHECKING: from .configuration_lxmert import LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, LxmertConfig from .tokenization_lxmert import LxmertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_lxmert_fast import LxmertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_lxmert import ( LxmertEncoder, LxmertForPreTraining, LxmertForQuestionAnswering, LxmertModel, LxmertPreTrainedModel, LxmertVisualFeatureEncoder, LxmertXLayer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_lxmert import ( TF_LXMERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFLxmertForPreTraining, TFLxmertMainLayer, TFLxmertModel, TFLxmertPreTrainedModel, TFLxmertVisualFeatureEncoder, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
"""simple docstring""" import math import sys def __lowerCAmelCase (_UpperCamelCase ): if number != int(_UpperCamelCase ): raise ValueError('the value of input must be a natural number' ) if number < 0: raise ValueError('the value of input must not be a negative number' ) if number == 0: return 1 __lowerCAmelCase : Any = [-1] * (number + 1) __lowerCAmelCase : List[Any] = 0 for i in range(1 , number + 1 ): __lowerCAmelCase : List[Any] = sys.maxsize __lowerCAmelCase : Optional[int] = int(math.sqrt(_UpperCamelCase ) ) for j in range(1 , root + 1 ): __lowerCAmelCase : Optional[Any] = 1 + answers[i - (j**2)] __lowerCAmelCase : Any = min(_UpperCamelCase , _UpperCamelCase ) __lowerCAmelCase : List[str] = answer return answers[number] if __name__ == "__main__": import doctest doctest.testmod()
86
0
'''simple docstring''' import logging from pathlib import Path import numpy as np import pytorch_lightning as pl import torch from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint from pytorch_lightning.utilities import rank_zero_only from utils_rag import save_json def _lowerCamelCase ( lowercase : Dict ) -> Any: _a = filter(lambda lowercase : p.requires_grad , model.parameters() ) _a = sum([np.prod(p.size() ) for p in model_parameters] ) return params lowerCAmelCase_ : int = logging.getLogger(__name__) def _lowerCamelCase ( lowercase : List[Any] , lowercase : Any ) -> Any: if metric == "rouge2": _a = "{val_avg_rouge2:.4f}-{step_count}" elif metric == "bleu": _a = "{val_avg_bleu:.4f}-{step_count}" elif metric == "em": _a = "{val_avg_em:.4f}-{step_count}" else: raise NotImplementedError( F'seq2seq callbacks only support rouge2 and bleu, got {metric}, You can make your own by adding to this' " function." ) _a = ModelCheckpoint( dirpath=lowercase , filename=lowercase , monitor=F'val_{metric}' , mode="max" , save_top_k=3 , every_n_epochs=1 , ) return checkpoint_callback def _lowerCamelCase ( lowercase : Optional[int] , lowercase : Optional[int] ) -> Union[str, Any]: return EarlyStopping( monitor=F'val_{metric}' , mode="min" if "loss" in metric else "max" , patience=lowercase , verbose=lowercase , ) class __SCREAMING_SNAKE_CASE (pl.Callback ): """simple docstring""" def UpperCamelCase__ ( self : Optional[int] , __a : str , __a : List[Any] ): _a = {f'lr_group_{i}': param["lr"] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups )} pl_module.logger.log_metrics(__a ) @rank_zero_only def UpperCamelCase__ ( self : Optional[int] , __a : pl.Trainer , __a : pl.LightningModule , __a : str , __a : Tuple=True ): logger.info(f'***** {type_path} results at step {trainer.global_step:05d} *****' ) _a = trainer.callback_metrics trainer.logger.log_metrics({k: v for k, v in metrics.items() if k not in ["log", "progress_bar", "preds"]} ) # Log results _a = Path(pl_module.hparams.output_dir ) if type_path == "test": _a = od / "test_results.txt" _a = od / "test_generations.txt" else: # this never gets hit. I prefer not to save intermediate generations, and results are in metrics.json # If people want this it will be easy enough to add back. _a = od / f'{type_path}_results/{trainer.global_step:05d}.txt' _a = od / f'{type_path}_generations/{trainer.global_step:05d}.txt' results_file.parent.mkdir(exist_ok=__a ) generations_file.parent.mkdir(exist_ok=__a ) with open(__a , "a+" ) as writer: for key in sorted(__a ): if key in ["log", "progress_bar", "preds"]: continue _a = metrics[key] if isinstance(__a , torch.Tensor ): _a = val.item() _a = f'{key}: {val:.6f}\n' writer.write(__a ) if not save_generations: return if "preds" in metrics: _a = "\n".join(metrics["preds"] ) generations_file.open("w+" ).write(__a ) @rank_zero_only def UpperCamelCase__ ( self : int , __a : List[Any] , __a : Union[str, Any] ): try: _a = pl_module.model.model.num_parameters() except AttributeError: _a = pl_module.model.num_parameters() _a = count_trainable_parameters(__a ) # mp stands for million parameters trainer.logger.log_metrics({"n_params": npars, "mp": npars / 1e6, "grad_mp": n_trainable_pars / 1e6} ) @rank_zero_only def UpperCamelCase__ ( self : Union[str, Any] , __a : pl.Trainer , __a : pl.LightningModule ): save_json(pl_module.metrics , pl_module.metrics_save_path ) return self._write_logs(__a , __a , "test" ) @rank_zero_only def UpperCamelCase__ ( self : Any , __a : pl.Trainer , __a : int ): save_json(pl_module.metrics , pl_module.metrics_save_path ) # Uncommenting this will save val generations # return self._write_logs(trainer, pl_module, "valid")
63
"""simple docstring""" import tempfile import unittest import numpy as np import transformers from transformers import GPTaTokenizer, GPTJConfig, is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax, tooslow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax import jax.numpy as jnp from transformers.modeling_flax_pytorch_utils import ( convert_pytorch_state_dict_to_flax, load_flax_weights_in_pytorch_model, ) from transformers.models.gptj.modeling_flax_gptj import FlaxGPTJForCausalLM, FlaxGPTJModel if is_torch_available(): import torch class A__ : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=14 , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=99 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=37 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=5_12 , _SCREAMING_SNAKE_CASE=0.02 , ): __lowerCAmelCase : Union[str, Any] = parent __lowerCAmelCase : Any = batch_size __lowerCAmelCase : Any = seq_length __lowerCAmelCase : Optional[Any] = is_training __lowerCAmelCase : Any = use_input_mask __lowerCAmelCase : Any = use_token_type_ids __lowerCAmelCase : Tuple = use_labels __lowerCAmelCase : Optional[Any] = vocab_size __lowerCAmelCase : Tuple = hidden_size __lowerCAmelCase : str = rotary_dim __lowerCAmelCase : Union[str, Any] = num_hidden_layers __lowerCAmelCase : Union[str, Any] = num_attention_heads __lowerCAmelCase : int = intermediate_size __lowerCAmelCase : List[str] = hidden_act __lowerCAmelCase : int = hidden_dropout_prob __lowerCAmelCase : Any = attention_probs_dropout_prob __lowerCAmelCase : List[Any] = max_position_embeddings __lowerCAmelCase : Optional[Any] = initializer_range __lowerCAmelCase : Tuple = None __lowerCAmelCase : int = vocab_size - 1 __lowerCAmelCase : Dict = vocab_size - 1 __lowerCAmelCase : int = vocab_size - 1 def __lowerCamelCase ( self ): __lowerCAmelCase : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __lowerCAmelCase : List[str] = None if self.use_input_mask: __lowerCAmelCase : Dict = random_attention_mask([self.batch_size, self.seq_length] ) __lowerCAmelCase : Optional[int] = GPTJConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , use_cache=_SCREAMING_SNAKE_CASE , bos_token_id=self.bos_token_id , eos_token_id=self.eos_token_id , pad_token_id=self.pad_token_id , rotary_dim=self.rotary_dim , ) return (config, input_ids, input_mask) def __lowerCamelCase ( self ): __lowerCAmelCase : Optional[int] = self.prepare_config_and_inputs() __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase : Any = config_and_inputs __lowerCAmelCase : Dict = {'input_ids': input_ids, 'attention_mask': attention_mask} return config, inputs_dict def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : List[str] = 20 __lowerCAmelCase : List[str] = model_class_name(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = model.init_cache(input_ids.shape[0] , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = jnp.ones((input_ids.shape[0], max_decoder_length) , dtype='i4' ) __lowerCAmelCase : Optional[Any] = jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1 )[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1) ) __lowerCAmelCase : Any = model( input_ids[:, :-1] , attention_mask=_SCREAMING_SNAKE_CASE , past_key_values=_SCREAMING_SNAKE_CASE , position_ids=_SCREAMING_SNAKE_CASE , ) __lowerCAmelCase : Any = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype='i4' ) __lowerCAmelCase : int = model( input_ids[:, -1:] , attention_mask=_SCREAMING_SNAKE_CASE , past_key_values=outputs_cache.past_key_values , position_ids=_SCREAMING_SNAKE_CASE , ) __lowerCAmelCase : Any = model(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=f"Max diff is {diff}" ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Tuple = 20 __lowerCAmelCase : List[str] = model_class_name(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Union[str, Any] = jnp.concatenate( [attention_mask, jnp.zeros((attention_mask.shape[0], max_decoder_length - attention_mask.shape[1]) )] , axis=-1 , ) __lowerCAmelCase : List[str] = model.init_cache(input_ids.shape[0] , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : str = jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1 )[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1) ) __lowerCAmelCase : Optional[Any] = model( input_ids[:, :-1] , attention_mask=_SCREAMING_SNAKE_CASE , past_key_values=_SCREAMING_SNAKE_CASE , position_ids=_SCREAMING_SNAKE_CASE , ) __lowerCAmelCase : str = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype='i4' ) __lowerCAmelCase : Tuple = model( input_ids[:, -1:] , past_key_values=outputs_cache.past_key_values , attention_mask=_SCREAMING_SNAKE_CASE , position_ids=_SCREAMING_SNAKE_CASE , ) __lowerCAmelCase : Union[str, Any] = model(_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=f"Max diff is {diff}" ) @require_flax class A__ ( _lowerCamelCase , _lowerCamelCase , unittest.TestCase): A_ : Tuple = (FlaxGPTJModel, FlaxGPTJForCausalLM) if is_flax_available() else () A_ : str = (FlaxGPTJForCausalLM,) if is_flax_available() else () def __lowerCamelCase ( self ): __lowerCAmelCase : int = FlaxGPTJModelTester(self ) def __lowerCamelCase ( self ): for model_class_name in self.all_model_classes: __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): for model_class_name in self.all_model_classes: __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward_with_attn_mask( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @tooslow def __lowerCamelCase ( self ): __lowerCAmelCase : Tuple = GPTaTokenizer.from_pretrained('gpt2' , pad_token='<|endoftext|>' , padding_side='left' ) __lowerCAmelCase : Optional[int] = tokenizer(['Hello this is a long string', 'Hey'] , return_tensors='np' , padding=_SCREAMING_SNAKE_CASE , truncation=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : int = FlaxGPTJForCausalLM.from_pretrained('EleutherAI/gpt-j-6B' ) __lowerCAmelCase : Any = False __lowerCAmelCase : Any = model.config.eos_token_id __lowerCAmelCase : Union[str, Any] = jax.jit(model.generate ) __lowerCAmelCase : Optional[Any] = jit_generate( inputs['input_ids'] , attention_mask=inputs['attention_mask'] , pad_token_id=tokenizer.pad_token_id ).sequences __lowerCAmelCase : str = tokenizer.batch_decode(_SCREAMING_SNAKE_CASE , skip_special_tokens=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = [ 'Hello this is a long string of text.\n\nI\'m trying to get the text of the', 'Hey, I\'m a little late to the party. I\'m going to', ] self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @is_pt_flax_cross_test def __lowerCamelCase ( self ): __lowerCAmelCase , __lowerCAmelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): # prepare inputs __lowerCAmelCase : str = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Union[str, Any] = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class __lowerCAmelCase : Dict = model_class.__name__[4:] # Skip the "Flax" at the beginning __lowerCAmelCase : Optional[int] = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase , __lowerCAmelCase : List[Any] = pt_inputs['input_ids'].shape __lowerCAmelCase : int = np.random.randint(0 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(_SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Tuple = 0 __lowerCAmelCase : Tuple = 1 __lowerCAmelCase : List[str] = 0 __lowerCAmelCase : Any = 1 __lowerCAmelCase : Optional[Any] = pt_model_class(_SCREAMING_SNAKE_CASE ).eval() __lowerCAmelCase : Any = model_class(_SCREAMING_SNAKE_CASE , dtype=jnp.floataa ) __lowerCAmelCase : int = convert_pytorch_state_dict_to_flax(pt_model.state_dict() , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : str = fx_state with torch.no_grad(): __lowerCAmelCase : Union[str, Any] = pt_model(**_SCREAMING_SNAKE_CASE ).to_tuple() __lowerCAmelCase : str = fx_model(**_SCREAMING_SNAKE_CASE ).to_tuple() self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , len(_SCREAMING_SNAKE_CASE ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output, pt_output in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) with tempfile.TemporaryDirectory() as tmpdirname: pt_model.save_pretrained(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Tuple = model_class.from_pretrained(_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = fx_model_loaded(**_SCREAMING_SNAKE_CASE ).to_tuple() self.assertEqual( len(_SCREAMING_SNAKE_CASE ) , len(_SCREAMING_SNAKE_CASE ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output_loaded, pt_output in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): self.assert_almost_equals(fx_output_loaded[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) @is_pt_flax_cross_test def __lowerCamelCase ( self ): __lowerCAmelCase , __lowerCAmelCase : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): # prepare inputs __lowerCAmelCase : List[str] = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class __lowerCAmelCase : Dict = model_class.__name__[4:] # Skip the "Flax" at the beginning __lowerCAmelCase : str = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = pt_model_class(_SCREAMING_SNAKE_CASE ).eval() __lowerCAmelCase : Tuple = model_class(_SCREAMING_SNAKE_CASE , dtype=jnp.floataa ) __lowerCAmelCase : List[str] = load_flax_weights_in_pytorch_model(_SCREAMING_SNAKE_CASE , fx_model.params ) __lowerCAmelCase , __lowerCAmelCase : int = pt_inputs['input_ids'].shape __lowerCAmelCase : List[str] = np.random.randint(0 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(_SCREAMING_SNAKE_CASE ): __lowerCAmelCase : str = 0 __lowerCAmelCase : Optional[Any] = 1 __lowerCAmelCase : Optional[int] = 0 __lowerCAmelCase : Optional[Any] = 1 # make sure weights are tied in PyTorch pt_model.tie_weights() with torch.no_grad(): __lowerCAmelCase : List[str] = pt_model(**_SCREAMING_SNAKE_CASE ).to_tuple() __lowerCAmelCase : Optional[int] = fx_model(**_SCREAMING_SNAKE_CASE ).to_tuple() self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , len(_SCREAMING_SNAKE_CASE ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output, pt_output in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) with tempfile.TemporaryDirectory() as tmpdirname: fx_model.save_pretrained(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = pt_model_class.from_pretrained(_SCREAMING_SNAKE_CASE , from_flax=_SCREAMING_SNAKE_CASE ) with torch.no_grad(): __lowerCAmelCase : Any = pt_model_loaded(**_SCREAMING_SNAKE_CASE ).to_tuple() self.assertEqual( len(_SCREAMING_SNAKE_CASE ) , len(_SCREAMING_SNAKE_CASE ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output, pt_output in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) @tooslow def __lowerCamelCase ( self ): for model_class_name in self.all_model_classes: __lowerCAmelCase : Optional[int] = model_class_name.from_pretrained('EleutherAI/gpt-j-6B' ) __lowerCAmelCase : List[Any] = model(np.ones((1, 1) ) ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE )
86
0
"""simple docstring""" import argparse import json import os import fairseq import torch from torch import nn from transformers import ( SpeechaTextaConfig, SpeechaTextaForCausalLM, SpeechaTextaTokenizer, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaModel, logging, ) logging.set_verbosity_info() A_ = logging.get_logger(__name__) A_ = { '''post_extract_proj''': '''feature_projection.projection''', '''encoder.pos_conv.0''': '''encoder.pos_conv_embed.conv''', '''self_attn.k_proj''': '''encoder.layers.*.attention.k_proj''', '''self_attn.v_proj''': '''encoder.layers.*.attention.v_proj''', '''self_attn.q_proj''': '''encoder.layers.*.attention.q_proj''', '''self_attn.out_proj''': '''encoder.layers.*.attention.out_proj''', '''self_attn_layer_norm''': '''encoder.layers.*.layer_norm''', '''fc1''': '''encoder.layers.*.feed_forward.intermediate_dense''', '''fc2''': '''encoder.layers.*.feed_forward.output_dense''', '''final_layer_norm''': '''encoder.layers.*.final_layer_norm''', '''encoder.layer_norm''': '''encoder.layer_norm''', '''w2v_model.layer_norm''': '''feature_projection.layer_norm''', '''quantizer.weight_proj''': '''quantizer.weight_proj''', '''quantizer.vars''': '''quantizer.codevectors''', '''project_q''': '''project_q''', '''final_proj''': '''project_hid''', '''w2v_encoder.proj''': '''lm_head''', '''mask_emb''': '''masked_spec_embed''', } A_ = [ '''lm_head''', '''quantizer.weight_proj''', '''quantizer.codevectors''', '''project_q''', '''project_hid''', ] def UpperCAmelCase__ (snake_case__ : str , snake_case__ : Dict , snake_case__ : Any , snake_case__ : str , snake_case__ : str ): """simple docstring""" for attribute in key.split(""".""" ): _snake_case : Optional[Any] = getattr(snake_case__ , snake_case__ ) if weight_type is not None: _snake_case : Optional[Any] = getattr(snake_case__ , snake_case__ ).shape else: _snake_case : Optional[Any] = hf_pointer.shape assert hf_shape == value.shape, ( F"Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be" F" {value.shape} for {full_name}" ) if weight_type == "weight": _snake_case : int = value elif weight_type == "weight_g": _snake_case : str = value elif weight_type == "weight_v": _snake_case : Tuple = value elif weight_type == "bias": _snake_case : List[str] = value else: _snake_case : int = value logger.info(F"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}." ) def UpperCAmelCase__ (snake_case__ : str , snake_case__ : List[str] ): """simple docstring""" _snake_case : List[Any] = [] _snake_case : Optional[Any] = fairseq_model.state_dict() _snake_case : str = hf_model.feature_extractor # if encoder has different dim to decoder -> use proj_weight _snake_case : Optional[Any] = None for name, value in fairseq_dict.items(): _snake_case : Optional[Any] = False if "conv_layers" in name: load_conv_layer( snake_case__ , snake_case__ , snake_case__ , snake_case__ , hf_model.config.feat_extract_norm == """group""" , ) _snake_case : Dict = True elif name.split(""".""" )[0] == "proj": _snake_case : Dict = fairseq_model.proj _snake_case : Optional[int] = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0]: _snake_case : Dict = True if "*" in mapped_key: _snake_case : Optional[int] = name.split(snake_case__ )[0].split(""".""" )[-2] _snake_case : Union[str, Any] = mapped_key.replace("""*""" , snake_case__ ) if "weight_g" in name: _snake_case : str = """weight_g""" elif "weight_v" in name: _snake_case : Optional[Any] = """weight_v""" elif "bias" in name: _snake_case : Union[str, Any] = """bias""" elif "weight" in name: _snake_case : int = """weight""" else: _snake_case : Optional[int] = None set_recursively(snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) continue if not is_used: unused_weights.append(snake_case__ ) logger.warning(F"Unused weights: {unused_weights}" ) return proj_weight def UpperCAmelCase__ (snake_case__ : Any , snake_case__ : Dict , snake_case__ : Union[str, Any] , snake_case__ : Union[str, Any] , snake_case__ : int ): """simple docstring""" _snake_case : Any = full_name.split("""conv_layers.""" )[-1] _snake_case : Optional[int] = name.split(""".""" ) _snake_case : List[str] = int(items[0] ) _snake_case : Dict = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( F"{full_name} has size {value.shape}, but" F" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found." ) _snake_case : Tuple = value logger.info(F"Feat extract conv layer {layer_id} was initialized from {full_name}." ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( F"{full_name} has size {value.shape}, but" F" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found." ) _snake_case : List[Any] = value logger.info(F"Feat extract conv layer {layer_id} was initialized from {full_name}." ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( F"{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was" " found." ) _snake_case : int = value logger.info(F"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( F"{full_name} has size {value.shape}, but" F" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found." ) _snake_case : List[str] = value logger.info(F"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) else: unused_weights.append(snake_case__ ) def UpperCAmelCase__ (snake_case__ : Union[str, Any] ): """simple docstring""" _snake_case , _snake_case : Optional[Any] = emb.weight.shape _snake_case : Optional[int] = nn.Linear(snake_case__ , snake_case__ , bias=snake_case__ ) _snake_case : Union[str, Any] = emb.weight.data return lin_layer def UpperCAmelCase__ (snake_case__ : List[Any] ): """simple docstring""" with open(snake_case__ , """r""" , encoding="""utf-8""" ) as f: _snake_case : Any = f.readlines() _snake_case : Optional[Any] = [line.split(""" """ )[0] for line in lines] _snake_case : str = len(snake_case__ ) _snake_case : Tuple = { """<s>""": 0, """<pad>""": 1, """</s>""": 2, """<unk>""": 3, } vocab_dict.update(dict(zip(snake_case__ , range(4 , num_words + 4 ) ) ) ) return vocab_dict @torch.no_grad() def UpperCAmelCase__ (snake_case__ : int , snake_case__ : List[str] , snake_case__ : int , snake_case__ : Dict , snake_case__ : List[Any] , snake_case__ : str , snake_case__ : Union[str, Any] , ): """simple docstring""" _snake_case : Optional[int] = WavaVecaConfig.from_pretrained(snake_case__ ) _snake_case : List[str] = SpeechaTextaConfig.from_pretrained( snake_case__ , vocab_size=snake_case__ , decoder_layers=snake_case__ , do_stable_layer_norm=snake_case__ ) _snake_case : Dict = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_60_00 , padding_value=0 , do_normalize=snake_case__ , return_attention_mask=snake_case__ , ) _snake_case , _snake_case , _snake_case : Optional[int] = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"""data""": """/""".join(dict_path.split("""/""" )[:-1] )} ) _snake_case : Optional[Any] = model[0].eval() # set weights for wav2vec2 encoder _snake_case : Any = WavaVecaModel(snake_case__ ) _snake_case : Optional[Any] = recursively_load_weights_wavaveca(model.encoder , snake_case__ ) _snake_case : Optional[Any] = SpeechaTextaForCausalLM(snake_case__ ) _snake_case , _snake_case : List[str] = hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict() , strict=snake_case__ ) # set output linear layer unexpected_keys.remove("""embed_out""" ) _snake_case : Any = nn.Parameter(model.decoder.embed_out.detach() ) # layer norm is init to identity matrix so leaving it is fine logger.warning(F"The following keys are missing when loading the decoder weights: {missing_keys}" ) logger.warning(F"The following keys are unexpected when loading the decoder weights: {unexpected_keys}" ) _snake_case : Any = SpeechEncoderDecoderModel(encoder=snake_case__ , decoder=snake_case__ ) _snake_case : Any = False # add projection layer _snake_case : int = nn.Parameter(projection_layer.weight ) _snake_case : Any = nn.Parameter(projection_layer.bias ) _snake_case : Any = create_vocab_dict(snake_case__ ) with open(os.path.join(snake_case__ , """vocab.json""" ) , """w""" ) as fp: json.dump(snake_case__ , snake_case__ ) _snake_case : Dict = SpeechaTextaTokenizer(os.path.join(snake_case__ , """vocab.json""" ) ) tokenizer.save_pretrained(snake_case__ ) _snake_case : str = hf_wavavec.config.to_dict() _snake_case : List[str] = tokenizer.pad_token_id _snake_case : Union[str, Any] = tokenizer.bos_token_id _snake_case : Union[str, Any] = tokenizer.eos_token_id _snake_case : Optional[Any] = """speech_to_text_2""" _snake_case : Optional[int] = """wav2vec2""" _snake_case : Tuple = SpeechEncoderDecoderConfig.from_dict(snake_case__ ) hf_wavavec.save_pretrained(snake_case__ ) feature_extractor.save_pretrained(snake_case__ ) if __name__ == "__main__": A_ = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--dict_path''', default=None, type=str, help='''Path to dict of fine-tuned model''') parser.add_argument( '''--encoder_config_path''', default='''facebook/wav2vec2-large-lv60''', type=str, help='''Path to hf encoder wav2vec2 checkpoint config''', ) parser.add_argument( '''--decoder_config_path''', default='''facebook/s2t-small-mustc-en-fr-st''', type=str, help='''Path to hf decoder s2t checkpoint config''', ) parser.add_argument('''--vocab_size''', default=1_02_24, type=int, help='''Vocab size of decoder''') parser.add_argument('''--num_decoder_layers''', default=7, type=int, help='''Number of decoder layers''') A_ = parser.parse_args() convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.dict_path, encoder_config_path=args.encoder_config_path, decoder_config_path=args.decoder_config_path, vocab_size=args.vocab_size, num_decoder_layers=args.num_decoder_layers, )
64
"""simple docstring""" 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 , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=13 , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=99 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=37 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=5_12 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=None , ): __lowerCAmelCase : Tuple = parent __lowerCAmelCase : Optional[int] = 13 __lowerCAmelCase : List[Any] = 7 __lowerCAmelCase : int = True __lowerCAmelCase : Optional[int] = True __lowerCAmelCase : List[Any] = True __lowerCAmelCase : Optional[int] = True __lowerCAmelCase : Optional[Any] = 99 __lowerCAmelCase : int = 3_84 __lowerCAmelCase : Union[str, Any] = 2 __lowerCAmelCase : Tuple = 4 __lowerCAmelCase : str = 37 __lowerCAmelCase : Any = 'gelu' __lowerCAmelCase : List[str] = 0.1 __lowerCAmelCase : Any = 0.1 __lowerCAmelCase : Union[str, Any] = 5_12 __lowerCAmelCase : int = 16 __lowerCAmelCase : Union[str, Any] = 2 __lowerCAmelCase : int = 0.02 __lowerCAmelCase : Dict = 3 __lowerCAmelCase : Tuple = 4 __lowerCAmelCase : Tuple = 1_28 __lowerCAmelCase : Optional[int] = 2 __lowerCAmelCase : List[str] = 9 __lowerCAmelCase : int = 1 __lowerCAmelCase : int = None def __lowerCamelCase ( self ): __lowerCAmelCase : Any = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __lowerCAmelCase : Optional[int] = None if self.use_input_mask: __lowerCAmelCase : str = random_attention_mask([self.batch_size, self.seq_length] ) __lowerCAmelCase : Tuple = None if self.use_token_type_ids: __lowerCAmelCase : Dict = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __lowerCAmelCase : Optional[Any] = None __lowerCAmelCase : Dict = None __lowerCAmelCase : Union[str, Any] = None if self.use_labels: __lowerCAmelCase : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCAmelCase : Dict = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __lowerCAmelCase : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) __lowerCAmelCase : Union[str, 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=_SCREAMING_SNAKE_CASE , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Optional[int] = TFConvBertModel(config=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids} __lowerCAmelCase : Tuple = [input_ids, input_mask] __lowerCAmelCase : Any = model(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Any = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Any = TFConvBertForMaskedLM(config=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } __lowerCAmelCase : Optional[Any] = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Tuple = self.num_labels __lowerCAmelCase : Optional[Any] = TFConvBertForSequenceClassification(config=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : int = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } __lowerCAmelCase : Union[str, Any] = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : int = self.num_choices __lowerCAmelCase : List[str] = TFConvBertForMultipleChoice(config=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = tf.tile(tf.expand_dims(_SCREAMING_SNAKE_CASE , 1 ) , (1, self.num_choices, 1) ) __lowerCAmelCase : Dict = tf.tile(tf.expand_dims(_SCREAMING_SNAKE_CASE , 1 ) , (1, self.num_choices, 1) ) __lowerCAmelCase : Union[str, Any] = tf.tile(tf.expand_dims(_SCREAMING_SNAKE_CASE , 1 ) , (1, self.num_choices, 1) ) __lowerCAmelCase : Tuple = { 'input_ids': multiple_choice_inputs_ids, 'attention_mask': multiple_choice_input_mask, 'token_type_ids': multiple_choice_token_type_ids, } __lowerCAmelCase : str = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : str = self.num_labels __lowerCAmelCase : Any = TFConvBertForTokenClassification(config=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } __lowerCAmelCase : Union[str, Any] = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : str = TFConvBertForQuestionAnswering(config=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Union[str, Any] = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } __lowerCAmelCase : Optional[int] = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __lowerCamelCase ( self ): __lowerCAmelCase : Union[str, Any] = self.prepare_config_and_inputs() ( ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ) : List[str] = config_and_inputs __lowerCAmelCase : Any = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_tf class A__ ( _lowerCamelCase , _lowerCamelCase , unittest.TestCase): A_ : List[str] = ( ( TFConvBertModel, TFConvBertForMaskedLM, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertForMultipleChoice, ) if is_tf_available() else () ) A_ : str = ( { 'feature-extraction': TFConvBertModel, 'fill-mask': TFConvBertForMaskedLM, 'question-answering': TFConvBertForQuestionAnswering, 'text-classification': TFConvBertForSequenceClassification, 'token-classification': TFConvBertForTokenClassification, 'zero-shot': TFConvBertForSequenceClassification, } if is_tf_available() else {} ) A_ : List[Any] = False A_ : str = False A_ : List[Any] = False def __lowerCamelCase ( self ): __lowerCAmelCase : Dict = TFConvBertModelTester(self ) __lowerCAmelCase : Any = ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , hidden_size=37 ) def __lowerCamelCase ( self ): self.config_tester.run_common_tests() def __lowerCamelCase ( self ): __lowerCAmelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_SCREAMING_SNAKE_CASE ) @slow def __lowerCamelCase ( self ): __lowerCAmelCase , __lowerCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() __lowerCAmelCase : Any = True __lowerCAmelCase : Dict = True if hasattr(_SCREAMING_SNAKE_CASE , 'use_cache' ): __lowerCAmelCase : int = True __lowerCAmelCase : List[str] = getattr(self.model_tester , 'encoder_seq_length' , self.model_tester.seq_length ) __lowerCAmelCase : str = getattr(self.model_tester , 'key_length' , _SCREAMING_SNAKE_CASE ) for model_class in self.all_model_classes: __lowerCAmelCase : str = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : str = model_class(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = len(model(_SCREAMING_SNAKE_CASE ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(_SCREAMING_SNAKE_CASE , saved_model=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = os.path.join(_SCREAMING_SNAKE_CASE , 'saved_model' , '1' ) __lowerCAmelCase : int = tf.keras.models.load_model(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = model(_SCREAMING_SNAKE_CASE ) if self.is_encoder_decoder: __lowerCAmelCase : List[str] = outputs['encoder_hidden_states'] __lowerCAmelCase : Tuple = outputs['encoder_attentions'] else: __lowerCAmelCase : Optional[int] = outputs['hidden_states'] __lowerCAmelCase : Tuple = outputs['attentions'] self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Union[str, Any] = getattr( self.model_tester , 'expected_num_hidden_layers' , self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) self.assertListEqual( list(output_hidden_states[0].shape[-2:] ) , [self.model_tester.seq_length, self.model_tester.hidden_size] , ) self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , 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 __lowerCamelCase ( self ): __lowerCAmelCase : Tuple = TFConvBertModel.from_pretrained('YituTech/conv-bert-base' ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase , __lowerCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs_for_common() __lowerCAmelCase : Optional[Any] = True __lowerCAmelCase : List[Any] = getattr(self.model_tester , 'decoder_seq_length' , self.model_tester.seq_length ) __lowerCAmelCase : str = getattr(self.model_tester , 'encoder_seq_length' , self.model_tester.seq_length ) __lowerCAmelCase : Tuple = getattr(self.model_tester , 'key_length' , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = getattr(self.model_tester , 'key_length' , _SCREAMING_SNAKE_CASE ) def check_decoder_attentions_output(_SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Union[str, Any] = len(_SCREAMING_SNAKE_CASE ) self.assertEqual(out_len % 2 , 0 ) __lowerCAmelCase : Optional[Any] = outputs.decoder_attentions self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , 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(_SCREAMING_SNAKE_CASE ): __lowerCAmelCase : str = [ t.numpy() for t in (outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions) ] self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , 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: __lowerCAmelCase : List[str] = True __lowerCAmelCase : Optional[int] = False __lowerCAmelCase : List[Any] = model_class(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = model(self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) __lowerCAmelCase : Tuple = len(_SCREAMING_SNAKE_CASE ) self.assertEqual(config.output_hidden_states , _SCREAMING_SNAKE_CASE ) check_encoder_attentions_output(_SCREAMING_SNAKE_CASE ) if self.is_encoder_decoder: __lowerCAmelCase : Any = model_class(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = model(self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) self.assertEqual(config.output_hidden_states , _SCREAMING_SNAKE_CASE ) check_decoder_attentions_output(_SCREAMING_SNAKE_CASE ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] __lowerCAmelCase : Optional[Any] = True __lowerCAmelCase : str = model_class(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = model(self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) self.assertEqual(config.output_hidden_states , _SCREAMING_SNAKE_CASE ) check_encoder_attentions_output(_SCREAMING_SNAKE_CASE ) # Check attention is always last and order is fine __lowerCAmelCase : Dict = True __lowerCAmelCase : Optional[Any] = True __lowerCAmelCase : List[Any] = model_class(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = model(self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(_SCREAMING_SNAKE_CASE ) ) self.assertEqual(model.config.output_hidden_states , _SCREAMING_SNAKE_CASE ) check_encoder_attentions_output(_SCREAMING_SNAKE_CASE ) @require_tf class A__ ( unittest.TestCase): @slow def __lowerCamelCase ( self ): __lowerCAmelCase : Dict = TFConvBertModel.from_pretrained('YituTech/conv-bert-base' ) __lowerCAmelCase : int = tf.constant([[0, 1, 2, 3, 4, 5]] ) __lowerCAmelCase : Tuple = model(_SCREAMING_SNAKE_CASE )[0] __lowerCAmelCase : Tuple = [1, 6, 7_68] self.assertEqual(output.shape , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = tf.constant( [ [ [-0.0347_5493, -0.468_6034, -0.3063_8832], [0.2263_7248, -0.2698_8646, -0.742_3424], [0.1032_4868, -0.4501_3508, -0.5828_0784], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 )
86
0
from __future__ import annotations def lowerCAmelCase_ ( __A ) -> list[int]: '''simple docstring''' return [ord(__A ) - 96 for elem in plain] def lowerCAmelCase_ ( __A ) -> str: '''simple docstring''' return "".join(chr(elem + 96 ) for elem in encoded ) def lowerCAmelCase_ ( ) -> None: '''simple docstring''' UpperCAmelCase__ = encode(input("-> " ).strip().lower() ) print("Encoded: ", __A ) print("Decoded:", decode(__A ) ) if __name__ == "__main__": main()
65
"""simple docstring""" 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 DetrImageProcessor class A__ ( unittest.TestCase): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=30 , _SCREAMING_SNAKE_CASE=4_00 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=1 / 2_55 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , _SCREAMING_SNAKE_CASE=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __lowerCAmelCase : Any = size if size is not None else {'shortest_edge': 18, 'longest_edge': 13_33} __lowerCAmelCase : Optional[int] = parent __lowerCAmelCase : int = batch_size __lowerCAmelCase : str = num_channels __lowerCAmelCase : Optional[int] = min_resolution __lowerCAmelCase : List[Any] = max_resolution __lowerCAmelCase : Union[str, Any] = do_resize __lowerCAmelCase : Optional[Any] = size __lowerCAmelCase : Dict = do_rescale __lowerCAmelCase : Optional[Any] = rescale_factor __lowerCAmelCase : Any = do_normalize __lowerCAmelCase : List[str] = image_mean __lowerCAmelCase : Union[str, Any] = image_std __lowerCAmelCase : Optional[int] = do_pad def __lowerCamelCase ( self ): return { "do_resize": self.do_resize, "size": self.size, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_pad": self.do_pad, } def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ): if not batched: __lowerCAmelCase : str = image_inputs[0] if isinstance(_SCREAMING_SNAKE_CASE , Image.Image ): __lowerCAmelCase , __lowerCAmelCase : Optional[int] = image.size else: __lowerCAmelCase , __lowerCAmelCase : Union[str, Any] = image.shape[1], image.shape[2] if w < h: __lowerCAmelCase : str = int(self.size['shortest_edge'] * h / w ) __lowerCAmelCase : Optional[int] = self.size['shortest_edge'] elif w > h: __lowerCAmelCase : str = self.size['shortest_edge'] __lowerCAmelCase : Union[str, Any] = int(self.size['shortest_edge'] * w / h ) else: __lowerCAmelCase : str = self.size['shortest_edge'] __lowerCAmelCase : Optional[Any] = self.size['shortest_edge'] else: __lowerCAmelCase : str = [] for image in image_inputs: __lowerCAmelCase , __lowerCAmelCase : List[Any] = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __lowerCAmelCase : Any = max(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : item[0] )[0] __lowerCAmelCase : Dict = max(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class A__ ( _lowerCamelCase , unittest.TestCase): A_ : List[str] = DetrImageProcessor if is_vision_available() else None def __lowerCamelCase ( self ): __lowerCAmelCase : List[Any] = DetrImageProcessingTester(self ) @property def __lowerCamelCase ( self ): return self.image_processor_tester.prepare_image_processor_dict() def __lowerCamelCase ( self ): __lowerCAmelCase : Dict = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'image_mean' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'image_std' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_normalize' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_rescale' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'rescale_factor' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_resize' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'size' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_pad' ) ) def __lowerCamelCase ( self ): __lowerCAmelCase : Optional[Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'shortest_edge': 18, 'longest_edge': 13_33} ) self.assertEqual(image_processor.do_pad , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=_SCREAMING_SNAKE_CASE ) self.assertEqual(image_processor.size , {'shortest_edge': 42, 'longest_edge': 84} ) self.assertEqual(image_processor.do_pad , _SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): pass def __lowerCamelCase ( self ): # Initialize image_processing __lowerCAmelCase : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __lowerCAmelCase : str = 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 __lowerCAmelCase : int = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values __lowerCAmelCase , __lowerCAmelCase : List[Any] = self.image_processor_tester.get_expected_values(_SCREAMING_SNAKE_CASE ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __lowerCAmelCase , __lowerCAmelCase : int = self.image_processor_tester.get_expected_values(_SCREAMING_SNAKE_CASE , batched=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Union[str, Any] = image_processing(_SCREAMING_SNAKE_CASE , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __lowerCamelCase ( self ): # Initialize image_processing __lowerCAmelCase : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __lowerCAmelCase : str = 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 __lowerCAmelCase : Tuple = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values __lowerCAmelCase , __lowerCAmelCase : Tuple = self.image_processor_tester.get_expected_values(_SCREAMING_SNAKE_CASE ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __lowerCAmelCase : Union[str, Any] = image_processing(_SCREAMING_SNAKE_CASE , return_tensors='pt' ).pixel_values __lowerCAmelCase , __lowerCAmelCase : List[Any] = self.image_processor_tester.get_expected_values(_SCREAMING_SNAKE_CASE , batched=_SCREAMING_SNAKE_CASE ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __lowerCamelCase ( self ): # Initialize image_processing __lowerCAmelCase : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __lowerCAmelCase : int = 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 __lowerCAmelCase : Any = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values __lowerCAmelCase , __lowerCAmelCase : Dict = self.image_processor_tester.get_expected_values(_SCREAMING_SNAKE_CASE ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __lowerCAmelCase : Tuple = image_processing(_SCREAMING_SNAKE_CASE , return_tensors='pt' ).pixel_values __lowerCAmelCase , __lowerCAmelCase : Any = self.image_processor_tester.get_expected_values(_SCREAMING_SNAKE_CASE , batched=_SCREAMING_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 __lowerCamelCase ( self ): # prepare image and target __lowerCAmelCase : Union[str, Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' , 'r' ) as f: __lowerCAmelCase : Any = json.loads(f.read() ) __lowerCAmelCase : Tuple = {'image_id': 3_97_69, 'annotations': target} # encode them __lowerCAmelCase : Dict = DetrImageProcessor.from_pretrained('facebook/detr-resnet-50' ) __lowerCAmelCase : int = image_processing(images=_SCREAMING_SNAKE_CASE , annotations=_SCREAMING_SNAKE_CASE , return_tensors='pt' ) # verify pixel values __lowerCAmelCase : str = torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding['pixel_values'].shape , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : int = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 ) ) # verify area __lowerCAmelCase : List[str] = torch.tensor([5887.9600, 1_1250.2061, 48_9353.8438, 83_7122.7500, 14_7967.5156, 16_5732.3438] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , _SCREAMING_SNAKE_CASE ) ) # verify boxes __lowerCAmelCase : Tuple = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : str = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , _SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # verify image_id __lowerCAmelCase : Dict = torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , _SCREAMING_SNAKE_CASE ) ) # verify is_crowd __lowerCAmelCase : Optional[int] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , _SCREAMING_SNAKE_CASE ) ) # verify class_labels __lowerCAmelCase : Union[str, Any] = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , _SCREAMING_SNAKE_CASE ) ) # verify orig_size __lowerCAmelCase : int = torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , _SCREAMING_SNAKE_CASE ) ) # verify size __lowerCAmelCase : List[Any] = torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , _SCREAMING_SNAKE_CASE ) ) @slow def __lowerCamelCase ( self ): # prepare image, target and masks_path __lowerCAmelCase : Optional[int] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' , 'r' ) as f: __lowerCAmelCase : Optional[int] = json.loads(f.read() ) __lowerCAmelCase : Optional[int] = {'file_name': '000000039769.png', 'image_id': 3_97_69, 'segments_info': target} __lowerCAmelCase : Union[str, Any] = pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic' ) # encode them __lowerCAmelCase : Optional[int] = DetrImageProcessor.from_pretrained('facebook/detr-resnet-50-panoptic' ) __lowerCAmelCase : Optional[Any] = image_processing(images=_SCREAMING_SNAKE_CASE , annotations=_SCREAMING_SNAKE_CASE , masks_path=_SCREAMING_SNAKE_CASE , return_tensors='pt' ) # verify pixel values __lowerCAmelCase : str = torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding['pixel_values'].shape , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 ) ) # verify area __lowerCAmelCase : int = torch.tensor([14_7979.6875, 16_5527.0469, 48_4638.5938, 1_1292.9375, 5879.6562, 7634.1147] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , _SCREAMING_SNAKE_CASE ) ) # verify boxes __lowerCAmelCase : Optional[int] = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , _SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # verify image_id __lowerCAmelCase : str = torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , _SCREAMING_SNAKE_CASE ) ) # verify is_crowd __lowerCAmelCase : Optional[int] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , _SCREAMING_SNAKE_CASE ) ) # verify class_labels __lowerCAmelCase : str = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , _SCREAMING_SNAKE_CASE ) ) # verify masks __lowerCAmelCase : Dict = 82_28_73 self.assertEqual(encoding['labels'][0]['masks'].sum().item() , _SCREAMING_SNAKE_CASE ) # verify orig_size __lowerCAmelCase : str = torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , _SCREAMING_SNAKE_CASE ) ) # verify size __lowerCAmelCase : List[Any] = torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , _SCREAMING_SNAKE_CASE ) )
86
0
"""simple docstring""" import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler from tensorflow.keras.layers import LSTM, Dense from tensorflow.keras.models import Sequential if __name__ == "__main__": __a = pd.read_csv("sample_data.csv", header=None) __a = df.shape[:1][0] # If you're using some other dataset input the target column __a = df.iloc[:, 1:2] __a = actual_data.values.reshape(len_data, 1) __a = MinMaxScaler().fit_transform(actual_data) __a = 10 __a = 5 __a = 20 __a = len_data - periods * look_back __a = actual_data[:division] __a = actual_data[division - look_back :] __a , __a = [], [] __a , __a = [], [] for i in range(0, len(train_data) - forward_days - look_back + 1): train_x.append(train_data[i : i + look_back]) train_y.append(train_data[i + look_back : i + look_back + forward_days]) for i in range(0, len(test_data) - forward_days - look_back + 1): test_x.append(test_data[i : i + look_back]) test_y.append(test_data[i + look_back : i + look_back + forward_days]) __a = np.array(train_x) __a = np.array(test_x) __a = np.array([list(i.ravel()) for i in train_y]) __a = np.array([list(i.ravel()) for i in test_y]) __a = Sequential() model.add(LSTM(1_28, input_shape=(look_back, 1), return_sequences=True)) model.add(LSTM(64, input_shape=(1_28, 1))) model.add(Dense(forward_days)) model.compile(loss="mean_squared_error", optimizer="adam") __a = model.fit( x_train, y_train, epochs=1_50, verbose=1, shuffle=True, batch_size=4 ) __a = model.predict(x_test)
66
"""simple docstring""" import numpy as np def __lowerCAmelCase (_UpperCamelCase ): return 1 / (1 + np.exp(-vector )) def __lowerCAmelCase (_UpperCamelCase ): return vector * sigmoid(_UpperCamelCase ) if __name__ == "__main__": import doctest doctest.testmod()
86
0
'''simple docstring''' import os __UpperCAmelCase ={"I": 1, "V": 5, "X": 1_0, "L": 5_0, "C": 1_0_0, "D": 5_0_0, "M": 1_0_0_0} def __lowerCAmelCase ( UpperCamelCase__ ) -> int: __lowerCamelCase = 0 __lowerCamelCase = 0 while index < len(UpperCamelCase__ ) - 1: __lowerCamelCase = SYMBOLS[numerals[index]] __lowerCamelCase = SYMBOLS[numerals[index + 1]] if current_value < next_value: total_value -= current_value else: total_value += current_value index += 1 total_value += SYMBOLS[numerals[index]] return total_value def __lowerCAmelCase ( UpperCamelCase__ ) -> str: __lowerCamelCase = '''''' __lowerCamelCase = num // 10_00 numerals += m_count * "M" num %= 10_00 __lowerCamelCase = num // 1_00 if c_count == 9: numerals += "CM" c_count -= 9 elif c_count == 4: numerals += "CD" c_count -= 4 if c_count >= 5: numerals += "D" c_count -= 5 numerals += c_count * "C" num %= 1_00 __lowerCamelCase = num // 10 if x_count == 9: numerals += "XC" x_count -= 9 elif x_count == 4: numerals += "XL" x_count -= 4 if x_count >= 5: numerals += "L" x_count -= 5 numerals += x_count * "X" num %= 10 if num == 9: numerals += "IX" num -= 9 elif num == 4: numerals += "IV" num -= 4 if num >= 5: numerals += "V" num -= 5 numerals += num * "I" return numerals def __lowerCAmelCase ( UpperCamelCase__ = "/p089_roman.txt" ) -> int: __lowerCamelCase = 0 with open(os.path.dirname(UpperCamelCase__ ) + roman_numerals_filename ) as filea: __lowerCamelCase = filea.readlines() for line in lines: __lowerCamelCase = line.strip() __lowerCamelCase = parse_roman_numerals(UpperCamelCase__ ) __lowerCamelCase = generate_roman_numerals(UpperCamelCase__ ) savings += len(UpperCamelCase__ ) - len(UpperCamelCase__ ) return savings if __name__ == "__main__": print(f'{solution() = }')
67
"""simple docstring""" import unittest from transformers import MobileBertConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, MobileBertForMaskedLM, MobileBertForMultipleChoice, MobileBertForNextSentencePrediction, MobileBertForPreTraining, MobileBertForQuestionAnswering, MobileBertForSequenceClassification, MobileBertForTokenClassification, MobileBertModel, ) class A__ : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=13 , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=99 , _SCREAMING_SNAKE_CASE=64 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=37 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=5_12 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=None , ): __lowerCAmelCase : Optional[int] = parent __lowerCAmelCase : Union[str, Any] = batch_size __lowerCAmelCase : Dict = seq_length __lowerCAmelCase : Dict = is_training __lowerCAmelCase : List[str] = use_input_mask __lowerCAmelCase : int = use_token_type_ids __lowerCAmelCase : Optional[int] = use_labels __lowerCAmelCase : List[Any] = vocab_size __lowerCAmelCase : Dict = hidden_size __lowerCAmelCase : Tuple = embedding_size __lowerCAmelCase : List[Any] = num_hidden_layers __lowerCAmelCase : Tuple = num_attention_heads __lowerCAmelCase : Union[str, Any] = intermediate_size __lowerCAmelCase : Optional[Any] = hidden_act __lowerCAmelCase : Optional[int] = hidden_dropout_prob __lowerCAmelCase : Dict = attention_probs_dropout_prob __lowerCAmelCase : Any = max_position_embeddings __lowerCAmelCase : Any = type_vocab_size __lowerCAmelCase : Union[str, Any] = type_sequence_label_size __lowerCAmelCase : List[str] = initializer_range __lowerCAmelCase : str = num_labels __lowerCAmelCase : int = num_choices __lowerCAmelCase : Union[str, Any] = scope def __lowerCamelCase ( self ): __lowerCAmelCase : Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __lowerCAmelCase : Optional[int] = None if self.use_input_mask: __lowerCAmelCase : Optional[int] = random_attention_mask([self.batch_size, self.seq_length] ) __lowerCAmelCase : str = None if self.use_token_type_ids: __lowerCAmelCase : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __lowerCAmelCase : Union[str, Any] = None __lowerCAmelCase : Optional[int] = None __lowerCAmelCase : Union[str, Any] = None if self.use_labels: __lowerCAmelCase : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCAmelCase : Dict = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __lowerCAmelCase : Dict = ids_tensor([self.batch_size] , self.num_choices ) __lowerCAmelCase : str = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowerCamelCase ( self ): return MobileBertConfig( 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 , embedding_size=self.embedding_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=_SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : str = MobileBertModel(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() __lowerCAmelCase : Optional[Any] = model(_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = model(_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : int = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Union[str, Any] = MobileBertForMaskedLM(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() __lowerCAmelCase : Any = model(_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Optional[Any] = MobileBertForNextSentencePrediction(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() __lowerCAmelCase : Dict = model( _SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : List[Any] = MobileBertForPreTraining(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() __lowerCAmelCase : List[Any] = model( _SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE , next_sentence_label=_SCREAMING_SNAKE_CASE , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Optional[int] = MobileBertForQuestionAnswering(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() __lowerCAmelCase : List[str] = model( _SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_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 __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Optional[int] = self.num_labels __lowerCAmelCase : Tuple = MobileBertForSequenceClassification(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() __lowerCAmelCase : str = model(_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Optional[Any] = self.num_labels __lowerCAmelCase : int = MobileBertForTokenClassification(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() __lowerCAmelCase : Optional[Any] = model(_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Optional[int] = self.num_choices __lowerCAmelCase : List[str] = MobileBertForMultipleChoice(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() __lowerCAmelCase : str = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __lowerCAmelCase : List[Any] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __lowerCAmelCase : List[Any] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __lowerCAmelCase : List[str] = model( _SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __lowerCamelCase ( self ): __lowerCAmelCase : Optional[Any] = self.prepare_config_and_inputs() ( ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ) : Optional[Any] = config_and_inputs __lowerCAmelCase : List[str] = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class A__ ( _lowerCamelCase , _lowerCamelCase , unittest.TestCase): A_ : str = ( ( MobileBertModel, MobileBertForMaskedLM, MobileBertForMultipleChoice, MobileBertForNextSentencePrediction, MobileBertForPreTraining, MobileBertForQuestionAnswering, MobileBertForSequenceClassification, MobileBertForTokenClassification, ) if is_torch_available() else () ) A_ : List[str] = ( { 'feature-extraction': MobileBertModel, 'fill-mask': MobileBertForMaskedLM, 'question-answering': MobileBertForQuestionAnswering, 'text-classification': MobileBertForSequenceClassification, 'token-classification': MobileBertForTokenClassification, 'zero-shot': MobileBertForSequenceClassification, } if is_torch_available() else {} ) A_ : Dict = True def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ): __lowerCAmelCase : List[str] = super()._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) if return_labels: if model_class in get_values(_SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Tuple = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=_SCREAMING_SNAKE_CASE ) return inputs_dict def __lowerCamelCase ( self ): __lowerCAmelCase : Optional[Any] = MobileBertModelTester(self ) __lowerCAmelCase : str = ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , hidden_size=37 ) def __lowerCamelCase ( self ): self.config_tester.run_common_tests() def __lowerCamelCase ( self ): __lowerCAmelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_model(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_masked_lm(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_multiple_choice(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_next_sequence_prediction(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_pretraining(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_question_answering(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_sequence_classification(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_token_classification(*_SCREAMING_SNAKE_CASE ) def __lowerCAmelCase (_UpperCamelCase ): return torch.tensor( _UpperCamelCase , dtype=torch.long , device=_UpperCamelCase , ) lowerCamelCase__ = 1E-3 @require_torch @require_sentencepiece @require_tokenizers class A__ ( unittest.TestCase): @slow def __lowerCamelCase ( self ): __lowerCAmelCase : Union[str, Any] = MobileBertModel.from_pretrained('google/mobilebert-uncased' ).to(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = _long_tensor([[1_01, 71_10, 10_05, 10_56, 20_23, 1_13_33, 1_74_13, 10_29, 1_02]] ) with torch.no_grad(): __lowerCAmelCase : int = model(_SCREAMING_SNAKE_CASE )[0] __lowerCAmelCase : Dict = torch.Size((1, 9, 5_12) ) self.assertEqual(output.shape , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = torch.tensor( [ [ [-2.4_73_65_26E07, 8.2_69_16_56E04, 1.6_52_18_38E05], [-5.7_54_17_04E-01, 3.9_05_60_22E00, 4.4_01_15_07E00], [2.6_04_73_59E00, 1.5_67_76_52E00, -1.7_32_41_88E-01], ] ] , device=_SCREAMING_SNAKE_CASE , ) # MobileBERT results range from 10e0 to 10e8. Even a 0.0000001% difference with a value of 10e8 results in a # ~1 difference, it's therefore not a good idea to measure using addition. # Here, we instead divide the expected result with the result in order to obtain ~1. We then check that the # result is held between bounds: 1 - TOLERANCE < expected_result / result < 1 + TOLERANCE __lowerCAmelCase : Tuple = torch.all((expected_slice / output[..., :3, :3]) >= 1 - TOLERANCE ) __lowerCAmelCase : Union[str, Any] = torch.all((expected_slice / output[..., :3, :3]) <= 1 + TOLERANCE ) self.assertTrue(lower_bound and upper_bound )
86
0
from __future__ import annotations class a__ : """simple docstring""" def __init__( self , lowercase=None ) -> Optional[int]: '''simple docstring''' A__ = data A__ = None def __repr__( self ) -> int: '''simple docstring''' A__ = [] A__ = self while temp: string_rep.append(F'{temp.data}' ) A__ = temp.next return "->".join(lowercase ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: list ) -> List[str]: '''simple docstring''' if not elements_list: raise Exception("The Elements List is empty" ) A__ = A__ = Node(elements_list[0] ) for i in range(1 , len(SCREAMING_SNAKE_CASE_ ) ): A__ = Node(elements_list[i] ) A__ = current.next return head def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Node ) -> None: '''simple docstring''' if head_node is not None and isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): print_reverse(head_node.next ) print(head_node.data ) def lowerCAmelCase__ ( ) -> List[Any]: '''simple docstring''' from doctest import testmod testmod() A__ = make_linked_list([1_4, 5_2, 1_4, 1_2, 4_3] ) print("Linked List:" ) print(SCREAMING_SNAKE_CASE_ ) print("Elements in Reverse:" ) print_reverse(SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": main()
68
"""simple docstring""" import re import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class A__ ( _lowerCamelCase): A_ : Any = ['image_processor', 'tokenizer'] A_ : Optional[Any] = 'AutoImageProcessor' A_ : str = 'AutoTokenizer' def __init__( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Union[str, Any] = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , _SCREAMING_SNAKE_CASE , ) __lowerCAmelCase : Any = kwargs.pop('feature_extractor' ) __lowerCAmelCase : str = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.' ) if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.' ) super().__init__(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Any = self.image_processor __lowerCAmelCase : Tuple = False def __call__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = kwargs.pop('images' , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Any = kwargs.pop('text' , _SCREAMING_SNAKE_CASE ) if len(_SCREAMING_SNAKE_CASE ) > 0: __lowerCAmelCase : Dict = args[0] __lowerCAmelCase : Union[str, Any] = args[1:] if images is None and text is None: raise ValueError('You need to specify either an `images` or `text` input to process.' ) if images is not None: __lowerCAmelCase : Union[str, Any] = self.image_processor(_SCREAMING_SNAKE_CASE , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) if text is not None: __lowerCAmelCase : Dict = self.tokenizer(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) if text is None: return inputs elif images is None: return encodings else: __lowerCAmelCase : Union[str, Any] = encodings['input_ids'] return inputs def __lowerCamelCase ( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ): return self.tokenizer.batch_decode(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ): return self.tokenizer.decode(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @contextmanager def __lowerCamelCase ( self ): 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 images inputs, or in a separate call.' ) __lowerCAmelCase : Any = True __lowerCAmelCase : Dict = self.tokenizer yield __lowerCAmelCase : Optional[int] = self.image_processor __lowerCAmelCase : Optional[Any] = False def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=None ): if added_vocab is None: __lowerCAmelCase : str = self.tokenizer.get_added_vocab() __lowerCAmelCase : List[Any] = {} while tokens: __lowerCAmelCase : int = re.search(R'<s_(.*?)>' , _SCREAMING_SNAKE_CASE , re.IGNORECASE ) if start_token is None: break __lowerCAmelCase : Union[str, Any] = start_token.group(1 ) __lowerCAmelCase : Tuple = re.search(Rf"</s_{key}>" , _SCREAMING_SNAKE_CASE , re.IGNORECASE ) __lowerCAmelCase : str = start_token.group() if end_token is None: __lowerCAmelCase : Optional[int] = tokens.replace(_SCREAMING_SNAKE_CASE , '' ) else: __lowerCAmelCase : Optional[Any] = end_token.group() __lowerCAmelCase : Tuple = re.escape(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Tuple = re.escape(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = re.search(f"{start_token_escaped}(.*?){end_token_escaped}" , _SCREAMING_SNAKE_CASE , re.IGNORECASE ) if content is not None: __lowerCAmelCase : List[str] = content.group(1 ).strip() if r"<s_" in content and r"</s_" in content: # non-leaf node __lowerCAmelCase : int = self.tokenajson(_SCREAMING_SNAKE_CASE , is_inner_value=_SCREAMING_SNAKE_CASE , added_vocab=_SCREAMING_SNAKE_CASE ) if value: if len(_SCREAMING_SNAKE_CASE ) == 1: __lowerCAmelCase : Tuple = value[0] __lowerCAmelCase : Tuple = value else: # leaf nodes __lowerCAmelCase : Any = [] for leaf in content.split(R'<sep/>' ): __lowerCAmelCase : List[Any] = leaf.strip() if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>": __lowerCAmelCase : Dict = leaf[1:-2] # for categorical special tokens output[key].append(_SCREAMING_SNAKE_CASE ) if len(output[key] ) == 1: __lowerCAmelCase : str = output[key][0] __lowerCAmelCase : Dict = tokens[tokens.find(_SCREAMING_SNAKE_CASE ) + len(_SCREAMING_SNAKE_CASE ) :].strip() if tokens[:6] == r"<sep/>": # non-leaf nodes return [output] + self.tokenajson(tokens[6:] , is_inner_value=_SCREAMING_SNAKE_CASE , added_vocab=_SCREAMING_SNAKE_CASE ) if len(_SCREAMING_SNAKE_CASE ): return [output] if is_inner_value else output else: return [] if is_inner_value else {"text_sequence": tokens} @property def __lowerCamelCase ( self ): warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , _SCREAMING_SNAKE_CASE , ) return self.image_processor_class @property def __lowerCamelCase ( self ): warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , _SCREAMING_SNAKE_CASE , ) return self.image_processor
86
0
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging __UpperCamelCase = logging.get_logger(__name__) __UpperCamelCase = {'''vocab_file''': '''spiece.model'''} __UpperCamelCase = { '''vocab_file''': { '''bert_for_seq_generation''': ( '''https://huggingface.co/google/bert_for_seq_generation_L-24_bbc_encoder/resolve/main/spiece.model''' ), } } __UpperCamelCase = {'''bert_for_seq_generation''': 512} class UpperCamelCase ( lowerCAmelCase__ ): SCREAMING_SNAKE_CASE_ = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE_ = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = ["input_ids", "attention_mask"] def __init__( self, lowerCAmelCase__, lowerCAmelCase__="<s>", lowerCAmelCase__="</s>", lowerCAmelCase__="<unk>", lowerCAmelCase__="<pad>", lowerCAmelCase__="<::::>", lowerCAmelCase__ = None, **lowerCAmelCase__, ) -> None: snake_case_ = {} if sp_model_kwargs is None else sp_model_kwargs # Add extra_ids to the special token list super().__init__( bos_token=lowerCAmelCase__, eos_token=lowerCAmelCase__, unk_token=lowerCAmelCase__, pad_token=lowerCAmelCase__, sep_token=lowerCAmelCase__, sp_model_kwargs=self.sp_model_kwargs, **lowerCAmelCase__, ) snake_case_ = vocab_file snake_case_ = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(lowerCAmelCase__) @property def a_ ( self) -> Tuple: return self.sp_model.get_piece_size() def a_ ( self) -> Optional[Any]: snake_case_ = {self.convert_ids_to_tokens(lowerCAmelCase__): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def __getstate__( self) -> Any: snake_case_ = self.__dict__.copy() snake_case_ = None return state def __setstate__( self, lowerCAmelCase__) -> Optional[Any]: snake_case_ = d # for backward compatibility if not hasattr(self, 'sp_model_kwargs'): snake_case_ = {} snake_case_ = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(self.vocab_file) def a_ ( self, lowerCAmelCase__) -> List[str]: return self.sp_model.encode(lowerCAmelCase__, out_type=lowerCAmelCase__) def a_ ( self, lowerCAmelCase__) -> Union[str, Any]: return self.sp_model.piece_to_id(lowerCAmelCase__) def a_ ( self, lowerCAmelCase__) -> Tuple: snake_case_ = self.sp_model.IdToPiece(lowerCAmelCase__) return token def a_ ( self, lowerCAmelCase__) -> Any: snake_case_ = [] snake_case_ = '' for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(lowerCAmelCase__) + token snake_case_ = [] else: current_sub_tokens.append(lowerCAmelCase__) out_string += self.sp_model.decode(lowerCAmelCase__) return out_string.strip() def a_ ( self, lowerCAmelCase__, lowerCAmelCase__ = None) -> Tuple[str]: if not os.path.isdir(lowerCAmelCase__): logger.error(f'Vocabulary path ({save_directory}) should be a directory') return snake_case_ = os.path.join( lowerCAmelCase__, (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']) if os.path.abspath(self.vocab_file) != os.path.abspath(lowerCAmelCase__) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file, lowerCAmelCase__) elif not os.path.isfile(self.vocab_file): with open(lowerCAmelCase__, 'wb') as fi: snake_case_ = self.sp_model.serialized_model_proto() fi.write(lowerCAmelCase__) return (out_vocab_file,)
69
"""simple docstring""" def __lowerCAmelCase (_UpperCamelCase ): __lowerCAmelCase : Tuple = 0 while num > 0: digit_sum += num % 10 num //= 10 return digit_sum def __lowerCAmelCase (_UpperCamelCase = 100 ): __lowerCAmelCase : Optional[int] = 1 __lowerCAmelCase : Optional[Any] = 2 for i in range(2 , max_n + 1 ): __lowerCAmelCase : Any = pre_numerator __lowerCAmelCase : Union[str, Any] = 2 * i // 3 if i % 3 == 0 else 1 __lowerCAmelCase : int = cur_numerator __lowerCAmelCase : Dict = e_cont * pre_numerator + temp return sum_digits(_UpperCamelCase ) if __name__ == "__main__": print(f'{solution() = }')
86
0
'''simple docstring''' import os import unittest from huggingface_hub.utils import are_progress_bars_disabled import transformers.models.bart.tokenization_bart from transformers import logging from transformers.testing_utils import CaptureLogger, mockenv, mockenv_context from transformers.utils.logging import disable_progress_bar, enable_progress_bar class UpperCAmelCase ( unittest.TestCase ): def lowercase__ ( self : List[Any] ) -> Optional[Any]: _lowerCAmelCase = logging.get_logger() # the current default level is logging.WARNING _lowerCAmelCase = logging.get_verbosity() logging.set_verbosity_error() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_warning() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_info() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_debug() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) # restore to the original level logging.set_verbosity(__snake_case ) def lowercase__ ( self : int ) -> str: _lowerCAmelCase = logging.get_verbosity() _lowerCAmelCase = logging.get_logger("""transformers.models.bart.tokenization_bart""" ) _lowerCAmelCase = """Testing 1, 2, 3""" # should be able to log warnings (if default settings weren't overridden by `pytest --log-level-all`) if level_origin <= logging.WARNING: with CaptureLogger(__snake_case ) as cl: logger.warning(__snake_case ) self.assertEqual(cl.out , msg + """\n""" ) # this is setting the level for all of `transformers.*` loggers logging.set_verbosity_error() # should not be able to log warnings with CaptureLogger(__snake_case ) as cl: logger.warning(__snake_case ) self.assertEqual(cl.out , """""" ) # should be able to log warnings again logging.set_verbosity_warning() with CaptureLogger(__snake_case ) as cl: logger.warning(__snake_case ) self.assertEqual(cl.out , msg + """\n""" ) # restore to the original level logging.set_verbosity(__snake_case ) @mockenv(TRANSFORMERS_VERBOSITY="""error""" ) def lowercase__ ( self : Tuple ) -> Tuple: # reset for the env var to take effect, next time some logger call is made transformers.utils.logging._reset_library_root_logger() # this action activates the env var _lowerCAmelCase = logging.get_logger("""transformers.models.bart.tokenization_bart""" ) _lowerCAmelCase = os.getenv("""TRANSFORMERS_VERBOSITY""" , __snake_case ) _lowerCAmelCase = logging.log_levels[env_level_str] _lowerCAmelCase = logging.get_verbosity() self.assertEqual( __snake_case , __snake_case , f"TRANSFORMERS_VERBOSITY={env_level_str}/{env_level}, but internal verbosity is {current_level}" , ) # restore to the original level _lowerCAmelCase = """""" transformers.utils.logging._reset_library_root_logger() @mockenv(TRANSFORMERS_VERBOSITY="""super-error""" ) def lowercase__ ( self : Optional[int] ) -> Any: # reset for the env var to take effect, next time some logger call is made transformers.utils.logging._reset_library_root_logger() _lowerCAmelCase = logging.logging.getLogger() with CaptureLogger(__snake_case ) as cl: # this action activates the env var logging.get_logger("""transformers.models.bart.tokenization_bart""" ) self.assertIn("""Unknown option TRANSFORMERS_VERBOSITY=super-error""" , cl.out ) # no need to restore as nothing was changed def lowercase__ ( self : Dict ) -> Any: # testing `logger.warning_advice()` transformers.utils.logging._reset_library_root_logger() _lowerCAmelCase = logging.get_logger("""transformers.models.bart.tokenization_bart""" ) _lowerCAmelCase = """Testing 1, 2, 3""" with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS="""1""" ): # nothing should be logged as env var disables this method with CaptureLogger(__snake_case ) as cl: logger.warning_advice(__snake_case ) self.assertEqual(cl.out , """""" ) with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS="""""" ): # should log normally as TRANSFORMERS_NO_ADVISORY_WARNINGS is unset with CaptureLogger(__snake_case ) as cl: logger.warning_advice(__snake_case ) self.assertEqual(cl.out , msg + """\n""" ) def UpperCamelCase__ ( ): """simple docstring""" disable_progress_bar() assert are_progress_bars_disabled() enable_progress_bar() assert not are_progress_bars_disabled()
70
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { """microsoft/markuplm-base""": """https://huggingface.co/microsoft/markuplm-base/resolve/main/config.json""", """microsoft/markuplm-large""": """https://huggingface.co/microsoft/markuplm-large/resolve/main/config.json""", } class A__ ( _lowerCamelCase): A_ : List[Any] = 'markuplm' def __init__( self , _SCREAMING_SNAKE_CASE=3_05_22 , _SCREAMING_SNAKE_CASE=7_68 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=30_72 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=5_12 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE=1E-12 , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=2_56 , _SCREAMING_SNAKE_CASE=10_24 , _SCREAMING_SNAKE_CASE=2_16 , _SCREAMING_SNAKE_CASE=10_01 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=50 , _SCREAMING_SNAKE_CASE="absolute" , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE , ): super().__init__( pad_token_id=_SCREAMING_SNAKE_CASE , bos_token_id=_SCREAMING_SNAKE_CASE , eos_token_id=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) __lowerCAmelCase : Union[str, Any] = vocab_size __lowerCAmelCase : Any = hidden_size __lowerCAmelCase : List[Any] = num_hidden_layers __lowerCAmelCase : Tuple = num_attention_heads __lowerCAmelCase : Union[str, Any] = hidden_act __lowerCAmelCase : List[Any] = intermediate_size __lowerCAmelCase : List[str] = hidden_dropout_prob __lowerCAmelCase : List[str] = attention_probs_dropout_prob __lowerCAmelCase : Optional[int] = max_position_embeddings __lowerCAmelCase : int = type_vocab_size __lowerCAmelCase : Tuple = initializer_range __lowerCAmelCase : int = layer_norm_eps __lowerCAmelCase : List[str] = position_embedding_type __lowerCAmelCase : List[Any] = use_cache __lowerCAmelCase : Optional[Any] = classifier_dropout # additional properties __lowerCAmelCase : Optional[int] = max_depth __lowerCAmelCase : List[str] = max_xpath_tag_unit_embeddings __lowerCAmelCase : Optional[Any] = max_xpath_subs_unit_embeddings __lowerCAmelCase : Any = tag_pad_id __lowerCAmelCase : Union[str, Any] = subs_pad_id __lowerCAmelCase : int = xpath_unit_hidden_size
86
0
import re from filelock import FileLock try: import nltk A_ :Any = True except (ImportError, ModuleNotFoundError): A_ :Union[str, Any] = False if NLTK_AVAILABLE: with FileLock('''.lock''') as lock: nltk.download('''punkt''', quiet=True) def A ( a_ ) -> str: re.sub('<n>' ,'' ,a_ ) # remove pegasus newline char assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)" return "\n".join(nltk.sent_tokenize(a_ ) )
71
"""simple docstring""" import argparse import torch # Step 1. clone https://github.com/microsoft/unilm # Step 2. git checkout to https://github.com/microsoft/unilm/commit/b94ec76c36f02fb2b0bf0dcb0b8554a2185173cd # Step 3. cd unilm # Step 4. ln -s $(realpath wavlm/modules.py) ./ # create simlink # import classes from unilm.wavlm.WavLM import WavLM as WavLMOrig from unilm.wavlm.WavLM import WavLMConfig as WavLMConfigOrig from transformers import WavLMConfig, WavLMModel, logging logging.set_verbosity_info() lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { """post_extract_proj""": """feature_projection.projection""", """encoder.pos_conv.0""": """encoder.pos_conv_embed.conv""", """self_attn.k_proj""": """encoder.layers.*.attention.k_proj""", """self_attn.v_proj""": """encoder.layers.*.attention.v_proj""", """self_attn.q_proj""": """encoder.layers.*.attention.q_proj""", """self_attn.out_proj""": """encoder.layers.*.attention.out_proj""", """self_attn.grep_linear""": """encoder.layers.*.attention.gru_rel_pos_linear""", """self_attn.relative_attention_bias""": """encoder.layers.*.attention.rel_attn_embed""", """self_attn.grep_a""": """encoder.layers.*.attention.gru_rel_pos_const""", """self_attn_layer_norm""": """encoder.layers.*.layer_norm""", """fc1""": """encoder.layers.*.feed_forward.intermediate_dense""", """fc2""": """encoder.layers.*.feed_forward.output_dense""", """final_layer_norm""": """encoder.layers.*.final_layer_norm""", """encoder.layer_norm""": """encoder.layer_norm""", """w2v_model.layer_norm""": """feature_projection.layer_norm""", """quantizer.weight_proj""": """quantizer.weight_proj""", """quantizer.vars""": """quantizer.codevectors""", """project_q""": """project_q""", """final_proj""": """project_hid""", """w2v_encoder.proj""": """ctc_proj""", """mask_emb""": """masked_spec_embed""", } lowerCamelCase__ = [ """ctc_proj""", """quantizer.weight_proj""", """quantizer.codevectors""", """project_q""", """project_hid""", ] def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): for attribute in key.split('.' ): __lowerCAmelCase : str = getattr(_UpperCamelCase , _UpperCamelCase ) if weight_type is not None: __lowerCAmelCase : Tuple = getattr(_UpperCamelCase , _UpperCamelCase ).shape else: __lowerCAmelCase : Dict = hf_pointer.shape assert hf_shape == value.shape, ( F"Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be" F" {value.shape} for {full_name}" ) if weight_type == "weight": __lowerCAmelCase : Union[str, Any] = value elif weight_type == "weight_g": __lowerCAmelCase : List[Any] = value elif weight_type == "weight_v": __lowerCAmelCase : Any = value elif weight_type == "bias": __lowerCAmelCase : List[str] = value else: __lowerCAmelCase : List[Any] = value logger.info(F"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}." ) def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase ): __lowerCAmelCase : Any = [] __lowerCAmelCase : Optional[int] = fairseq_model.state_dict() __lowerCAmelCase : Union[str, Any] = hf_model.feature_extractor for name, value in fairseq_dict.items(): __lowerCAmelCase : Union[str, Any] = False if "conv_layers" in name: load_conv_layer( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , hf_model.config.feat_extract_norm == 'group' , ) __lowerCAmelCase : str = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]: __lowerCAmelCase : int = True if "*" in mapped_key: __lowerCAmelCase : List[str] = name.split(_UpperCamelCase )[0].split('.' )[-2] __lowerCAmelCase : Optional[Any] = mapped_key.replace('*' , _UpperCamelCase ) if "weight_g" in name: __lowerCAmelCase : Union[str, Any] = 'weight_g' elif "weight_v" in name: __lowerCAmelCase : int = 'weight_v' elif "bias" in name and "relative_attention_bias" not in name: __lowerCAmelCase : Optional[Any] = 'bias' elif "weight" in name: # TODO: don't match quantizer.weight_proj __lowerCAmelCase : List[str] = 'weight' else: __lowerCAmelCase : Optional[Any] = None set_recursively(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) continue if not is_used: unused_weights.append(_UpperCamelCase ) logger.warning(F"Unused weights: {unused_weights}" ) def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): __lowerCAmelCase : List[Any] = full_name.split('conv_layers.' )[-1] __lowerCAmelCase : Any = name.split('.' ) __lowerCAmelCase : List[Any] = int(items[0] ) __lowerCAmelCase : Tuple = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( F"{full_name} has size {value.shape}, but" F" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found." ) __lowerCAmelCase : Tuple = value logger.info(F"Feat extract conv layer {layer_id} was initialized from {full_name}." ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( F"{full_name} has size {value.shape}, but" F" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found." ) __lowerCAmelCase : int = value logger.info(F"Feat extract conv layer {layer_id} was initialized from {full_name}." ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( F"{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was" " found." ) __lowerCAmelCase : Optional[Any] = value logger.info(F"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( F"{full_name} has size {value.shape}, but" F" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found." ) __lowerCAmelCase : Any = value logger.info(F"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) else: unused_weights.append(_UpperCamelCase ) @torch.no_grad() def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase=None ): # load the pre-trained checkpoints __lowerCAmelCase : Any = torch.load(_UpperCamelCase ) __lowerCAmelCase : List[str] = WavLMConfigOrig(checkpoint['cfg'] ) __lowerCAmelCase : Optional[Any] = WavLMOrig(_UpperCamelCase ) model.load_state_dict(checkpoint['model'] ) model.eval() if config_path is not None: __lowerCAmelCase : Dict = WavLMConfig.from_pretrained(_UpperCamelCase ) else: __lowerCAmelCase : List[str] = WavLMConfig() __lowerCAmelCase : List[str] = WavLMModel(_UpperCamelCase ) recursively_load_weights(_UpperCamelCase , _UpperCamelCase ) hf_wavlm.save_pretrained(_UpperCamelCase ) if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to fairseq checkpoint""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") lowerCamelCase__ = parser.parse_args() convert_wavlm_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
86
0
"""simple docstring""" from typing import List from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { '''snap-research/efficientformer-l1-300''': ( '''https://huggingface.co/snap-research/efficientformer-l1-300/resolve/main/config.json''' ), } class __snake_case ( _lowercase): snake_case__ : Any = "efficientformer" def __init__( self : List[str] , __lowerCAmelCase : List[int] = [3, 2, 6, 4] , __lowerCAmelCase : List[int] = [4_8, 9_6, 2_2_4, 4_4_8] , __lowerCAmelCase : List[bool] = [True, True, True, True] , __lowerCAmelCase : int = 4_4_8 , __lowerCAmelCase : int = 3_2 , __lowerCAmelCase : int = 4 , __lowerCAmelCase : int = 7 , __lowerCAmelCase : int = 5 , __lowerCAmelCase : int = 8 , __lowerCAmelCase : int = 4 , __lowerCAmelCase : float = 0.0 , __lowerCAmelCase : int = 1_6 , __lowerCAmelCase : int = 3 , __lowerCAmelCase : int = 3 , __lowerCAmelCase : int = 3 , __lowerCAmelCase : int = 2 , __lowerCAmelCase : int = 1 , __lowerCAmelCase : float = 0.0 , __lowerCAmelCase : int = 1 , __lowerCAmelCase : bool = True , __lowerCAmelCase : bool = True , __lowerCAmelCase : float = 1E-5 , __lowerCAmelCase : str = "gelu" , __lowerCAmelCase : float = 0.02 , __lowerCAmelCase : float = 1E-12 , __lowerCAmelCase : int = 2_2_4 , __lowerCAmelCase : float = 1E-05 , **__lowerCAmelCase : str , ): """simple docstring""" super().__init__(**__lowerCAmelCase ) _lowerCamelCase : List[Any] = hidden_act _lowerCamelCase : Union[str, Any] = hidden_dropout_prob _lowerCamelCase : Dict = hidden_sizes _lowerCamelCase : int = num_hidden_layers _lowerCamelCase : Optional[int] = num_attention_heads _lowerCamelCase : List[str] = initializer_range _lowerCamelCase : List[str] = layer_norm_eps _lowerCamelCase : int = patch_size _lowerCamelCase : List[str] = num_channels _lowerCamelCase : Optional[int] = depths _lowerCamelCase : Union[str, Any] = mlp_expansion_ratio _lowerCamelCase : Tuple = downsamples _lowerCamelCase : int = dim _lowerCamelCase : Union[str, Any] = key_dim _lowerCamelCase : int = attention_ratio _lowerCamelCase : str = resolution _lowerCamelCase : Dict = pool_size _lowerCamelCase : int = downsample_patch_size _lowerCamelCase : List[Any] = downsample_stride _lowerCamelCase : Optional[Any] = downsample_pad _lowerCamelCase : Any = drop_path_rate _lowerCamelCase : List[str] = num_metaad_blocks _lowerCamelCase : List[Any] = distillation _lowerCamelCase : Union[str, Any] = use_layer_scale _lowerCamelCase : Optional[int] = layer_scale_init_value _lowerCamelCase : Any = image_size _lowerCamelCase : Optional[int] = batch_norm_eps
72
"""simple docstring""" import os import pytest from attr import dataclass lowerCamelCase__ = """us-east-1""" # defaults region @dataclass class A__ : A_ : str A_ : Union[str, Any] = 'arn:aws:iam::558105141721:role/sagemaker_execution_role' A_ : Optional[int] = { 'task_name': 'mnli', 'per_device_train_batch_size': 1_6, 'per_device_eval_batch_size': 1_6, 'do_train': True, 'do_eval': True, 'do_predict': True, 'output_dir': '/opt/ml/model', 'overwrite_output_dir': True, 'max_steps': 5_0_0, 'save_steps': 5_5_0_0, } A_ : List[Any] = {**hyperparameters, 'max_steps': 1_0_0_0} @property def __lowerCamelCase ( self ): if self.framework == "pytorch": return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"eval_accuracy.*=\D*(.*?)$"}, {"Name": "eval_loss", "Regex": r"eval_loss.*=\D*(.*?)$"}, ] else: return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"loss.*=\D*(.*?)]?$"}, {"Name": "eval_loss", "Regex": r"sparse_categorical_accuracy.*=\D*(.*?)]?$"}, ] @property def __lowerCamelCase ( self ): return f"{self.framework}-transfromers-test" @property def __lowerCamelCase ( self ): return f"./tests/sagemaker/scripts/{self.framework}" @property def __lowerCamelCase ( self ): if self.framework == "pytorch": return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-pytorch-training:1.7.1-transformers4.6.1-gpu-py36-cu110-ubuntu18.04" else: return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-tensorflow-training:2.4.1-transformers4.6.1-gpu-py37-cu110-ubuntu18.04" @pytest.fixture(scope='class' ) def __lowerCAmelCase (_UpperCamelCase ): __lowerCAmelCase : str = SageMakerTestEnvironment(framework=request.cls.framework )
86
0
import argparse import struct import unittest class A_ : def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : bytes): __lowerCamelCase : Dict = data # Initialize hash values __lowerCamelCase : List[str] = [ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19, ] # Initialize round constants __lowerCamelCase : Tuple = [ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, ] __lowerCamelCase : int = self.preprocessing(self.data) self.final_hash() @staticmethod def lowerCAmelCase ( SCREAMING_SNAKE_CASE__ : bytes): __lowerCamelCase : List[Any] = b'\x80' + (b'\x00' * (6_3 - (len(SCREAMING_SNAKE_CASE__) + 8) % 6_4)) __lowerCamelCase : List[Any] = struct.pack('>Q' ,(len(SCREAMING_SNAKE_CASE__) * 8)) return data + padding + big_endian_integer def lowerCAmelCase ( self : List[Any]): # Convert into blocks of 64 bytes __lowerCamelCase : Dict = [ self.preprocessed_data[x : x + 6_4] for x in range(0 ,len(self.preprocessed_data) ,6_4) ] for block in self.blocks: # Convert the given block into a list of 4 byte integers __lowerCamelCase : Optional[Any] = list(struct.unpack('>16L' ,SCREAMING_SNAKE_CASE__)) # add 48 0-ed integers words += [0] * 4_8 __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : List[str] = self.hashes for index in range(0 ,6_4): if index > 1_5: # modify the zero-ed indexes at the end of the array __lowerCamelCase : Any = ( self.ror(words[index - 1_5] ,7) ^ self.ror(words[index - 1_5] ,1_8) ^ (words[index - 1_5] >> 3) ) __lowerCamelCase : Tuple = ( self.ror(words[index - 2] ,1_7) ^ self.ror(words[index - 2] ,1_9) ^ (words[index - 2] >> 1_0) ) __lowerCamelCase : List[Any] = ( words[index - 1_6] + sa + words[index - 7] + sa ) % 0x100000000 # Compression __lowerCamelCase : Any = self.ror(SCREAMING_SNAKE_CASE__ ,6) ^ self.ror(SCREAMING_SNAKE_CASE__ ,1_1) ^ self.ror(SCREAMING_SNAKE_CASE__ ,2_5) __lowerCamelCase : Tuple = (e & f) ^ ((~e & 0xffffffff) & g) __lowerCamelCase : str = ( h + sa + ch + self.round_constants[index] + words[index] ) % 0x100000000 __lowerCamelCase : Dict = self.ror(SCREAMING_SNAKE_CASE__ ,2) ^ self.ror(SCREAMING_SNAKE_CASE__ ,1_3) ^ self.ror(SCREAMING_SNAKE_CASE__ ,2_2) __lowerCamelCase : Any = (a & b) ^ (a & c) ^ (b & c) __lowerCamelCase : int = (sa + maj) % 0x100000000 __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Dict = ( g, f, e, ((d + tempa) % 0x100000000), c, b, a, ((tempa + tempa) % 0x100000000), ) __lowerCamelCase : Tuple = [a, b, c, d, e, f, g, h] # Modify final values __lowerCamelCase : Dict = [ ((element + mutated_hash_values[index]) % 0x100000000) for index, element in enumerate(self.hashes) ] __lowerCamelCase : Any = ''.join([hex(SCREAMING_SNAKE_CASE__)[2:].zfill(8) for value in self.hashes]) def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int): return 0xffffffff & (value << (3_2 - rotations)) | (value >> rotations) class A_ ( unittest.TestCase ): def lowerCAmelCase ( self : List[str]): import hashlib __lowerCamelCase : List[str] = bytes('Test String' ,'utf-8') self.assertEqual(SHAaaa(SCREAMING_SNAKE_CASE__).hash ,hashlib.shaaaa(SCREAMING_SNAKE_CASE__).hexdigest()) def SCREAMING_SNAKE_CASE__ ( ) -> None: import doctest doctest.testmod() __lowerCamelCase : List[str] = argparse.ArgumentParser() parser.add_argument( '-s' , '--string' , dest='input_string' , default='Hello World!! Welcome to Cryptography' , help='Hash the string' , ) parser.add_argument( '-f' , '--file' , dest='input_file' , help='Hash contents of a file' ) __lowerCamelCase : Optional[Any] = parser.parse_args() __lowerCamelCase : str = args.input_string # hash input should be a bytestring if args.input_file: with open(args.input_file , 'rb' ) as f: __lowerCamelCase : str = f.read() else: __lowerCamelCase : Optional[int] = bytes(lowerCamelCase__ , 'utf-8' ) print(SHAaaa(lowerCamelCase__ ).hash ) if __name__ == "__main__": main()
73
"""simple docstring""" from __future__ import annotations lowerCamelCase__ = list[tuple[int, int]] lowerCamelCase__ = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] lowerCamelCase__ = ([-1, 0], [0, -1], [1, 0], [0, 1]) # up, left, down, right class A__ : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , ): __lowerCAmelCase : int = pos_x __lowerCAmelCase : Optional[Any] = pos_y __lowerCAmelCase : Optional[int] = (pos_y, pos_x) __lowerCAmelCase : Union[str, Any] = goal_x __lowerCAmelCase : Any = goal_y __lowerCAmelCase : Optional[Any] = g_cost __lowerCAmelCase : Any = parent __lowerCAmelCase : Union[str, Any] = self.calculate_heuristic() def __lowerCamelCase ( self ): __lowerCAmelCase : str = abs(self.pos_x - self.goal_x ) __lowerCAmelCase : str = abs(self.pos_y - self.goal_y ) return dx + dy def __lt__( self , _SCREAMING_SNAKE_CASE ): return self.f_cost < other.f_cost class A__ : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Optional[int] = Node(start[1] , start[0] , goal[1] , goal[0] , 0 , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Any = Node(goal[1] , goal[0] , goal[1] , goal[0] , 9_99_99 , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Tuple = [self.start] __lowerCAmelCase : list[Node] = [] __lowerCAmelCase : str = False def __lowerCamelCase ( self ): while self.open_nodes: # Open Nodes are sorted using __lt__ self.open_nodes.sort() __lowerCAmelCase : Optional[int] = self.open_nodes.pop(0 ) if current_node.pos == self.target.pos: __lowerCAmelCase : Union[str, Any] = True return self.retrace_path(_SCREAMING_SNAKE_CASE ) self.closed_nodes.append(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = self.get_successors(_SCREAMING_SNAKE_CASE ) for child_node in successors: if child_node in self.closed_nodes: continue if child_node not in self.open_nodes: self.open_nodes.append(_SCREAMING_SNAKE_CASE ) else: # retrieve the best current path __lowerCAmelCase : Optional[Any] = self.open_nodes.pop(self.open_nodes.index(_SCREAMING_SNAKE_CASE ) ) if child_node.g_cost < better_node.g_cost: self.open_nodes.append(_SCREAMING_SNAKE_CASE ) else: self.open_nodes.append(_SCREAMING_SNAKE_CASE ) if not self.reached: return [self.start.pos] return None def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Dict = [] for action in delta: __lowerCAmelCase : Optional[int] = parent.pos_x + action[1] __lowerCAmelCase : Union[str, Any] = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(_SCREAMING_SNAKE_CASE ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , self.target.pos_y , self.target.pos_x , parent.g_cost + 1 , _SCREAMING_SNAKE_CASE , ) ) return successors def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Union[str, Any] = node __lowerCAmelCase : Optional[int] = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) __lowerCAmelCase : int = current_node.parent path.reverse() return path if __name__ == "__main__": lowerCamelCase__ = (0, 0) lowerCamelCase__ = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) print("""------""") lowerCamelCase__ = GreedyBestFirst(init, goal) lowerCamelCase__ = greedy_bf.search() if path: for pos_x, pos_y in path: lowerCamelCase__ = 2 for elem in grid: print(elem)
86
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowercase = { '''configuration_swinv2''': ['''SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Swinv2Config'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Swinv2ForImageClassification''', '''Swinv2ForMaskedImageModeling''', '''Swinv2Model''', '''Swinv2PreTrainedModel''', ] if TYPE_CHECKING: from .configuration_swinva import SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP, SwinvaConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_swinva import ( SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST, SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel, SwinvaPreTrainedModel, ) else: import sys _lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
74
"""simple docstring""" def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): return round(float(moles / volume ) * nfactor ) def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): return round(float((moles * 0.0821 * temperature) / (volume) ) ) def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): return round(float((moles * 0.0821 * temperature) / (pressure) ) ) def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): return round(float((pressure * volume) / (0.0821 * moles) ) ) if __name__ == "__main__": import doctest doctest.testmod()
86
0
'''simple docstring''' def a_ ( __snake_case : int , __snake_case : int ) -> int: """simple docstring""" while b: lowerCamelCase_, lowerCamelCase_ =b, a % b return a def a_ ( __snake_case : int , __snake_case : int ) -> int: """simple docstring""" return a if b == 0 else euclidean_gcd_recursive(__snake_case , a % b ) def a_ ( ) -> str: """simple docstring""" print(F'''euclidean_gcd(3, 5) = {euclidean_gcd(3 , 5 )}''' ) print(F'''euclidean_gcd(5, 3) = {euclidean_gcd(5 , 3 )}''' ) print(F'''euclidean_gcd(1, 3) = {euclidean_gcd(1 , 3 )}''' ) print(F'''euclidean_gcd(3, 6) = {euclidean_gcd(3 , 6 )}''' ) print(F'''euclidean_gcd(6, 3) = {euclidean_gcd(6 , 3 )}''' ) print(F'''euclidean_gcd_recursive(3, 5) = {euclidean_gcd_recursive(3 , 5 )}''' ) print(F'''euclidean_gcd_recursive(5, 3) = {euclidean_gcd_recursive(5 , 3 )}''' ) print(F'''euclidean_gcd_recursive(1, 3) = {euclidean_gcd_recursive(1 , 3 )}''' ) print(F'''euclidean_gcd_recursive(3, 6) = {euclidean_gcd_recursive(3 , 6 )}''' ) print(F'''euclidean_gcd_recursive(6, 3) = {euclidean_gcd_recursive(6 , 3 )}''' ) if __name__ == "__main__": main()
75
"""simple docstring""" import enum import warnings from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING from ..utils import add_end_docstrings, is_tf_available from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf class A__ ( enum.Enum): A_ : List[Any] = 0 A_ : Dict = 1 A_ : Union[str, Any] = 2 @add_end_docstrings(_lowerCamelCase) class A__ ( _lowerCamelCase): A_ : str = '\n In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The\n voice of Nicholas\'s young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western\n Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision\n and denounces one of the men as a horse thief. Although his father initially slaps him for making such an\n accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of\n the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop,\n begging for his blessing. <eod> </s> <eos>\n ' def __init__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ): super().__init__(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) self.check_model_type( TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == 'tf' else MODEL_FOR_CAUSAL_LM_MAPPING ) if "prefix" not in self._preprocess_params: # This is very specific. The logic is quite complex and needs to be done # as a "default". # It also defines both some preprocess_kwargs and generate_kwargs # which is why we cannot put them in their respective methods. __lowerCAmelCase : Any = None if self.model.config.prefix is not None: __lowerCAmelCase : str = self.model.config.prefix if prefix is None and self.model.__class__.__name__ in [ "XLNetLMHeadModel", "TransfoXLLMHeadModel", "TFXLNetLMHeadModel", "TFTransfoXLLMHeadModel", ]: # For XLNet and TransformerXL we add an article to the prompt to give more state to the model. __lowerCAmelCase : Tuple = self.XL_PREFIX if prefix is not None: # Recalculate some generate_kwargs linked to prefix. __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase : Union[str, Any] = self._sanitize_parameters(prefix=_SCREAMING_SNAKE_CASE , **self._forward_params ) __lowerCAmelCase : List[str] = {**self._preprocess_params, **preprocess_params} __lowerCAmelCase : List[str] = {**self._forward_params, **forward_params} def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE , ): __lowerCAmelCase : Optional[int] = {} if prefix is not None: __lowerCAmelCase : Union[str, Any] = prefix if prefix: __lowerCAmelCase : Dict = self.tokenizer( _SCREAMING_SNAKE_CASE , padding=_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE , return_tensors=self.framework ) __lowerCAmelCase : List[Any] = prefix_inputs['input_ids'].shape[-1] if handle_long_generation is not None: if handle_long_generation not in {"hole"}: raise ValueError( f"{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected" ' [None, \'hole\']' ) __lowerCAmelCase : int = handle_long_generation preprocess_params.update(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : int = generate_kwargs __lowerCAmelCase : List[Any] = {} if return_full_text is not None and return_type is None: if return_text is not None: raise ValueError('`return_text` is mutually exclusive with `return_full_text`' ) if return_tensors is not None: raise ValueError('`return_full_text` is mutually exclusive with `return_tensors`' ) __lowerCAmelCase : Optional[Any] = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT if return_tensors is not None and return_type is None: if return_text is not None: raise ValueError('`return_text` is mutually exclusive with `return_tensors`' ) __lowerCAmelCase : List[Any] = ReturnType.TENSORS if return_type is not None: __lowerCAmelCase : Optional[Any] = return_type if clean_up_tokenization_spaces is not None: __lowerCAmelCase : Tuple = clean_up_tokenization_spaces if stop_sequence is not None: __lowerCAmelCase : Union[str, Any] = self.tokenizer.encode(_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE ) if len(_SCREAMING_SNAKE_CASE ) > 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.' ) __lowerCAmelCase : Optional[Any] = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def __lowerCamelCase ( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ): # Parse arguments if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]: kwargs.update({'add_space_before_punct_symbol': True} ) return super()._parse_and_tokenize(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def __call__( self , _SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ): return super().__call__(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE="" , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Any = self.tokenizer( prefix + prompt_text , padding=_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE , return_tensors=self.framework ) __lowerCAmelCase : Optional[Any] = prompt_text if handle_long_generation == "hole": __lowerCAmelCase : str = inputs['input_ids'].shape[-1] if "max_new_tokens" in generate_kwargs: __lowerCAmelCase : Union[str, Any] = generate_kwargs['max_new_tokens'] else: __lowerCAmelCase : Any = generate_kwargs.get('max_length' , self.model.config.max_length ) - cur_len if new_tokens < 0: raise ValueError('We cannot infer how many new tokens are expected' ) if cur_len + new_tokens > self.tokenizer.model_max_length: __lowerCAmelCase : Any = self.tokenizer.model_max_length - new_tokens if keep_length <= 0: raise ValueError( 'We cannot use `hole` to handle this generation the number of desired tokens exceeds the' ' models max length' ) __lowerCAmelCase : int = inputs['input_ids'][:, -keep_length:] if "attention_mask" in inputs: __lowerCAmelCase : List[Any] = inputs['attention_mask'][:, -keep_length:] return inputs def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ): __lowerCAmelCase : str = model_inputs['input_ids'] __lowerCAmelCase : List[Any] = model_inputs.get('attention_mask' , _SCREAMING_SNAKE_CASE ) # Allow empty prompts if input_ids.shape[1] == 0: __lowerCAmelCase : Dict = None __lowerCAmelCase : str = None __lowerCAmelCase : Tuple = 1 else: __lowerCAmelCase : Any = input_ids.shape[0] __lowerCAmelCase : Union[str, Any] = model_inputs.pop('prompt_text' ) # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline. __lowerCAmelCase : Optional[int] = generate_kwargs.pop('prefix_length' , 0 ) if prefix_length > 0: __lowerCAmelCase : Any = 'max_new_tokens' in generate_kwargs or ( 'generation_config' in generate_kwargs and generate_kwargs['generation_config'].max_new_tokens is not None ) if not has_max_new_tokens: __lowerCAmelCase : List[str] = generate_kwargs.get('max_length' ) or self.model.config.max_length generate_kwargs["max_length"] += prefix_length __lowerCAmelCase : Dict = 'min_new_tokens' in generate_kwargs or ( 'generation_config' in generate_kwargs and generate_kwargs['generation_config'].min_new_tokens is not None ) if not has_min_new_tokens and "min_length" in generate_kwargs: generate_kwargs["min_length"] += prefix_length # BS x SL __lowerCAmelCase : Optional[int] = self.model.generate(input_ids=_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = generated_sequence.shape[0] if self.framework == "pt": __lowerCAmelCase : Dict = generated_sequence.reshape(_SCREAMING_SNAKE_CASE , out_b // in_b , *generated_sequence.shape[1:] ) elif self.framework == "tf": __lowerCAmelCase : Any = tf.reshape(_SCREAMING_SNAKE_CASE , (in_b, out_b // in_b, *generated_sequence.shape[1:]) ) return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text} def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=ReturnType.FULL_TEXT , _SCREAMING_SNAKE_CASE=True ): __lowerCAmelCase : Any = model_outputs['generated_sequence'][0] __lowerCAmelCase : Tuple = model_outputs['input_ids'] __lowerCAmelCase : Any = model_outputs['prompt_text'] __lowerCAmelCase : int = generated_sequence.numpy().tolist() __lowerCAmelCase : Union[str, Any] = [] for sequence in generated_sequence: if return_type == ReturnType.TENSORS: __lowerCAmelCase : int = {'generated_token_ids': sequence} elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}: # Decode text __lowerCAmelCase : Any = self.tokenizer.decode( _SCREAMING_SNAKE_CASE , skip_special_tokens=_SCREAMING_SNAKE_CASE , clean_up_tokenization_spaces=_SCREAMING_SNAKE_CASE , ) # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used if input_ids is None: __lowerCAmelCase : Optional[Any] = 0 else: __lowerCAmelCase : Any = len( self.tokenizer.decode( input_ids[0] , skip_special_tokens=_SCREAMING_SNAKE_CASE , clean_up_tokenization_spaces=_SCREAMING_SNAKE_CASE , ) ) if return_type == ReturnType.FULL_TEXT: __lowerCAmelCase : Union[str, Any] = prompt_text + text[prompt_length:] else: __lowerCAmelCase : int = text[prompt_length:] __lowerCAmelCase : Dict = {'generated_text': all_text} records.append(_SCREAMING_SNAKE_CASE ) return records
86
0
import unittest from accelerate import debug_launcher from accelerate.test_utils import require_cpu, test_ops, test_script @require_cpu class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCamelCase ( self : Optional[int] ) -> Optional[Any]: """simple docstring""" debug_launcher(test_script.main ) def __UpperCamelCase ( self : int ) -> str: """simple docstring""" debug_launcher(test_ops.main )
76
"""simple docstring""" from __future__ import annotations import bisect def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase = 0 , _UpperCamelCase = -1 ): if hi < 0: __lowerCAmelCase : Tuple = len(_UpperCamelCase ) while lo < hi: __lowerCAmelCase : Optional[int] = lo + (hi - lo) // 2 if sorted_collection[mid] < item: __lowerCAmelCase : int = mid + 1 else: __lowerCAmelCase : List[str] = mid return lo def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase = 0 , _UpperCamelCase = -1 ): if hi < 0: __lowerCAmelCase : List[Any] = len(_UpperCamelCase ) while lo < hi: __lowerCAmelCase : Union[str, Any] = lo + (hi - lo) // 2 if sorted_collection[mid] <= item: __lowerCAmelCase : Dict = mid + 1 else: __lowerCAmelCase : str = mid return lo def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase = 0 , _UpperCamelCase = -1 ): sorted_collection.insert(bisect_left(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) , _UpperCamelCase ) def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase = 0 , _UpperCamelCase = -1 ): sorted_collection.insert(bisect_right(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) , _UpperCamelCase ) def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase ): __lowerCAmelCase : List[Any] = 0 __lowerCAmelCase : int = len(_UpperCamelCase ) - 1 while left <= right: __lowerCAmelCase : List[Any] = left + (right - left) // 2 __lowerCAmelCase : Union[str, Any] = sorted_collection[midpoint] if current_item == item: return midpoint elif item < current_item: __lowerCAmelCase : Tuple = midpoint - 1 else: __lowerCAmelCase : str = midpoint + 1 return None def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase ): __lowerCAmelCase : Union[str, Any] = bisect.bisect_left(_UpperCamelCase , _UpperCamelCase ) if index != len(_UpperCamelCase ) and sorted_collection[index] == item: return index return None def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): if right < left: return None __lowerCAmelCase : List[str] = left + (right - left) // 2 if sorted_collection[midpoint] == item: return midpoint elif sorted_collection[midpoint] > item: return binary_search_by_recursion(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , midpoint - 1 ) else: return binary_search_by_recursion(_UpperCamelCase , _UpperCamelCase , midpoint + 1 , _UpperCamelCase ) if __name__ == "__main__": lowerCamelCase__ = input("""Enter numbers separated by comma:\n""").strip() lowerCamelCase__ = sorted(int(item) for item in user_input.split(""",""")) lowerCamelCase__ = int(input("""Enter a single number to be found in the list:\n""")) lowerCamelCase__ = binary_search(collection, target) if result is None: print(f'{target} was not found in {collection}.') else: print(f'{target} was found at position {result} in {collection}.')
86
0
"""simple docstring""" import random def a_ ( _lowerCAmelCase : list , _lowerCAmelCase : int ): '''simple docstring''' lowercase__ , lowercase__ , lowercase__ : List[Any] = [], [], [] for element in data: if element < pivot: less.append(_lowerCAmelCase ) elif element > pivot: greater.append(_lowerCAmelCase ) else: equal.append(_lowerCAmelCase ) return less, equal, greater def a_ ( _lowerCAmelCase : list , _lowerCAmelCase : int ): '''simple docstring''' if index >= len(_lowerCAmelCase ) or index < 0: return None lowercase__ : List[str] = items[random.randint(0 , len(_lowerCAmelCase ) - 1 )] lowercase__ : str = 0 lowercase__ , lowercase__ , lowercase__ : str = _partition(_lowerCAmelCase , _lowerCAmelCase ) lowercase__ : Tuple = len(_lowerCAmelCase ) lowercase__ : Any = len(_lowerCAmelCase ) # index is the pivot if m <= index < m + count: return pivot # must be in smaller elif m > index: return quick_select(_lowerCAmelCase , _lowerCAmelCase ) # must be in larger else: return quick_select(_lowerCAmelCase , index - (m + count) )
77
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available, is_torch_available from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, is_pt_tf_cross_test, slow if is_tf_available(): from transformers import ( AutoConfig, BertConfig, GPTaConfig, TaConfig, TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSeqaSeqLM, TFAutoModelForSequenceClassification, TFAutoModelWithLMHead, TFBertForMaskedLM, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertModel, TFGPTaLMHeadModel, TFRobertaForMaskedLM, TFTaForConditionalGeneration, ) from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST if is_torch_available(): from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForPreTraining, AutoModelForQuestionAnswering, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoModelWithLMHead, BertForMaskedLM, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, BertModel, GPTaLMHeadModel, RobertaForMaskedLM, TaForConditionalGeneration, ) @is_pt_tf_cross_test class A__ ( unittest.TestCase): @slow def __lowerCamelCase ( self ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __lowerCAmelCase : Tuple = AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = TFAutoModel.from_pretrained(_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = AutoModel.from_pretrained(_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @slow def __lowerCamelCase ( self ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __lowerCAmelCase : int = AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Tuple = TFAutoModelForPreTraining.from_pretrained(_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : str = AutoModelForPreTraining.from_pretrained(_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @slow def __lowerCamelCase ( self ): for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCAmelCase : Dict = AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = TFAutoModelForCausalLM.from_pretrained(_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase , __lowerCAmelCase : List[str] = TFAutoModelForCausalLM.from_pretrained( _SCREAMING_SNAKE_CASE , output_loading_info=_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Any = AutoModelForCausalLM.from_pretrained(_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase , __lowerCAmelCase : List[Any] = AutoModelForCausalLM.from_pretrained( _SCREAMING_SNAKE_CASE , output_loading_info=_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @slow def __lowerCamelCase ( self ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCAmelCase : Dict = AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : int = TFAutoModelWithLMHead.from_pretrained(_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = AutoModelWithLMHead.from_pretrained(_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @slow def __lowerCamelCase ( self ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCAmelCase : Optional[Any] = AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = TFAutoModelForMaskedLM.from_pretrained(_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase , __lowerCAmelCase : int = TFAutoModelForMaskedLM.from_pretrained( _SCREAMING_SNAKE_CASE , output_loading_info=_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Union[str, Any] = AutoModelForMaskedLM.from_pretrained(_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase , __lowerCAmelCase : str = AutoModelForMaskedLM.from_pretrained( _SCREAMING_SNAKE_CASE , output_loading_info=_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @slow def __lowerCamelCase ( self ): for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCAmelCase : Optional[int] = AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Tuple = TFAutoModelForSeqaSeqLM.from_pretrained(_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase , __lowerCAmelCase : Tuple = TFAutoModelForSeqaSeqLM.from_pretrained( _SCREAMING_SNAKE_CASE , output_loading_info=_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : int = AutoModelForSeqaSeqLM.from_pretrained(_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase , __lowerCAmelCase : Dict = AutoModelForSeqaSeqLM.from_pretrained( _SCREAMING_SNAKE_CASE , output_loading_info=_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @slow def __lowerCamelCase ( self ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __lowerCAmelCase : Dict = AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = TFAutoModelForSequenceClassification.from_pretrained(_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Union[str, Any] = AutoModelForSequenceClassification.from_pretrained(_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @slow def __lowerCamelCase ( self ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __lowerCAmelCase : Union[str, Any] = AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = TFAutoModelForQuestionAnswering.from_pretrained(_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Union[str, Any] = AutoModelForQuestionAnswering.from_pretrained(_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : List[Any] = TFAutoModelWithLMHead.from_pretrained(_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) self.assertEqual(model.num_parameters() , 1_44_10 ) self.assertEqual(model.num_parameters(only_trainable=_SCREAMING_SNAKE_CASE ) , 1_44_10 ) __lowerCAmelCase : Tuple = AutoModelWithLMHead.from_pretrained(_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) self.assertEqual(model.num_parameters() , 1_44_10 ) self.assertEqual(model.num_parameters(only_trainable=_SCREAMING_SNAKE_CASE ) , 1_44_10 ) def __lowerCamelCase ( self ): __lowerCAmelCase : int = TFAutoModelWithLMHead.from_pretrained(_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) self.assertEqual(model.num_parameters() , 1_44_10 ) self.assertEqual(model.num_parameters(only_trainable=_SCREAMING_SNAKE_CASE ) , 1_44_10 ) __lowerCAmelCase : Tuple = AutoModelWithLMHead.from_pretrained(_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) self.assertEqual(model.num_parameters() , 1_44_10 ) self.assertEqual(model.num_parameters(only_trainable=_SCREAMING_SNAKE_CASE ) , 1_44_10 )
86
0
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import normalizers from ....tokenization_utils_fast import PreTrainedTokenizerFast from ....utils import logging from .tokenization_retribert import RetriBertTokenizer snake_case_ = logging.get_logger(__name__) snake_case_ = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""} snake_case_ = { """vocab_file""": { """yjernite/retribert-base-uncased""": ( """https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/vocab.txt""" ), }, """tokenizer_file""": { """yjernite/retribert-base-uncased""": ( """https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/tokenizer.json""" ), }, } snake_case_ = { """yjernite/retribert-base-uncased""": 512, } snake_case_ = { """yjernite/retribert-base-uncased""": {"""do_lower_case""": True}, } class A_ ( SCREAMING_SNAKE_CASE_ ): """simple docstring""" __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = PRETRAINED_INIT_CONFIGURATION __UpperCamelCase = RetriBertTokenizer __UpperCamelCase = ["""input_ids""", """attention_mask"""] def __init__( self :str , lowercase_ :List[str]=None , lowercase_ :List[str]=None , lowercase_ :str=True , lowercase_ :List[str]="[UNK]" , lowercase_ :Optional[Any]="[SEP]" , lowercase_ :Tuple="[PAD]" , lowercase_ :int="[CLS]" , lowercase_ :Optional[Any]="[MASK]" , lowercase_ :str=True , lowercase_ :Dict=None , **lowercase_ :List[Any] , ) -> Union[str, Any]: super().__init__( lowercase_ , tokenizer_file=lowercase_ , do_lower_case=lowercase_ , unk_token=lowercase_ , sep_token=lowercase_ , pad_token=lowercase_ , cls_token=lowercase_ , mask_token=lowercase_ , tokenize_chinese_chars=lowercase_ , strip_accents=lowercase_ , **lowercase_ , ) UpperCAmelCase = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' , lowercase_ ) != do_lower_case or normalizer_state.get('strip_accents' , lowercase_ ) != strip_accents or normalizer_state.get('handle_chinese_chars' , lowercase_ ) != tokenize_chinese_chars ): UpperCAmelCase = getattr(lowercase_ , normalizer_state.pop('type' ) ) UpperCAmelCase = do_lower_case UpperCAmelCase = strip_accents UpperCAmelCase = tokenize_chinese_chars UpperCAmelCase = normalizer_class(**lowercase_ ) UpperCAmelCase = do_lower_case def UpperCAmelCase__ ( self :Any , lowercase_ :Any , lowercase_ :Tuple=None ) -> Union[str, Any]: UpperCAmelCase = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def UpperCAmelCase__ ( self :Tuple , lowercase_ :List[int] , lowercase_ :Optional[List[int]] = None ) -> List[int]: UpperCAmelCase = [self.sep_token_id] UpperCAmelCase = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCAmelCase__ ( self :Union[str, Any] , lowercase_ :str , lowercase_ :Optional[str] = None ) -> Tuple[str]: UpperCAmelCase = self._tokenizer.model.save(lowercase_ , name=lowercase_ ) return tuple(lowercase_ )
78
"""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 lowerCamelCase__ = logging.get_logger(__name__) # pylint: disable=invalid-name lowerCamelCase__ = """ 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 (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase=8 ): __lowerCAmelCase : Dict = h // scale_factor**2 if h % scale_factor**2 != 0: new_h += 1 __lowerCAmelCase : List[str] = w // scale_factor**2 if w % scale_factor**2 != 0: new_w += 1 return new_h * scale_factor, new_w * scale_factor class A__ ( _lowerCamelCase): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , ): super().__init__() self.register_modules( text_encoder=_SCREAMING_SNAKE_CASE , tokenizer=_SCREAMING_SNAKE_CASE , unet=_SCREAMING_SNAKE_CASE , scheduler=_SCREAMING_SNAKE_CASE , movq=_SCREAMING_SNAKE_CASE , ) __lowerCAmelCase : Dict = 2 ** (len(self.movq.config.block_out_channels ) - 1) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): if latents is None: __lowerCAmelCase : Tuple = randn_tensor(_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , device=_SCREAMING_SNAKE_CASE , dtype=_SCREAMING_SNAKE_CASE ) else: if latents.shape != shape: raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}" ) __lowerCAmelCase : Any = latents.to(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = latents * scheduler.init_noise_sigma return latents def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , ): __lowerCAmelCase : Tuple = len(_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else 1 # get prompt text embeddings __lowerCAmelCase : Dict = self.tokenizer( _SCREAMING_SNAKE_CASE , padding='max_length' , truncation=_SCREAMING_SNAKE_CASE , max_length=77 , return_attention_mask=_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE , return_tensors='pt' , ) __lowerCAmelCase : Tuple = text_inputs.input_ids __lowerCAmelCase : Union[str, Any] = self.tokenizer(_SCREAMING_SNAKE_CASE , padding='longest' , return_tensors='pt' ).input_ids if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : List[Any] = 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}" ) __lowerCAmelCase : Dict = text_input_ids.to(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = text_inputs.attention_mask.to(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase , __lowerCAmelCase : str = self.text_encoder( input_ids=_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Any = prompt_embeds.repeat_interleave(_SCREAMING_SNAKE_CASE , dim=0 ) __lowerCAmelCase : Dict = text_encoder_hidden_states.repeat_interleave(_SCREAMING_SNAKE_CASE , dim=0 ) __lowerCAmelCase : Optional[int] = text_mask.repeat_interleave(_SCREAMING_SNAKE_CASE , dim=0 ) if do_classifier_free_guidance: __lowerCAmelCase : List[str] if negative_prompt is None: __lowerCAmelCase : Union[str, Any] = [''] * batch_size elif type(_SCREAMING_SNAKE_CASE ) is not type(_SCREAMING_SNAKE_CASE ): raise TypeError( f"`negative_prompt` should be the same type to `prompt`, but got {type(_SCREAMING_SNAKE_CASE )} !=" f" {type(_SCREAMING_SNAKE_CASE )}." ) elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Optional[int] = [negative_prompt] elif batch_size != len(_SCREAMING_SNAKE_CASE ): raise ValueError( f"`negative_prompt`: {negative_prompt} has batch size {len(_SCREAMING_SNAKE_CASE )}, but `prompt`:" f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" ' the batch size of `prompt`.' ) else: __lowerCAmelCase : Optional[int] = negative_prompt __lowerCAmelCase : Tuple = self.tokenizer( _SCREAMING_SNAKE_CASE , padding='max_length' , max_length=77 , truncation=_SCREAMING_SNAKE_CASE , return_attention_mask=_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE , return_tensors='pt' , ) __lowerCAmelCase : Union[str, Any] = uncond_input.input_ids.to(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = uncond_input.attention_mask.to(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase , __lowerCAmelCase : Any = self.text_encoder( input_ids=_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE ) # duplicate unconditional embeddings for each generation per prompt, using mps friendly method __lowerCAmelCase : List[str] = negative_prompt_embeds.shape[1] __lowerCAmelCase : Any = negative_prompt_embeds.repeat(1 , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = negative_prompt_embeds.view(batch_size * num_images_per_prompt , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : int = uncond_text_encoder_hidden_states.shape[1] __lowerCAmelCase : List[Any] = uncond_text_encoder_hidden_states.repeat(1 , _SCREAMING_SNAKE_CASE , 1 ) __lowerCAmelCase : Optional[int] = uncond_text_encoder_hidden_states.view( batch_size * num_images_per_prompt , _SCREAMING_SNAKE_CASE , -1 ) __lowerCAmelCase : Optional[Any] = uncond_text_mask.repeat_interleave(_SCREAMING_SNAKE_CASE , 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 __lowerCAmelCase : Tuple = torch.cat([negative_prompt_embeds, prompt_embeds] ) __lowerCAmelCase : Tuple = torch.cat([uncond_text_encoder_hidden_states, text_encoder_hidden_states] ) __lowerCAmelCase : int = torch.cat([uncond_text_mask, text_mask] ) return prompt_embeds, text_encoder_hidden_states, text_mask def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE=0 ): if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('Please install accelerate via `pip install accelerate`' ) __lowerCAmelCase : Union[str, Any] = torch.device(f"cuda:{gpu_id}" ) __lowerCAmelCase : List[Any] = [ self.unet, self.text_encoder, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE=0 ): 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.' ) __lowerCAmelCase : str = torch.device(f"cuda:{gpu_id}" ) if self.device.type != "cpu": self.to('cpu' , silence_dtype_warnings=_SCREAMING_SNAKE_CASE ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) __lowerCAmelCase : Any = None for cpu_offloaded_model in [self.text_encoder, self.unet, self.movq]: __lowerCAmelCase , __lowerCAmelCase : Any = cpu_offload_with_hook(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , prev_module_hook=_SCREAMING_SNAKE_CASE ) if self.safety_checker is not None: __lowerCAmelCase , __lowerCAmelCase : Dict = cpu_offload_with_hook(self.safety_checker , _SCREAMING_SNAKE_CASE , prev_module_hook=_SCREAMING_SNAKE_CASE ) # We'll offload the last model manually. __lowerCAmelCase : Optional[Any] = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def __lowerCamelCase ( self ): if not hasattr(self.unet , '_hf_hook' ): return self.device for module in self.unet.modules(): if ( hasattr(_SCREAMING_SNAKE_CASE , '_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(_SCREAMING_SNAKE_CASE ) def __call__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 5_12 , _SCREAMING_SNAKE_CASE = 5_12 , _SCREAMING_SNAKE_CASE = 1_00 , _SCREAMING_SNAKE_CASE = 4.0 , _SCREAMING_SNAKE_CASE = 1 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = "pil" , _SCREAMING_SNAKE_CASE = True , ): if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : List[str] = 1 elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Optional[int] = len(_SCREAMING_SNAKE_CASE ) else: raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(_SCREAMING_SNAKE_CASE )}" ) __lowerCAmelCase : Dict = self._execution_device __lowerCAmelCase : Optional[Any] = batch_size * num_images_per_prompt __lowerCAmelCase : Optional[int] = guidance_scale > 1.0 __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase : int = self._encode_prompt( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : int = torch.cat(_SCREAMING_SNAKE_CASE , dim=0 ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Dict = torch.cat(_SCREAMING_SNAKE_CASE , dim=0 ) if do_classifier_free_guidance: __lowerCAmelCase : Optional[Any] = image_embeds.repeat_interleave(_SCREAMING_SNAKE_CASE , dim=0 ) __lowerCAmelCase : int = negative_image_embeds.repeat_interleave(_SCREAMING_SNAKE_CASE , dim=0 ) __lowerCAmelCase : Any = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to( dtype=prompt_embeds.dtype , device=_SCREAMING_SNAKE_CASE ) self.scheduler.set_timesteps(_SCREAMING_SNAKE_CASE , device=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = self.scheduler.timesteps __lowerCAmelCase : int = self.unet.config.in_channels __lowerCAmelCase , __lowerCAmelCase : Any = get_new_h_w(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , self.movq_scale_factor ) # create initial latent __lowerCAmelCase : str = self.prepare_latents( (batch_size, num_channels_latents, height, width) , text_encoder_hidden_states.dtype , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , self.scheduler , ) for i, t in enumerate(self.progress_bar(_SCREAMING_SNAKE_CASE ) ): # expand the latents if we are doing classifier free guidance __lowerCAmelCase : List[str] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents __lowerCAmelCase : Union[str, Any] = {'text_embeds': prompt_embeds, 'image_embeds': image_embeds} __lowerCAmelCase : Optional[Any] = self.unet( sample=_SCREAMING_SNAKE_CASE , timestep=_SCREAMING_SNAKE_CASE , encoder_hidden_states=_SCREAMING_SNAKE_CASE , added_cond_kwargs=_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , )[0] if do_classifier_free_guidance: __lowerCAmelCase , __lowerCAmelCase : Dict = noise_pred.split(latents.shape[1] , dim=1 ) __lowerCAmelCase , __lowerCAmelCase : Optional[Any] = noise_pred.chunk(2 ) __lowerCAmelCase , __lowerCAmelCase : int = variance_pred.chunk(2 ) __lowerCAmelCase : Dict = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) __lowerCAmelCase : 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"] ): __lowerCAmelCase , __lowerCAmelCase : Union[str, Any] = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 __lowerCAmelCase : List[str] = self.scheduler.step( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , ).prev_sample # post-processing __lowerCAmelCase : Tuple = self.movq.decode(_SCREAMING_SNAKE_CASE , force_not_quantize=_SCREAMING_SNAKE_CASE )['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"]: __lowerCAmelCase : List[str] = image * 0.5 + 0.5 __lowerCAmelCase : Dict = image.clamp(0 , 1 ) __lowerCAmelCase : Dict = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": __lowerCAmelCase : Union[str, Any] = self.numpy_to_pil(_SCREAMING_SNAKE_CASE ) if not return_dict: return (image,) return ImagePipelineOutput(images=_SCREAMING_SNAKE_CASE )
86
0
'''simple docstring''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionPanoramaPipeline, UNetaDConditionModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() @skip_mps class _UpperCAmelCase ( snake_case_ , snake_case_ , unittest.TestCase ): """simple docstring""" snake_case = StableDiffusionPanoramaPipeline snake_case = TEXT_TO_IMAGE_PARAMS snake_case = TEXT_TO_IMAGE_BATCH_PARAMS snake_case = TEXT_TO_IMAGE_IMAGE_PARAMS snake_case = TEXT_TO_IMAGE_IMAGE_PARAMS def lowerCAmelCase ( self : str ): '''simple docstring''' torch.manual_seed(0 ) _A = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=1 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") , cross_attention_dim=32 , ) _A = DDIMScheduler() torch.manual_seed(0 ) _A = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) torch.manual_seed(0 ) _A = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) _A = CLIPTextModel(__UpperCAmelCase ) _A = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) _A = { "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "safety_checker": None, "feature_extractor": None, } return components def lowerCAmelCase ( self : List[Any] , __UpperCAmelCase : Any , __UpperCAmelCase : List[Any]=0 ): '''simple docstring''' _A = torch.manual_seed(__UpperCAmelCase ) _A = { "prompt": "a photo of the dolomites", "generator": generator, # Setting height and width to None to prevent OOMs on CPU. "height": None, "width": None, "num_inference_steps": 1, "guidance_scale": 6.0, "output_type": "numpy", } return inputs def lowerCAmelCase ( self : List[Any] ): '''simple docstring''' _A = "cpu" # ensure determinism for the device-dependent torch.Generator _A = self.get_dummy_components() _A = StableDiffusionPanoramaPipeline(**__UpperCAmelCase ) _A = sd_pipe.to(__UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=__UpperCAmelCase ) _A = self.get_dummy_inputs(__UpperCAmelCase ) _A = sd_pipe(**__UpperCAmelCase ).images _A = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _A = np.array([0.6186, 0.5374, 0.4915, 0.4135, 0.4114, 0.4563, 0.5128, 0.4977, 0.4757] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def lowerCAmelCase ( self : List[Any] ): '''simple docstring''' super().test_inference_batch_consistent(batch_sizes=[1, 2] ) def lowerCAmelCase ( self : List[Any] ): '''simple docstring''' super().test_inference_batch_single_identical(batch_size=2 , expected_max_diff=3.25E-3 ) def lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' _A = "cpu" # ensure determinism for the device-dependent torch.Generator _A = self.get_dummy_components() _A = StableDiffusionPanoramaPipeline(**__UpperCAmelCase ) _A = sd_pipe.to(__UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=__UpperCAmelCase ) _A = self.get_dummy_inputs(__UpperCAmelCase ) _A = "french fries" _A = sd_pipe(**__UpperCAmelCase , negative_prompt=__UpperCAmelCase ) _A = output.images _A = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _A = np.array([0.6187, 0.5375, 0.4915, 0.4136, 0.4114, 0.4563, 0.5128, 0.4976, 0.4757] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def lowerCAmelCase ( self : Optional[Any] ): '''simple docstring''' _A = "cpu" # ensure determinism for the device-dependent torch.Generator _A = self.get_dummy_components() _A = StableDiffusionPanoramaPipeline(**__UpperCAmelCase ) _A = sd_pipe.to(__UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=__UpperCAmelCase ) _A = self.get_dummy_inputs(__UpperCAmelCase ) _A = sd_pipe(**__UpperCAmelCase , view_batch_size=2 ) _A = output.images _A = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _A = np.array([0.6187, 0.5375, 0.4915, 0.4136, 0.4114, 0.4563, 0.5128, 0.4976, 0.4757] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def lowerCAmelCase ( self : List[str] ): '''simple docstring''' _A = "cpu" # ensure determinism for the device-dependent torch.Generator _A = self.get_dummy_components() _A = EulerAncestralDiscreteScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule="scaled_linear" ) _A = StableDiffusionPanoramaPipeline(**__UpperCAmelCase ) _A = sd_pipe.to(__UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=__UpperCAmelCase ) _A = self.get_dummy_inputs(__UpperCAmelCase ) _A = sd_pipe(**__UpperCAmelCase ).images _A = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _A = np.array([0.4024, 0.6510, 0.4901, 0.5378, 0.5813, 0.5622, 0.4795, 0.4467, 0.4952] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def lowerCAmelCase ( self : Dict ): '''simple docstring''' _A = "cpu" # ensure determinism for the device-dependent torch.Generator _A = self.get_dummy_components() _A = PNDMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule="scaled_linear" , skip_prk_steps=__UpperCAmelCase ) _A = StableDiffusionPanoramaPipeline(**__UpperCAmelCase ) _A = sd_pipe.to(__UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=__UpperCAmelCase ) _A = self.get_dummy_inputs(__UpperCAmelCase ) _A = sd_pipe(**__UpperCAmelCase ).images _A = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _A = np.array([0.6391, 0.6291, 0.4861, 0.5134, 0.5552, 0.4578, 0.5032, 0.5023, 0.4539] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch_gpu class _UpperCAmelCase ( unittest.TestCase ): """simple docstring""" def lowerCAmelCase ( self : Tuple ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCAmelCase ( self : int , __UpperCAmelCase : Union[str, Any]=0 ): '''simple docstring''' _A = torch.manual_seed(__UpperCAmelCase ) _A = { "prompt": "a photo of the dolomites", "generator": generator, "num_inference_steps": 3, "guidance_scale": 7.5, "output_type": "numpy", } return inputs def lowerCAmelCase ( self : List[Any] ): '''simple docstring''' _A = "stabilityai/stable-diffusion-2-base" _A = DDIMScheduler.from_pretrained(__UpperCAmelCase , subfolder="scheduler" ) _A = StableDiffusionPanoramaPipeline.from_pretrained(__UpperCAmelCase , scheduler=__UpperCAmelCase , safety_checker=__UpperCAmelCase ) pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) pipe.enable_attention_slicing() _A = self.get_inputs() _A = pipe(**__UpperCAmelCase ).images _A = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 2048, 3) _A = np.array( [ 0.36968392, 0.27025372, 0.32446766, 0.28379387, 0.36363274, 0.30733347, 0.27100027, 0.27054125, 0.25536096, ] ) assert np.abs(expected_slice - image_slice ).max() < 1E-2 def lowerCAmelCase ( self : Optional[Any] ): '''simple docstring''' _A = StableDiffusionPanoramaPipeline.from_pretrained( "stabilityai/stable-diffusion-2-base" , safety_checker=__UpperCAmelCase ) _A = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) pipe.enable_attention_slicing() _A = self.get_inputs() _A = pipe(**__UpperCAmelCase ).images _A = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 2048, 3) _A = np.array( [ [ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ] ] ) assert np.abs(expected_slice - image_slice ).max() < 1E-3 def lowerCAmelCase ( self : Tuple ): '''simple docstring''' _A = 0 def callback_fn(__UpperCAmelCase : int , __UpperCAmelCase : int , __UpperCAmelCase : torch.FloatTensor ) -> None: _A = True nonlocal number_of_steps number_of_steps += 1 if step == 1: _A = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 256) _A = latents[0, -3:, -3:, -1] _A = np.array( [ 0.18681869, 0.33907816, 0.5361276, 0.14432865, -0.02856611, -0.73941123, 0.23397987, 0.47322682, -0.37823164, ] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5E-2 elif step == 2: _A = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 256) _A = latents[0, -3:, -3:, -1] _A = np.array( [ 0.18539645, 0.33987248, 0.5378559, 0.14437142, -0.02455261, -0.7338317, 0.23990755, 0.47356272, -0.3786505, ] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5E-2 _A = False _A = "stabilityai/stable-diffusion-2-base" _A = DDIMScheduler.from_pretrained(__UpperCAmelCase , subfolder="scheduler" ) _A = StableDiffusionPanoramaPipeline.from_pretrained(__UpperCAmelCase , scheduler=__UpperCAmelCase , safety_checker=__UpperCAmelCase ) _A = pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) pipe.enable_attention_slicing() _A = self.get_inputs() pipe(**__UpperCAmelCase , callback=__UpperCAmelCase , callback_steps=1 ) assert callback_fn.has_been_called assert number_of_steps == 3 def lowerCAmelCase ( self : Dict ): '''simple docstring''' torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() _A = "stabilityai/stable-diffusion-2-base" _A = DDIMScheduler.from_pretrained(__UpperCAmelCase , subfolder="scheduler" ) _A = StableDiffusionPanoramaPipeline.from_pretrained(__UpperCAmelCase , scheduler=__UpperCAmelCase , safety_checker=__UpperCAmelCase ) _A = pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() _A = self.get_inputs() _A = pipe(**__UpperCAmelCase ) _A = torch.cuda.max_memory_allocated() # make sure that less than 5.2 GB is allocated assert mem_bytes < 5.5 * 10**9
79
"""simple docstring""" import unittest from transformers import BarthezTokenizer, BarthezTokenizerFast, BatchEncoding from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers @require_sentencepiece @slow # see https://github.com/huggingface/transformers/issues/11457 class A__ ( _lowerCamelCase , unittest.TestCase): A_ : Union[str, Any] = BarthezTokenizer A_ : Tuple = BarthezTokenizerFast A_ : Dict = True A_ : List[str] = True def __lowerCamelCase ( self ): super().setUp() __lowerCAmelCase : str = BarthezTokenizerFast.from_pretrained('moussaKam/mbarthez' ) tokenizer.save_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname , legacy_format=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Any = tokenizer def __lowerCamelCase ( self ): __lowerCAmelCase : Optional[Any] = '<pad>' __lowerCAmelCase : Union[str, Any] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : List[Any] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<s>' ) self.assertEqual(vocab_keys[1] , '<pad>' ) self.assertEqual(vocab_keys[-1] , '<mask>' ) self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , 10_11_22 ) def __lowerCamelCase ( self ): self.assertEqual(self.get_tokenizer().vocab_size , 10_11_22 ) @require_torch def __lowerCamelCase ( self ): __lowerCAmelCase : List[str] = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] __lowerCAmelCase : Optional[Any] = [0, 57, 30_18, 7_03_07, 91, 2] __lowerCAmelCase : Optional[int] = self.tokenizer( _SCREAMING_SNAKE_CASE , max_length=len(_SCREAMING_SNAKE_CASE ) , padding=_SCREAMING_SNAKE_CASE , truncation=_SCREAMING_SNAKE_CASE , return_tensors='pt' ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) self.assertEqual((2, 6) , batch.input_ids.shape ) self.assertEqual((2, 6) , batch.attention_mask.shape ) __lowerCAmelCase : List[str] = batch.input_ids.tolist()[0] self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): if not self.test_rust_tokenizer: return __lowerCAmelCase : Tuple = self.get_tokenizer() __lowerCAmelCase : Optional[int] = self.get_rust_tokenizer() __lowerCAmelCase : List[str] = 'I was born in 92000, and this is falsé.' __lowerCAmelCase : Optional[int] = tokenizer.tokenize(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Union[str, Any] = rust_tokenizer.tokenize(_SCREAMING_SNAKE_CASE ) self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = tokenizer.encode(_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = rust_tokenizer.encode(_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE ) self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = self.get_rust_tokenizer() __lowerCAmelCase : List[Any] = tokenizer.encode(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = rust_tokenizer.encode(_SCREAMING_SNAKE_CASE ) self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @slow def __lowerCamelCase ( self ): # fmt: off __lowerCAmelCase : str = {'input_ids': [[0, 4_90, 1_43_28, 45_07, 3_54, 47, 4_36_69, 95, 25, 7_81_17, 2_02_15, 1_97_79, 1_90, 22, 4_00, 4, 3_53_43, 8_03_10, 6_03, 86, 2_49_37, 1_05, 3_34_38, 9_47_62, 1_96, 3_96_42, 7, 15, 1_59_33, 1_73, 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], [0, 1_05_34, 87, 25, 66, 33_58, 1_96, 5_52_89, 8, 8_29_61, 81, 22_04, 7_52_03, 7, 15, 7_63, 1_29_56, 2_16, 1_78, 1_43_28, 95_95, 13_77, 6_96_93, 7, 4_48, 7_10_21, 1_96, 1_81_06, 14_37, 1_39_74, 1_08, 90_83, 4, 4_93_15, 7, 39, 86, 13_26, 27_93, 4_63_33, 4, 4_48, 1_96, 7_45_88, 7, 4_93_15, 7, 39, 21, 8_22, 3_84_70, 74, 21, 6_67_23, 6_24_80, 8, 2_20_50, 5, 2]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on # moussaKam/mbarthez is a french model. So we also use french texts. __lowerCAmelCase : Union[str, Any] = [ 'Le transformeur est un modèle d\'apprentissage profond introduit en 2017, ' 'utilisé principalement dans le domaine du traitement automatique des langues (TAL).', 'À l\'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus ' 'pour gérer des données séquentielles, telles que le langage naturel, pour des tâches ' 'telles que la traduction et la synthèse de texte.', ] self.tokenizer_integration_test_util( expected_encoding=_SCREAMING_SNAKE_CASE , model_name='moussaKam/mbarthez' , revision='c2e4ecbca5e3cd2c37fe1ac285ca4fbdf1366fb6' , sequences=_SCREAMING_SNAKE_CASE , )
86
0
'''simple docstring''' # tests directory-specific settings - this file is run automatically # by pytest before any tests are run import sys import warnings from os.path import abspath, dirname, join # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. a__ : List[Any] = abspath(join(dirname(dirname(__file__)), 'src')) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action='ignore', category=FutureWarning) def _UpperCamelCase ( __A ) -> Any: '''simple docstring''' from diffusers.utils.testing_utils import pytest_addoption_shared pytest_addoption_shared(__A ) def _UpperCamelCase ( __A ) -> Dict: '''simple docstring''' from diffusers.utils.testing_utils import pytest_terminal_summary_main UpperCamelCase__ = terminalreporter.config.getoption("--make-reports" ) if make_reports: pytest_terminal_summary_main(__A , id=__A )
80
"""simple docstring""" 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__ = { """sail/poolformer_s12""": """https://huggingface.co/sail/poolformer_s12/resolve/main/config.json""", # See all PoolFormer models at https://huggingface.co/models?filter=poolformer } class A__ ( _lowerCamelCase): A_ : Optional[int] = 'poolformer' def __init__( self , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=4.0 , _SCREAMING_SNAKE_CASE=[2, 2, 6, 2] , _SCREAMING_SNAKE_CASE=[64, 1_28, 3_20, 5_12] , _SCREAMING_SNAKE_CASE=[7, 3, 3, 3] , _SCREAMING_SNAKE_CASE=[4, 2, 2, 2] , _SCREAMING_SNAKE_CASE=[2, 1, 1, 1] , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=1E-5 , _SCREAMING_SNAKE_CASE=0.02 , **_SCREAMING_SNAKE_CASE , ): __lowerCAmelCase : int = num_channels __lowerCAmelCase : str = patch_size __lowerCAmelCase : Optional[Any] = stride __lowerCAmelCase : Optional[int] = padding __lowerCAmelCase : List[Any] = pool_size __lowerCAmelCase : int = hidden_sizes __lowerCAmelCase : str = mlp_ratio __lowerCAmelCase : Optional[int] = depths __lowerCAmelCase : str = patch_sizes __lowerCAmelCase : str = strides __lowerCAmelCase : Optional[int] = num_encoder_blocks __lowerCAmelCase : Any = drop_path_rate __lowerCAmelCase : Any = hidden_act __lowerCAmelCase : Dict = use_layer_scale __lowerCAmelCase : Union[str, Any] = layer_scale_init_value __lowerCAmelCase : Dict = initializer_range super().__init__(**_SCREAMING_SNAKE_CASE ) class A__ ( _lowerCamelCase): A_ : List[str] = version.parse('1.11') @property def __lowerCamelCase ( self ): return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def __lowerCamelCase ( self ): return 2E-3
86
0
"""simple docstring""" lowerCamelCase_ : Optional[Any] = """ # Transformers installation ! pip install transformers datasets # To install from source instead of the last release, comment the command above and uncomment the following one. # ! pip install git+https://github.com/huggingface/transformers.git """ lowerCamelCase_ : str = [{"""type""": """code""", """content""": INSTALL_CONTENT}] lowerCamelCase_ : Any = { """{processor_class}""": """FakeProcessorClass""", """{model_class}""": """FakeModelClass""", """{object_class}""": """FakeObjectClass""", }
81
"""simple docstring""" import gc import unittest import numpy as np import torch from diffusers import AutoencoderKL, DDIMScheduler, DiTPipeline, DPMSolverMultistepScheduler, TransformeraDModel from diffusers.utils import is_xformers_available, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS, CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class A__ ( _lowerCamelCase , unittest.TestCase): A_ : Union[str, Any] = DiTPipeline A_ : Union[str, Any] = CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS A_ : List[Any] = PipelineTesterMixin.required_optional_params - { 'latents', 'num_images_per_prompt', 'callback', 'callback_steps', } A_ : Optional[Any] = CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS A_ : Tuple = False def __lowerCamelCase ( self ): torch.manual_seed(0 ) __lowerCAmelCase : List[str] = TransformeraDModel( sample_size=16 , num_layers=2 , patch_size=4 , attention_head_dim=8 , num_attention_heads=2 , in_channels=4 , out_channels=8 , attention_bias=_SCREAMING_SNAKE_CASE , activation_fn='gelu-approximate' , num_embeds_ada_norm=10_00 , norm_type='ada_norm_zero' , norm_elementwise_affine=_SCREAMING_SNAKE_CASE , ) __lowerCAmelCase : str = AutoencoderKL() __lowerCAmelCase : Union[str, Any] = DDIMScheduler() __lowerCAmelCase : Dict = {'transformer': transformer.eval(), 'vae': vae.eval(), 'scheduler': scheduler} return components def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=0 ): if str(_SCREAMING_SNAKE_CASE ).startswith('mps' ): __lowerCAmelCase : List[str] = torch.manual_seed(_SCREAMING_SNAKE_CASE ) else: __lowerCAmelCase : List[str] = torch.Generator(device=_SCREAMING_SNAKE_CASE ).manual_seed(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Any = { 'class_labels': [1], 'generator': generator, 'num_inference_steps': 2, 'output_type': 'numpy', } return inputs def __lowerCamelCase ( self ): __lowerCAmelCase : List[str] = 'cpu' __lowerCAmelCase : Any = self.get_dummy_components() __lowerCAmelCase : Union[str, Any] = self.pipeline_class(**_SCREAMING_SNAKE_CASE ) pipe.to(_SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Tuple = self.get_dummy_inputs(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = pipe(**_SCREAMING_SNAKE_CASE ).images __lowerCAmelCase : List[str] = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 16, 16, 3) ) __lowerCAmelCase : Optional[int] = np.array([0.2946, 0.6601, 0.4329, 0.3296, 0.4144, 0.5319, 0.7273, 0.5013, 0.4457] ) __lowerCAmelCase : List[Any] = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(_SCREAMING_SNAKE_CASE , 1E-3 ) def __lowerCamelCase ( self ): self._test_inference_batch_single_identical(relax_max_difference=_SCREAMING_SNAKE_CASE , expected_max_diff=1E-3 ) @unittest.skipIf( torch_device != 'cuda' or not is_xformers_available() , reason='XFormers attention is only available with CUDA and `xformers` installed' , ) def __lowerCamelCase ( self ): self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 ) @require_torch_gpu @slow class A__ ( unittest.TestCase): def __lowerCamelCase ( self ): super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCamelCase ( self ): __lowerCAmelCase : Dict = torch.manual_seed(0 ) __lowerCAmelCase : int = DiTPipeline.from_pretrained('facebook/DiT-XL-2-256' ) pipe.to('cuda' ) __lowerCAmelCase : Optional[Any] = ['vase', 'umbrella', 'white shark', 'white wolf'] __lowerCAmelCase : Optional[Any] = pipe.get_label_ids(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = pipe(_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , num_inference_steps=40 , output_type='np' ).images for word, image in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Tuple = load_numpy( f"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/dit/{word}.npy" ) assert np.abs((expected_image - image).max() ) < 1E-2 def __lowerCamelCase ( self ): __lowerCAmelCase : Any = DiTPipeline.from_pretrained('facebook/DiT-XL-2-512' ) __lowerCAmelCase : Union[str, Any] = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.to('cuda' ) __lowerCAmelCase : Dict = ['vase', 'umbrella'] __lowerCAmelCase : List[str] = pipe.get_label_ids(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Any = torch.manual_seed(0 ) __lowerCAmelCase : Optional[Any] = pipe(_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , num_inference_steps=25 , output_type='np' ).images for word, image in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Dict = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' f"/dit/{word}_512.npy" ) assert np.abs((expected_image - image).max() ) < 1E-1
86
0
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A__ = logging.get_logger(__name__) A__ = { """sail/poolformer_s12""": """https://huggingface.co/sail/poolformer_s12/resolve/main/config.json""", # See all PoolFormer models at https://huggingface.co/models?filter=poolformer } class __lowerCAmelCase ( lowerCamelCase__ ): __lowerCamelCase = '''poolformer''' def __init__( self , _snake_case=3 , _snake_case=16 , _snake_case=16 , _snake_case=3 , _snake_case=4.0 , _snake_case=[2, 2, 6, 2] , _snake_case=[64, 128, 320, 512] , _snake_case=[7, 3, 3, 3] , _snake_case=[4, 2, 2, 2] , _snake_case=[2, 1, 1, 1] , _snake_case=4 , _snake_case=0.0 , _snake_case="gelu" , _snake_case=True , _snake_case=1e-5 , _snake_case=0.02 , **_snake_case , ): """simple docstring""" _lowerCAmelCase = num_channels _lowerCAmelCase = patch_size _lowerCAmelCase = stride _lowerCAmelCase = padding _lowerCAmelCase = pool_size _lowerCAmelCase = hidden_sizes _lowerCAmelCase = mlp_ratio _lowerCAmelCase = depths _lowerCAmelCase = patch_sizes _lowerCAmelCase = strides _lowerCAmelCase = num_encoder_blocks _lowerCAmelCase = drop_path_rate _lowerCAmelCase = hidden_act _lowerCAmelCase = use_layer_scale _lowerCAmelCase = layer_scale_init_value _lowerCAmelCase = initializer_range super().__init__(**_snake_case ) class __lowerCAmelCase ( lowerCamelCase__ ): __lowerCamelCase = version.parse('''1.11''' ) @property def snake_case ( self ): """simple docstring""" return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def snake_case ( self ): """simple docstring""" return 2e-3
82
"""simple docstring""" import gc import random import unittest import numpy as np import torch from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import floats_tensor, load_image, load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class A__ ( _lowerCamelCase , unittest.TestCase): A_ : str = ShapEImgaImgPipeline A_ : str = ['image'] A_ : int = ['image'] A_ : Tuple = [ 'num_images_per_prompt', 'num_inference_steps', 'generator', 'latents', 'guidance_scale', 'frame_size', 'output_type', 'return_dict', ] A_ : Tuple = False @property def __lowerCamelCase ( self ): return 32 @property def __lowerCamelCase ( self ): return 32 @property def __lowerCamelCase ( self ): return self.time_input_dim * 4 @property def __lowerCamelCase ( self ): return 8 @property def __lowerCamelCase ( self ): torch.manual_seed(0 ) __lowerCAmelCase : Any = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=64 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=1 , ) __lowerCAmelCase : Tuple = CLIPVisionModel(_SCREAMING_SNAKE_CASE ) return model @property def __lowerCamelCase ( self ): __lowerCAmelCase : Any = CLIPImageProcessor( crop_size=2_24 , do_center_crop=_SCREAMING_SNAKE_CASE , do_normalize=_SCREAMING_SNAKE_CASE , do_resize=_SCREAMING_SNAKE_CASE , image_mean=[0.4814_5466, 0.457_8275, 0.4082_1073] , image_std=[0.2686_2954, 0.2613_0258, 0.2757_7711] , resample=3 , size=2_24 , ) return image_processor @property def __lowerCamelCase ( self ): torch.manual_seed(0 ) __lowerCAmelCase : Optional[Any] = { 'num_attention_heads': 2, 'attention_head_dim': 16, 'embedding_dim': self.time_input_dim, 'num_embeddings': 32, 'embedding_proj_dim': self.text_embedder_hidden_size, 'time_embed_dim': self.time_embed_dim, 'num_layers': 1, 'clip_embed_dim': self.time_input_dim * 2, 'additional_embeddings': 0, 'time_embed_act_fn': 'gelu', 'norm_in_type': 'layer', 'embedding_proj_norm_type': 'layer', 'encoder_hid_proj_type': None, 'added_emb_type': None, } __lowerCAmelCase : List[Any] = PriorTransformer(**_SCREAMING_SNAKE_CASE ) return model @property def __lowerCamelCase ( self ): torch.manual_seed(0 ) __lowerCAmelCase : Dict = { 'param_shapes': ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), 'd_latent': self.time_input_dim, 'd_hidden': self.renderer_dim, 'n_output': 12, 'background': ( 0.1, 0.1, 0.1, ), } __lowerCAmelCase : int = ShapERenderer(**_SCREAMING_SNAKE_CASE ) return model def __lowerCamelCase ( self ): __lowerCAmelCase : Any = self.dummy_prior __lowerCAmelCase : List[Any] = self.dummy_image_encoder __lowerCAmelCase : int = self.dummy_image_processor __lowerCAmelCase : Any = self.dummy_renderer __lowerCAmelCase : Any = HeunDiscreteScheduler( beta_schedule='exp' , num_train_timesteps=10_24 , prediction_type='sample' , use_karras_sigmas=_SCREAMING_SNAKE_CASE , clip_sample=_SCREAMING_SNAKE_CASE , clip_sample_range=1.0 , ) __lowerCAmelCase : Tuple = { 'prior': prior, 'image_encoder': image_encoder, 'image_processor': image_processor, 'renderer': renderer, 'scheduler': scheduler, } return components def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=0 ): __lowerCAmelCase : Optional[Any] = floats_tensor((1, 3, 64, 64) , rng=random.Random(_SCREAMING_SNAKE_CASE ) ).to(_SCREAMING_SNAKE_CASE ) if str(_SCREAMING_SNAKE_CASE ).startswith('mps' ): __lowerCAmelCase : int = torch.manual_seed(_SCREAMING_SNAKE_CASE ) else: __lowerCAmelCase : str = torch.Generator(device=_SCREAMING_SNAKE_CASE ).manual_seed(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = { 'image': input_image, 'generator': generator, 'num_inference_steps': 1, 'frame_size': 32, 'output_type': 'np', } return inputs def __lowerCamelCase ( self ): __lowerCAmelCase : str = 'cpu' __lowerCAmelCase : Dict = self.get_dummy_components() __lowerCAmelCase : Optional[int] = self.pipeline_class(**_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = pipe.to(_SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = pipe(**self.get_dummy_inputs(_SCREAMING_SNAKE_CASE ) ) __lowerCAmelCase : Any = output.images[0] __lowerCAmelCase : Optional[Any] = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) __lowerCAmelCase : List[Any] = np.array( [ 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def __lowerCamelCase ( self ): # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def __lowerCamelCase ( self ): __lowerCAmelCase : str = torch_device == 'cpu' __lowerCAmelCase : Optional[Any] = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=_SCREAMING_SNAKE_CASE , relax_max_difference=_SCREAMING_SNAKE_CASE , ) def __lowerCamelCase ( self ): __lowerCAmelCase : str = self.get_dummy_components() __lowerCAmelCase : List[str] = self.pipeline_class(**_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = pipe.to(_SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = 1 __lowerCAmelCase : List[str] = 2 __lowerCAmelCase : Union[str, Any] = self.get_dummy_inputs(_SCREAMING_SNAKE_CASE ) for key in inputs.keys(): if key in self.batch_params: __lowerCAmelCase : Optional[Any] = batch_size * [inputs[key]] __lowerCAmelCase : List[str] = pipe(**_SCREAMING_SNAKE_CASE , num_images_per_prompt=_SCREAMING_SNAKE_CASE )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class A__ ( unittest.TestCase): def __lowerCamelCase ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCamelCase ( self ): __lowerCAmelCase : int = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/shap_e/corgi.png' ) __lowerCAmelCase : Any = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/shap_e/test_shap_e_img2img_out.npy' ) __lowerCAmelCase : Union[str, Any] = ShapEImgaImgPipeline.from_pretrained('openai/shap-e-img2img' ) __lowerCAmelCase : Dict = pipe.to(_SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Tuple = torch.Generator(device=_SCREAMING_SNAKE_CASE ).manual_seed(0 ) __lowerCAmelCase : int = pipe( _SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , guidance_scale=3.0 , num_inference_steps=64 , frame_size=64 , output_type='np' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
86
0
'''simple docstring''' import unittest import torch from torch import nn from diffusers.models.activations import get_activation class lowercase__ ( unittest.TestCase ): def UpperCamelCase_ ( self : Dict ): '''simple docstring''' _UpperCamelCase : Union[str, Any] = get_activation('swish' ) self.assertIsInstance(lowerCamelCase__ ,nn.SiLU ) self.assertEqual(act(torch.tensor(-100 ,dtype=torch.floataa ) ).item() ,0 ) self.assertNotEqual(act(torch.tensor(-1 ,dtype=torch.floataa ) ).item() ,0 ) self.assertEqual(act(torch.tensor(0 ,dtype=torch.floataa ) ).item() ,0 ) self.assertEqual(act(torch.tensor(20 ,dtype=torch.floataa ) ).item() ,20 ) def UpperCamelCase_ ( self : Optional[int] ): '''simple docstring''' _UpperCamelCase : List[str] = get_activation('silu' ) self.assertIsInstance(lowerCamelCase__ ,nn.SiLU ) self.assertEqual(act(torch.tensor(-100 ,dtype=torch.floataa ) ).item() ,0 ) self.assertNotEqual(act(torch.tensor(-1 ,dtype=torch.floataa ) ).item() ,0 ) self.assertEqual(act(torch.tensor(0 ,dtype=torch.floataa ) ).item() ,0 ) self.assertEqual(act(torch.tensor(20 ,dtype=torch.floataa ) ).item() ,20 ) def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' _UpperCamelCase : Dict = get_activation('mish' ) self.assertIsInstance(lowerCamelCase__ ,nn.Mish ) self.assertEqual(act(torch.tensor(-200 ,dtype=torch.floataa ) ).item() ,0 ) self.assertNotEqual(act(torch.tensor(-1 ,dtype=torch.floataa ) ).item() ,0 ) self.assertEqual(act(torch.tensor(0 ,dtype=torch.floataa ) ).item() ,0 ) self.assertEqual(act(torch.tensor(20 ,dtype=torch.floataa ) ).item() ,20 ) def UpperCamelCase_ ( self : int ): '''simple docstring''' _UpperCamelCase : Dict = get_activation('gelu' ) self.assertIsInstance(lowerCamelCase__ ,nn.GELU ) self.assertEqual(act(torch.tensor(-100 ,dtype=torch.floataa ) ).item() ,0 ) self.assertNotEqual(act(torch.tensor(-1 ,dtype=torch.floataa ) ).item() ,0 ) self.assertEqual(act(torch.tensor(0 ,dtype=torch.floataa ) ).item() ,0 ) self.assertEqual(act(torch.tensor(20 ,dtype=torch.floataa ) ).item() ,20 )
83
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase__ = {"""configuration_fnet""": ["""FNET_PRETRAINED_CONFIG_ARCHIVE_MAP""", """FNetConfig"""]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = ["""FNetTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = ["""FNetTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ """FNET_PRETRAINED_MODEL_ARCHIVE_LIST""", """FNetForMaskedLM""", """FNetForMultipleChoice""", """FNetForNextSentencePrediction""", """FNetForPreTraining""", """FNetForQuestionAnswering""", """FNetForSequenceClassification""", """FNetForTokenClassification""", """FNetLayer""", """FNetModel""", """FNetPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_fnet import FNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet import FNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet_fast import FNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_fnet import ( FNET_PRETRAINED_MODEL_ARCHIVE_LIST, FNetForMaskedLM, FNetForMultipleChoice, FNetForNextSentencePrediction, FNetForPreTraining, FNetForQuestionAnswering, FNetForSequenceClassification, FNetForTokenClassification, FNetLayer, FNetModel, FNetPreTrainedModel, ) else: import sys lowerCamelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
86
0
"""simple docstring""" import os import posixpath import uuid from dataclasses import dataclass from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union import numpy as np import pyarrow as pa import datasets from datasets.arrow_writer import ArrowWriter, ParquetWriter from datasets.config import MAX_SHARD_SIZE from datasets.filesystems import ( is_remote_filesystem, rename, ) from datasets.iterable_dataset import _BaseExamplesIterable from datasets.utils.py_utils import convert_file_size_to_int __UpperCAmelCase = datasets.utils.logging.get_logger(__name__) if TYPE_CHECKING: import pyspark @dataclass class _SCREAMING_SNAKE_CASE ( datasets.BuilderConfig ): UpperCAmelCase_ :Optional[datasets.Features] = None def _snake_case ( lowercase__ : "pyspark.sql.DataFrame" , lowercase__ : List[int] , ) -> Any: '''simple docstring''' import pyspark def generate_fn(): lowerCAmelCase_ :List[Any] = df.select("""*""" , pyspark.sql.functions.spark_partition_id().alias("""part_id""" ) ) for partition_id in partition_order: lowerCAmelCase_ :Optional[int] = df_with_partition_id.select("""*""" ).where(f"""part_id = {partition_id}""" ).drop("""part_id""" ) lowerCAmelCase_ :Optional[Any] = partition_df.collect() lowerCAmelCase_ :Dict = 0 for row in rows: yield f"""{partition_id}_{row_id}""", row.asDict() row_id += 1 return generate_fn class _SCREAMING_SNAKE_CASE ( _BaseExamplesIterable ): def __init__( self , __A , __A=None , ) -> Optional[Any]: lowerCAmelCase_ :List[str] = df lowerCAmelCase_ :str = partition_order or range(self.df.rdd.getNumPartitions() ) lowerCAmelCase_ :int = _generate_iterable_examples(self.df , self.partition_order ) def __iter__( self ) -> Tuple: yield from self.generate_examples_fn() def __lowerCAmelCase ( self , __A ) -> "SparkExamplesIterable": lowerCAmelCase_ :List[Any] = list(range(self.df.rdd.getNumPartitions() ) ) generator.shuffle(__A ) return SparkExamplesIterable(self.df , partition_order=__A ) def __lowerCAmelCase ( self , __A , __A ) -> "SparkExamplesIterable": lowerCAmelCase_ :Optional[Any] = self.split_shard_indices_by_worker(__A , __A ) return SparkExamplesIterable(self.df , partition_order=__A ) @property def __lowerCAmelCase ( self ) -> int: return len(self.partition_order ) class _SCREAMING_SNAKE_CASE ( datasets.DatasetBuilder ): UpperCAmelCase_ :Optional[Any] = SparkConfig def __init__( self , __A , __A = None , __A = None , **__A , ) -> int: import pyspark lowerCAmelCase_ :Tuple = pyspark.sql.SparkSession.builder.getOrCreate() lowerCAmelCase_ :Union[str, Any] = df lowerCAmelCase_ :Optional[Any] = working_dir super().__init__( cache_dir=__A , config_name=str(self.df.semanticHash() ) , **__A , ) def __lowerCAmelCase ( self ) -> int: # Returns the path of the created file. def create_cache_and_write_probe(__A ): # makedirs with exist_ok will recursively create the directory. It will not throw an error if directories # already exist. os.makedirs(self._cache_dir , exist_ok=__A ) lowerCAmelCase_ :Union[str, Any] = os.path.join(self._cache_dir , """fs_test""" + uuid.uuida().hex ) # Opening the file in append mode will create a new file unless it already exists, in which case it will not # change the file contents. open(__A , """a""" ) return [probe_file] if self._spark.conf.get("""spark.master""" , """""" ).startswith("""local""" ): return # If the cluster is multi-node, make sure that the user provided a cache_dir and that it is on an NFS # accessible to the driver. # TODO: Stream batches to the driver using ArrowCollectSerializer instead of throwing an error. if self._cache_dir: lowerCAmelCase_ :int = ( self._spark.sparkContext.parallelize(range(1 ) , 1 ).mapPartitions(__A ).collect() ) if os.path.isfile(probe[0] ): return raise ValueError( """When using Dataset.from_spark on a multi-node cluster, the driver and all workers should be able to access cache_dir""" ) def __lowerCAmelCase ( self ) -> Optional[Any]: return datasets.DatasetInfo(features=self.config.features ) def __lowerCAmelCase ( self , __A ) -> Any: return [datasets.SplitGenerator(name=datasets.Split.TRAIN )] def __lowerCAmelCase ( self , __A ) -> Union[str, Any]: import pyspark def get_arrow_batch_size(__A ): for batch in it: yield pa.RecordBatch.from_pydict({"""batch_bytes""": [batch.nbytes]} ) lowerCAmelCase_ :Tuple = self.df.count() lowerCAmelCase_ :Union[str, Any] = df_num_rows if df_num_rows <= 100 else 100 # Approximate the size of each row (in Arrow format) by averaging over a max-100-row sample. lowerCAmelCase_ :Tuple = ( self.df.limit(__A ) .repartition(1 ) .mapInArrow(__A , """batch_bytes: long""" ) .agg(pyspark.sql.functions.sum("""batch_bytes""" ).alias("""sample_bytes""" ) ) .collect()[0] .sample_bytes / sample_num_rows ) lowerCAmelCase_ :List[Any] = approx_bytes_per_row * df_num_rows if approx_total_size > max_shard_size: # Make sure there is at least one row per partition. lowerCAmelCase_ :str = min(__A , int(approx_total_size / max_shard_size ) ) lowerCAmelCase_ :Optional[int] = self.df.repartition(__A ) def __lowerCAmelCase ( self , __A , __A , __A , ) -> Iterable[Tuple[int, bool, Union[int, tuple]]]: import pyspark lowerCAmelCase_ :Optional[int] = ParquetWriter if file_format == """parquet""" else ArrowWriter lowerCAmelCase_ :Dict = os.path.join(self._working_dir , os.path.basename(__A ) ) if self._working_dir else fpath lowerCAmelCase_ :Optional[Any] = file_format == """parquet""" # Define these so that we don't reference self in write_arrow, which will result in a pickling error due to # pickling the SparkContext. lowerCAmelCase_ :List[str] = self.config.features lowerCAmelCase_ :List[Any] = self._writer_batch_size lowerCAmelCase_ :str = self._fs.storage_options def write_arrow(__A ): # Within the same SparkContext, no two task attempts will share the same attempt ID. lowerCAmelCase_ :Dict = pyspark.TaskContext().taskAttemptId() lowerCAmelCase_ :int = next(__A , __A ) if first_batch is None: # Some partitions might not receive any data. return pa.RecordBatch.from_arrays( [[task_id], [0], [0]] , names=["""task_id""", """num_examples""", """num_bytes"""] , ) lowerCAmelCase_ :Tuple = 0 lowerCAmelCase_ :List[str] = writer_class( features=__A , path=working_fpath.replace("""SSSSS""" , f"""{shard_id:05d}""" ).replace("""TTTTT""" , f"""{task_id:05d}""" ) , writer_batch_size=__A , storage_options=__A , embed_local_files=__A , ) lowerCAmelCase_ :int = pa.Table.from_batches([first_batch] ) writer.write_table(__A ) for batch in it: if max_shard_size is not None and writer._num_bytes >= max_shard_size: lowerCAmelCase_ , lowerCAmelCase_ :int = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=["""task_id""", """num_examples""", """num_bytes"""] , ) shard_id += 1 lowerCAmelCase_ :int = writer_class( features=writer._features , path=working_fpath.replace("""SSSSS""" , f"""{shard_id:05d}""" ).replace("""TTTTT""" , f"""{task_id:05d}""" ) , writer_batch_size=__A , storage_options=__A , embed_local_files=__A , ) lowerCAmelCase_ :Any = pa.Table.from_batches([batch] ) writer.write_table(__A ) if writer._num_bytes > 0: lowerCAmelCase_ , lowerCAmelCase_ :Any = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=["""task_id""", """num_examples""", """num_bytes"""] , ) if working_fpath != fpath: for file in os.listdir(os.path.dirname(__A ) ): lowerCAmelCase_ :Optional[int] = os.path.join(os.path.dirname(__A ) , os.path.basename(__A ) ) shutil.move(__A , __A ) lowerCAmelCase_ :Optional[int] = ( self.df.mapInArrow(__A , """task_id: long, num_examples: long, num_bytes: long""" ) .groupBy("""task_id""" ) .agg( pyspark.sql.functions.sum("""num_examples""" ).alias("""total_num_examples""" ) , pyspark.sql.functions.sum("""num_bytes""" ).alias("""total_num_bytes""" ) , pyspark.sql.functions.count("""num_bytes""" ).alias("""num_shards""" ) , pyspark.sql.functions.collect_list("""num_examples""" ).alias("""shard_lengths""" ) , ) .collect() ) for row in stats: yield row.task_id, (row.total_num_examples, row.total_num_bytes, row.num_shards, row.shard_lengths) def __lowerCAmelCase ( self , __A , __A = "arrow" , __A = None , __A = None , **__A , ) -> Any: self._validate_cache_dir() lowerCAmelCase_ :Tuple = convert_file_size_to_int(max_shard_size or MAX_SHARD_SIZE ) self._repartition_df_if_needed(__A ) lowerCAmelCase_ :Optional[Any] = not is_remote_filesystem(self._fs ) lowerCAmelCase_ :Tuple = os.path.join if is_local else posixpath.join lowerCAmelCase_ :List[Any] = """-TTTTT-SSSSS-of-NNNNN""" lowerCAmelCase_ :int = f"""{self.name}-{split_generator.name}{SUFFIX}.{file_format}""" lowerCAmelCase_ :Optional[Any] = path_join(self._output_dir , __A ) lowerCAmelCase_ :Dict = 0 lowerCAmelCase_ :Any = 0 lowerCAmelCase_ :str = 0 lowerCAmelCase_ :Union[str, Any] = [] lowerCAmelCase_ :List[str] = [] for task_id, content in self._prepare_split_single(__A , __A , __A ): ( ( lowerCAmelCase_ ) , ( lowerCAmelCase_ ) , ( lowerCAmelCase_ ) , ( lowerCAmelCase_ ) , ) :List[Any] = content if num_bytes > 0: total_num_examples += num_examples total_num_bytes += num_bytes total_shards += num_shards task_id_and_num_shards.append((task_id, num_shards) ) all_shard_lengths.extend(__A ) lowerCAmelCase_ :Optional[int] = total_num_examples lowerCAmelCase_ :Tuple = total_num_bytes # should rename everything at the end logger.debug(f"""Renaming {total_shards} shards.""" ) if total_shards > 1: lowerCAmelCase_ :Any = all_shard_lengths # Define fs outside of _rename_shard so that we don't reference self in the function, which will result in a # pickling error due to pickling the SparkContext. lowerCAmelCase_ :List[str] = self._fs # use the -SSSSS-of-NNNNN pattern def _rename_shard( __A , __A , __A , ): rename( __A , fpath.replace("""SSSSS""" , f"""{shard_id:05d}""" ).replace("""TTTTT""" , f"""{task_id:05d}""" ) , fpath.replace("""TTTTT-SSSSS""" , f"""{global_shard_id:05d}""" ).replace("""NNNNN""" , f"""{total_shards:05d}""" ) , ) lowerCAmelCase_ :Tuple = [] lowerCAmelCase_ :Tuple = 0 for i in range(len(__A ) ): lowerCAmelCase_ , lowerCAmelCase_ :Dict = task_id_and_num_shards[i] for shard_id in range(__A ): args.append([task_id, shard_id, global_shard_id] ) global_shard_id += 1 self._spark.sparkContext.parallelize(__A , len(__A ) ).map(lambda __A : _rename_shard(*__A ) ).collect() else: # don't use any pattern lowerCAmelCase_ :Optional[int] = 0 lowerCAmelCase_ :Optional[Any] = task_id_and_num_shards[0][0] self._rename( fpath.replace("""SSSSS""" , f"""{shard_id:05d}""" ).replace("""TTTTT""" , f"""{task_id:05d}""" ) , fpath.replace(__A , """""" ) , ) def __lowerCAmelCase ( self , __A , ) -> SparkExamplesIterable: return SparkExamplesIterable(self.df )
84
"""simple docstring""" import math import sys def __lowerCAmelCase (_UpperCamelCase ): if number != int(_UpperCamelCase ): raise ValueError('the value of input must be a natural number' ) if number < 0: raise ValueError('the value of input must not be a negative number' ) if number == 0: return 1 __lowerCAmelCase : Any = [-1] * (number + 1) __lowerCAmelCase : List[Any] = 0 for i in range(1 , number + 1 ): __lowerCAmelCase : List[Any] = sys.maxsize __lowerCAmelCase : Optional[int] = int(math.sqrt(_UpperCamelCase ) ) for j in range(1 , root + 1 ): __lowerCAmelCase : Optional[Any] = 1 + answers[i - (j**2)] __lowerCAmelCase : Any = min(_UpperCamelCase , _UpperCamelCase ) __lowerCAmelCase : List[str] = answer return answers[number] if __name__ == "__main__": import doctest doctest.testmod()
86
0
'''simple docstring''' import unittest from transformers import ( MODEL_FOR_OBJECT_DETECTION_MAPPING, AutoFeatureExtractor, AutoModelForObjectDetection, ObjectDetectionPipeline, is_vision_available, pipeline, ) from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_pytesseract, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class _snake_case : @staticmethod def lowerCAmelCase__ ( *a__ , **a__ ) -> List[str]: '''simple docstring''' pass @is_pipeline_test @require_vision @require_timm @require_torch class _snake_case ( unittest.TestCase ): lowerCAmelCase_ : str = MODEL_FOR_OBJECT_DETECTION_MAPPING def lowerCAmelCase__ ( self , a__ , a__ , a__ ) -> Tuple: '''simple docstring''' snake_case_ = ObjectDetectionPipeline(model=a__ , image_processor=a__ ) return object_detector, ["./tests/fixtures/tests_samples/COCO/000000039769.png"] def lowerCAmelCase__ ( self , a__ , a__ ) -> List[Any]: '''simple docstring''' snake_case_ = object_detector("./tests/fixtures/tests_samples/COCO/000000039769.png" , threshold=0.0 ) self.assertGreater(len(a__ ) , 0 ) for detected_object in outputs: self.assertEqual( a__ , { "score": ANY(a__ ), "label": ANY(a__ ), "box": {"xmin": ANY(a__ ), "ymin": ANY(a__ ), "xmax": ANY(a__ ), "ymax": ANY(a__ )}, } , ) import datasets snake_case_ = datasets.load_dataset("hf-internal-testing/fixtures_image_utils" , "image" , split="test" ) snake_case_ = [ Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ), "http://images.cocodataset.org/val2017/000000039769.jpg", # RGBA dataset[0]["file"], # LA dataset[1]["file"], # L dataset[2]["file"], ] snake_case_ = object_detector(a__ , threshold=0.0 ) self.assertEqual(len(a__ ) , len(a__ ) ) for outputs in batch_outputs: self.assertGreater(len(a__ ) , 0 ) for detected_object in outputs: self.assertEqual( a__ , { "score": ANY(a__ ), "label": ANY(a__ ), "box": {"xmin": ANY(a__ ), "ymin": ANY(a__ ), "xmax": ANY(a__ ), "ymax": ANY(a__ )}, } , ) @require_tf @unittest.skip("Object detection not implemented in TF" ) def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' pass @require_torch def lowerCAmelCase__ ( self ) -> List[str]: '''simple docstring''' snake_case_ = "hf-internal-testing/tiny-detr-mobilenetsv3" snake_case_ = AutoModelForObjectDetection.from_pretrained(a__ ) snake_case_ = AutoFeatureExtractor.from_pretrained(a__ ) snake_case_ = ObjectDetectionPipeline(model=a__ , feature_extractor=a__ ) snake_case_ = object_detector("http://images.cocodataset.org/val2017/000000039769.jpg" , threshold=0.0 ) self.assertEqual( nested_simplify(a__ , decimals=4 ) , [ {"score": 0.3_3_7_6, "label": "LABEL_0", "box": {"xmin": 159, "ymin": 120, "xmax": 480, "ymax": 359}}, {"score": 0.3_3_7_6, "label": "LABEL_0", "box": {"xmin": 159, "ymin": 120, "xmax": 480, "ymax": 359}}, ] , ) snake_case_ = object_detector( [ "http://images.cocodataset.org/val2017/000000039769.jpg", "http://images.cocodataset.org/val2017/000000039769.jpg", ] , threshold=0.0 , ) self.assertEqual( nested_simplify(a__ , decimals=4 ) , [ [ {"score": 0.3_3_7_6, "label": "LABEL_0", "box": {"xmin": 159, "ymin": 120, "xmax": 480, "ymax": 359}}, {"score": 0.3_3_7_6, "label": "LABEL_0", "box": {"xmin": 159, "ymin": 120, "xmax": 480, "ymax": 359}}, ], [ {"score": 0.3_3_7_6, "label": "LABEL_0", "box": {"xmin": 159, "ymin": 120, "xmax": 480, "ymax": 359}}, {"score": 0.3_3_7_6, "label": "LABEL_0", "box": {"xmin": 159, "ymin": 120, "xmax": 480, "ymax": 359}}, ], ] , ) @require_torch @slow def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' snake_case_ = "facebook/detr-resnet-50" snake_case_ = AutoModelForObjectDetection.from_pretrained(a__ ) snake_case_ = AutoFeatureExtractor.from_pretrained(a__ ) snake_case_ = ObjectDetectionPipeline(model=a__ , feature_extractor=a__ ) snake_case_ = object_detector("http://images.cocodataset.org/val2017/000000039769.jpg" ) self.assertEqual( nested_simplify(a__ , decimals=4 ) , [ {"score": 0.9_9_8_2, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 175, "ymax": 117}}, {"score": 0.9_9_6_0, "label": "remote", "box": {"xmin": 333, "ymin": 72, "xmax": 368, "ymax": 187}}, {"score": 0.9_9_5_5, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 639, "ymax": 473}}, {"score": 0.9_9_8_8, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}}, {"score": 0.9_9_8_7, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}}, ] , ) snake_case_ = object_detector( [ "http://images.cocodataset.org/val2017/000000039769.jpg", "http://images.cocodataset.org/val2017/000000039769.jpg", ] ) self.assertEqual( nested_simplify(a__ , decimals=4 ) , [ [ {"score": 0.9_9_8_2, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 175, "ymax": 117}}, {"score": 0.9_9_6_0, "label": "remote", "box": {"xmin": 333, "ymin": 72, "xmax": 368, "ymax": 187}}, {"score": 0.9_9_5_5, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 639, "ymax": 473}}, {"score": 0.9_9_8_8, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}}, {"score": 0.9_9_8_7, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}}, ], [ {"score": 0.9_9_8_2, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 175, "ymax": 117}}, {"score": 0.9_9_6_0, "label": "remote", "box": {"xmin": 333, "ymin": 72, "xmax": 368, "ymax": 187}}, {"score": 0.9_9_5_5, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 639, "ymax": 473}}, {"score": 0.9_9_8_8, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}}, {"score": 0.9_9_8_7, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}}, ], ] , ) @require_torch @slow def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' snake_case_ = "facebook/detr-resnet-50" snake_case_ = pipeline("object-detection" , model=a__ ) snake_case_ = object_detector("http://images.cocodataset.org/val2017/000000039769.jpg" ) self.assertEqual( nested_simplify(a__ , decimals=4 ) , [ {"score": 0.9_9_8_2, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 175, "ymax": 117}}, {"score": 0.9_9_6_0, "label": "remote", "box": {"xmin": 333, "ymin": 72, "xmax": 368, "ymax": 187}}, {"score": 0.9_9_5_5, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 639, "ymax": 473}}, {"score": 0.9_9_8_8, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}}, {"score": 0.9_9_8_7, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}}, ] , ) snake_case_ = object_detector( [ "http://images.cocodataset.org/val2017/000000039769.jpg", "http://images.cocodataset.org/val2017/000000039769.jpg", ] ) self.assertEqual( nested_simplify(a__ , decimals=4 ) , [ [ {"score": 0.9_9_8_2, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 175, "ymax": 117}}, {"score": 0.9_9_6_0, "label": "remote", "box": {"xmin": 333, "ymin": 72, "xmax": 368, "ymax": 187}}, {"score": 0.9_9_5_5, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 639, "ymax": 473}}, {"score": 0.9_9_8_8, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}}, {"score": 0.9_9_8_7, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}}, ], [ {"score": 0.9_9_8_2, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 175, "ymax": 117}}, {"score": 0.9_9_6_0, "label": "remote", "box": {"xmin": 333, "ymin": 72, "xmax": 368, "ymax": 187}}, {"score": 0.9_9_5_5, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 639, "ymax": 473}}, {"score": 0.9_9_8_8, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}}, {"score": 0.9_9_8_7, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}}, ], ] , ) @require_torch @slow def lowerCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' snake_case_ = 0.9_9_8_5 snake_case_ = "facebook/detr-resnet-50" snake_case_ = pipeline("object-detection" , model=a__ ) snake_case_ = object_detector("http://images.cocodataset.org/val2017/000000039769.jpg" , threshold=a__ ) self.assertEqual( nested_simplify(a__ , decimals=4 ) , [ {"score": 0.9_9_8_8, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}}, {"score": 0.9_9_8_7, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}}, ] , ) @require_torch @require_pytesseract @slow def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' snake_case_ = "Narsil/layoutlmv3-finetuned-funsd" snake_case_ = 0.9_9_9_3 snake_case_ = pipeline("object-detection" , model=a__ , threshold=a__ ) snake_case_ = object_detector( "https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png" ) self.assertEqual( nested_simplify(a__ , decimals=4 ) , [ {"score": 0.9_9_9_3, "label": "I-ANSWER", "box": {"xmin": 294, "ymin": 254, "xmax": 343, "ymax": 264}}, {"score": 0.9_9_9_3, "label": "I-ANSWER", "box": {"xmin": 294, "ymin": 254, "xmax": 343, "ymax": 264}}, ] , )
85
"""simple docstring""" import tempfile import unittest import numpy as np import transformers from transformers import GPTaTokenizer, GPTJConfig, is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax, tooslow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax import jax.numpy as jnp from transformers.modeling_flax_pytorch_utils import ( convert_pytorch_state_dict_to_flax, load_flax_weights_in_pytorch_model, ) from transformers.models.gptj.modeling_flax_gptj import FlaxGPTJForCausalLM, FlaxGPTJModel if is_torch_available(): import torch class A__ : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=14 , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=99 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=37 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=5_12 , _SCREAMING_SNAKE_CASE=0.02 , ): __lowerCAmelCase : Union[str, Any] = parent __lowerCAmelCase : Any = batch_size __lowerCAmelCase : Any = seq_length __lowerCAmelCase : Optional[Any] = is_training __lowerCAmelCase : Any = use_input_mask __lowerCAmelCase : Any = use_token_type_ids __lowerCAmelCase : Tuple = use_labels __lowerCAmelCase : Optional[Any] = vocab_size __lowerCAmelCase : Tuple = hidden_size __lowerCAmelCase : str = rotary_dim __lowerCAmelCase : Union[str, Any] = num_hidden_layers __lowerCAmelCase : Union[str, Any] = num_attention_heads __lowerCAmelCase : int = intermediate_size __lowerCAmelCase : List[str] = hidden_act __lowerCAmelCase : int = hidden_dropout_prob __lowerCAmelCase : Any = attention_probs_dropout_prob __lowerCAmelCase : List[Any] = max_position_embeddings __lowerCAmelCase : Optional[Any] = initializer_range __lowerCAmelCase : Tuple = None __lowerCAmelCase : int = vocab_size - 1 __lowerCAmelCase : Dict = vocab_size - 1 __lowerCAmelCase : int = vocab_size - 1 def __lowerCamelCase ( self ): __lowerCAmelCase : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __lowerCAmelCase : List[str] = None if self.use_input_mask: __lowerCAmelCase : Dict = random_attention_mask([self.batch_size, self.seq_length] ) __lowerCAmelCase : Optional[int] = GPTJConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , use_cache=_SCREAMING_SNAKE_CASE , bos_token_id=self.bos_token_id , eos_token_id=self.eos_token_id , pad_token_id=self.pad_token_id , rotary_dim=self.rotary_dim , ) return (config, input_ids, input_mask) def __lowerCamelCase ( self ): __lowerCAmelCase : Optional[int] = self.prepare_config_and_inputs() __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase : Any = config_and_inputs __lowerCAmelCase : Dict = {'input_ids': input_ids, 'attention_mask': attention_mask} return config, inputs_dict def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : List[str] = 20 __lowerCAmelCase : List[str] = model_class_name(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = model.init_cache(input_ids.shape[0] , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = jnp.ones((input_ids.shape[0], max_decoder_length) , dtype='i4' ) __lowerCAmelCase : Optional[Any] = jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1 )[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1) ) __lowerCAmelCase : Any = model( input_ids[:, :-1] , attention_mask=_SCREAMING_SNAKE_CASE , past_key_values=_SCREAMING_SNAKE_CASE , position_ids=_SCREAMING_SNAKE_CASE , ) __lowerCAmelCase : Any = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype='i4' ) __lowerCAmelCase : int = model( input_ids[:, -1:] , attention_mask=_SCREAMING_SNAKE_CASE , past_key_values=outputs_cache.past_key_values , position_ids=_SCREAMING_SNAKE_CASE , ) __lowerCAmelCase : Any = model(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=f"Max diff is {diff}" ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Tuple = 20 __lowerCAmelCase : List[str] = model_class_name(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Union[str, Any] = jnp.concatenate( [attention_mask, jnp.zeros((attention_mask.shape[0], max_decoder_length - attention_mask.shape[1]) )] , axis=-1 , ) __lowerCAmelCase : List[str] = model.init_cache(input_ids.shape[0] , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : str = jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1 )[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1) ) __lowerCAmelCase : Optional[Any] = model( input_ids[:, :-1] , attention_mask=_SCREAMING_SNAKE_CASE , past_key_values=_SCREAMING_SNAKE_CASE , position_ids=_SCREAMING_SNAKE_CASE , ) __lowerCAmelCase : str = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype='i4' ) __lowerCAmelCase : Tuple = model( input_ids[:, -1:] , past_key_values=outputs_cache.past_key_values , attention_mask=_SCREAMING_SNAKE_CASE , position_ids=_SCREAMING_SNAKE_CASE , ) __lowerCAmelCase : Union[str, Any] = model(_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=f"Max diff is {diff}" ) @require_flax class A__ ( _lowerCamelCase , _lowerCamelCase , unittest.TestCase): A_ : Tuple = (FlaxGPTJModel, FlaxGPTJForCausalLM) if is_flax_available() else () A_ : str = (FlaxGPTJForCausalLM,) if is_flax_available() else () def __lowerCamelCase ( self ): __lowerCAmelCase : int = FlaxGPTJModelTester(self ) def __lowerCamelCase ( self ): for model_class_name in self.all_model_classes: __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): for model_class_name in self.all_model_classes: __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward_with_attn_mask( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @tooslow def __lowerCamelCase ( self ): __lowerCAmelCase : Tuple = GPTaTokenizer.from_pretrained('gpt2' , pad_token='<|endoftext|>' , padding_side='left' ) __lowerCAmelCase : Optional[int] = tokenizer(['Hello this is a long string', 'Hey'] , return_tensors='np' , padding=_SCREAMING_SNAKE_CASE , truncation=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : int = FlaxGPTJForCausalLM.from_pretrained('EleutherAI/gpt-j-6B' ) __lowerCAmelCase : Any = False __lowerCAmelCase : Any = model.config.eos_token_id __lowerCAmelCase : Union[str, Any] = jax.jit(model.generate ) __lowerCAmelCase : Optional[Any] = jit_generate( inputs['input_ids'] , attention_mask=inputs['attention_mask'] , pad_token_id=tokenizer.pad_token_id ).sequences __lowerCAmelCase : str = tokenizer.batch_decode(_SCREAMING_SNAKE_CASE , skip_special_tokens=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = [ 'Hello this is a long string of text.\n\nI\'m trying to get the text of the', 'Hey, I\'m a little late to the party. I\'m going to', ] self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @is_pt_flax_cross_test def __lowerCamelCase ( self ): __lowerCAmelCase , __lowerCAmelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): # prepare inputs __lowerCAmelCase : str = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Union[str, Any] = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class __lowerCAmelCase : Dict = model_class.__name__[4:] # Skip the "Flax" at the beginning __lowerCAmelCase : Optional[int] = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase , __lowerCAmelCase : List[Any] = pt_inputs['input_ids'].shape __lowerCAmelCase : int = np.random.randint(0 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(_SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Tuple = 0 __lowerCAmelCase : Tuple = 1 __lowerCAmelCase : List[str] = 0 __lowerCAmelCase : Any = 1 __lowerCAmelCase : Optional[Any] = pt_model_class(_SCREAMING_SNAKE_CASE ).eval() __lowerCAmelCase : Any = model_class(_SCREAMING_SNAKE_CASE , dtype=jnp.floataa ) __lowerCAmelCase : int = convert_pytorch_state_dict_to_flax(pt_model.state_dict() , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : str = fx_state with torch.no_grad(): __lowerCAmelCase : Union[str, Any] = pt_model(**_SCREAMING_SNAKE_CASE ).to_tuple() __lowerCAmelCase : str = fx_model(**_SCREAMING_SNAKE_CASE ).to_tuple() self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , len(_SCREAMING_SNAKE_CASE ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output, pt_output in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) with tempfile.TemporaryDirectory() as tmpdirname: pt_model.save_pretrained(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Tuple = model_class.from_pretrained(_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = fx_model_loaded(**_SCREAMING_SNAKE_CASE ).to_tuple() self.assertEqual( len(_SCREAMING_SNAKE_CASE ) , len(_SCREAMING_SNAKE_CASE ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output_loaded, pt_output in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): self.assert_almost_equals(fx_output_loaded[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) @is_pt_flax_cross_test def __lowerCamelCase ( self ): __lowerCAmelCase , __lowerCAmelCase : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): # prepare inputs __lowerCAmelCase : List[str] = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class __lowerCAmelCase : Dict = model_class.__name__[4:] # Skip the "Flax" at the beginning __lowerCAmelCase : str = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = pt_model_class(_SCREAMING_SNAKE_CASE ).eval() __lowerCAmelCase : Tuple = model_class(_SCREAMING_SNAKE_CASE , dtype=jnp.floataa ) __lowerCAmelCase : List[str] = load_flax_weights_in_pytorch_model(_SCREAMING_SNAKE_CASE , fx_model.params ) __lowerCAmelCase , __lowerCAmelCase : int = pt_inputs['input_ids'].shape __lowerCAmelCase : List[str] = np.random.randint(0 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(_SCREAMING_SNAKE_CASE ): __lowerCAmelCase : str = 0 __lowerCAmelCase : Optional[Any] = 1 __lowerCAmelCase : Optional[int] = 0 __lowerCAmelCase : Optional[Any] = 1 # make sure weights are tied in PyTorch pt_model.tie_weights() with torch.no_grad(): __lowerCAmelCase : List[str] = pt_model(**_SCREAMING_SNAKE_CASE ).to_tuple() __lowerCAmelCase : Optional[int] = fx_model(**_SCREAMING_SNAKE_CASE ).to_tuple() self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , len(_SCREAMING_SNAKE_CASE ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output, pt_output in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) with tempfile.TemporaryDirectory() as tmpdirname: fx_model.save_pretrained(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = pt_model_class.from_pretrained(_SCREAMING_SNAKE_CASE , from_flax=_SCREAMING_SNAKE_CASE ) with torch.no_grad(): __lowerCAmelCase : Any = pt_model_loaded(**_SCREAMING_SNAKE_CASE ).to_tuple() self.assertEqual( len(_SCREAMING_SNAKE_CASE ) , len(_SCREAMING_SNAKE_CASE ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output, pt_output in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) @tooslow def __lowerCamelCase ( self ): for model_class_name in self.all_model_classes: __lowerCAmelCase : Optional[int] = model_class_name.from_pretrained('EleutherAI/gpt-j-6B' ) __lowerCAmelCase : List[Any] = model(np.ones((1, 1) ) ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE )
86
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available UpperCamelCase = {'''configuration_speech_encoder_decoder''': ['''SpeechEncoderDecoderConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ['''SpeechEncoderDecoderModel'''] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ['''FlaxSpeechEncoderDecoderModel'''] if TYPE_CHECKING: from .configuration_speech_encoder_decoder import SpeechEncoderDecoderConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_encoder_decoder import SpeechEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_speech_encoder_decoder import FlaxSpeechEncoderDecoderModel else: import sys UpperCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
87
"""simple docstring""" 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 , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=13 , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=99 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=37 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=5_12 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=None , ): __lowerCAmelCase : Tuple = parent __lowerCAmelCase : Optional[int] = 13 __lowerCAmelCase : List[Any] = 7 __lowerCAmelCase : int = True __lowerCAmelCase : Optional[int] = True __lowerCAmelCase : List[Any] = True __lowerCAmelCase : Optional[int] = True __lowerCAmelCase : Optional[Any] = 99 __lowerCAmelCase : int = 3_84 __lowerCAmelCase : Union[str, Any] = 2 __lowerCAmelCase : Tuple = 4 __lowerCAmelCase : str = 37 __lowerCAmelCase : Any = 'gelu' __lowerCAmelCase : List[str] = 0.1 __lowerCAmelCase : Any = 0.1 __lowerCAmelCase : Union[str, Any] = 5_12 __lowerCAmelCase : int = 16 __lowerCAmelCase : Union[str, Any] = 2 __lowerCAmelCase : int = 0.02 __lowerCAmelCase : Dict = 3 __lowerCAmelCase : Tuple = 4 __lowerCAmelCase : Tuple = 1_28 __lowerCAmelCase : Optional[int] = 2 __lowerCAmelCase : List[str] = 9 __lowerCAmelCase : int = 1 __lowerCAmelCase : int = None def __lowerCamelCase ( self ): __lowerCAmelCase : Any = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __lowerCAmelCase : Optional[int] = None if self.use_input_mask: __lowerCAmelCase : str = random_attention_mask([self.batch_size, self.seq_length] ) __lowerCAmelCase : Tuple = None if self.use_token_type_ids: __lowerCAmelCase : Dict = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __lowerCAmelCase : Optional[Any] = None __lowerCAmelCase : Dict = None __lowerCAmelCase : Union[str, Any] = None if self.use_labels: __lowerCAmelCase : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCAmelCase : Dict = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __lowerCAmelCase : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) __lowerCAmelCase : Union[str, 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=_SCREAMING_SNAKE_CASE , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Optional[int] = TFConvBertModel(config=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids} __lowerCAmelCase : Tuple = [input_ids, input_mask] __lowerCAmelCase : Any = model(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Any = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Any = TFConvBertForMaskedLM(config=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } __lowerCAmelCase : Optional[Any] = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Tuple = self.num_labels __lowerCAmelCase : Optional[Any] = TFConvBertForSequenceClassification(config=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : int = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } __lowerCAmelCase : Union[str, Any] = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : int = self.num_choices __lowerCAmelCase : List[str] = TFConvBertForMultipleChoice(config=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = tf.tile(tf.expand_dims(_SCREAMING_SNAKE_CASE , 1 ) , (1, self.num_choices, 1) ) __lowerCAmelCase : Dict = tf.tile(tf.expand_dims(_SCREAMING_SNAKE_CASE , 1 ) , (1, self.num_choices, 1) ) __lowerCAmelCase : Union[str, Any] = tf.tile(tf.expand_dims(_SCREAMING_SNAKE_CASE , 1 ) , (1, self.num_choices, 1) ) __lowerCAmelCase : Tuple = { 'input_ids': multiple_choice_inputs_ids, 'attention_mask': multiple_choice_input_mask, 'token_type_ids': multiple_choice_token_type_ids, } __lowerCAmelCase : str = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : str = self.num_labels __lowerCAmelCase : Any = TFConvBertForTokenClassification(config=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } __lowerCAmelCase : Union[str, Any] = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : str = TFConvBertForQuestionAnswering(config=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Union[str, Any] = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } __lowerCAmelCase : Optional[int] = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __lowerCamelCase ( self ): __lowerCAmelCase : Union[str, Any] = self.prepare_config_and_inputs() ( ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ) : List[str] = config_and_inputs __lowerCAmelCase : Any = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_tf class A__ ( _lowerCamelCase , _lowerCamelCase , unittest.TestCase): A_ : List[str] = ( ( TFConvBertModel, TFConvBertForMaskedLM, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertForMultipleChoice, ) if is_tf_available() else () ) A_ : str = ( { 'feature-extraction': TFConvBertModel, 'fill-mask': TFConvBertForMaskedLM, 'question-answering': TFConvBertForQuestionAnswering, 'text-classification': TFConvBertForSequenceClassification, 'token-classification': TFConvBertForTokenClassification, 'zero-shot': TFConvBertForSequenceClassification, } if is_tf_available() else {} ) A_ : List[Any] = False A_ : str = False A_ : List[Any] = False def __lowerCamelCase ( self ): __lowerCAmelCase : Dict = TFConvBertModelTester(self ) __lowerCAmelCase : Any = ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , hidden_size=37 ) def __lowerCamelCase ( self ): self.config_tester.run_common_tests() def __lowerCamelCase ( self ): __lowerCAmelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_SCREAMING_SNAKE_CASE ) @slow def __lowerCamelCase ( self ): __lowerCAmelCase , __lowerCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() __lowerCAmelCase : Any = True __lowerCAmelCase : Dict = True if hasattr(_SCREAMING_SNAKE_CASE , 'use_cache' ): __lowerCAmelCase : int = True __lowerCAmelCase : List[str] = getattr(self.model_tester , 'encoder_seq_length' , self.model_tester.seq_length ) __lowerCAmelCase : str = getattr(self.model_tester , 'key_length' , _SCREAMING_SNAKE_CASE ) for model_class in self.all_model_classes: __lowerCAmelCase : str = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : str = model_class(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = len(model(_SCREAMING_SNAKE_CASE ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(_SCREAMING_SNAKE_CASE , saved_model=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = os.path.join(_SCREAMING_SNAKE_CASE , 'saved_model' , '1' ) __lowerCAmelCase : int = tf.keras.models.load_model(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = model(_SCREAMING_SNAKE_CASE ) if self.is_encoder_decoder: __lowerCAmelCase : List[str] = outputs['encoder_hidden_states'] __lowerCAmelCase : Tuple = outputs['encoder_attentions'] else: __lowerCAmelCase : Optional[int] = outputs['hidden_states'] __lowerCAmelCase : Tuple = outputs['attentions'] self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Union[str, Any] = getattr( self.model_tester , 'expected_num_hidden_layers' , self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) self.assertListEqual( list(output_hidden_states[0].shape[-2:] ) , [self.model_tester.seq_length, self.model_tester.hidden_size] , ) self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , 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 __lowerCamelCase ( self ): __lowerCAmelCase : Tuple = TFConvBertModel.from_pretrained('YituTech/conv-bert-base' ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase , __lowerCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs_for_common() __lowerCAmelCase : Optional[Any] = True __lowerCAmelCase : List[Any] = getattr(self.model_tester , 'decoder_seq_length' , self.model_tester.seq_length ) __lowerCAmelCase : str = getattr(self.model_tester , 'encoder_seq_length' , self.model_tester.seq_length ) __lowerCAmelCase : Tuple = getattr(self.model_tester , 'key_length' , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = getattr(self.model_tester , 'key_length' , _SCREAMING_SNAKE_CASE ) def check_decoder_attentions_output(_SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Union[str, Any] = len(_SCREAMING_SNAKE_CASE ) self.assertEqual(out_len % 2 , 0 ) __lowerCAmelCase : Optional[Any] = outputs.decoder_attentions self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , 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(_SCREAMING_SNAKE_CASE ): __lowerCAmelCase : str = [ t.numpy() for t in (outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions) ] self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , 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: __lowerCAmelCase : List[str] = True __lowerCAmelCase : Optional[int] = False __lowerCAmelCase : List[Any] = model_class(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = model(self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) __lowerCAmelCase : Tuple = len(_SCREAMING_SNAKE_CASE ) self.assertEqual(config.output_hidden_states , _SCREAMING_SNAKE_CASE ) check_encoder_attentions_output(_SCREAMING_SNAKE_CASE ) if self.is_encoder_decoder: __lowerCAmelCase : Any = model_class(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = model(self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) self.assertEqual(config.output_hidden_states , _SCREAMING_SNAKE_CASE ) check_decoder_attentions_output(_SCREAMING_SNAKE_CASE ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] __lowerCAmelCase : Optional[Any] = True __lowerCAmelCase : str = model_class(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = model(self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) self.assertEqual(config.output_hidden_states , _SCREAMING_SNAKE_CASE ) check_encoder_attentions_output(_SCREAMING_SNAKE_CASE ) # Check attention is always last and order is fine __lowerCAmelCase : Dict = True __lowerCAmelCase : Optional[Any] = True __lowerCAmelCase : List[Any] = model_class(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = model(self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(_SCREAMING_SNAKE_CASE ) ) self.assertEqual(model.config.output_hidden_states , _SCREAMING_SNAKE_CASE ) check_encoder_attentions_output(_SCREAMING_SNAKE_CASE ) @require_tf class A__ ( unittest.TestCase): @slow def __lowerCamelCase ( self ): __lowerCAmelCase : Dict = TFConvBertModel.from_pretrained('YituTech/conv-bert-base' ) __lowerCAmelCase : int = tf.constant([[0, 1, 2, 3, 4, 5]] ) __lowerCAmelCase : Tuple = model(_SCREAMING_SNAKE_CASE )[0] __lowerCAmelCase : Tuple = [1, 6, 7_68] self.assertEqual(output.shape , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = tf.constant( [ [ [-0.0347_5493, -0.468_6034, -0.3063_8832], [0.2263_7248, -0.2698_8646, -0.742_3424], [0.1032_4868, -0.4501_3508, -0.5828_0784], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 )
86
0
def a__ ( A_, A_ ): '''simple docstring''' _validate_point(A_ ) _validate_point(A_ ) if len(A_ ) != len(A_ ): raise ValueError("""Both points must be in the same n-dimensional space""" ) return float(sum(abs(a - b ) for a, b in zip(A_, A_ ) ) ) def a__ ( A_ ): '''simple docstring''' if point: if isinstance(A_, A_ ): for item in point: if not isinstance(A_, (int, float) ): __magic_name__ = ( """Expected a list of numbers as input, found """ f'''{type(A_ ).__name__}''' ) raise TypeError(A_ ) else: __magic_name__ = f'''Expected a list of numbers as input, found {type(A_ ).__name__}''' raise TypeError(A_ ) else: raise ValueError("""Missing an input""" ) def a__ ( A_, A_ ): '''simple docstring''' _validate_point(A_ ) _validate_point(A_ ) if len(A_ ) != len(A_ ): raise ValueError("""Both points must be in the same n-dimensional space""" ) return float(sum(abs(x - y ) for x, y in zip(A_, A_ ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
88
"""simple docstring""" 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 DetrImageProcessor class A__ ( unittest.TestCase): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=30 , _SCREAMING_SNAKE_CASE=4_00 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=1 / 2_55 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , _SCREAMING_SNAKE_CASE=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __lowerCAmelCase : Any = size if size is not None else {'shortest_edge': 18, 'longest_edge': 13_33} __lowerCAmelCase : Optional[int] = parent __lowerCAmelCase : int = batch_size __lowerCAmelCase : str = num_channels __lowerCAmelCase : Optional[int] = min_resolution __lowerCAmelCase : List[Any] = max_resolution __lowerCAmelCase : Union[str, Any] = do_resize __lowerCAmelCase : Optional[Any] = size __lowerCAmelCase : Dict = do_rescale __lowerCAmelCase : Optional[Any] = rescale_factor __lowerCAmelCase : Any = do_normalize __lowerCAmelCase : List[str] = image_mean __lowerCAmelCase : Union[str, Any] = image_std __lowerCAmelCase : Optional[int] = do_pad def __lowerCamelCase ( self ): return { "do_resize": self.do_resize, "size": self.size, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_pad": self.do_pad, } def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ): if not batched: __lowerCAmelCase : str = image_inputs[0] if isinstance(_SCREAMING_SNAKE_CASE , Image.Image ): __lowerCAmelCase , __lowerCAmelCase : Optional[int] = image.size else: __lowerCAmelCase , __lowerCAmelCase : Union[str, Any] = image.shape[1], image.shape[2] if w < h: __lowerCAmelCase : str = int(self.size['shortest_edge'] * h / w ) __lowerCAmelCase : Optional[int] = self.size['shortest_edge'] elif w > h: __lowerCAmelCase : str = self.size['shortest_edge'] __lowerCAmelCase : Union[str, Any] = int(self.size['shortest_edge'] * w / h ) else: __lowerCAmelCase : str = self.size['shortest_edge'] __lowerCAmelCase : Optional[Any] = self.size['shortest_edge'] else: __lowerCAmelCase : str = [] for image in image_inputs: __lowerCAmelCase , __lowerCAmelCase : List[Any] = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __lowerCAmelCase : Any = max(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : item[0] )[0] __lowerCAmelCase : Dict = max(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class A__ ( _lowerCamelCase , unittest.TestCase): A_ : List[str] = DetrImageProcessor if is_vision_available() else None def __lowerCamelCase ( self ): __lowerCAmelCase : List[Any] = DetrImageProcessingTester(self ) @property def __lowerCamelCase ( self ): return self.image_processor_tester.prepare_image_processor_dict() def __lowerCamelCase ( self ): __lowerCAmelCase : Dict = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'image_mean' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'image_std' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_normalize' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_rescale' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'rescale_factor' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_resize' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'size' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_pad' ) ) def __lowerCamelCase ( self ): __lowerCAmelCase : Optional[Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'shortest_edge': 18, 'longest_edge': 13_33} ) self.assertEqual(image_processor.do_pad , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=_SCREAMING_SNAKE_CASE ) self.assertEqual(image_processor.size , {'shortest_edge': 42, 'longest_edge': 84} ) self.assertEqual(image_processor.do_pad , _SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): pass def __lowerCamelCase ( self ): # Initialize image_processing __lowerCAmelCase : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __lowerCAmelCase : str = 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 __lowerCAmelCase : int = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values __lowerCAmelCase , __lowerCAmelCase : List[Any] = self.image_processor_tester.get_expected_values(_SCREAMING_SNAKE_CASE ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __lowerCAmelCase , __lowerCAmelCase : int = self.image_processor_tester.get_expected_values(_SCREAMING_SNAKE_CASE , batched=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Union[str, Any] = image_processing(_SCREAMING_SNAKE_CASE , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __lowerCamelCase ( self ): # Initialize image_processing __lowerCAmelCase : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __lowerCAmelCase : str = 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 __lowerCAmelCase : Tuple = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values __lowerCAmelCase , __lowerCAmelCase : Tuple = self.image_processor_tester.get_expected_values(_SCREAMING_SNAKE_CASE ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __lowerCAmelCase : Union[str, Any] = image_processing(_SCREAMING_SNAKE_CASE , return_tensors='pt' ).pixel_values __lowerCAmelCase , __lowerCAmelCase : List[Any] = self.image_processor_tester.get_expected_values(_SCREAMING_SNAKE_CASE , batched=_SCREAMING_SNAKE_CASE ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __lowerCamelCase ( self ): # Initialize image_processing __lowerCAmelCase : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __lowerCAmelCase : int = 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 __lowerCAmelCase : Any = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values __lowerCAmelCase , __lowerCAmelCase : Dict = self.image_processor_tester.get_expected_values(_SCREAMING_SNAKE_CASE ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __lowerCAmelCase : Tuple = image_processing(_SCREAMING_SNAKE_CASE , return_tensors='pt' ).pixel_values __lowerCAmelCase , __lowerCAmelCase : Any = self.image_processor_tester.get_expected_values(_SCREAMING_SNAKE_CASE , batched=_SCREAMING_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 __lowerCamelCase ( self ): # prepare image and target __lowerCAmelCase : Union[str, Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' , 'r' ) as f: __lowerCAmelCase : Any = json.loads(f.read() ) __lowerCAmelCase : Tuple = {'image_id': 3_97_69, 'annotations': target} # encode them __lowerCAmelCase : Dict = DetrImageProcessor.from_pretrained('facebook/detr-resnet-50' ) __lowerCAmelCase : int = image_processing(images=_SCREAMING_SNAKE_CASE , annotations=_SCREAMING_SNAKE_CASE , return_tensors='pt' ) # verify pixel values __lowerCAmelCase : str = torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding['pixel_values'].shape , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : int = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 ) ) # verify area __lowerCAmelCase : List[str] = torch.tensor([5887.9600, 1_1250.2061, 48_9353.8438, 83_7122.7500, 14_7967.5156, 16_5732.3438] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , _SCREAMING_SNAKE_CASE ) ) # verify boxes __lowerCAmelCase : Tuple = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : str = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , _SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # verify image_id __lowerCAmelCase : Dict = torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , _SCREAMING_SNAKE_CASE ) ) # verify is_crowd __lowerCAmelCase : Optional[int] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , _SCREAMING_SNAKE_CASE ) ) # verify class_labels __lowerCAmelCase : Union[str, Any] = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , _SCREAMING_SNAKE_CASE ) ) # verify orig_size __lowerCAmelCase : int = torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , _SCREAMING_SNAKE_CASE ) ) # verify size __lowerCAmelCase : List[Any] = torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , _SCREAMING_SNAKE_CASE ) ) @slow def __lowerCamelCase ( self ): # prepare image, target and masks_path __lowerCAmelCase : Optional[int] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' , 'r' ) as f: __lowerCAmelCase : Optional[int] = json.loads(f.read() ) __lowerCAmelCase : Optional[int] = {'file_name': '000000039769.png', 'image_id': 3_97_69, 'segments_info': target} __lowerCAmelCase : Union[str, Any] = pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic' ) # encode them __lowerCAmelCase : Optional[int] = DetrImageProcessor.from_pretrained('facebook/detr-resnet-50-panoptic' ) __lowerCAmelCase : Optional[Any] = image_processing(images=_SCREAMING_SNAKE_CASE , annotations=_SCREAMING_SNAKE_CASE , masks_path=_SCREAMING_SNAKE_CASE , return_tensors='pt' ) # verify pixel values __lowerCAmelCase : str = torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding['pixel_values'].shape , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 ) ) # verify area __lowerCAmelCase : int = torch.tensor([14_7979.6875, 16_5527.0469, 48_4638.5938, 1_1292.9375, 5879.6562, 7634.1147] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , _SCREAMING_SNAKE_CASE ) ) # verify boxes __lowerCAmelCase : Optional[int] = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , _SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # verify image_id __lowerCAmelCase : str = torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , _SCREAMING_SNAKE_CASE ) ) # verify is_crowd __lowerCAmelCase : Optional[int] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , _SCREAMING_SNAKE_CASE ) ) # verify class_labels __lowerCAmelCase : str = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , _SCREAMING_SNAKE_CASE ) ) # verify masks __lowerCAmelCase : Dict = 82_28_73 self.assertEqual(encoding['labels'][0]['masks'].sum().item() , _SCREAMING_SNAKE_CASE ) # verify orig_size __lowerCAmelCase : str = torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , _SCREAMING_SNAKE_CASE ) ) # verify size __lowerCAmelCase : List[Any] = torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , _SCREAMING_SNAKE_CASE ) )
86
0
'''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 = '''true''' def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_=82 , lowerCAmelCase_=16 ) -> Union[str, Any]: set_seed(42 ) _a : Union[str, Any] = RegressionModel() _a : Dict = deepcopy(lowerCAmelCase_ ) _a : Any = RegressionDataset(length=lowerCAmelCase_ ) _a : List[str] = DataLoader(lowerCAmelCase_ , batch_size=lowerCAmelCase_ ) model.to(accelerator.device ) _a , _a : int = accelerator.prepare(lowerCAmelCase_ , lowerCAmelCase_ ) return model, ddp_model, dataloader def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_=False ) -> Optional[int]: _a : Optional[int] = AutoTokenizer.from_pretrained('hf-internal-testing/mrpc-bert-base-cased' ) _a : Dict = load_dataset('glue' , 'mrpc' , split='validation' ) def tokenize_function(lowerCAmelCase_ ): _a : Optional[Any] = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=lowerCAmelCase_ , max_length=lowerCAmelCase_ ) return outputs with accelerator.main_process_first(): _a : int = dataset.map( lowerCAmelCase_ , batched=lowerCAmelCase_ , remove_columns=['idx', 'sentence1', 'sentence2'] , ) _a : Union[str, Any] = tokenized_datasets.rename_column('label' , 'labels' ) def collate_fn(lowerCAmelCase_ ): if use_longest: return tokenizer.pad(lowerCAmelCase_ , padding='longest' , return_tensors='pt' ) return tokenizer.pad(lowerCAmelCase_ , padding='max_length' , max_length=128 , return_tensors='pt' ) return DataLoader(lowerCAmelCase_ , shuffle=lowerCAmelCase_ , collate_fn=lowerCAmelCase_ , batch_size=16 ) def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> str: _a : Optional[int] = Accelerator(dispatch_batches=lowerCAmelCase_ , split_batches=lowerCAmelCase_ ) _a : Optional[Any] = get_dataloader(lowerCAmelCase_ , not dispatch_batches ) _a : List[str] = AutoModelForSequenceClassification.from_pretrained( 'hf-internal-testing/mrpc-bert-base-cased' , return_dict=lowerCAmelCase_ ) _a , _a : Optional[int] = accelerator.prepare(lowerCAmelCase_ , lowerCAmelCase_ ) return {"ddp": [ddp_model, ddp_dataloader, "cuda:0"], "no": [model, dataloader, accelerator.device]}, accelerator def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) -> List[str]: _a : Union[str, Any] = [] for batch in dataloader: _a , _a : Any = batch.values() with torch.no_grad(): _a : str = model(lowerCAmelCase_ ) _a , _a : Optional[int] = accelerator.gather_for_metrics((logit, target) ) logits_and_targets.append((logit, target) ) _a , _a : Dict = [], [] for logit, targ in logits_and_targets: logits.append(lowerCAmelCase_ ) targs.append(lowerCAmelCase_ ) _a , _a : Dict = torch.cat(lowerCAmelCase_ ), torch.cat(lowerCAmelCase_ ) return logits, targs def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_=82 , lowerCAmelCase_=False , lowerCAmelCase_=False , lowerCAmelCase_=16 ) -> List[Any]: _a , _a , _a : int = get_basic_setup(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) _a , _a : Union[str, Any] = generate_predictions(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) assert ( len(lowerCAmelCase_ ) == num_samples ), f"""Unexpected number of inputs:\n Expected: {num_samples}\n Actual: {len(lowerCAmelCase_ )}""" def __lowerCamelCase ( lowerCAmelCase_ = False , lowerCAmelCase_ = False ) -> List[Any]: _a : Optional[Any] = evaluate.load('glue' , 'mrpc' ) _a , _a : Any = get_mrpc_setup(lowerCAmelCase_ , lowerCAmelCase_ ) # First do baseline _a , _a , _a : str = setup['no'] model.to(lowerCAmelCase_ ) model.eval() for batch in dataloader: batch.to(lowerCAmelCase_ ) with torch.inference_mode(): _a : List[Any] = model(**lowerCAmelCase_ ) _a : Optional[Any] = outputs.logits.argmax(dim=-1 ) metric.add_batch(predictions=lowerCAmelCase_ , references=batch['labels'] ) _a : Any = metric.compute() # Then do distributed _a , _a , _a : int = setup['ddp'] model.eval() for batch in dataloader: with torch.inference_mode(): _a : List[str] = model(**lowerCAmelCase_ ) _a : int = outputs.logits.argmax(dim=-1 ) _a : Optional[int] = batch['labels'] _a , _a : Dict = accelerator.gather_for_metrics((preds, references) ) metric.add_batch(predictions=lowerCAmelCase_ , references=lowerCAmelCase_ ) _a : Any = 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 __lowerCamelCase ( ) -> str: _a : Optional[int] = Accelerator(split_batches=lowerCAmelCase_ , dispatch_batches=lowerCAmelCase_ ) 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(lowerCAmelCase_ , lowerCAmelCase_ ) 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]: _a : Optional[Any] = Accelerator(split_batches=lowerCAmelCase_ , dispatch_batches=lowerCAmelCase_ ) if accelerator.is_local_main_process: print(f"""With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`, length=99""" ) test_torch_metrics(lowerCAmelCase_ , 99 ) accelerator.state._reset_state() if accelerator.is_local_main_process: print('**Test last batch is not dropped when perfectly divisible**' ) _a : int = Accelerator() test_torch_metrics(lowerCAmelCase_ , 512 ) accelerator.state._reset_state() def __lowerCamelCase ( lowerCAmelCase_ ) -> int: # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
89
"""simple docstring""" import numpy as np def __lowerCAmelCase (_UpperCamelCase ): return 1 / (1 + np.exp(-vector )) def __lowerCAmelCase (_UpperCamelCase ): return vector * sigmoid(_UpperCamelCase ) if __name__ == "__main__": import doctest doctest.testmod()
86
0
import gc import random import unittest import numpy as np import torch from diffusers import ( DDIMScheduler, KandinskyVaaControlnetPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class __lowerCAmelCase ( __magic_name__ , unittest.TestCase ): """simple docstring""" snake_case_ = KandinskyVaaControlnetPipeline snake_case_ = ['''image_embeds''', '''negative_image_embeds''', '''hint'''] snake_case_ = ['''image_embeds''', '''negative_image_embeds''', '''hint'''] snake_case_ = [ '''generator''', '''height''', '''width''', '''latents''', '''guidance_scale''', '''num_inference_steps''', '''return_dict''', '''guidance_scale''', '''num_images_per_prompt''', '''output_type''', '''return_dict''', ] snake_case_ = False @property def lowercase_ ( self ) -> str: '''simple docstring''' return 32 @property def lowercase_ ( self ) -> Tuple: '''simple docstring''' return 32 @property def lowercase_ ( self ) -> Tuple: '''simple docstring''' return self.time_input_dim @property def lowercase_ ( self ) -> str: '''simple docstring''' return self.time_input_dim * 4 @property def lowercase_ ( self ) -> List[Any]: '''simple docstring''' return 100 @property def lowercase_ ( self ) -> Any: '''simple docstring''' torch.manual_seed(0 ) __lowerCamelCase = { '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, } __lowerCamelCase = UNetaDConditionModel(**lowerCamelCase__ ) return model @property def lowercase_ ( self ) -> Union[str, Any]: '''simple docstring''' return { "block_out_channels": [32, 32, 64, 64], "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": 12, "out_channels": 3, "up_block_types": ["AttnUpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"], "vq_embed_dim": 4, } @property def lowercase_ ( self ) -> List[str]: '''simple docstring''' torch.manual_seed(0 ) __lowerCamelCase = VQModel(**self.dummy_movq_kwargs ) return model def lowercase_ ( self ) -> Optional[int]: '''simple docstring''' __lowerCamelCase = self.dummy_unet __lowerCamelCase = self.dummy_movq __lowerCamelCase = DDIMScheduler( num_train_timesteps=1_000 , beta_schedule='linear' , beta_start=0.0_00_85 , beta_end=0.0_12 , clip_sample=lowerCamelCase__ , set_alpha_to_one=lowerCamelCase__ , steps_offset=1 , prediction_type='epsilon' , thresholding=lowerCamelCase__ , ) __lowerCamelCase = { 'unet': unet, 'scheduler': scheduler, 'movq': movq, } return components def lowercase_ ( self , lowerCamelCase__ , lowerCamelCase__=0 ) -> Union[str, Any]: '''simple docstring''' __lowerCamelCase = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(lowerCamelCase__ ) ).to(lowerCamelCase__ ) __lowerCamelCase = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( lowerCamelCase__ ) # create hint __lowerCamelCase = floats_tensor((1, 3, 64, 64) , rng=random.Random(lowerCamelCase__ ) ).to(lowerCamelCase__ ) if str(lowerCamelCase__ ).startswith('mps' ): __lowerCamelCase = torch.manual_seed(lowerCamelCase__ ) else: __lowerCamelCase = torch.Generator(device=lowerCamelCase__ ).manual_seed(lowerCamelCase__ ) __lowerCamelCase = { 'image_embeds': image_embeds, 'negative_image_embeds': negative_image_embeds, 'hint': hint, 'generator': generator, 'height': 64, 'width': 64, 'guidance_scale': 4.0, 'num_inference_steps': 2, 'output_type': 'np', } return inputs def lowercase_ ( self ) -> str: '''simple docstring''' __lowerCamelCase = 'cpu' __lowerCamelCase = self.get_dummy_components() __lowerCamelCase = self.pipeline_class(**lowerCamelCase__ ) __lowerCamelCase = pipe.to(lowerCamelCase__ ) pipe.set_progress_bar_config(disable=lowerCamelCase__ ) __lowerCamelCase = pipe(**self.get_dummy_inputs(lowerCamelCase__ ) ) __lowerCamelCase = output.images __lowerCamelCase = pipe( **self.get_dummy_inputs(lowerCamelCase__ ) , return_dict=lowerCamelCase__ , )[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.6_95_98_26, 0.86_82_79, 0.7_55_80_92, 0.68_76_94_67, 0.85_80_58_04, 0.65_97_74_96, 0.44_88_53_02, 0.5_95_91_11, 0.4_25_15_95] ) 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 __lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def lowercase_ ( self ) -> List[Any]: '''simple docstring''' # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def lowercase_ ( self ) -> Any: '''simple docstring''' __lowerCamelCase = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinskyv22/kandinskyv22_controlnet_robotcat_fp16.npy' ) __lowerCamelCase = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinskyv22/hint_image_cat.png' ) __lowerCamelCase = torch.from_numpy(np.array(lowerCamelCase__ ) ).float() / 2_55.0 __lowerCamelCase = hint.permute(2 , 0 , 1 ).unsqueeze(0 ) __lowerCamelCase = KandinskyVaaPriorPipeline.from_pretrained( 'kandinsky-community/kandinsky-2-2-prior' , torch_dtype=torch.floataa ) pipe_prior.to(lowerCamelCase__ ) __lowerCamelCase = KandinskyVaaControlnetPipeline.from_pretrained( 'kandinsky-community/kandinsky-2-2-controlnet-depth' , torch_dtype=torch.floataa ) __lowerCamelCase = pipeline.to(lowerCamelCase__ ) pipeline.set_progress_bar_config(disable=lowerCamelCase__ ) __lowerCamelCase = 'A robot, 4k photo' __lowerCamelCase = torch.Generator(device='cuda' ).manual_seed(0 ) __lowerCamelCase , __lowerCamelCase = pipe_prior( lowerCamelCase__ , generator=lowerCamelCase__ , num_inference_steps=5 , negative_prompt='' , ).to_tuple() __lowerCamelCase = torch.Generator(device='cuda' ).manual_seed(0 ) __lowerCamelCase = pipeline( image_embeds=lowerCamelCase__ , negative_image_embeds=lowerCamelCase__ , hint=lowerCamelCase__ , generator=lowerCamelCase__ , num_inference_steps=100 , output_type='np' , ) __lowerCamelCase = output.images[0] assert image.shape == (512, 512, 3) assert_mean_pixel_difference(lowerCamelCase__ , lowerCamelCase__ )
90
"""simple docstring""" import unittest from transformers import MobileBertConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, MobileBertForMaskedLM, MobileBertForMultipleChoice, MobileBertForNextSentencePrediction, MobileBertForPreTraining, MobileBertForQuestionAnswering, MobileBertForSequenceClassification, MobileBertForTokenClassification, MobileBertModel, ) class A__ : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=13 , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=99 , _SCREAMING_SNAKE_CASE=64 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=37 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=5_12 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=None , ): __lowerCAmelCase : Optional[int] = parent __lowerCAmelCase : Union[str, Any] = batch_size __lowerCAmelCase : Dict = seq_length __lowerCAmelCase : Dict = is_training __lowerCAmelCase : List[str] = use_input_mask __lowerCAmelCase : int = use_token_type_ids __lowerCAmelCase : Optional[int] = use_labels __lowerCAmelCase : List[Any] = vocab_size __lowerCAmelCase : Dict = hidden_size __lowerCAmelCase : Tuple = embedding_size __lowerCAmelCase : List[Any] = num_hidden_layers __lowerCAmelCase : Tuple = num_attention_heads __lowerCAmelCase : Union[str, Any] = intermediate_size __lowerCAmelCase : Optional[Any] = hidden_act __lowerCAmelCase : Optional[int] = hidden_dropout_prob __lowerCAmelCase : Dict = attention_probs_dropout_prob __lowerCAmelCase : Any = max_position_embeddings __lowerCAmelCase : Any = type_vocab_size __lowerCAmelCase : Union[str, Any] = type_sequence_label_size __lowerCAmelCase : List[str] = initializer_range __lowerCAmelCase : str = num_labels __lowerCAmelCase : int = num_choices __lowerCAmelCase : Union[str, Any] = scope def __lowerCamelCase ( self ): __lowerCAmelCase : Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __lowerCAmelCase : Optional[int] = None if self.use_input_mask: __lowerCAmelCase : Optional[int] = random_attention_mask([self.batch_size, self.seq_length] ) __lowerCAmelCase : str = None if self.use_token_type_ids: __lowerCAmelCase : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __lowerCAmelCase : Union[str, Any] = None __lowerCAmelCase : Optional[int] = None __lowerCAmelCase : Union[str, Any] = None if self.use_labels: __lowerCAmelCase : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCAmelCase : Dict = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __lowerCAmelCase : Dict = ids_tensor([self.batch_size] , self.num_choices ) __lowerCAmelCase : str = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowerCamelCase ( self ): return MobileBertConfig( 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 , embedding_size=self.embedding_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=_SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : str = MobileBertModel(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() __lowerCAmelCase : Optional[Any] = model(_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = model(_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : int = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Union[str, Any] = MobileBertForMaskedLM(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() __lowerCAmelCase : Any = model(_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Optional[Any] = MobileBertForNextSentencePrediction(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() __lowerCAmelCase : Dict = model( _SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : List[Any] = MobileBertForPreTraining(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() __lowerCAmelCase : List[Any] = model( _SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE , next_sentence_label=_SCREAMING_SNAKE_CASE , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Optional[int] = MobileBertForQuestionAnswering(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() __lowerCAmelCase : List[str] = model( _SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_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 __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Optional[int] = self.num_labels __lowerCAmelCase : Tuple = MobileBertForSequenceClassification(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() __lowerCAmelCase : str = model(_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Optional[Any] = self.num_labels __lowerCAmelCase : int = MobileBertForTokenClassification(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() __lowerCAmelCase : Optional[Any] = model(_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Optional[int] = self.num_choices __lowerCAmelCase : List[str] = MobileBertForMultipleChoice(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() __lowerCAmelCase : str = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __lowerCAmelCase : List[Any] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __lowerCAmelCase : List[Any] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __lowerCAmelCase : List[str] = model( _SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __lowerCamelCase ( self ): __lowerCAmelCase : Optional[Any] = self.prepare_config_and_inputs() ( ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ) : Optional[Any] = config_and_inputs __lowerCAmelCase : List[str] = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class A__ ( _lowerCamelCase , _lowerCamelCase , unittest.TestCase): A_ : str = ( ( MobileBertModel, MobileBertForMaskedLM, MobileBertForMultipleChoice, MobileBertForNextSentencePrediction, MobileBertForPreTraining, MobileBertForQuestionAnswering, MobileBertForSequenceClassification, MobileBertForTokenClassification, ) if is_torch_available() else () ) A_ : List[str] = ( { 'feature-extraction': MobileBertModel, 'fill-mask': MobileBertForMaskedLM, 'question-answering': MobileBertForQuestionAnswering, 'text-classification': MobileBertForSequenceClassification, 'token-classification': MobileBertForTokenClassification, 'zero-shot': MobileBertForSequenceClassification, } if is_torch_available() else {} ) A_ : Dict = True def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ): __lowerCAmelCase : List[str] = super()._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) if return_labels: if model_class in get_values(_SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Tuple = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=_SCREAMING_SNAKE_CASE ) return inputs_dict def __lowerCamelCase ( self ): __lowerCAmelCase : Optional[Any] = MobileBertModelTester(self ) __lowerCAmelCase : str = ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , hidden_size=37 ) def __lowerCamelCase ( self ): self.config_tester.run_common_tests() def __lowerCamelCase ( self ): __lowerCAmelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_model(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_masked_lm(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_multiple_choice(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_next_sequence_prediction(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_pretraining(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_question_answering(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_sequence_classification(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_token_classification(*_SCREAMING_SNAKE_CASE ) def __lowerCAmelCase (_UpperCamelCase ): return torch.tensor( _UpperCamelCase , dtype=torch.long , device=_UpperCamelCase , ) lowerCamelCase__ = 1E-3 @require_torch @require_sentencepiece @require_tokenizers class A__ ( unittest.TestCase): @slow def __lowerCamelCase ( self ): __lowerCAmelCase : Union[str, Any] = MobileBertModel.from_pretrained('google/mobilebert-uncased' ).to(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = _long_tensor([[1_01, 71_10, 10_05, 10_56, 20_23, 1_13_33, 1_74_13, 10_29, 1_02]] ) with torch.no_grad(): __lowerCAmelCase : int = model(_SCREAMING_SNAKE_CASE )[0] __lowerCAmelCase : Dict = torch.Size((1, 9, 5_12) ) self.assertEqual(output.shape , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = torch.tensor( [ [ [-2.4_73_65_26E07, 8.2_69_16_56E04, 1.6_52_18_38E05], [-5.7_54_17_04E-01, 3.9_05_60_22E00, 4.4_01_15_07E00], [2.6_04_73_59E00, 1.5_67_76_52E00, -1.7_32_41_88E-01], ] ] , device=_SCREAMING_SNAKE_CASE , ) # MobileBERT results range from 10e0 to 10e8. Even a 0.0000001% difference with a value of 10e8 results in a # ~1 difference, it's therefore not a good idea to measure using addition. # Here, we instead divide the expected result with the result in order to obtain ~1. We then check that the # result is held between bounds: 1 - TOLERANCE < expected_result / result < 1 + TOLERANCE __lowerCAmelCase : Tuple = torch.all((expected_slice / output[..., :3, :3]) >= 1 - TOLERANCE ) __lowerCAmelCase : Union[str, Any] = torch.all((expected_slice / output[..., :3, :3]) <= 1 + TOLERANCE ) self.assertTrue(lower_bound and upper_bound )
86
0
"""simple docstring""" import unittest from transformers import BigBirdTokenizer, BigBirdTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin UpperCAmelCase_ : str = """▁""" UpperCAmelCase_ : List[Any] = get_tests_dir("""fixtures/test_sentencepiece.model""") @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = BigBirdTokenizer __UpperCamelCase = BigBirdTokenizerFast __UpperCamelCase = True __UpperCamelCase = True def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' super().setUp() SCREAMING_SNAKE_CASE_ : Any = self.tokenizer_class(lowercase_ , keep_accents=lowercase_) tokenizer.save_pretrained(self.tmpdirname) def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = '''<s>''' SCREAMING_SNAKE_CASE_ : Tuple = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowercase_) , lowercase_) self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowercase_) , lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = list(self.get_tokenizer().get_vocab().keys()) self.assertEqual(vocab_keys[0] , '''<unk>''') self.assertEqual(vocab_keys[1] , '''<s>''') self.assertEqual(vocab_keys[-1] , '''[MASK]''') self.assertEqual(len(lowercase_) , 1004) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1000) def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' if not self.test_rust_tokenizer: return SCREAMING_SNAKE_CASE_ : List[Any] = self.get_tokenizer() SCREAMING_SNAKE_CASE_ : int = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE_ : Optional[Any] = '''I was born in 92000, and this is falsé.''' SCREAMING_SNAKE_CASE_ : Optional[Any] = tokenizer.tokenize(lowercase_) SCREAMING_SNAKE_CASE_ : str = rust_tokenizer.tokenize(lowercase_) self.assertListEqual(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = tokenizer.encode(lowercase_ , add_special_tokens=lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = rust_tokenizer.encode(lowercase_ , add_special_tokens=lowercase_) self.assertListEqual(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE_ : Optional[Any] = tokenizer.encode(lowercase_) SCREAMING_SNAKE_CASE_ : str = rust_tokenizer.encode(lowercase_) self.assertListEqual(lowercase_ , lowercase_) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = BigBirdTokenizer(lowercase_ , keep_accents=lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = tokenizer.tokenize('''This is a test''') self.assertListEqual(lowercase_ , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est''']) self.assertListEqual( tokenizer.convert_tokens_to_ids(lowercase_) , [285, 46, 10, 170, 382] , ) SCREAMING_SNAKE_CASE_ : Optional[int] = tokenizer.tokenize('''I was born in 92000, and this is falsé.''') self.assertListEqual( lowercase_ , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''é''', '''.''', ] , ) SCREAMING_SNAKE_CASE_ : Dict = tokenizer.convert_tokens_to_ids(lowercase_) self.assertListEqual( lowercase_ , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] , ) SCREAMING_SNAKE_CASE_ : Dict = tokenizer.convert_ids_to_tokens(lowercase_) self.assertListEqual( lowercase_ , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''<unk>''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''<unk>''', '''.''', ] , ) @cached_property def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' return BigBirdTokenizer.from_pretrained('''google/bigbird-roberta-base''') @slow def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = '''Hello World!''' SCREAMING_SNAKE_CASE_ : List[Any] = [65, 18536, 2260, 101, 66] self.assertListEqual(lowercase_ , self.big_tokenizer.encode(lowercase_)) @slow def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = ( '''This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will''' ''' add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth''' ) # fmt: off SCREAMING_SNAKE_CASE_ : List[str] = [65, 871, 419, 358, 946, 991, 2521, 452, 358, 1357, 387, 7751, 3536, 112, 985, 456, 126, 865, 938, 5400, 5734, 458, 1368, 467, 786, 2462, 5246, 1159, 633, 865, 4519, 457, 582, 852, 2557, 427, 916, 508, 405, 34324, 497, 391, 408, 11342, 1244, 385, 100, 938, 985, 456, 574, 362, 12597, 3200, 3129, 1172, 66] # noqa: E231 # fmt: on self.assertListEqual(lowercase_ , self.big_tokenizer.encode(lowercase_)) @require_torch @slow def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' import torch from transformers import BigBirdConfig, BigBirdModel # Build sequence SCREAMING_SNAKE_CASE_ : List[Any] = list(self.big_tokenizer.get_vocab().keys())[:10] SCREAMING_SNAKE_CASE_ : str = ''' '''.join(lowercase_) SCREAMING_SNAKE_CASE_ : str = self.big_tokenizer.encode_plus(lowercase_ , return_tensors='''pt''' , return_token_type_ids=lowercase_) SCREAMING_SNAKE_CASE_ : int = self.big_tokenizer.batch_encode_plus( [sequence + ''' ''' + sequence] , return_tensors='''pt''' , return_token_type_ids=lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = BigBirdConfig(attention_type='''original_full''') SCREAMING_SNAKE_CASE_ : int = BigBirdModel(lowercase_) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**lowercase_) model(**lowercase_) @slow def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = BigBirdTokenizer.from_pretrained('''google/bigbird-roberta-base''') SCREAMING_SNAKE_CASE_ : List[Any] = tokenizer.decode(tokenizer('''Paris is the [MASK].''').input_ids) self.assertTrue(decoded_text == '''[CLS] Paris is the[MASK].[SEP]''') @slow def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = {'''input_ids''': [[65, 39286, 458, 36335, 2001, 456, 13073, 13266, 455, 113, 7746, 1741, 11157, 391, 13073, 13266, 455, 113, 3967, 35412, 113, 4936, 109, 3870, 2377, 113, 30084, 45720, 458, 134, 17496, 112, 503, 11672, 113, 118, 112, 5665, 13347, 38687, 112, 1496, 31389, 112, 3268, 47264, 134, 962, 112, 16377, 8035, 23130, 430, 12169, 15518, 28592, 458, 146, 41697, 109, 391, 12169, 15518, 16689, 458, 146, 41358, 109, 452, 726, 4034, 111, 763, 35412, 5082, 388, 1903, 111, 9051, 391, 2870, 48918, 1900, 1123, 550, 998, 112, 9586, 15985, 455, 391, 410, 22955, 37636, 114, 66], [65, 448, 17496, 419, 3663, 385, 763, 113, 27533, 2870, 3283, 13043, 1639, 24713, 523, 656, 24013, 18550, 2521, 517, 27014, 21244, 420, 1212, 1465, 391, 927, 4833, 388, 578, 11786, 114, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [65, 484, 2169, 7687, 21932, 18146, 726, 363, 17032, 3391, 114, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=lowercase_ , model_name='''google/bigbird-roberta-base''' , revision='''215c99f1600e06f83acce68422f2035b2b5c3510''' , )
91
"""simple docstring""" import re import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class A__ ( _lowerCamelCase): A_ : Any = ['image_processor', 'tokenizer'] A_ : Optional[Any] = 'AutoImageProcessor' A_ : str = 'AutoTokenizer' def __init__( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Union[str, Any] = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , _SCREAMING_SNAKE_CASE , ) __lowerCAmelCase : Any = kwargs.pop('feature_extractor' ) __lowerCAmelCase : str = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.' ) if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.' ) super().__init__(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Any = self.image_processor __lowerCAmelCase : Tuple = False def __call__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = kwargs.pop('images' , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Any = kwargs.pop('text' , _SCREAMING_SNAKE_CASE ) if len(_SCREAMING_SNAKE_CASE ) > 0: __lowerCAmelCase : Dict = args[0] __lowerCAmelCase : Union[str, Any] = args[1:] if images is None and text is None: raise ValueError('You need to specify either an `images` or `text` input to process.' ) if images is not None: __lowerCAmelCase : Union[str, Any] = self.image_processor(_SCREAMING_SNAKE_CASE , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) if text is not None: __lowerCAmelCase : Dict = self.tokenizer(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) if text is None: return inputs elif images is None: return encodings else: __lowerCAmelCase : Union[str, Any] = encodings['input_ids'] return inputs def __lowerCamelCase ( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ): return self.tokenizer.batch_decode(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ): return self.tokenizer.decode(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @contextmanager def __lowerCamelCase ( self ): 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 images inputs, or in a separate call.' ) __lowerCAmelCase : Any = True __lowerCAmelCase : Dict = self.tokenizer yield __lowerCAmelCase : Optional[int] = self.image_processor __lowerCAmelCase : Optional[Any] = False def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=None ): if added_vocab is None: __lowerCAmelCase : str = self.tokenizer.get_added_vocab() __lowerCAmelCase : List[Any] = {} while tokens: __lowerCAmelCase : int = re.search(R'<s_(.*?)>' , _SCREAMING_SNAKE_CASE , re.IGNORECASE ) if start_token is None: break __lowerCAmelCase : Union[str, Any] = start_token.group(1 ) __lowerCAmelCase : Tuple = re.search(Rf"</s_{key}>" , _SCREAMING_SNAKE_CASE , re.IGNORECASE ) __lowerCAmelCase : str = start_token.group() if end_token is None: __lowerCAmelCase : Optional[int] = tokens.replace(_SCREAMING_SNAKE_CASE , '' ) else: __lowerCAmelCase : Optional[Any] = end_token.group() __lowerCAmelCase : Tuple = re.escape(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Tuple = re.escape(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = re.search(f"{start_token_escaped}(.*?){end_token_escaped}" , _SCREAMING_SNAKE_CASE , re.IGNORECASE ) if content is not None: __lowerCAmelCase : List[str] = content.group(1 ).strip() if r"<s_" in content and r"</s_" in content: # non-leaf node __lowerCAmelCase : int = self.tokenajson(_SCREAMING_SNAKE_CASE , is_inner_value=_SCREAMING_SNAKE_CASE , added_vocab=_SCREAMING_SNAKE_CASE ) if value: if len(_SCREAMING_SNAKE_CASE ) == 1: __lowerCAmelCase : Tuple = value[0] __lowerCAmelCase : Tuple = value else: # leaf nodes __lowerCAmelCase : Any = [] for leaf in content.split(R'<sep/>' ): __lowerCAmelCase : List[Any] = leaf.strip() if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>": __lowerCAmelCase : Dict = leaf[1:-2] # for categorical special tokens output[key].append(_SCREAMING_SNAKE_CASE ) if len(output[key] ) == 1: __lowerCAmelCase : str = output[key][0] __lowerCAmelCase : Dict = tokens[tokens.find(_SCREAMING_SNAKE_CASE ) + len(_SCREAMING_SNAKE_CASE ) :].strip() if tokens[:6] == r"<sep/>": # non-leaf nodes return [output] + self.tokenajson(tokens[6:] , is_inner_value=_SCREAMING_SNAKE_CASE , added_vocab=_SCREAMING_SNAKE_CASE ) if len(_SCREAMING_SNAKE_CASE ): return [output] if is_inner_value else output else: return [] if is_inner_value else {"text_sequence": tokens} @property def __lowerCamelCase ( self ): warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , _SCREAMING_SNAKE_CASE , ) return self.image_processor_class @property def __lowerCamelCase ( self ): warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , _SCREAMING_SNAKE_CASE , ) return self.image_processor
86
0
import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def _a ( ): __lowerCAmelCase = ArgumentParser( description=( "PyTorch TPU distributed training launch helper utility that will spawn up multiple distributed processes" ) ) # Optional arguments for the launch helper parser.add_argument("--num_cores" , type=SCREAMING_SNAKE_CASE_ , default=1 , help="Number of TPU cores to use (1 or 8)." ) # positional parser.add_argument( "training_script" , type=SCREAMING_SNAKE_CASE_ , help=( "The full path to the single TPU training " "program/script to be launched in parallel, " "followed by all the arguments for the " "training script" ) , ) # rest from the training program parser.add_argument("training_script_args" , nargs=SCREAMING_SNAKE_CASE_ ) return parser.parse_args() def _a ( ): __lowerCAmelCase = parse_args() # Import training_script as a module. __lowerCAmelCase = Path(args.training_script ) sys.path.append(str(script_fpath.parent.resolve() ) ) __lowerCAmelCase = script_fpath.stem __lowerCAmelCase = importlib.import_module(SCREAMING_SNAKE_CASE_ ) # Patch sys.argv __lowerCAmelCase = [args.training_script] + args.training_script_args + ["--tpu_num_cores", str(args.num_cores )] xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores ) if __name__ == "__main__": main()
92
"""simple docstring""" def __lowerCAmelCase (_UpperCamelCase ): __lowerCAmelCase : Tuple = 0 while num > 0: digit_sum += num % 10 num //= 10 return digit_sum def __lowerCAmelCase (_UpperCamelCase = 100 ): __lowerCAmelCase : Optional[int] = 1 __lowerCAmelCase : Optional[Any] = 2 for i in range(2 , max_n + 1 ): __lowerCAmelCase : Any = pre_numerator __lowerCAmelCase : Union[str, Any] = 2 * i // 3 if i % 3 == 0 else 1 __lowerCAmelCase : int = cur_numerator __lowerCAmelCase : Dict = e_cont * pre_numerator + temp return sum_digits(_UpperCamelCase ) if __name__ == "__main__": print(f'{solution() = }')
86
0
'''simple docstring''' _lowercase : Optional[int] = {"a": ["c", "b"], "b": ["d", "e"], "c": [], "d": [], "e": []} _lowercase : str = ["a", "b", "c", "d", "e"] def snake_case_ ( __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" lowercase_ : Optional[int] = start # add current to visited visited.append(__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = edges[current] for neighbor in neighbors: # if neighbor not in visited, visit if neighbor not in visited: lowercase_ : Dict = topological_sort(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # if all neighbors visited add current to sort sort.append(__SCREAMING_SNAKE_CASE ) # if all vertices haven't been visited select a new one to visit if len(__SCREAMING_SNAKE_CASE ) != len(__SCREAMING_SNAKE_CASE ): for vertice in vertices: if vertice not in visited: lowercase_ : List[Any] = topological_sort(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # return sort return sort if __name__ == "__main__": _lowercase : Dict = topological_sort("a", [], []) print(sort)
93
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { """microsoft/markuplm-base""": """https://huggingface.co/microsoft/markuplm-base/resolve/main/config.json""", """microsoft/markuplm-large""": """https://huggingface.co/microsoft/markuplm-large/resolve/main/config.json""", } class A__ ( _lowerCamelCase): A_ : List[Any] = 'markuplm' def __init__( self , _SCREAMING_SNAKE_CASE=3_05_22 , _SCREAMING_SNAKE_CASE=7_68 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=30_72 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=5_12 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE=1E-12 , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=2_56 , _SCREAMING_SNAKE_CASE=10_24 , _SCREAMING_SNAKE_CASE=2_16 , _SCREAMING_SNAKE_CASE=10_01 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=50 , _SCREAMING_SNAKE_CASE="absolute" , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE , ): super().__init__( pad_token_id=_SCREAMING_SNAKE_CASE , bos_token_id=_SCREAMING_SNAKE_CASE , eos_token_id=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) __lowerCAmelCase : Union[str, Any] = vocab_size __lowerCAmelCase : Any = hidden_size __lowerCAmelCase : List[Any] = num_hidden_layers __lowerCAmelCase : Tuple = num_attention_heads __lowerCAmelCase : Union[str, Any] = hidden_act __lowerCAmelCase : List[Any] = intermediate_size __lowerCAmelCase : List[str] = hidden_dropout_prob __lowerCAmelCase : List[str] = attention_probs_dropout_prob __lowerCAmelCase : Optional[int] = max_position_embeddings __lowerCAmelCase : int = type_vocab_size __lowerCAmelCase : Tuple = initializer_range __lowerCAmelCase : int = layer_norm_eps __lowerCAmelCase : List[str] = position_embedding_type __lowerCAmelCase : List[Any] = use_cache __lowerCAmelCase : Optional[Any] = classifier_dropout # additional properties __lowerCAmelCase : Optional[int] = max_depth __lowerCAmelCase : List[str] = max_xpath_tag_unit_embeddings __lowerCAmelCase : Optional[Any] = max_xpath_subs_unit_embeddings __lowerCAmelCase : Any = tag_pad_id __lowerCAmelCase : Union[str, Any] = subs_pad_id __lowerCAmelCase : int = xpath_unit_hidden_size
86
0
from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case : Tuple = logging.get_logger(__name__) snake_case : Dict = { '''transfo-xl-wt103''': '''https://huggingface.co/transfo-xl-wt103/resolve/main/config.json''', } class _snake_case ( _snake_case ): SCREAMING_SNAKE_CASE__ = 'transfo-xl' SCREAMING_SNAKE_CASE__ = ['mems'] SCREAMING_SNAKE_CASE__ = { 'n_token': 'vocab_size', 'hidden_size': 'd_model', 'num_attention_heads': 'n_head', 'num_hidden_layers': 'n_layer', } def __init__( self , _lowerCamelCase=26_7735 , _lowerCamelCase=[2_0000, 4_0000, 20_0000] , _lowerCamelCase=1024 , _lowerCamelCase=1024 , _lowerCamelCase=16 , _lowerCamelCase=64 , _lowerCamelCase=4096 , _lowerCamelCase=4 , _lowerCamelCase=False , _lowerCamelCase=18 , _lowerCamelCase=1600 , _lowerCamelCase=1000 , _lowerCamelCase=True , _lowerCamelCase=True , _lowerCamelCase=0 , _lowerCamelCase=-1 , _lowerCamelCase=True , _lowerCamelCase=0.1 , _lowerCamelCase=0.0 , _lowerCamelCase=True , _lowerCamelCase="normal" , _lowerCamelCase=0.01 , _lowerCamelCase=0.01 , _lowerCamelCase=0.02 , _lowerCamelCase=1e-5 , _lowerCamelCase=0 , **_lowerCamelCase , ): a :List[str] = vocab_size a :Union[str, Any] = [] self.cutoffs.extend(_lowerCamelCase ) if proj_share_all_but_first: a :Optional[int] = [False] + [True] * len(self.cutoffs ) else: a :Any = [False] + [False] * len(self.cutoffs ) a :Optional[int] = d_model a :Union[str, Any] = d_embed a :str = d_head a :Optional[Any] = d_inner a :Optional[Any] = div_val a :int = pre_lnorm a :Dict = n_layer a :List[Any] = n_head a :Any = mem_len a :Any = same_length a :str = attn_type a :Optional[Any] = clamp_len a :Optional[int] = sample_softmax a :Optional[int] = adaptive a :Optional[int] = dropout a :Tuple = dropatt a :Dict = untie_r a :List[Any] = init a :int = init_range a :Optional[int] = proj_init_std a :Optional[Any] = init_std a :Optional[Any] = layer_norm_epsilon super().__init__(eos_token_id=_lowerCamelCase , **_lowerCamelCase ) @property def SCREAMING_SNAKE_CASE__ ( self ): # Message copied from Transformer-XL documentation logger.info(F'''The model {self.model_type} is one of the few models that has no sequence length limit.''' ) return -1 @max_position_embeddings.setter def SCREAMING_SNAKE_CASE__ ( self , _lowerCamelCase ): # Message copied from Transformer-XL documentation raise NotImplementedError( F'''The model {self.model_type} is one of the few models that has no sequence length limit.''' )
94
"""simple docstring""" import argparse import torch # Step 1. clone https://github.com/microsoft/unilm # Step 2. git checkout to https://github.com/microsoft/unilm/commit/b94ec76c36f02fb2b0bf0dcb0b8554a2185173cd # Step 3. cd unilm # Step 4. ln -s $(realpath wavlm/modules.py) ./ # create simlink # import classes from unilm.wavlm.WavLM import WavLM as WavLMOrig from unilm.wavlm.WavLM import WavLMConfig as WavLMConfigOrig from transformers import WavLMConfig, WavLMModel, logging logging.set_verbosity_info() lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { """post_extract_proj""": """feature_projection.projection""", """encoder.pos_conv.0""": """encoder.pos_conv_embed.conv""", """self_attn.k_proj""": """encoder.layers.*.attention.k_proj""", """self_attn.v_proj""": """encoder.layers.*.attention.v_proj""", """self_attn.q_proj""": """encoder.layers.*.attention.q_proj""", """self_attn.out_proj""": """encoder.layers.*.attention.out_proj""", """self_attn.grep_linear""": """encoder.layers.*.attention.gru_rel_pos_linear""", """self_attn.relative_attention_bias""": """encoder.layers.*.attention.rel_attn_embed""", """self_attn.grep_a""": """encoder.layers.*.attention.gru_rel_pos_const""", """self_attn_layer_norm""": """encoder.layers.*.layer_norm""", """fc1""": """encoder.layers.*.feed_forward.intermediate_dense""", """fc2""": """encoder.layers.*.feed_forward.output_dense""", """final_layer_norm""": """encoder.layers.*.final_layer_norm""", """encoder.layer_norm""": """encoder.layer_norm""", """w2v_model.layer_norm""": """feature_projection.layer_norm""", """quantizer.weight_proj""": """quantizer.weight_proj""", """quantizer.vars""": """quantizer.codevectors""", """project_q""": """project_q""", """final_proj""": """project_hid""", """w2v_encoder.proj""": """ctc_proj""", """mask_emb""": """masked_spec_embed""", } lowerCamelCase__ = [ """ctc_proj""", """quantizer.weight_proj""", """quantizer.codevectors""", """project_q""", """project_hid""", ] def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): for attribute in key.split('.' ): __lowerCAmelCase : str = getattr(_UpperCamelCase , _UpperCamelCase ) if weight_type is not None: __lowerCAmelCase : Tuple = getattr(_UpperCamelCase , _UpperCamelCase ).shape else: __lowerCAmelCase : Dict = hf_pointer.shape assert hf_shape == value.shape, ( F"Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be" F" {value.shape} for {full_name}" ) if weight_type == "weight": __lowerCAmelCase : Union[str, Any] = value elif weight_type == "weight_g": __lowerCAmelCase : List[Any] = value elif weight_type == "weight_v": __lowerCAmelCase : Any = value elif weight_type == "bias": __lowerCAmelCase : List[str] = value else: __lowerCAmelCase : List[Any] = value logger.info(F"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}." ) def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase ): __lowerCAmelCase : Any = [] __lowerCAmelCase : Optional[int] = fairseq_model.state_dict() __lowerCAmelCase : Union[str, Any] = hf_model.feature_extractor for name, value in fairseq_dict.items(): __lowerCAmelCase : Union[str, Any] = False if "conv_layers" in name: load_conv_layer( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , hf_model.config.feat_extract_norm == 'group' , ) __lowerCAmelCase : str = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]: __lowerCAmelCase : int = True if "*" in mapped_key: __lowerCAmelCase : List[str] = name.split(_UpperCamelCase )[0].split('.' )[-2] __lowerCAmelCase : Optional[Any] = mapped_key.replace('*' , _UpperCamelCase ) if "weight_g" in name: __lowerCAmelCase : Union[str, Any] = 'weight_g' elif "weight_v" in name: __lowerCAmelCase : int = 'weight_v' elif "bias" in name and "relative_attention_bias" not in name: __lowerCAmelCase : Optional[Any] = 'bias' elif "weight" in name: # TODO: don't match quantizer.weight_proj __lowerCAmelCase : List[str] = 'weight' else: __lowerCAmelCase : Optional[Any] = None set_recursively(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) continue if not is_used: unused_weights.append(_UpperCamelCase ) logger.warning(F"Unused weights: {unused_weights}" ) def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): __lowerCAmelCase : List[Any] = full_name.split('conv_layers.' )[-1] __lowerCAmelCase : Any = name.split('.' ) __lowerCAmelCase : List[Any] = int(items[0] ) __lowerCAmelCase : Tuple = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( F"{full_name} has size {value.shape}, but" F" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found." ) __lowerCAmelCase : Tuple = value logger.info(F"Feat extract conv layer {layer_id} was initialized from {full_name}." ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( F"{full_name} has size {value.shape}, but" F" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found." ) __lowerCAmelCase : int = value logger.info(F"Feat extract conv layer {layer_id} was initialized from {full_name}." ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( F"{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was" " found." ) __lowerCAmelCase : Optional[Any] = value logger.info(F"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( F"{full_name} has size {value.shape}, but" F" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found." ) __lowerCAmelCase : Any = value logger.info(F"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) else: unused_weights.append(_UpperCamelCase ) @torch.no_grad() def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase=None ): # load the pre-trained checkpoints __lowerCAmelCase : Any = torch.load(_UpperCamelCase ) __lowerCAmelCase : List[str] = WavLMConfigOrig(checkpoint['cfg'] ) __lowerCAmelCase : Optional[Any] = WavLMOrig(_UpperCamelCase ) model.load_state_dict(checkpoint['model'] ) model.eval() if config_path is not None: __lowerCAmelCase : Dict = WavLMConfig.from_pretrained(_UpperCamelCase ) else: __lowerCAmelCase : List[str] = WavLMConfig() __lowerCAmelCase : List[str] = WavLMModel(_UpperCamelCase ) recursively_load_weights(_UpperCamelCase , _UpperCamelCase ) hf_wavlm.save_pretrained(_UpperCamelCase ) if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to fairseq checkpoint""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") lowerCamelCase__ = parser.parse_args() convert_wavlm_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
86
0
import numpy as np def _A ( SCREAMING_SNAKE_CASE : np.array ): """simple docstring""" return 1 / (1 + np.exp(-vector )) if __name__ == "__main__": import doctest doctest.testmod()
95
"""simple docstring""" import os import pytest from attr import dataclass lowerCamelCase__ = """us-east-1""" # defaults region @dataclass class A__ : A_ : str A_ : Union[str, Any] = 'arn:aws:iam::558105141721:role/sagemaker_execution_role' A_ : Optional[int] = { 'task_name': 'mnli', 'per_device_train_batch_size': 1_6, 'per_device_eval_batch_size': 1_6, 'do_train': True, 'do_eval': True, 'do_predict': True, 'output_dir': '/opt/ml/model', 'overwrite_output_dir': True, 'max_steps': 5_0_0, 'save_steps': 5_5_0_0, } A_ : List[Any] = {**hyperparameters, 'max_steps': 1_0_0_0} @property def __lowerCamelCase ( self ): if self.framework == "pytorch": return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"eval_accuracy.*=\D*(.*?)$"}, {"Name": "eval_loss", "Regex": r"eval_loss.*=\D*(.*?)$"}, ] else: return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"loss.*=\D*(.*?)]?$"}, {"Name": "eval_loss", "Regex": r"sparse_categorical_accuracy.*=\D*(.*?)]?$"}, ] @property def __lowerCamelCase ( self ): return f"{self.framework}-transfromers-test" @property def __lowerCamelCase ( self ): return f"./tests/sagemaker/scripts/{self.framework}" @property def __lowerCamelCase ( self ): if self.framework == "pytorch": return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-pytorch-training:1.7.1-transformers4.6.1-gpu-py36-cu110-ubuntu18.04" else: return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-tensorflow-training:2.4.1-transformers4.6.1-gpu-py37-cu110-ubuntu18.04" @pytest.fixture(scope='class' ) def __lowerCAmelCase (_UpperCamelCase ): __lowerCAmelCase : str = SageMakerTestEnvironment(framework=request.cls.framework )
86
0
"""simple docstring""" import math def _snake_case ( lowercase__ ): if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(lowercase__ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def _snake_case ( lowercase__ = 0.1 ): _lowerCamelCase : Tuple = 3 _lowerCamelCase : Optional[int] = 3 while primes / (2 * j - 1) >= ratio: for i in range(j * j + j + 1 , (j + 2) * (j + 2) , j + 1 ): primes += is_prime(lowercase__ ) j += 2 return j if __name__ == "__main__": import doctest doctest.testmod()
96
"""simple docstring""" from __future__ import annotations lowerCamelCase__ = list[tuple[int, int]] lowerCamelCase__ = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] lowerCamelCase__ = ([-1, 0], [0, -1], [1, 0], [0, 1]) # up, left, down, right class A__ : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , ): __lowerCAmelCase : int = pos_x __lowerCAmelCase : Optional[Any] = pos_y __lowerCAmelCase : Optional[int] = (pos_y, pos_x) __lowerCAmelCase : Union[str, Any] = goal_x __lowerCAmelCase : Any = goal_y __lowerCAmelCase : Optional[Any] = g_cost __lowerCAmelCase : Any = parent __lowerCAmelCase : Union[str, Any] = self.calculate_heuristic() def __lowerCamelCase ( self ): __lowerCAmelCase : str = abs(self.pos_x - self.goal_x ) __lowerCAmelCase : str = abs(self.pos_y - self.goal_y ) return dx + dy def __lt__( self , _SCREAMING_SNAKE_CASE ): return self.f_cost < other.f_cost class A__ : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Optional[int] = Node(start[1] , start[0] , goal[1] , goal[0] , 0 , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Any = Node(goal[1] , goal[0] , goal[1] , goal[0] , 9_99_99 , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Tuple = [self.start] __lowerCAmelCase : list[Node] = [] __lowerCAmelCase : str = False def __lowerCamelCase ( self ): while self.open_nodes: # Open Nodes are sorted using __lt__ self.open_nodes.sort() __lowerCAmelCase : Optional[int] = self.open_nodes.pop(0 ) if current_node.pos == self.target.pos: __lowerCAmelCase : Union[str, Any] = True return self.retrace_path(_SCREAMING_SNAKE_CASE ) self.closed_nodes.append(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = self.get_successors(_SCREAMING_SNAKE_CASE ) for child_node in successors: if child_node in self.closed_nodes: continue if child_node not in self.open_nodes: self.open_nodes.append(_SCREAMING_SNAKE_CASE ) else: # retrieve the best current path __lowerCAmelCase : Optional[Any] = self.open_nodes.pop(self.open_nodes.index(_SCREAMING_SNAKE_CASE ) ) if child_node.g_cost < better_node.g_cost: self.open_nodes.append(_SCREAMING_SNAKE_CASE ) else: self.open_nodes.append(_SCREAMING_SNAKE_CASE ) if not self.reached: return [self.start.pos] return None def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Dict = [] for action in delta: __lowerCAmelCase : Optional[int] = parent.pos_x + action[1] __lowerCAmelCase : Union[str, Any] = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(_SCREAMING_SNAKE_CASE ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , self.target.pos_y , self.target.pos_x , parent.g_cost + 1 , _SCREAMING_SNAKE_CASE , ) ) return successors def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Union[str, Any] = node __lowerCAmelCase : Optional[int] = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) __lowerCAmelCase : int = current_node.parent path.reverse() return path if __name__ == "__main__": lowerCamelCase__ = (0, 0) lowerCamelCase__ = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) print("""------""") lowerCamelCase__ = GreedyBestFirst(init, goal) lowerCamelCase__ = greedy_bf.search() if path: for pos_x, pos_y in path: lowerCamelCase__ = 2 for elem in grid: print(elem)
86
0
'''simple docstring''' from __future__ import annotations from fractions import Fraction from math import gcd, sqrt def a ( __a ) -> bool: '''simple docstring''' UpperCamelCase__ :int = int(number**0.5 ) return number == sq * sq def a ( __a , __a , __a , __a , __a , __a ) -> tuple[int, int]: '''simple docstring''' UpperCamelCase__ :int = x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den UpperCamelCase__ :int = x_den * y_den * z_den UpperCamelCase__ :int = gcd(__a , __a ) top //= hcf bottom //= hcf return top, bottom def a ( __a = 35 ) -> int: '''simple docstring''' UpperCamelCase__ :set = set() UpperCamelCase__ :int UpperCamelCase__ :Fraction = Fraction(0 ) UpperCamelCase__ :tuple[int, int] for x_num in range(1 , order + 1 ): for x_den in range(x_num + 1 , order + 1 ): for y_num in range(1 , order + 1 ): for y_den in range(y_num + 1 , order + 1 ): # n=1 UpperCamelCase__ :int = x_num * y_den + x_den * y_num UpperCamelCase__ :Any = x_den * y_den UpperCamelCase__ :Tuple = gcd(__a , __a ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: UpperCamelCase__ :Tuple = add_three( __a , __a , __a , __a , __a , __a ) unique_s.add(__a ) # n=2 UpperCamelCase__ :List[str] = ( x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num ) UpperCamelCase__ :Dict = x_den * x_den * y_den * y_den if is_sq(__a ) and is_sq(__a ): UpperCamelCase__ :Any = int(sqrt(__a ) ) UpperCamelCase__ :Optional[int] = int(sqrt(__a ) ) UpperCamelCase__ :int = gcd(__a , __a ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: UpperCamelCase__ :Tuple = add_three( __a , __a , __a , __a , __a , __a ) unique_s.add(__a ) # n=-1 UpperCamelCase__ :Tuple = x_num * y_num UpperCamelCase__ :Union[str, Any] = x_den * y_num + x_num * y_den UpperCamelCase__ :List[str] = gcd(__a , __a ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: UpperCamelCase__ :Union[str, Any] = add_three( __a , __a , __a , __a , __a , __a ) unique_s.add(__a ) # n=2 UpperCamelCase__ :Optional[Any] = x_num * x_num * y_num * y_num UpperCamelCase__ :Tuple = ( x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den ) if is_sq(__a ) and is_sq(__a ): UpperCamelCase__ :str = int(sqrt(__a ) ) UpperCamelCase__ :Any = int(sqrt(__a ) ) UpperCamelCase__ :Dict = gcd(__a , __a ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: UpperCamelCase__ :int = add_three( __a , __a , __a , __a , __a , __a ) unique_s.add(__a ) for num, den in unique_s: total += Fraction(__a , __a ) return total.denominator + total.numerator if __name__ == "__main__": print(F"""{solution() = }""")
97
"""simple docstring""" def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): return round(float(moles / volume ) * nfactor ) def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): return round(float((moles * 0.0821 * temperature) / (volume) ) ) def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): return round(float((moles * 0.0821 * temperature) / (pressure) ) ) def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): return round(float((pressure * volume) / (0.0821 * moles) ) ) if __name__ == "__main__": import doctest doctest.testmod()
86
0
"""simple docstring""" from typing import Dict, Iterable, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format, to_pil_image from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_pytesseract_available, is_vision_available, logging, requires_backends if is_vision_available(): import PIL # soft dependency if is_pytesseract_available(): import pytesseract lowerCAmelCase__ : Union[str, Any] = logging.get_logger(__name__) def a_ ( lowerCamelCase , lowerCamelCase , lowerCamelCase ): return [ int(1_0_0_0 * (box[0] / width) ), int(1_0_0_0 * (box[1] / height) ), int(1_0_0_0 * (box[2] / width) ), int(1_0_0_0 * (box[3] / height) ), ] def a_ ( lowerCamelCase , lowerCamelCase , lowerCamelCase ): UpperCAmelCase__ = to_pil_image(lowerCamelCase ) UpperCAmelCase__ , UpperCAmelCase__ = pil_image.size UpperCAmelCase__ = pytesseract.image_to_data(lowerCamelCase , lang=lowerCamelCase , output_type='dict' , config=lowerCamelCase ) UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ = data['text'], data['left'], data['top'], data['width'], data['height'] # filter empty words and corresponding coordinates UpperCAmelCase__ = [idx for idx, word in enumerate(lowerCamelCase ) if not word.strip()] UpperCAmelCase__ = [word for idx, word in enumerate(lowerCamelCase ) if idx not in irrelevant_indices] UpperCAmelCase__ = [coord for idx, coord in enumerate(lowerCamelCase ) if idx not in irrelevant_indices] UpperCAmelCase__ = [coord for idx, coord in enumerate(lowerCamelCase ) if idx not in irrelevant_indices] UpperCAmelCase__ = [coord for idx, coord in enumerate(lowerCamelCase ) if idx not in irrelevant_indices] UpperCAmelCase__ = [coord for idx, coord in enumerate(lowerCamelCase ) if idx not in irrelevant_indices] # turn coordinates into (left, top, left+width, top+height) format UpperCAmelCase__ = [] for x, y, w, h in zip(lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ): UpperCAmelCase__ = [x, y, x + w, y + h] actual_boxes.append(lowerCamelCase ) # finally, normalize the bounding boxes UpperCAmelCase__ = [] for box in actual_boxes: normalized_boxes.append(normalize_box(lowerCamelCase , lowerCamelCase , lowerCamelCase ) ) assert len(lowerCamelCase ) == len(lowerCamelCase ), "Not as many words as there are bounding boxes" return words, normalized_boxes class snake_case ( __UpperCAmelCase ): """simple docstring""" snake_case__ = ["pixel_values"] def __init__( self : int ,lowerCamelCase__ : bool = True ,lowerCamelCase__ : Dict[str, int] = None ,lowerCamelCase__ : PILImageResampling = PILImageResampling.BILINEAR ,lowerCamelCase__ : bool = True ,lowerCamelCase__ : float = 1 / 255 ,lowerCamelCase__ : bool = True ,lowerCamelCase__ : Union[float, Iterable[float]] = None ,lowerCamelCase__ : Union[float, Iterable[float]] = None ,lowerCamelCase__ : bool = True ,lowerCamelCase__ : Optional[str] = None ,lowerCamelCase__ : Optional[str] = "" ,**lowerCamelCase__ : Any ,): super().__init__(**lowerCamelCase__ ) UpperCAmelCase__ = size if size is not None else {'height': 224, 'width': 224} UpperCAmelCase__ = get_size_dict(lowerCamelCase__ ) UpperCAmelCase__ = do_resize UpperCAmelCase__ = size UpperCAmelCase__ = resample UpperCAmelCase__ = do_rescale UpperCAmelCase__ = rescale_value UpperCAmelCase__ = do_normalize UpperCAmelCase__ = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN UpperCAmelCase__ = image_std if image_std is not None else IMAGENET_STANDARD_STD UpperCAmelCase__ = apply_ocr UpperCAmelCase__ = ocr_lang UpperCAmelCase__ = tesseract_config def __lowerCAmelCase ( self : List[str] ,lowerCamelCase__ : np.ndarray ,lowerCamelCase__ : Dict[str, int] ,lowerCamelCase__ : PILImageResampling = PILImageResampling.BILINEAR ,lowerCamelCase__ : Optional[Union[str, ChannelDimension]] = None ,**lowerCamelCase__ : str ,): UpperCAmelCase__ = get_size_dict(lowerCamelCase__ ) if "height" not in size or "width" not in size: raise ValueError(f'''The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}''' ) UpperCAmelCase__ = (size['height'], size['width']) return resize(lowerCamelCase__ ,size=lowerCamelCase__ ,resample=lowerCamelCase__ ,data_format=lowerCamelCase__ ,**lowerCamelCase__ ) def __lowerCAmelCase ( self : str ,lowerCamelCase__ : np.ndarray ,lowerCamelCase__ : Union[int, float] ,lowerCamelCase__ : Optional[Union[str, ChannelDimension]] = None ,**lowerCamelCase__ : Dict ,): return rescale(lowerCamelCase__ ,scale=lowerCamelCase__ ,data_format=lowerCamelCase__ ,**lowerCamelCase__ ) def __lowerCAmelCase ( self : Dict ,lowerCamelCase__ : np.ndarray ,lowerCamelCase__ : Union[float, Iterable[float]] ,lowerCamelCase__ : Union[float, Iterable[float]] ,lowerCamelCase__ : Optional[Union[str, ChannelDimension]] = None ,**lowerCamelCase__ : Optional[int] ,): return normalize(lowerCamelCase__ ,mean=lowerCamelCase__ ,std=lowerCamelCase__ ,data_format=lowerCamelCase__ ,**lowerCamelCase__ ) def __lowerCAmelCase ( self : List[Any] ,lowerCamelCase__ : ImageInput ,lowerCamelCase__ : bool = None ,lowerCamelCase__ : Dict[str, int] = None ,lowerCamelCase__ : Union[str, Any]=None ,lowerCamelCase__ : bool = None ,lowerCamelCase__ : float = None ,lowerCamelCase__ : bool = None ,lowerCamelCase__ : Union[float, Iterable[float]] = None ,lowerCamelCase__ : Union[float, Iterable[float]] = None ,lowerCamelCase__ : bool = None ,lowerCamelCase__ : Optional[str] = None ,lowerCamelCase__ : Optional[str] = None ,lowerCamelCase__ : Optional[Union[str, TensorType]] = None ,lowerCamelCase__ : ChannelDimension = ChannelDimension.FIRST ,**lowerCamelCase__ : str ,): UpperCAmelCase__ = do_resize if do_resize is not None else self.do_resize UpperCAmelCase__ = size if size is not None else self.size UpperCAmelCase__ = get_size_dict(lowerCamelCase__ ) UpperCAmelCase__ = resample if resample is not None else self.resample UpperCAmelCase__ = do_rescale if do_rescale is not None else self.do_rescale UpperCAmelCase__ = rescale_factor if rescale_factor is not None else self.rescale_factor UpperCAmelCase__ = do_normalize if do_normalize is not None else self.do_normalize UpperCAmelCase__ = image_mean if image_mean is not None else self.image_mean UpperCAmelCase__ = image_std if image_std is not None else self.image_std UpperCAmelCase__ = apply_ocr if apply_ocr is not None else self.apply_ocr UpperCAmelCase__ = ocr_lang if ocr_lang is not None else self.ocr_lang UpperCAmelCase__ = tesseract_config if tesseract_config is not None else self.tesseract_config UpperCAmelCase__ = make_list_of_images(lowerCamelCase__ ) if not valid_images(lowerCamelCase__ ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None: raise ValueError('Size must be specified if do_resize is True.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('If do_normalize is True, image_mean and image_std must be specified.' ) # All transformations expect numpy arrays. UpperCAmelCase__ = [to_numpy_array(lowerCamelCase__ ) for image in images] # Tesseract OCR to get words + normalized bounding boxes if apply_ocr: requires_backends(self ,'pytesseract' ) UpperCAmelCase__ = [] UpperCAmelCase__ = [] for image in images: UpperCAmelCase__ , UpperCAmelCase__ = apply_tesseract(lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ) words_batch.append(lowerCamelCase__ ) boxes_batch.append(lowerCamelCase__ ) if do_resize: UpperCAmelCase__ = [self.resize(image=lowerCamelCase__ ,size=lowerCamelCase__ ,resample=lowerCamelCase__ ) for image in images] if do_rescale: UpperCAmelCase__ = [self.rescale(image=lowerCamelCase__ ,scale=lowerCamelCase__ ) for image in images] if do_normalize: UpperCAmelCase__ = [self.normalize(image=lowerCamelCase__ ,mean=lowerCamelCase__ ,std=lowerCamelCase__ ) for image in images] UpperCAmelCase__ = [to_channel_dimension_format(lowerCamelCase__ ,lowerCamelCase__ ) for image in images] UpperCAmelCase__ = BatchFeature(data={'pixel_values': images} ,tensor_type=lowerCamelCase__ ) if apply_ocr: UpperCAmelCase__ = words_batch UpperCAmelCase__ = boxes_batch return data
98
"""simple docstring""" import enum import warnings from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING from ..utils import add_end_docstrings, is_tf_available from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf class A__ ( enum.Enum): A_ : List[Any] = 0 A_ : Dict = 1 A_ : Union[str, Any] = 2 @add_end_docstrings(_lowerCamelCase) class A__ ( _lowerCamelCase): A_ : str = '\n In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The\n voice of Nicholas\'s young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western\n Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision\n and denounces one of the men as a horse thief. Although his father initially slaps him for making such an\n accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of\n the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop,\n begging for his blessing. <eod> </s> <eos>\n ' def __init__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ): super().__init__(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) self.check_model_type( TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == 'tf' else MODEL_FOR_CAUSAL_LM_MAPPING ) if "prefix" not in self._preprocess_params: # This is very specific. The logic is quite complex and needs to be done # as a "default". # It also defines both some preprocess_kwargs and generate_kwargs # which is why we cannot put them in their respective methods. __lowerCAmelCase : Any = None if self.model.config.prefix is not None: __lowerCAmelCase : str = self.model.config.prefix if prefix is None and self.model.__class__.__name__ in [ "XLNetLMHeadModel", "TransfoXLLMHeadModel", "TFXLNetLMHeadModel", "TFTransfoXLLMHeadModel", ]: # For XLNet and TransformerXL we add an article to the prompt to give more state to the model. __lowerCAmelCase : Tuple = self.XL_PREFIX if prefix is not None: # Recalculate some generate_kwargs linked to prefix. __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase : Union[str, Any] = self._sanitize_parameters(prefix=_SCREAMING_SNAKE_CASE , **self._forward_params ) __lowerCAmelCase : List[str] = {**self._preprocess_params, **preprocess_params} __lowerCAmelCase : List[str] = {**self._forward_params, **forward_params} def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE , ): __lowerCAmelCase : Optional[int] = {} if prefix is not None: __lowerCAmelCase : Union[str, Any] = prefix if prefix: __lowerCAmelCase : Dict = self.tokenizer( _SCREAMING_SNAKE_CASE , padding=_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE , return_tensors=self.framework ) __lowerCAmelCase : List[Any] = prefix_inputs['input_ids'].shape[-1] if handle_long_generation is not None: if handle_long_generation not in {"hole"}: raise ValueError( f"{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected" ' [None, \'hole\']' ) __lowerCAmelCase : int = handle_long_generation preprocess_params.update(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : int = generate_kwargs __lowerCAmelCase : List[Any] = {} if return_full_text is not None and return_type is None: if return_text is not None: raise ValueError('`return_text` is mutually exclusive with `return_full_text`' ) if return_tensors is not None: raise ValueError('`return_full_text` is mutually exclusive with `return_tensors`' ) __lowerCAmelCase : Optional[Any] = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT if return_tensors is not None and return_type is None: if return_text is not None: raise ValueError('`return_text` is mutually exclusive with `return_tensors`' ) __lowerCAmelCase : List[Any] = ReturnType.TENSORS if return_type is not None: __lowerCAmelCase : Optional[Any] = return_type if clean_up_tokenization_spaces is not None: __lowerCAmelCase : Tuple = clean_up_tokenization_spaces if stop_sequence is not None: __lowerCAmelCase : Union[str, Any] = self.tokenizer.encode(_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE ) if len(_SCREAMING_SNAKE_CASE ) > 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.' ) __lowerCAmelCase : Optional[Any] = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def __lowerCamelCase ( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ): # Parse arguments if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]: kwargs.update({'add_space_before_punct_symbol': True} ) return super()._parse_and_tokenize(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def __call__( self , _SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ): return super().__call__(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE="" , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Any = self.tokenizer( prefix + prompt_text , padding=_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE , return_tensors=self.framework ) __lowerCAmelCase : Optional[Any] = prompt_text if handle_long_generation == "hole": __lowerCAmelCase : str = inputs['input_ids'].shape[-1] if "max_new_tokens" in generate_kwargs: __lowerCAmelCase : Union[str, Any] = generate_kwargs['max_new_tokens'] else: __lowerCAmelCase : Any = generate_kwargs.get('max_length' , self.model.config.max_length ) - cur_len if new_tokens < 0: raise ValueError('We cannot infer how many new tokens are expected' ) if cur_len + new_tokens > self.tokenizer.model_max_length: __lowerCAmelCase : Any = self.tokenizer.model_max_length - new_tokens if keep_length <= 0: raise ValueError( 'We cannot use `hole` to handle this generation the number of desired tokens exceeds the' ' models max length' ) __lowerCAmelCase : int = inputs['input_ids'][:, -keep_length:] if "attention_mask" in inputs: __lowerCAmelCase : List[Any] = inputs['attention_mask'][:, -keep_length:] return inputs def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ): __lowerCAmelCase : str = model_inputs['input_ids'] __lowerCAmelCase : List[Any] = model_inputs.get('attention_mask' , _SCREAMING_SNAKE_CASE ) # Allow empty prompts if input_ids.shape[1] == 0: __lowerCAmelCase : Dict = None __lowerCAmelCase : str = None __lowerCAmelCase : Tuple = 1 else: __lowerCAmelCase : Any = input_ids.shape[0] __lowerCAmelCase : Union[str, Any] = model_inputs.pop('prompt_text' ) # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline. __lowerCAmelCase : Optional[int] = generate_kwargs.pop('prefix_length' , 0 ) if prefix_length > 0: __lowerCAmelCase : Any = 'max_new_tokens' in generate_kwargs or ( 'generation_config' in generate_kwargs and generate_kwargs['generation_config'].max_new_tokens is not None ) if not has_max_new_tokens: __lowerCAmelCase : List[str] = generate_kwargs.get('max_length' ) or self.model.config.max_length generate_kwargs["max_length"] += prefix_length __lowerCAmelCase : Dict = 'min_new_tokens' in generate_kwargs or ( 'generation_config' in generate_kwargs and generate_kwargs['generation_config'].min_new_tokens is not None ) if not has_min_new_tokens and "min_length" in generate_kwargs: generate_kwargs["min_length"] += prefix_length # BS x SL __lowerCAmelCase : Optional[int] = self.model.generate(input_ids=_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = generated_sequence.shape[0] if self.framework == "pt": __lowerCAmelCase : Dict = generated_sequence.reshape(_SCREAMING_SNAKE_CASE , out_b // in_b , *generated_sequence.shape[1:] ) elif self.framework == "tf": __lowerCAmelCase : Any = tf.reshape(_SCREAMING_SNAKE_CASE , (in_b, out_b // in_b, *generated_sequence.shape[1:]) ) return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text} def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=ReturnType.FULL_TEXT , _SCREAMING_SNAKE_CASE=True ): __lowerCAmelCase : Any = model_outputs['generated_sequence'][0] __lowerCAmelCase : Tuple = model_outputs['input_ids'] __lowerCAmelCase : Any = model_outputs['prompt_text'] __lowerCAmelCase : int = generated_sequence.numpy().tolist() __lowerCAmelCase : Union[str, Any] = [] for sequence in generated_sequence: if return_type == ReturnType.TENSORS: __lowerCAmelCase : int = {'generated_token_ids': sequence} elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}: # Decode text __lowerCAmelCase : Any = self.tokenizer.decode( _SCREAMING_SNAKE_CASE , skip_special_tokens=_SCREAMING_SNAKE_CASE , clean_up_tokenization_spaces=_SCREAMING_SNAKE_CASE , ) # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used if input_ids is None: __lowerCAmelCase : Optional[Any] = 0 else: __lowerCAmelCase : Any = len( self.tokenizer.decode( input_ids[0] , skip_special_tokens=_SCREAMING_SNAKE_CASE , clean_up_tokenization_spaces=_SCREAMING_SNAKE_CASE , ) ) if return_type == ReturnType.FULL_TEXT: __lowerCAmelCase : Union[str, Any] = prompt_text + text[prompt_length:] else: __lowerCAmelCase : int = text[prompt_length:] __lowerCAmelCase : Dict = {'generated_text': all_text} records.append(_SCREAMING_SNAKE_CASE ) return records
86
0
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_nllb import NllbTokenizer else: lowercase : str = None lowercase : Optional[Any] = logging.get_logger(__name__) lowercase : List[Any] = {"""vocab_file""": """sentencepiece.bpe.model""", """tokenizer_file""": """tokenizer.json"""} lowercase : List[Any] = { """vocab_file""": { """facebook/nllb-200-distilled-600M""": ( """https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/sentencepiece.bpe.model""" ), }, """tokenizer_file""": { """facebook/nllb-200-distilled-600M""": ( """https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/tokenizer.json""" ), }, } lowercase : List[Any] = { """facebook/nllb-large-en-ro""": 1_0_2_4, """facebook/nllb-200-distilled-600M""": 1_0_2_4, } # fmt: off lowercase : Tuple = ["""ace_Arab""", """ace_Latn""", """acm_Arab""", """acq_Arab""", """aeb_Arab""", """afr_Latn""", """ajp_Arab""", """aka_Latn""", """amh_Ethi""", """apc_Arab""", """arb_Arab""", """ars_Arab""", """ary_Arab""", """arz_Arab""", """asm_Beng""", """ast_Latn""", """awa_Deva""", """ayr_Latn""", """azb_Arab""", """azj_Latn""", """bak_Cyrl""", """bam_Latn""", """ban_Latn""", """bel_Cyrl""", """bem_Latn""", """ben_Beng""", """bho_Deva""", """bjn_Arab""", """bjn_Latn""", """bod_Tibt""", """bos_Latn""", """bug_Latn""", """bul_Cyrl""", """cat_Latn""", """ceb_Latn""", """ces_Latn""", """cjk_Latn""", """ckb_Arab""", """crh_Latn""", """cym_Latn""", """dan_Latn""", """deu_Latn""", """dik_Latn""", """dyu_Latn""", """dzo_Tibt""", """ell_Grek""", """eng_Latn""", """epo_Latn""", """est_Latn""", """eus_Latn""", """ewe_Latn""", """fao_Latn""", """pes_Arab""", """fij_Latn""", """fin_Latn""", """fon_Latn""", """fra_Latn""", """fur_Latn""", """fuv_Latn""", """gla_Latn""", """gle_Latn""", """glg_Latn""", """grn_Latn""", """guj_Gujr""", """hat_Latn""", """hau_Latn""", """heb_Hebr""", """hin_Deva""", """hne_Deva""", """hrv_Latn""", """hun_Latn""", """hye_Armn""", """ibo_Latn""", """ilo_Latn""", """ind_Latn""", """isl_Latn""", """ita_Latn""", """jav_Latn""", """jpn_Jpan""", """kab_Latn""", """kac_Latn""", """kam_Latn""", """kan_Knda""", """kas_Arab""", """kas_Deva""", """kat_Geor""", """knc_Arab""", """knc_Latn""", """kaz_Cyrl""", """kbp_Latn""", """kea_Latn""", """khm_Khmr""", """kik_Latn""", """kin_Latn""", """kir_Cyrl""", """kmb_Latn""", """kon_Latn""", """kor_Hang""", """kmr_Latn""", """lao_Laoo""", """lvs_Latn""", """lij_Latn""", """lim_Latn""", """lin_Latn""", """lit_Latn""", """lmo_Latn""", """ltg_Latn""", """ltz_Latn""", """lua_Latn""", """lug_Latn""", """luo_Latn""", """lus_Latn""", """mag_Deva""", """mai_Deva""", """mal_Mlym""", """mar_Deva""", """min_Latn""", """mkd_Cyrl""", """plt_Latn""", """mlt_Latn""", """mni_Beng""", """khk_Cyrl""", """mos_Latn""", """mri_Latn""", """zsm_Latn""", """mya_Mymr""", """nld_Latn""", """nno_Latn""", """nob_Latn""", """npi_Deva""", """nso_Latn""", """nus_Latn""", """nya_Latn""", """oci_Latn""", """gaz_Latn""", """ory_Orya""", """pag_Latn""", """pan_Guru""", """pap_Latn""", """pol_Latn""", """por_Latn""", """prs_Arab""", """pbt_Arab""", """quy_Latn""", """ron_Latn""", """run_Latn""", """rus_Cyrl""", """sag_Latn""", """san_Deva""", """sat_Beng""", """scn_Latn""", """shn_Mymr""", """sin_Sinh""", """slk_Latn""", """slv_Latn""", """smo_Latn""", """sna_Latn""", """snd_Arab""", """som_Latn""", """sot_Latn""", """spa_Latn""", """als_Latn""", """srd_Latn""", """srp_Cyrl""", """ssw_Latn""", """sun_Latn""", """swe_Latn""", """swh_Latn""", """szl_Latn""", """tam_Taml""", """tat_Cyrl""", """tel_Telu""", """tgk_Cyrl""", """tgl_Latn""", """tha_Thai""", """tir_Ethi""", """taq_Latn""", """taq_Tfng""", """tpi_Latn""", """tsn_Latn""", """tso_Latn""", """tuk_Latn""", """tum_Latn""", """tur_Latn""", """twi_Latn""", """tzm_Tfng""", """uig_Arab""", """ukr_Cyrl""", """umb_Latn""", """urd_Arab""", """uzn_Latn""", """vec_Latn""", """vie_Latn""", """war_Latn""", """wol_Latn""", """xho_Latn""", """ydd_Hebr""", """yor_Latn""", """yue_Hant""", """zho_Hans""", """zho_Hant""", """zul_Latn"""] class A__ ( __UpperCAmelCase ): """simple docstring""" __A : List[Any] = VOCAB_FILES_NAMES __A : int = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __A : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP __A : List[str] = ['''input_ids''', '''attention_mask'''] __A : int = NllbTokenizer __A : List[int] = [] __A : List[int] = [] def __init__( self , lowercase=None , lowercase=None , lowercase="<s>" , lowercase="</s>" , lowercase="</s>" , lowercase="<s>" , lowercase="<unk>" , lowercase="<pad>" , lowercase="<mask>" , lowercase=None , lowercase=None , lowercase=None , lowercase=False , **lowercase , ) -> Union[str, Any]: '''simple docstring''' a__ : Optional[Any] = AddedToken(lowercase , lstrip=lowercase , rstrip=lowercase) if isinstance(lowercase , lowercase) else mask_token a__ : str = legacy_behaviour super().__init__( vocab_file=lowercase , tokenizer_file=lowercase , bos_token=lowercase , eos_token=lowercase , sep_token=lowercase , cls_token=lowercase , unk_token=lowercase , pad_token=lowercase , mask_token=lowercase , src_lang=lowercase , tgt_lang=lowercase , additional_special_tokens=lowercase , legacy_behaviour=lowercase , **lowercase , ) a__ : Optional[int] = vocab_file a__ : str = False if not self.vocab_file else True a__ : List[Any] = 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}) a__ : Any = { lang_code: self.convert_tokens_to_ids(lowercase) for lang_code in FAIRSEQ_LANGUAGE_CODES } a__ : str = src_lang if src_lang is not None else 'eng_Latn' a__ : int = self.convert_tokens_to_ids(self._src_lang) a__ : Any = tgt_lang self.set_src_lang_special_tokens(self._src_lang) @property def __lowercase ( self) -> str: '''simple docstring''' return self._src_lang @src_lang.setter def __lowercase ( self , lowercase) -> None: '''simple docstring''' a__ : Tuple = new_src_lang self.set_src_lang_special_tokens(self._src_lang) def __lowercase ( self , lowercase , lowercase = None) -> List[int]: '''simple docstring''' 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 __lowercase ( self , lowercase , lowercase = None) -> List[int]: '''simple docstring''' a__ : Optional[int] = [self.sep_token_id] a__ : Optional[Any] = [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 __lowercase ( self , lowercase , lowercase , lowercase , lowercase , **lowercase) -> str: '''simple docstring''' if src_lang is None or tgt_lang is None: raise ValueError('Translation requires a `src_lang` and a `tgt_lang` for this model') a__ : List[str] = src_lang a__ : Any = self(lowercase , add_special_tokens=lowercase , return_tensors=lowercase , **lowercase) a__ : Optional[int] = self.convert_tokens_to_ids(lowercase) a__ : List[str] = tgt_lang_id return inputs def __lowercase ( self , lowercase , lowercase = "eng_Latn" , lowercase = None , lowercase = "fra_Latn" , **lowercase , ) -> BatchEncoding: '''simple docstring''' a__ : Any = src_lang a__ : str = tgt_lang return super().prepare_seqaseq_batch(lowercase , lowercase , **lowercase) def __lowercase ( self) -> Dict: '''simple docstring''' return self.set_src_lang_special_tokens(self.src_lang) def __lowercase ( self) -> int: '''simple docstring''' return self.set_tgt_lang_special_tokens(self.tgt_lang) def __lowercase ( self , lowercase) -> None: '''simple docstring''' a__ : List[str] = self.convert_tokens_to_ids(lowercase) if self.legacy_behaviour: a__ : Optional[Any] = [] a__ : Optional[Any] = [self.eos_token_id, self.cur_lang_code] else: a__ : int = [self.cur_lang_code] a__ : Union[str, Any] = [self.eos_token_id] a__ : List[Any] = self.convert_ids_to_tokens(self.prefix_tokens) a__ : Optional[Any] = self.convert_ids_to_tokens(self.suffix_tokens) a__ : Optional[int] = 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 __lowercase ( self , lowercase) -> None: '''simple docstring''' a__ : Optional[Any] = self.convert_tokens_to_ids(lowercase) if self.legacy_behaviour: a__ : int = [] a__ : Union[str, Any] = [self.eos_token_id, self.cur_lang_code] else: a__ : Dict = [self.cur_lang_code] a__ : List[Any] = [self.eos_token_id] a__ : Optional[int] = self.convert_ids_to_tokens(self.prefix_tokens) a__ : int = self.convert_ids_to_tokens(self.suffix_tokens) a__ : int = 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 __lowercase ( self , lowercase , lowercase = None) -> Tuple[str]: '''simple docstring''' if not self.can_save_slow_tokenizer: raise ValueError( 'Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ' 'tokenizer.') if not os.path.isdir(lowercase): logger.error(F'Vocabulary path ({save_directory}) should be a directory.') return a__ : Any = os.path.join( lowercase , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']) if os.path.abspath(self.vocab_file) != os.path.abspath(lowercase): copyfile(self.vocab_file , lowercase) return (out_vocab_file,)
99
"""simple docstring""" from __future__ import annotations import bisect def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase = 0 , _UpperCamelCase = -1 ): if hi < 0: __lowerCAmelCase : Tuple = len(_UpperCamelCase ) while lo < hi: __lowerCAmelCase : Optional[int] = lo + (hi - lo) // 2 if sorted_collection[mid] < item: __lowerCAmelCase : int = mid + 1 else: __lowerCAmelCase : List[str] = mid return lo def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase = 0 , _UpperCamelCase = -1 ): if hi < 0: __lowerCAmelCase : List[Any] = len(_UpperCamelCase ) while lo < hi: __lowerCAmelCase : Union[str, Any] = lo + (hi - lo) // 2 if sorted_collection[mid] <= item: __lowerCAmelCase : Dict = mid + 1 else: __lowerCAmelCase : str = mid return lo def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase = 0 , _UpperCamelCase = -1 ): sorted_collection.insert(bisect_left(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) , _UpperCamelCase ) def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase = 0 , _UpperCamelCase = -1 ): sorted_collection.insert(bisect_right(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) , _UpperCamelCase ) def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase ): __lowerCAmelCase : List[Any] = 0 __lowerCAmelCase : int = len(_UpperCamelCase ) - 1 while left <= right: __lowerCAmelCase : List[Any] = left + (right - left) // 2 __lowerCAmelCase : Union[str, Any] = sorted_collection[midpoint] if current_item == item: return midpoint elif item < current_item: __lowerCAmelCase : Tuple = midpoint - 1 else: __lowerCAmelCase : str = midpoint + 1 return None def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase ): __lowerCAmelCase : Union[str, Any] = bisect.bisect_left(_UpperCamelCase , _UpperCamelCase ) if index != len(_UpperCamelCase ) and sorted_collection[index] == item: return index return None def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): if right < left: return None __lowerCAmelCase : List[str] = left + (right - left) // 2 if sorted_collection[midpoint] == item: return midpoint elif sorted_collection[midpoint] > item: return binary_search_by_recursion(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , midpoint - 1 ) else: return binary_search_by_recursion(_UpperCamelCase , _UpperCamelCase , midpoint + 1 , _UpperCamelCase ) if __name__ == "__main__": lowerCamelCase__ = input("""Enter numbers separated by comma:\n""").strip() lowerCamelCase__ = sorted(int(item) for item in user_input.split(""",""")) lowerCamelCase__ = int(input("""Enter a single number to be found in the list:\n""")) lowerCamelCase__ = binary_search(collection, target) if result is None: print(f'{target} was not found in {collection}.') else: print(f'{target} was found at position {result} in {collection}.')
86
0
"""simple docstring""" import math def _lowerCAmelCase ( UpperCamelCase_ , UpperCamelCase_ ): __SCREAMING_SNAKE_CASE = len(UpperCamelCase_ ) __SCREAMING_SNAKE_CASE = int(math.floor(math.sqrt(UpperCamelCase_ ) ) ) __SCREAMING_SNAKE_CASE = 0 while arr[min(UpperCamelCase_ , UpperCamelCase_ ) - 1] < x: __SCREAMING_SNAKE_CASE = step step += int(math.floor(math.sqrt(UpperCamelCase_ ) ) ) if prev >= n: return -1 while arr[prev] < x: __SCREAMING_SNAKE_CASE = prev + 1 if prev == min(UpperCamelCase_ , UpperCamelCase_ ): return -1 if arr[prev] == x: return prev return -1 if __name__ == "__main__": __magic_name__ = input("Enter numbers separated by a comma:\n").strip() __magic_name__ = [int(item) for item in user_input.split(",")] __magic_name__ = int(input("Enter the number to be searched:\n")) __magic_name__ = jump_search(arr, x) if res == -1: print("Number not found!") else: print(F"""Number {x} is at index {res}""")
100
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available, is_torch_available from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, is_pt_tf_cross_test, slow if is_tf_available(): from transformers import ( AutoConfig, BertConfig, GPTaConfig, TaConfig, TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSeqaSeqLM, TFAutoModelForSequenceClassification, TFAutoModelWithLMHead, TFBertForMaskedLM, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertModel, TFGPTaLMHeadModel, TFRobertaForMaskedLM, TFTaForConditionalGeneration, ) from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST if is_torch_available(): from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForPreTraining, AutoModelForQuestionAnswering, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoModelWithLMHead, BertForMaskedLM, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, BertModel, GPTaLMHeadModel, RobertaForMaskedLM, TaForConditionalGeneration, ) @is_pt_tf_cross_test class A__ ( unittest.TestCase): @slow def __lowerCamelCase ( self ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __lowerCAmelCase : Tuple = AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = TFAutoModel.from_pretrained(_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = AutoModel.from_pretrained(_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @slow def __lowerCamelCase ( self ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __lowerCAmelCase : int = AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Tuple = TFAutoModelForPreTraining.from_pretrained(_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : str = AutoModelForPreTraining.from_pretrained(_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @slow def __lowerCamelCase ( self ): for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCAmelCase : Dict = AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = TFAutoModelForCausalLM.from_pretrained(_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase , __lowerCAmelCase : List[str] = TFAutoModelForCausalLM.from_pretrained( _SCREAMING_SNAKE_CASE , output_loading_info=_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Any = AutoModelForCausalLM.from_pretrained(_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase , __lowerCAmelCase : List[Any] = AutoModelForCausalLM.from_pretrained( _SCREAMING_SNAKE_CASE , output_loading_info=_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @slow def __lowerCamelCase ( self ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCAmelCase : Dict = AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : int = TFAutoModelWithLMHead.from_pretrained(_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = AutoModelWithLMHead.from_pretrained(_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @slow def __lowerCamelCase ( self ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCAmelCase : Optional[Any] = AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = TFAutoModelForMaskedLM.from_pretrained(_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase , __lowerCAmelCase : int = TFAutoModelForMaskedLM.from_pretrained( _SCREAMING_SNAKE_CASE , output_loading_info=_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Union[str, Any] = AutoModelForMaskedLM.from_pretrained(_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase , __lowerCAmelCase : str = AutoModelForMaskedLM.from_pretrained( _SCREAMING_SNAKE_CASE , output_loading_info=_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @slow def __lowerCamelCase ( self ): for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCAmelCase : Optional[int] = AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Tuple = TFAutoModelForSeqaSeqLM.from_pretrained(_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase , __lowerCAmelCase : Tuple = TFAutoModelForSeqaSeqLM.from_pretrained( _SCREAMING_SNAKE_CASE , output_loading_info=_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : int = AutoModelForSeqaSeqLM.from_pretrained(_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase , __lowerCAmelCase : Dict = AutoModelForSeqaSeqLM.from_pretrained( _SCREAMING_SNAKE_CASE , output_loading_info=_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @slow def __lowerCamelCase ( self ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __lowerCAmelCase : Dict = AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = TFAutoModelForSequenceClassification.from_pretrained(_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Union[str, Any] = AutoModelForSequenceClassification.from_pretrained(_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @slow def __lowerCamelCase ( self ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __lowerCAmelCase : Union[str, Any] = AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = TFAutoModelForQuestionAnswering.from_pretrained(_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Union[str, Any] = AutoModelForQuestionAnswering.from_pretrained(_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : List[Any] = TFAutoModelWithLMHead.from_pretrained(_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) self.assertEqual(model.num_parameters() , 1_44_10 ) self.assertEqual(model.num_parameters(only_trainable=_SCREAMING_SNAKE_CASE ) , 1_44_10 ) __lowerCAmelCase : Tuple = AutoModelWithLMHead.from_pretrained(_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) self.assertEqual(model.num_parameters() , 1_44_10 ) self.assertEqual(model.num_parameters(only_trainable=_SCREAMING_SNAKE_CASE ) , 1_44_10 ) def __lowerCamelCase ( self ): __lowerCAmelCase : int = TFAutoModelWithLMHead.from_pretrained(_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) self.assertEqual(model.num_parameters() , 1_44_10 ) self.assertEqual(model.num_parameters(only_trainable=_SCREAMING_SNAKE_CASE ) , 1_44_10 ) __lowerCAmelCase : Tuple = AutoModelWithLMHead.from_pretrained(_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) self.assertEqual(model.num_parameters() , 1_44_10 ) self.assertEqual(model.num_parameters(only_trainable=_SCREAMING_SNAKE_CASE ) , 1_44_10 )
86
0
import copy import unittest from transformers.models.auto import get_values from transformers.testing_utils import require_torch, 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, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_MULTIPLE_CHOICE_MAPPING, MODEL_FOR_QUESTION_ANSWERING_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaModel, ) from transformers.models.layoutlmva.modeling_layoutlmva import LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class lowercase : def __init__( self ,A__ ,A__=2 ,A__=3 ,A__=4 ,A__=2 ,A__=7 ,A__=True ,A__=True ,A__=True ,A__=True ,A__=9_9 ,A__=3_6 ,A__=3 ,A__=4 ,A__=3_7 ,A__="gelu" ,A__=0.1 ,A__=0.1 ,A__=5_1_2 ,A__=1_6 ,A__=2 ,A__=0.02 ,A__=6 ,A__=6 ,A__=3 ,A__=4 ,A__=None ,A__=1_0_0_0 ,): lowercase = parent lowercase = batch_size lowercase = num_channels lowercase = image_size lowercase = patch_size lowercase = text_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 = coordinate_size lowercase = shape_size lowercase = num_labels lowercase = num_choices lowercase = scope lowercase = range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) lowercase = text_seq_length lowercase = (image_size // patch_size) ** 2 + 1 lowercase = self.text_seq_length + self.image_seq_length def A__ ( self): lowercase = ids_tensor([self.batch_size, self.text_seq_length] ,self.vocab_size) lowercase = ids_tensor([self.batch_size, self.text_seq_length, 4] ,self.range_bbox) # Ensure that bbox is legal for i in range(bbox.shape[0]): for j in range(bbox.shape[1]): if bbox[i, j, 3] < bbox[i, j, 1]: lowercase = bbox[i, j, 3] lowercase = bbox[i, j, 1] lowercase = t if bbox[i, j, 2] < bbox[i, j, 0]: lowercase = bbox[i, j, 2] lowercase = bbox[i, j, 0] lowercase = t lowercase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) lowercase = None if self.use_input_mask: lowercase = random_attention_mask([self.batch_size, self.text_seq_length]) lowercase = None if self.use_token_type_ids: lowercase = ids_tensor([self.batch_size, self.text_seq_length] ,self.type_vocab_size) 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.text_seq_length] ,self.num_labels) lowercase = LayoutLMvaConfig( 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 ,coordinate_size=self.coordinate_size ,shape_size=self.shape_size ,input_size=self.image_size ,patch_size=self.patch_size ,) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def A__ ( self ,A__ ,A__ ,A__ ,A__ ,A__ ,A__ ,A__ ,A__): lowercase = LayoutLMvaModel(config=A__) model.to(A__) model.eval() # text + image lowercase = model(A__ ,pixel_values=A__) lowercase = model( A__ ,bbox=A__ ,pixel_values=A__ ,attention_mask=A__ ,token_type_ids=A__) lowercase = model(A__ ,bbox=A__ ,pixel_values=A__ ,token_type_ids=A__) lowercase = model(A__ ,bbox=A__ ,pixel_values=A__) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size)) # text only lowercase = model(A__) self.parent.assertEqual( result.last_hidden_state.shape ,(self.batch_size, self.text_seq_length, self.hidden_size)) # image only lowercase = model(pixel_values=A__) self.parent.assertEqual( result.last_hidden_state.shape ,(self.batch_size, self.image_seq_length, self.hidden_size)) def A__ ( self ,A__ ,A__ ,A__ ,A__ ,A__ ,A__ ,A__ ,A__): lowercase = self.num_labels lowercase = LayoutLMvaForSequenceClassification(A__) model.to(A__) model.eval() lowercase = model( A__ ,bbox=A__ ,pixel_values=A__ ,attention_mask=A__ ,token_type_ids=A__ ,labels=A__ ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels)) def A__ ( self ,A__ ,A__ ,A__ ,A__ ,A__ ,A__ ,A__ ,A__): lowercase = self.num_labels lowercase = LayoutLMvaForTokenClassification(config=A__) model.to(A__) model.eval() lowercase = model( A__ ,bbox=A__ ,pixel_values=A__ ,attention_mask=A__ ,token_type_ids=A__ ,labels=A__ ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.text_seq_length, self.num_labels)) def A__ ( self ,A__ ,A__ ,A__ ,A__ ,A__ ,A__ ,A__ ,A__): lowercase = LayoutLMvaForQuestionAnswering(config=A__) model.to(A__) model.eval() lowercase = model( A__ ,bbox=A__ ,pixel_values=A__ ,attention_mask=A__ ,token_type_ids=A__ ,start_positions=A__ ,end_positions=A__ ,) self.parent.assertEqual(result.start_logits.shape ,(self.batch_size, self.seq_length)) self.parent.assertEqual(result.end_logits.shape ,(self.batch_size, self.seq_length)) def A__ ( self): lowercase = self.prepare_config_and_inputs() ( ( lowercase ) , ( lowercase ) , ( lowercase ) , ( lowercase ) , ( lowercase ) , ( lowercase ) , ( lowercase ) , ( lowercase ) , ) = config_and_inputs lowercase = { '''input_ids''': input_ids, '''bbox''': bbox, '''pixel_values''': pixel_values, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask, } return config, inputs_dict @require_torch class lowercase ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , unittest.TestCase ): lowercase_ : Dict =False lowercase_ : Any =False lowercase_ : Tuple =False lowercase_ : Any =( ( LayoutLMvaModel, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaForQuestionAnswering, ) if is_torch_available() else () ) lowercase_ : int =( {'''document-question-answering''': LayoutLMvaForQuestionAnswering, '''feature-extraction''': LayoutLMvaModel} if is_torch_available() else {} ) def A__ ( self ,A__ ,A__ ,A__ ,A__ ,A__): # `DocumentQuestionAnsweringPipeline` is expected to work with this model, but it combines the text and visual # embedding along the sequence dimension (dim 1), which causes an error during post-processing as `p_mask` has # the sequence dimension of the text embedding only. # (see the line `embedding_output = torch.cat([embedding_output, visual_embeddings], dim=1)`) return True def A__ ( self): lowercase = LayoutLMvaModelTester(self) lowercase = ConfigTester(self ,config_class=A__ ,hidden_size=3_7) def A__ ( self ,A__ ,A__ ,A__=False): lowercase = copy.deepcopy(A__) if model_class in get_values(A__): lowercase = { k: v.unsqueeze(1).expand(-1 ,self.model_tester.num_choices ,-1).contiguous() if isinstance(A__ ,torch.Tensor) and v.ndim > 1 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(A__): lowercase = torch.ones(self.model_tester.batch_size ,dtype=torch.long ,device=A__) elif model_class in get_values(A__): lowercase = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=A__) lowercase = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=A__) elif model_class in [ *get_values(A__), ]: lowercase = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=A__) elif model_class in [ *get_values(A__), ]: lowercase = torch.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) ,dtype=torch.long ,device=A__ ,) return inputs_dict def A__ ( self): self.config_tester.run_common_tests() def A__ ( self): lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A__) def A__ ( self): 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(*A__) def A__ ( self): lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*A__) def A__ ( self): lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*A__) def A__ ( self): lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*A__) @slow def A__ ( self): for model_name in LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowercase = LayoutLMvaModel.from_pretrained(A__) self.assertIsNotNone(A__) def UpperCamelCase ( ): '''simple docstring''' lowercase = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch class lowercase ( unittest.TestCase ): @cached_property def A__ ( self): return LayoutLMvaImageProcessor(apply_ocr=A__) if is_vision_available() else None @slow def A__ ( self): lowercase = LayoutLMvaModel.from_pretrained('''microsoft/layoutlmv3-base''').to(A__) lowercase = self.default_image_processor lowercase = prepare_img() lowercase = image_processor(images=A__ ,return_tensors='''pt''').pixel_values.to(A__) lowercase = torch.tensor([[1, 2]]) lowercase = torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]]).unsqueeze(0) # forward pass lowercase = model( input_ids=input_ids.to(A__) ,bbox=bbox.to(A__) ,pixel_values=pixel_values.to(A__) ,) # verify the logits lowercase = torch.Size((1, 1_9_9, 7_6_8)) self.assertEqual(outputs.last_hidden_state.shape ,A__) lowercase = torch.tensor( [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]]).to(A__) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3] ,A__ ,atol=1E-4))
101
"""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 lowerCamelCase__ = logging.get_logger(__name__) # pylint: disable=invalid-name lowerCamelCase__ = """ 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 (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase=8 ): __lowerCAmelCase : Dict = h // scale_factor**2 if h % scale_factor**2 != 0: new_h += 1 __lowerCAmelCase : List[str] = w // scale_factor**2 if w % scale_factor**2 != 0: new_w += 1 return new_h * scale_factor, new_w * scale_factor class A__ ( _lowerCamelCase): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , ): super().__init__() self.register_modules( text_encoder=_SCREAMING_SNAKE_CASE , tokenizer=_SCREAMING_SNAKE_CASE , unet=_SCREAMING_SNAKE_CASE , scheduler=_SCREAMING_SNAKE_CASE , movq=_SCREAMING_SNAKE_CASE , ) __lowerCAmelCase : Dict = 2 ** (len(self.movq.config.block_out_channels ) - 1) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): if latents is None: __lowerCAmelCase : Tuple = randn_tensor(_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , device=_SCREAMING_SNAKE_CASE , dtype=_SCREAMING_SNAKE_CASE ) else: if latents.shape != shape: raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}" ) __lowerCAmelCase : Any = latents.to(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = latents * scheduler.init_noise_sigma return latents def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , ): __lowerCAmelCase : Tuple = len(_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else 1 # get prompt text embeddings __lowerCAmelCase : Dict = self.tokenizer( _SCREAMING_SNAKE_CASE , padding='max_length' , truncation=_SCREAMING_SNAKE_CASE , max_length=77 , return_attention_mask=_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE , return_tensors='pt' , ) __lowerCAmelCase : Tuple = text_inputs.input_ids __lowerCAmelCase : Union[str, Any] = self.tokenizer(_SCREAMING_SNAKE_CASE , padding='longest' , return_tensors='pt' ).input_ids if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : List[Any] = 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}" ) __lowerCAmelCase : Dict = text_input_ids.to(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = text_inputs.attention_mask.to(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase , __lowerCAmelCase : str = self.text_encoder( input_ids=_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Any = prompt_embeds.repeat_interleave(_SCREAMING_SNAKE_CASE , dim=0 ) __lowerCAmelCase : Dict = text_encoder_hidden_states.repeat_interleave(_SCREAMING_SNAKE_CASE , dim=0 ) __lowerCAmelCase : Optional[int] = text_mask.repeat_interleave(_SCREAMING_SNAKE_CASE , dim=0 ) if do_classifier_free_guidance: __lowerCAmelCase : List[str] if negative_prompt is None: __lowerCAmelCase : Union[str, Any] = [''] * batch_size elif type(_SCREAMING_SNAKE_CASE ) is not type(_SCREAMING_SNAKE_CASE ): raise TypeError( f"`negative_prompt` should be the same type to `prompt`, but got {type(_SCREAMING_SNAKE_CASE )} !=" f" {type(_SCREAMING_SNAKE_CASE )}." ) elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Optional[int] = [negative_prompt] elif batch_size != len(_SCREAMING_SNAKE_CASE ): raise ValueError( f"`negative_prompt`: {negative_prompt} has batch size {len(_SCREAMING_SNAKE_CASE )}, but `prompt`:" f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" ' the batch size of `prompt`.' ) else: __lowerCAmelCase : Optional[int] = negative_prompt __lowerCAmelCase : Tuple = self.tokenizer( _SCREAMING_SNAKE_CASE , padding='max_length' , max_length=77 , truncation=_SCREAMING_SNAKE_CASE , return_attention_mask=_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE , return_tensors='pt' , ) __lowerCAmelCase : Union[str, Any] = uncond_input.input_ids.to(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = uncond_input.attention_mask.to(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase , __lowerCAmelCase : Any = self.text_encoder( input_ids=_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE ) # duplicate unconditional embeddings for each generation per prompt, using mps friendly method __lowerCAmelCase : List[str] = negative_prompt_embeds.shape[1] __lowerCAmelCase : Any = negative_prompt_embeds.repeat(1 , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = negative_prompt_embeds.view(batch_size * num_images_per_prompt , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : int = uncond_text_encoder_hidden_states.shape[1] __lowerCAmelCase : List[Any] = uncond_text_encoder_hidden_states.repeat(1 , _SCREAMING_SNAKE_CASE , 1 ) __lowerCAmelCase : Optional[int] = uncond_text_encoder_hidden_states.view( batch_size * num_images_per_prompt , _SCREAMING_SNAKE_CASE , -1 ) __lowerCAmelCase : Optional[Any] = uncond_text_mask.repeat_interleave(_SCREAMING_SNAKE_CASE , 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 __lowerCAmelCase : Tuple = torch.cat([negative_prompt_embeds, prompt_embeds] ) __lowerCAmelCase : Tuple = torch.cat([uncond_text_encoder_hidden_states, text_encoder_hidden_states] ) __lowerCAmelCase : int = torch.cat([uncond_text_mask, text_mask] ) return prompt_embeds, text_encoder_hidden_states, text_mask def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE=0 ): if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('Please install accelerate via `pip install accelerate`' ) __lowerCAmelCase : Union[str, Any] = torch.device(f"cuda:{gpu_id}" ) __lowerCAmelCase : List[Any] = [ self.unet, self.text_encoder, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE=0 ): 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.' ) __lowerCAmelCase : str = torch.device(f"cuda:{gpu_id}" ) if self.device.type != "cpu": self.to('cpu' , silence_dtype_warnings=_SCREAMING_SNAKE_CASE ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) __lowerCAmelCase : Any = None for cpu_offloaded_model in [self.text_encoder, self.unet, self.movq]: __lowerCAmelCase , __lowerCAmelCase : Any = cpu_offload_with_hook(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , prev_module_hook=_SCREAMING_SNAKE_CASE ) if self.safety_checker is not None: __lowerCAmelCase , __lowerCAmelCase : Dict = cpu_offload_with_hook(self.safety_checker , _SCREAMING_SNAKE_CASE , prev_module_hook=_SCREAMING_SNAKE_CASE ) # We'll offload the last model manually. __lowerCAmelCase : Optional[Any] = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def __lowerCamelCase ( self ): if not hasattr(self.unet , '_hf_hook' ): return self.device for module in self.unet.modules(): if ( hasattr(_SCREAMING_SNAKE_CASE , '_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(_SCREAMING_SNAKE_CASE ) def __call__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 5_12 , _SCREAMING_SNAKE_CASE = 5_12 , _SCREAMING_SNAKE_CASE = 1_00 , _SCREAMING_SNAKE_CASE = 4.0 , _SCREAMING_SNAKE_CASE = 1 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = "pil" , _SCREAMING_SNAKE_CASE = True , ): if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : List[str] = 1 elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Optional[int] = len(_SCREAMING_SNAKE_CASE ) else: raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(_SCREAMING_SNAKE_CASE )}" ) __lowerCAmelCase : Dict = self._execution_device __lowerCAmelCase : Optional[Any] = batch_size * num_images_per_prompt __lowerCAmelCase : Optional[int] = guidance_scale > 1.0 __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase : int = self._encode_prompt( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : int = torch.cat(_SCREAMING_SNAKE_CASE , dim=0 ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Dict = torch.cat(_SCREAMING_SNAKE_CASE , dim=0 ) if do_classifier_free_guidance: __lowerCAmelCase : Optional[Any] = image_embeds.repeat_interleave(_SCREAMING_SNAKE_CASE , dim=0 ) __lowerCAmelCase : int = negative_image_embeds.repeat_interleave(_SCREAMING_SNAKE_CASE , dim=0 ) __lowerCAmelCase : Any = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to( dtype=prompt_embeds.dtype , device=_SCREAMING_SNAKE_CASE ) self.scheduler.set_timesteps(_SCREAMING_SNAKE_CASE , device=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = self.scheduler.timesteps __lowerCAmelCase : int = self.unet.config.in_channels __lowerCAmelCase , __lowerCAmelCase : Any = get_new_h_w(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , self.movq_scale_factor ) # create initial latent __lowerCAmelCase : str = self.prepare_latents( (batch_size, num_channels_latents, height, width) , text_encoder_hidden_states.dtype , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , self.scheduler , ) for i, t in enumerate(self.progress_bar(_SCREAMING_SNAKE_CASE ) ): # expand the latents if we are doing classifier free guidance __lowerCAmelCase : List[str] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents __lowerCAmelCase : Union[str, Any] = {'text_embeds': prompt_embeds, 'image_embeds': image_embeds} __lowerCAmelCase : Optional[Any] = self.unet( sample=_SCREAMING_SNAKE_CASE , timestep=_SCREAMING_SNAKE_CASE , encoder_hidden_states=_SCREAMING_SNAKE_CASE , added_cond_kwargs=_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , )[0] if do_classifier_free_guidance: __lowerCAmelCase , __lowerCAmelCase : Dict = noise_pred.split(latents.shape[1] , dim=1 ) __lowerCAmelCase , __lowerCAmelCase : Optional[Any] = noise_pred.chunk(2 ) __lowerCAmelCase , __lowerCAmelCase : int = variance_pred.chunk(2 ) __lowerCAmelCase : Dict = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) __lowerCAmelCase : 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"] ): __lowerCAmelCase , __lowerCAmelCase : Union[str, Any] = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 __lowerCAmelCase : List[str] = self.scheduler.step( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , ).prev_sample # post-processing __lowerCAmelCase : Tuple = self.movq.decode(_SCREAMING_SNAKE_CASE , force_not_quantize=_SCREAMING_SNAKE_CASE )['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"]: __lowerCAmelCase : List[str] = image * 0.5 + 0.5 __lowerCAmelCase : Dict = image.clamp(0 , 1 ) __lowerCAmelCase : Dict = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": __lowerCAmelCase : Union[str, Any] = self.numpy_to_pil(_SCREAMING_SNAKE_CASE ) if not return_dict: return (image,) return ImagePipelineOutput(images=_SCREAMING_SNAKE_CASE )
86
0
"""simple docstring""" from __future__ import annotations def lowercase ( _snake_case : float , _snake_case : float , _snake_case : float , ) ->tuple: """simple docstring""" if (electron_conc, hole_conc, intrinsic_conc).count(0 ) != 1: raise ValueError('''You cannot supply more or less than 2 values''' ) elif electron_conc < 0: raise ValueError('''Electron concentration cannot be negative in a semiconductor''' ) elif hole_conc < 0: raise ValueError('''Hole concentration cannot be negative in a semiconductor''' ) elif intrinsic_conc < 0: raise ValueError( '''Intrinsic concentration cannot be negative in a semiconductor''' ) elif electron_conc == 0: return ( "electron_conc", intrinsic_conc**2 / hole_conc, ) elif hole_conc == 0: return ( "hole_conc", intrinsic_conc**2 / electron_conc, ) elif intrinsic_conc == 0: return ( "intrinsic_conc", (electron_conc * hole_conc) ** 0.5, ) else: return (-1, -1) if __name__ == "__main__": import doctest doctest.testmod()
102
"""simple docstring""" import unittest from transformers import BarthezTokenizer, BarthezTokenizerFast, BatchEncoding from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers @require_sentencepiece @slow # see https://github.com/huggingface/transformers/issues/11457 class A__ ( _lowerCamelCase , unittest.TestCase): A_ : Union[str, Any] = BarthezTokenizer A_ : Tuple = BarthezTokenizerFast A_ : Dict = True A_ : List[str] = True def __lowerCamelCase ( self ): super().setUp() __lowerCAmelCase : str = BarthezTokenizerFast.from_pretrained('moussaKam/mbarthez' ) tokenizer.save_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname , legacy_format=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Any = tokenizer def __lowerCamelCase ( self ): __lowerCAmelCase : Optional[Any] = '<pad>' __lowerCAmelCase : Union[str, Any] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : List[Any] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<s>' ) self.assertEqual(vocab_keys[1] , '<pad>' ) self.assertEqual(vocab_keys[-1] , '<mask>' ) self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , 10_11_22 ) def __lowerCamelCase ( self ): self.assertEqual(self.get_tokenizer().vocab_size , 10_11_22 ) @require_torch def __lowerCamelCase ( self ): __lowerCAmelCase : List[str] = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] __lowerCAmelCase : Optional[Any] = [0, 57, 30_18, 7_03_07, 91, 2] __lowerCAmelCase : Optional[int] = self.tokenizer( _SCREAMING_SNAKE_CASE , max_length=len(_SCREAMING_SNAKE_CASE ) , padding=_SCREAMING_SNAKE_CASE , truncation=_SCREAMING_SNAKE_CASE , return_tensors='pt' ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) self.assertEqual((2, 6) , batch.input_ids.shape ) self.assertEqual((2, 6) , batch.attention_mask.shape ) __lowerCAmelCase : List[str] = batch.input_ids.tolist()[0] self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): if not self.test_rust_tokenizer: return __lowerCAmelCase : Tuple = self.get_tokenizer() __lowerCAmelCase : Optional[int] = self.get_rust_tokenizer() __lowerCAmelCase : List[str] = 'I was born in 92000, and this is falsé.' __lowerCAmelCase : Optional[int] = tokenizer.tokenize(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Union[str, Any] = rust_tokenizer.tokenize(_SCREAMING_SNAKE_CASE ) self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = tokenizer.encode(_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = rust_tokenizer.encode(_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE ) self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = self.get_rust_tokenizer() __lowerCAmelCase : List[Any] = tokenizer.encode(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = rust_tokenizer.encode(_SCREAMING_SNAKE_CASE ) self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @slow def __lowerCamelCase ( self ): # fmt: off __lowerCAmelCase : str = {'input_ids': [[0, 4_90, 1_43_28, 45_07, 3_54, 47, 4_36_69, 95, 25, 7_81_17, 2_02_15, 1_97_79, 1_90, 22, 4_00, 4, 3_53_43, 8_03_10, 6_03, 86, 2_49_37, 1_05, 3_34_38, 9_47_62, 1_96, 3_96_42, 7, 15, 1_59_33, 1_73, 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], [0, 1_05_34, 87, 25, 66, 33_58, 1_96, 5_52_89, 8, 8_29_61, 81, 22_04, 7_52_03, 7, 15, 7_63, 1_29_56, 2_16, 1_78, 1_43_28, 95_95, 13_77, 6_96_93, 7, 4_48, 7_10_21, 1_96, 1_81_06, 14_37, 1_39_74, 1_08, 90_83, 4, 4_93_15, 7, 39, 86, 13_26, 27_93, 4_63_33, 4, 4_48, 1_96, 7_45_88, 7, 4_93_15, 7, 39, 21, 8_22, 3_84_70, 74, 21, 6_67_23, 6_24_80, 8, 2_20_50, 5, 2]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on # moussaKam/mbarthez is a french model. So we also use french texts. __lowerCAmelCase : Union[str, Any] = [ 'Le transformeur est un modèle d\'apprentissage profond introduit en 2017, ' 'utilisé principalement dans le domaine du traitement automatique des langues (TAL).', 'À l\'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus ' 'pour gérer des données séquentielles, telles que le langage naturel, pour des tâches ' 'telles que la traduction et la synthèse de texte.', ] self.tokenizer_integration_test_util( expected_encoding=_SCREAMING_SNAKE_CASE , model_name='moussaKam/mbarthez' , revision='c2e4ecbca5e3cd2c37fe1ac285ca4fbdf1366fb6' , sequences=_SCREAMING_SNAKE_CASE , )
86
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 LevitImageProcessor class __snake_case ( unittest.TestCase ): def __init__( self : int , A_ : Optional[Any] , A_ : List[str]=7 , A_ : List[Any]=3 , A_ : int=1_8 , A_ : List[Any]=3_0 , A_ : Tuple=4_0_0 , A_ : Optional[Any]=True , A_ : int=None , A_ : str=True , A_ : str=None , A_ : List[str]=True , A_ : Optional[Any]=[0.5, 0.5, 0.5] , A_ : Optional[int]=[0.5, 0.5, 0.5] , ): lowerCAmelCase_ : Union[str, Any] = size if size is not None else {'''shortest_edge''': 1_8} lowerCAmelCase_ : Dict = crop_size if crop_size is not None else {'''height''': 1_8, '''width''': 1_8} lowerCAmelCase_ : Any = parent lowerCAmelCase_ : str = batch_size lowerCAmelCase_ : int = num_channels lowerCAmelCase_ : int = image_size lowerCAmelCase_ : Optional[Any] = min_resolution lowerCAmelCase_ : List[Any] = max_resolution lowerCAmelCase_ : Optional[Any] = do_resize lowerCAmelCase_ : Any = size lowerCAmelCase_ : Optional[int] = do_center_crop lowerCAmelCase_ : List[str] = crop_size lowerCAmelCase_ : Optional[Any] = do_normalize lowerCAmelCase_ : Tuple = image_mean lowerCAmelCase_ : Optional[int] = image_std def UpperCAmelCase__ ( self : List[Any]): return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "do_center_crop": self.do_center_crop, "size": self.size, "crop_size": self.crop_size, } @require_torch @require_vision class __snake_case ( UpperCamelCase_ ,unittest.TestCase ): _a = LevitImageProcessor if is_vision_available() else None def UpperCAmelCase__ ( self : Union[str, Any]): lowerCAmelCase_ : int = LevitImageProcessingTester(self) @property def UpperCAmelCase__ ( self : Union[str, Any]): return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase__ ( self : Optional[int]): lowerCAmelCase_ : str = self.image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(A_ , '''image_mean''')) self.assertTrue(hasattr(A_ , '''image_std''')) self.assertTrue(hasattr(A_ , '''do_normalize''')) self.assertTrue(hasattr(A_ , '''do_resize''')) self.assertTrue(hasattr(A_ , '''do_center_crop''')) self.assertTrue(hasattr(A_ , '''size''')) def UpperCAmelCase__ ( self : List[Any]): lowerCAmelCase_ : Dict = self.image_processing_class.from_dict(self.image_processor_dict) self.assertEqual(image_processor.size , {'''shortest_edge''': 1_8}) self.assertEqual(image_processor.crop_size , {'''height''': 1_8, '''width''': 1_8}) lowerCAmelCase_ : List[str] = self.image_processing_class.from_dict(self.image_processor_dict , size=4_2 , crop_size=8_4) self.assertEqual(image_processor.size , {'''shortest_edge''': 4_2}) self.assertEqual(image_processor.crop_size , {'''height''': 8_4, '''width''': 8_4}) def UpperCAmelCase__ ( self : Any): pass def UpperCAmelCase__ ( self : Optional[int]): # Initialize image_processing lowerCAmelCase_ : Tuple = self.image_processing_class(**self.image_processor_dict) # create random PIL images lowerCAmelCase_ : Any = 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_ : Union[str, Any] = image_processing(image_inputs[0] , return_tensors='''pt''').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched lowerCAmelCase_ : Dict = 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.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def UpperCAmelCase__ ( self : int): # Initialize image_processing lowerCAmelCase_ : int = self.image_processing_class(**self.image_processor_dict) # create random numpy tensors lowerCAmelCase_ : Union[str, Any] = 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[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 lowerCAmelCase_ : Tuple = 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.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def UpperCAmelCase__ ( self : Any): # Initialize image_processing lowerCAmelCase_ : Any = self.image_processing_class(**self.image_processor_dict) # create random PyTorch tensors lowerCAmelCase_ : Tuple = 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_ : Tuple = 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 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.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , )
103
"""simple docstring""" 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__ = { """sail/poolformer_s12""": """https://huggingface.co/sail/poolformer_s12/resolve/main/config.json""", # See all PoolFormer models at https://huggingface.co/models?filter=poolformer } class A__ ( _lowerCamelCase): A_ : Optional[int] = 'poolformer' def __init__( self , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=4.0 , _SCREAMING_SNAKE_CASE=[2, 2, 6, 2] , _SCREAMING_SNAKE_CASE=[64, 1_28, 3_20, 5_12] , _SCREAMING_SNAKE_CASE=[7, 3, 3, 3] , _SCREAMING_SNAKE_CASE=[4, 2, 2, 2] , _SCREAMING_SNAKE_CASE=[2, 1, 1, 1] , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=1E-5 , _SCREAMING_SNAKE_CASE=0.02 , **_SCREAMING_SNAKE_CASE , ): __lowerCAmelCase : int = num_channels __lowerCAmelCase : str = patch_size __lowerCAmelCase : Optional[Any] = stride __lowerCAmelCase : Optional[int] = padding __lowerCAmelCase : List[Any] = pool_size __lowerCAmelCase : int = hidden_sizes __lowerCAmelCase : str = mlp_ratio __lowerCAmelCase : Optional[int] = depths __lowerCAmelCase : str = patch_sizes __lowerCAmelCase : str = strides __lowerCAmelCase : Optional[int] = num_encoder_blocks __lowerCAmelCase : Any = drop_path_rate __lowerCAmelCase : Any = hidden_act __lowerCAmelCase : Dict = use_layer_scale __lowerCAmelCase : Union[str, Any] = layer_scale_init_value __lowerCAmelCase : Dict = initializer_range super().__init__(**_SCREAMING_SNAKE_CASE ) class A__ ( _lowerCamelCase): A_ : List[str] = version.parse('1.11') @property def __lowerCamelCase ( self ): return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def __lowerCamelCase ( self ): return 2E-3
86
0
'''simple docstring''' # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool lowerCAmelCase__ = { '''Acehnese Arabic''': '''ace_Arab''', '''Acehnese Latin''': '''ace_Latn''', '''Mesopotamian Arabic''': '''acm_Arab''', '''Ta\'izzi-Adeni Arabic''': '''acq_Arab''', '''Tunisian Arabic''': '''aeb_Arab''', '''Afrikaans''': '''afr_Latn''', '''South Levantine Arabic''': '''ajp_Arab''', '''Akan''': '''aka_Latn''', '''Amharic''': '''amh_Ethi''', '''North Levantine Arabic''': '''apc_Arab''', '''Modern Standard Arabic''': '''arb_Arab''', '''Modern Standard Arabic Romanized''': '''arb_Latn''', '''Najdi Arabic''': '''ars_Arab''', '''Moroccan Arabic''': '''ary_Arab''', '''Egyptian Arabic''': '''arz_Arab''', '''Assamese''': '''asm_Beng''', '''Asturian''': '''ast_Latn''', '''Awadhi''': '''awa_Deva''', '''Central Aymara''': '''ayr_Latn''', '''South Azerbaijani''': '''azb_Arab''', '''North Azerbaijani''': '''azj_Latn''', '''Bashkir''': '''bak_Cyrl''', '''Bambara''': '''bam_Latn''', '''Balinese''': '''ban_Latn''', '''Belarusian''': '''bel_Cyrl''', '''Bemba''': '''bem_Latn''', '''Bengali''': '''ben_Beng''', '''Bhojpuri''': '''bho_Deva''', '''Banjar Arabic''': '''bjn_Arab''', '''Banjar Latin''': '''bjn_Latn''', '''Standard Tibetan''': '''bod_Tibt''', '''Bosnian''': '''bos_Latn''', '''Buginese''': '''bug_Latn''', '''Bulgarian''': '''bul_Cyrl''', '''Catalan''': '''cat_Latn''', '''Cebuano''': '''ceb_Latn''', '''Czech''': '''ces_Latn''', '''Chokwe''': '''cjk_Latn''', '''Central Kurdish''': '''ckb_Arab''', '''Crimean Tatar''': '''crh_Latn''', '''Welsh''': '''cym_Latn''', '''Danish''': '''dan_Latn''', '''German''': '''deu_Latn''', '''Southwestern Dinka''': '''dik_Latn''', '''Dyula''': '''dyu_Latn''', '''Dzongkha''': '''dzo_Tibt''', '''Greek''': '''ell_Grek''', '''English''': '''eng_Latn''', '''Esperanto''': '''epo_Latn''', '''Estonian''': '''est_Latn''', '''Basque''': '''eus_Latn''', '''Ewe''': '''ewe_Latn''', '''Faroese''': '''fao_Latn''', '''Fijian''': '''fij_Latn''', '''Finnish''': '''fin_Latn''', '''Fon''': '''fon_Latn''', '''French''': '''fra_Latn''', '''Friulian''': '''fur_Latn''', '''Nigerian Fulfulde''': '''fuv_Latn''', '''Scottish Gaelic''': '''gla_Latn''', '''Irish''': '''gle_Latn''', '''Galician''': '''glg_Latn''', '''Guarani''': '''grn_Latn''', '''Gujarati''': '''guj_Gujr''', '''Haitian Creole''': '''hat_Latn''', '''Hausa''': '''hau_Latn''', '''Hebrew''': '''heb_Hebr''', '''Hindi''': '''hin_Deva''', '''Chhattisgarhi''': '''hne_Deva''', '''Croatian''': '''hrv_Latn''', '''Hungarian''': '''hun_Latn''', '''Armenian''': '''hye_Armn''', '''Igbo''': '''ibo_Latn''', '''Ilocano''': '''ilo_Latn''', '''Indonesian''': '''ind_Latn''', '''Icelandic''': '''isl_Latn''', '''Italian''': '''ita_Latn''', '''Javanese''': '''jav_Latn''', '''Japanese''': '''jpn_Jpan''', '''Kabyle''': '''kab_Latn''', '''Jingpho''': '''kac_Latn''', '''Kamba''': '''kam_Latn''', '''Kannada''': '''kan_Knda''', '''Kashmiri Arabic''': '''kas_Arab''', '''Kashmiri Devanagari''': '''kas_Deva''', '''Georgian''': '''kat_Geor''', '''Central Kanuri Arabic''': '''knc_Arab''', '''Central Kanuri Latin''': '''knc_Latn''', '''Kazakh''': '''kaz_Cyrl''', '''Kabiyè''': '''kbp_Latn''', '''Kabuverdianu''': '''kea_Latn''', '''Khmer''': '''khm_Khmr''', '''Kikuyu''': '''kik_Latn''', '''Kinyarwanda''': '''kin_Latn''', '''Kyrgyz''': '''kir_Cyrl''', '''Kimbundu''': '''kmb_Latn''', '''Northern Kurdish''': '''kmr_Latn''', '''Kikongo''': '''kon_Latn''', '''Korean''': '''kor_Hang''', '''Lao''': '''lao_Laoo''', '''Ligurian''': '''lij_Latn''', '''Limburgish''': '''lim_Latn''', '''Lingala''': '''lin_Latn''', '''Lithuanian''': '''lit_Latn''', '''Lombard''': '''lmo_Latn''', '''Latgalian''': '''ltg_Latn''', '''Luxembourgish''': '''ltz_Latn''', '''Luba-Kasai''': '''lua_Latn''', '''Ganda''': '''lug_Latn''', '''Luo''': '''luo_Latn''', '''Mizo''': '''lus_Latn''', '''Standard Latvian''': '''lvs_Latn''', '''Magahi''': '''mag_Deva''', '''Maithili''': '''mai_Deva''', '''Malayalam''': '''mal_Mlym''', '''Marathi''': '''mar_Deva''', '''Minangkabau Arabic ''': '''min_Arab''', '''Minangkabau Latin''': '''min_Latn''', '''Macedonian''': '''mkd_Cyrl''', '''Plateau Malagasy''': '''plt_Latn''', '''Maltese''': '''mlt_Latn''', '''Meitei Bengali''': '''mni_Beng''', '''Halh Mongolian''': '''khk_Cyrl''', '''Mossi''': '''mos_Latn''', '''Maori''': '''mri_Latn''', '''Burmese''': '''mya_Mymr''', '''Dutch''': '''nld_Latn''', '''Norwegian Nynorsk''': '''nno_Latn''', '''Norwegian Bokmål''': '''nob_Latn''', '''Nepali''': '''npi_Deva''', '''Northern Sotho''': '''nso_Latn''', '''Nuer''': '''nus_Latn''', '''Nyanja''': '''nya_Latn''', '''Occitan''': '''oci_Latn''', '''West Central Oromo''': '''gaz_Latn''', '''Odia''': '''ory_Orya''', '''Pangasinan''': '''pag_Latn''', '''Eastern Panjabi''': '''pan_Guru''', '''Papiamento''': '''pap_Latn''', '''Western Persian''': '''pes_Arab''', '''Polish''': '''pol_Latn''', '''Portuguese''': '''por_Latn''', '''Dari''': '''prs_Arab''', '''Southern Pashto''': '''pbt_Arab''', '''Ayacucho Quechua''': '''quy_Latn''', '''Romanian''': '''ron_Latn''', '''Rundi''': '''run_Latn''', '''Russian''': '''rus_Cyrl''', '''Sango''': '''sag_Latn''', '''Sanskrit''': '''san_Deva''', '''Santali''': '''sat_Olck''', '''Sicilian''': '''scn_Latn''', '''Shan''': '''shn_Mymr''', '''Sinhala''': '''sin_Sinh''', '''Slovak''': '''slk_Latn''', '''Slovenian''': '''slv_Latn''', '''Samoan''': '''smo_Latn''', '''Shona''': '''sna_Latn''', '''Sindhi''': '''snd_Arab''', '''Somali''': '''som_Latn''', '''Southern Sotho''': '''sot_Latn''', '''Spanish''': '''spa_Latn''', '''Tosk Albanian''': '''als_Latn''', '''Sardinian''': '''srd_Latn''', '''Serbian''': '''srp_Cyrl''', '''Swati''': '''ssw_Latn''', '''Sundanese''': '''sun_Latn''', '''Swedish''': '''swe_Latn''', '''Swahili''': '''swh_Latn''', '''Silesian''': '''szl_Latn''', '''Tamil''': '''tam_Taml''', '''Tatar''': '''tat_Cyrl''', '''Telugu''': '''tel_Telu''', '''Tajik''': '''tgk_Cyrl''', '''Tagalog''': '''tgl_Latn''', '''Thai''': '''tha_Thai''', '''Tigrinya''': '''tir_Ethi''', '''Tamasheq Latin''': '''taq_Latn''', '''Tamasheq Tifinagh''': '''taq_Tfng''', '''Tok Pisin''': '''tpi_Latn''', '''Tswana''': '''tsn_Latn''', '''Tsonga''': '''tso_Latn''', '''Turkmen''': '''tuk_Latn''', '''Tumbuka''': '''tum_Latn''', '''Turkish''': '''tur_Latn''', '''Twi''': '''twi_Latn''', '''Central Atlas Tamazight''': '''tzm_Tfng''', '''Uyghur''': '''uig_Arab''', '''Ukrainian''': '''ukr_Cyrl''', '''Umbundu''': '''umb_Latn''', '''Urdu''': '''urd_Arab''', '''Northern Uzbek''': '''uzn_Latn''', '''Venetian''': '''vec_Latn''', '''Vietnamese''': '''vie_Latn''', '''Waray''': '''war_Latn''', '''Wolof''': '''wol_Latn''', '''Xhosa''': '''xho_Latn''', '''Eastern Yiddish''': '''ydd_Hebr''', '''Yoruba''': '''yor_Latn''', '''Yue Chinese''': '''yue_Hant''', '''Chinese Simplified''': '''zho_Hans''', '''Chinese Traditional''': '''zho_Hant''', '''Standard Malay''': '''zsm_Latn''', '''Zulu''': '''zul_Latn''', } class lowercase_ (lowerCamelCase__ ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = 'facebook/nllb-200-distilled-600M' SCREAMING_SNAKE_CASE : Dict = ( 'This is a tool that translates text from a language to another. It takes three inputs: `text`, which should ' 'be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, ' 'which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in ' 'plain English, such as \'Romanian\', or \'Albanian\'. It returns the text translated in `tgt_lang`.' ) SCREAMING_SNAKE_CASE : Union[str, Any] = 'translator' SCREAMING_SNAKE_CASE : str = AutoTokenizer SCREAMING_SNAKE_CASE : List[str] = AutoModelForSeqaSeqLM SCREAMING_SNAKE_CASE : Union[str, Any] = LANGUAGE_CODES SCREAMING_SNAKE_CASE : Union[str, Any] = ['text', 'text', 'text'] SCREAMING_SNAKE_CASE : Tuple = ['text'] def SCREAMING_SNAKE_CASE ( self : Optional[Any] ,lowercase__ : Dict ,lowercase__ : List[Any] ,lowercase__ : str ): if src_lang not in self.lang_to_code: raise ValueError(F"{src_lang} is not a supported language." ) if tgt_lang not in self.lang_to_code: raise ValueError(F"{tgt_lang} is not a supported language." ) __lowercase = self.lang_to_code[src_lang] __lowercase = self.lang_to_code[tgt_lang] return self.pre_processor._build_translation_inputs( lowercase__ ,return_tensors='''pt''' ,src_lang=lowercase__ ,tgt_lang=lowercase__ ) def SCREAMING_SNAKE_CASE ( self : List[str] ,lowercase__ : List[str] ): return self.model.generate(**lowercase__ ) def SCREAMING_SNAKE_CASE ( self : Dict ,lowercase__ : List[str] ): return self.post_processor.decode(outputs[0].tolist() ,skip_special_tokens=lowercase__ )
104
"""simple docstring""" import gc import unittest import numpy as np import torch from diffusers import AutoencoderKL, DDIMScheduler, DiTPipeline, DPMSolverMultistepScheduler, TransformeraDModel from diffusers.utils import is_xformers_available, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS, CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class A__ ( _lowerCamelCase , unittest.TestCase): A_ : Union[str, Any] = DiTPipeline A_ : Union[str, Any] = CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS A_ : List[Any] = PipelineTesterMixin.required_optional_params - { 'latents', 'num_images_per_prompt', 'callback', 'callback_steps', } A_ : Optional[Any] = CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS A_ : Tuple = False def __lowerCamelCase ( self ): torch.manual_seed(0 ) __lowerCAmelCase : List[str] = TransformeraDModel( sample_size=16 , num_layers=2 , patch_size=4 , attention_head_dim=8 , num_attention_heads=2 , in_channels=4 , out_channels=8 , attention_bias=_SCREAMING_SNAKE_CASE , activation_fn='gelu-approximate' , num_embeds_ada_norm=10_00 , norm_type='ada_norm_zero' , norm_elementwise_affine=_SCREAMING_SNAKE_CASE , ) __lowerCAmelCase : str = AutoencoderKL() __lowerCAmelCase : Union[str, Any] = DDIMScheduler() __lowerCAmelCase : Dict = {'transformer': transformer.eval(), 'vae': vae.eval(), 'scheduler': scheduler} return components def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=0 ): if str(_SCREAMING_SNAKE_CASE ).startswith('mps' ): __lowerCAmelCase : List[str] = torch.manual_seed(_SCREAMING_SNAKE_CASE ) else: __lowerCAmelCase : List[str] = torch.Generator(device=_SCREAMING_SNAKE_CASE ).manual_seed(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Any = { 'class_labels': [1], 'generator': generator, 'num_inference_steps': 2, 'output_type': 'numpy', } return inputs def __lowerCamelCase ( self ): __lowerCAmelCase : List[str] = 'cpu' __lowerCAmelCase : Any = self.get_dummy_components() __lowerCAmelCase : Union[str, Any] = self.pipeline_class(**_SCREAMING_SNAKE_CASE ) pipe.to(_SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Tuple = self.get_dummy_inputs(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = pipe(**_SCREAMING_SNAKE_CASE ).images __lowerCAmelCase : List[str] = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 16, 16, 3) ) __lowerCAmelCase : Optional[int] = np.array([0.2946, 0.6601, 0.4329, 0.3296, 0.4144, 0.5319, 0.7273, 0.5013, 0.4457] ) __lowerCAmelCase : List[Any] = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(_SCREAMING_SNAKE_CASE , 1E-3 ) def __lowerCamelCase ( self ): self._test_inference_batch_single_identical(relax_max_difference=_SCREAMING_SNAKE_CASE , expected_max_diff=1E-3 ) @unittest.skipIf( torch_device != 'cuda' or not is_xformers_available() , reason='XFormers attention is only available with CUDA and `xformers` installed' , ) def __lowerCamelCase ( self ): self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 ) @require_torch_gpu @slow class A__ ( unittest.TestCase): def __lowerCamelCase ( self ): super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCamelCase ( self ): __lowerCAmelCase : Dict = torch.manual_seed(0 ) __lowerCAmelCase : int = DiTPipeline.from_pretrained('facebook/DiT-XL-2-256' ) pipe.to('cuda' ) __lowerCAmelCase : Optional[Any] = ['vase', 'umbrella', 'white shark', 'white wolf'] __lowerCAmelCase : Optional[Any] = pipe.get_label_ids(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = pipe(_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , num_inference_steps=40 , output_type='np' ).images for word, image in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Tuple = load_numpy( f"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/dit/{word}.npy" ) assert np.abs((expected_image - image).max() ) < 1E-2 def __lowerCamelCase ( self ): __lowerCAmelCase : Any = DiTPipeline.from_pretrained('facebook/DiT-XL-2-512' ) __lowerCAmelCase : Union[str, Any] = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.to('cuda' ) __lowerCAmelCase : Dict = ['vase', 'umbrella'] __lowerCAmelCase : List[str] = pipe.get_label_ids(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Any = torch.manual_seed(0 ) __lowerCAmelCase : Optional[Any] = pipe(_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , num_inference_steps=25 , output_type='np' ).images for word, image in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Dict = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' f"/dit/{word}_512.npy" ) assert np.abs((expected_image - image).max() ) < 1E-1
86
0
"""simple docstring""" from pathlib import PurePosixPath from typing import Optional import fsspec from fsspec import AbstractFileSystem from huggingface_hub.hf_api import DatasetInfo from ..utils.file_utils import get_authentication_headers_for_url from ..utils.hub import hf_hub_url class __UpperCamelCase ( a__ ): lowerCamelCase : Tuple ="""""" lowerCamelCase : Union[str, Any] ="""hf-legacy""" # "hf://"" is reserved for hffs def __init__( self , lowerCAmelCase__ = None , lowerCAmelCase__ = None , **lowerCAmelCase__ , ) -> Optional[int]: super().__init__(self , **lowerCAmelCase__ ) a : Any = repo_info a : str = token a : Any = None def __a ( self ) -> str: if self.dir_cache is None: a : Union[str, Any] = {} for hf_file in self.repo_info.siblings: # TODO(QL): add sizes a : Optional[int] = { "name": hf_file.rfilename, "size": None, "type": "file", } self.dir_cache.update( { str(lowerCAmelCase__ ): {"name": str(lowerCAmelCase__ ), "size": None, "type": "directory"} for d in list(PurePosixPath(hf_file.rfilename ).parents )[:-1] } ) def __a ( self , lowerCAmelCase__ , lowerCAmelCase__ = "rb" , **lowerCAmelCase__ , ) -> Tuple: if not isinstance(self.repo_info , lowerCAmelCase__ ): raise NotImplementedError(f"""Open is only implemented for dataset repositories, but got {self.repo_info}""" ) a : Union[str, Any] = hf_hub_url(self.repo_info.id , lowerCAmelCase__ , revision=self.repo_info.sha ) return fsspec.open( lowerCAmelCase__ , mode=lowerCAmelCase__ , headers=get_authentication_headers_for_url(lowerCAmelCase__ , use_auth_token=self.token ) , client_kwargs={"trust_env": True} , ).open() def __a ( self , lowerCAmelCase__ , **lowerCAmelCase__ ) -> Any: self._get_dirs() a : Dict = self._strip_protocol(lowerCAmelCase__ ) if path in self.dir_cache: return self.dir_cache[path] else: raise FileNotFoundError(lowerCAmelCase__ ) def __a ( self , lowerCAmelCase__ , lowerCAmelCase__=False , **lowerCAmelCase__ ) -> List[Any]: self._get_dirs() a : Union[str, Any] = PurePosixPath(path.strip("/" ) ) a : Optional[Any] = {} for p, f in self.dir_cache.items(): a : Union[str, Any] = PurePosixPath(p.strip("/" ) ) a : Tuple = p.parent if root == path: a : Optional[Any] = f a : int = list(paths.values() ) if detail: return out else: return sorted(f["name"] for f in out )
105
"""simple docstring""" import gc import random import unittest import numpy as np import torch from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import floats_tensor, load_image, load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class A__ ( _lowerCamelCase , unittest.TestCase): A_ : str = ShapEImgaImgPipeline A_ : str = ['image'] A_ : int = ['image'] A_ : Tuple = [ 'num_images_per_prompt', 'num_inference_steps', 'generator', 'latents', 'guidance_scale', 'frame_size', 'output_type', 'return_dict', ] A_ : Tuple = False @property def __lowerCamelCase ( self ): return 32 @property def __lowerCamelCase ( self ): return 32 @property def __lowerCamelCase ( self ): return self.time_input_dim * 4 @property def __lowerCamelCase ( self ): return 8 @property def __lowerCamelCase ( self ): torch.manual_seed(0 ) __lowerCAmelCase : Any = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=64 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=1 , ) __lowerCAmelCase : Tuple = CLIPVisionModel(_SCREAMING_SNAKE_CASE ) return model @property def __lowerCamelCase ( self ): __lowerCAmelCase : Any = CLIPImageProcessor( crop_size=2_24 , do_center_crop=_SCREAMING_SNAKE_CASE , do_normalize=_SCREAMING_SNAKE_CASE , do_resize=_SCREAMING_SNAKE_CASE , image_mean=[0.4814_5466, 0.457_8275, 0.4082_1073] , image_std=[0.2686_2954, 0.2613_0258, 0.2757_7711] , resample=3 , size=2_24 , ) return image_processor @property def __lowerCamelCase ( self ): torch.manual_seed(0 ) __lowerCAmelCase : Optional[Any] = { 'num_attention_heads': 2, 'attention_head_dim': 16, 'embedding_dim': self.time_input_dim, 'num_embeddings': 32, 'embedding_proj_dim': self.text_embedder_hidden_size, 'time_embed_dim': self.time_embed_dim, 'num_layers': 1, 'clip_embed_dim': self.time_input_dim * 2, 'additional_embeddings': 0, 'time_embed_act_fn': 'gelu', 'norm_in_type': 'layer', 'embedding_proj_norm_type': 'layer', 'encoder_hid_proj_type': None, 'added_emb_type': None, } __lowerCAmelCase : List[Any] = PriorTransformer(**_SCREAMING_SNAKE_CASE ) return model @property def __lowerCamelCase ( self ): torch.manual_seed(0 ) __lowerCAmelCase : Dict = { 'param_shapes': ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), 'd_latent': self.time_input_dim, 'd_hidden': self.renderer_dim, 'n_output': 12, 'background': ( 0.1, 0.1, 0.1, ), } __lowerCAmelCase : int = ShapERenderer(**_SCREAMING_SNAKE_CASE ) return model def __lowerCamelCase ( self ): __lowerCAmelCase : Any = self.dummy_prior __lowerCAmelCase : List[Any] = self.dummy_image_encoder __lowerCAmelCase : int = self.dummy_image_processor __lowerCAmelCase : Any = self.dummy_renderer __lowerCAmelCase : Any = HeunDiscreteScheduler( beta_schedule='exp' , num_train_timesteps=10_24 , prediction_type='sample' , use_karras_sigmas=_SCREAMING_SNAKE_CASE , clip_sample=_SCREAMING_SNAKE_CASE , clip_sample_range=1.0 , ) __lowerCAmelCase : Tuple = { 'prior': prior, 'image_encoder': image_encoder, 'image_processor': image_processor, 'renderer': renderer, 'scheduler': scheduler, } return components def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=0 ): __lowerCAmelCase : Optional[Any] = floats_tensor((1, 3, 64, 64) , rng=random.Random(_SCREAMING_SNAKE_CASE ) ).to(_SCREAMING_SNAKE_CASE ) if str(_SCREAMING_SNAKE_CASE ).startswith('mps' ): __lowerCAmelCase : int = torch.manual_seed(_SCREAMING_SNAKE_CASE ) else: __lowerCAmelCase : str = torch.Generator(device=_SCREAMING_SNAKE_CASE ).manual_seed(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = { 'image': input_image, 'generator': generator, 'num_inference_steps': 1, 'frame_size': 32, 'output_type': 'np', } return inputs def __lowerCamelCase ( self ): __lowerCAmelCase : str = 'cpu' __lowerCAmelCase : Dict = self.get_dummy_components() __lowerCAmelCase : Optional[int] = self.pipeline_class(**_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = pipe.to(_SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = pipe(**self.get_dummy_inputs(_SCREAMING_SNAKE_CASE ) ) __lowerCAmelCase : Any = output.images[0] __lowerCAmelCase : Optional[Any] = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) __lowerCAmelCase : List[Any] = np.array( [ 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def __lowerCamelCase ( self ): # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def __lowerCamelCase ( self ): __lowerCAmelCase : str = torch_device == 'cpu' __lowerCAmelCase : Optional[Any] = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=_SCREAMING_SNAKE_CASE , relax_max_difference=_SCREAMING_SNAKE_CASE , ) def __lowerCamelCase ( self ): __lowerCAmelCase : str = self.get_dummy_components() __lowerCAmelCase : List[str] = self.pipeline_class(**_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = pipe.to(_SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = 1 __lowerCAmelCase : List[str] = 2 __lowerCAmelCase : Union[str, Any] = self.get_dummy_inputs(_SCREAMING_SNAKE_CASE ) for key in inputs.keys(): if key in self.batch_params: __lowerCAmelCase : Optional[Any] = batch_size * [inputs[key]] __lowerCAmelCase : List[str] = pipe(**_SCREAMING_SNAKE_CASE , num_images_per_prompt=_SCREAMING_SNAKE_CASE )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class A__ ( unittest.TestCase): def __lowerCamelCase ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCamelCase ( self ): __lowerCAmelCase : int = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/shap_e/corgi.png' ) __lowerCAmelCase : Any = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/shap_e/test_shap_e_img2img_out.npy' ) __lowerCAmelCase : Union[str, Any] = ShapEImgaImgPipeline.from_pretrained('openai/shap-e-img2img' ) __lowerCAmelCase : Dict = pipe.to(_SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Tuple = torch.Generator(device=_SCREAMING_SNAKE_CASE ).manual_seed(0 ) __lowerCAmelCase : int = pipe( _SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , guidance_scale=3.0 , num_inference_steps=64 , frame_size=64 , output_type='np' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
86
0
"""simple docstring""" import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.generation import DisjunctiveConstraint @require_torch class SCREAMING_SNAKE_CASE ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self : Any ): # For consistency across different places the DisjunctiveConstraint is called, # dc.token_ids is a list of integers. It is also initialized only by integers. lowerCAmelCase__ : List[str] = [[1, 2, 4], [1, 2, 3, 4]] lowerCAmelCase__ : Optional[int] = DisjunctiveConstraint(lowercase_ ) self.assertTrue(isinstance(dc.token_ids ,lowercase_ ) ) with self.assertRaises(lowercase_ ): DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]] ) ) with self.assertRaises(lowercase_ ): DisjunctiveConstraint([torch.LongTensor([1, 2, 4] ), torch.LongTensor([1, 2, 3, 4, 5] )] ) def __lowerCAmelCase ( self : Tuple ): # We can't have constraints that are complete subsets of another. This leads to a preverse # interpretation of "constraint fulfillment": does generating [1,2,3] fulfill the constraint? # It would mean that it generated [1,2] which fulfills it, but it's in the middle of potentially # fulfilling [1,2,3,4]. If we believe that [1,2,3] does fulfill the constraint, then the algorithm # will necessarily never reach [1,2,3,4], giving users a false sense of control (better to just not allow it). lowerCAmelCase__ : List[str] = [[1, 2], [1, 2, 3, 4]] with self.assertRaises(lowercase_ ): DisjunctiveConstraint(lowercase_ ) # fails here def __lowerCAmelCase ( self : Optional[int] ): lowerCAmelCase__ : str = [[1, 2, 3], [1, 2, 4]] lowerCAmelCase__ : Optional[int] = DisjunctiveConstraint(lowercase_ ) lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ : Optional[int] = dc.update(1 ) lowerCAmelCase__ : int = stepped is True and completed is False and reset is False self.assertTrue(lowercase_ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ : Optional[Any] = dc.update(2 ) lowerCAmelCase__ : Optional[Any] = stepped is True and completed is False and reset is False self.assertTrue(lowercase_ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ : Union[str, Any] = dc.update(3 ) lowerCAmelCase__ : Any = stepped is True and completed is True and reset is False self.assertTrue(lowercase_ ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 3] ) def __lowerCAmelCase ( self : Union[str, Any] ): lowerCAmelCase__ : Optional[int] = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]] lowerCAmelCase__ : List[Any] = DisjunctiveConstraint(lowercase_ ) lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ : Any = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ : Optional[Any] = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ : Any = dc.update(4 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2, 4] ) lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ : Dict = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 4, 5] ) dc.reset() lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ : Optional[int] = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 3 ) self.assertTrue(dc.current_seq == [1] ) lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ : Dict = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 2 ) self.assertTrue(dc.current_seq == [1, 2] ) lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ : List[str] = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.remaining() == 0 ) self.assertTrue(dc.current_seq == [1, 2, 5] )
106
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase__ = {"""configuration_fnet""": ["""FNET_PRETRAINED_CONFIG_ARCHIVE_MAP""", """FNetConfig"""]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = ["""FNetTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = ["""FNetTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ """FNET_PRETRAINED_MODEL_ARCHIVE_LIST""", """FNetForMaskedLM""", """FNetForMultipleChoice""", """FNetForNextSentencePrediction""", """FNetForPreTraining""", """FNetForQuestionAnswering""", """FNetForSequenceClassification""", """FNetForTokenClassification""", """FNetLayer""", """FNetModel""", """FNetPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_fnet import FNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet import FNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet_fast import FNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_fnet import ( FNET_PRETRAINED_MODEL_ARCHIVE_LIST, FNetForMaskedLM, FNetForMultipleChoice, FNetForNextSentencePrediction, FNetForPreTraining, FNetForQuestionAnswering, FNetForSequenceClassification, FNetForTokenClassification, FNetLayer, FNetModel, FNetPreTrainedModel, ) else: import sys lowerCamelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
86
0
from __future__ import annotations def __magic_name__ ( A : list[list[int]] ): '''simple docstring''' a = len(A ) # We need to create solution object to save path. a = [[0 for _ in range(A )] for _ in range(A )] a = run_maze(A, 0, 0, A ) if solved: print("\n".join(str(A ) for row in solutions ) ) else: print("No solution exists!" ) return solved def __magic_name__ ( A : list[list[int]], A : int, A : int, A : list[list[int]] ): '''simple docstring''' a = len(A ) # Final check point. if i == j == (size - 1): a = 1 return True a = (not i < 0) and (not j < 0) # Check lower bounds a = (i < size) and (j < size) # Check upper bounds if lower_flag and upper_flag: # check for already visited and block points. a = (not solutions[i][j]) and (not maze[i][j]) if block_flag: # check visited a = 1 # check for directions if ( run_maze(A, i + 1, A, A ) or run_maze(A, A, j + 1, A ) or run_maze(A, i - 1, A, A ) or run_maze(A, A, j - 1, A ) ): return True a = 0 return False return False if __name__ == "__main__": import doctest doctest.testmod()
107
"""simple docstring""" import math import sys def __lowerCAmelCase (_UpperCamelCase ): if number != int(_UpperCamelCase ): raise ValueError('the value of input must be a natural number' ) if number < 0: raise ValueError('the value of input must not be a negative number' ) if number == 0: return 1 __lowerCAmelCase : Any = [-1] * (number + 1) __lowerCAmelCase : List[Any] = 0 for i in range(1 , number + 1 ): __lowerCAmelCase : List[Any] = sys.maxsize __lowerCAmelCase : Optional[int] = int(math.sqrt(_UpperCamelCase ) ) for j in range(1 , root + 1 ): __lowerCAmelCase : Optional[Any] = 1 + answers[i - (j**2)] __lowerCAmelCase : Any = min(_UpperCamelCase , _UpperCamelCase ) __lowerCAmelCase : List[str] = answer return answers[number] if __name__ == "__main__": import doctest doctest.testmod()
86
0
"""simple docstring""" from __future__ import annotations from decimal import Decimal from math import * # noqa: F403 from sympy import diff def a__ ( SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : float | Decimal , SCREAMING_SNAKE_CASE : float = 1_0**-1_0 ): '''simple docstring''' lowerCAmelCase : Any = a while True: lowerCAmelCase : str = Decimal(SCREAMING_SNAKE_CASE ) - ( Decimal(eval(SCREAMING_SNAKE_CASE ) ) / Decimal(eval(str(diff(SCREAMING_SNAKE_CASE ) ) ) ) # noqa: S307 ) # This number dictates the accuracy of the answer if abs(eval(SCREAMING_SNAKE_CASE ) ) < precision: # noqa: S307 return float(SCREAMING_SNAKE_CASE ) # Let's Execute if __name__ == "__main__": # Find root of trigonometric function # Find value of pi print(F"The root of sin(x) = 0 is {newton_raphson('sin(x)', 2)}") # Find root of polynomial print(F"The root of x**2 - 5*x + 2 = 0 is {newton_raphson('x**2 - 5*x + 2', 0.4)}") # Find Square Root of 5 print(F"The root of log(x) - 1 = 0 is {newton_raphson('log(x) - 1', 2)}") # Exponential Roots print(F"The root of exp(x) - 1 = 0 is {newton_raphson('exp(x) - 1', 0)}")
108
"""simple docstring""" import tempfile import unittest import numpy as np import transformers from transformers import GPTaTokenizer, GPTJConfig, is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax, tooslow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax import jax.numpy as jnp from transformers.modeling_flax_pytorch_utils import ( convert_pytorch_state_dict_to_flax, load_flax_weights_in_pytorch_model, ) from transformers.models.gptj.modeling_flax_gptj import FlaxGPTJForCausalLM, FlaxGPTJModel if is_torch_available(): import torch class A__ : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=14 , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=99 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=37 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=5_12 , _SCREAMING_SNAKE_CASE=0.02 , ): __lowerCAmelCase : Union[str, Any] = parent __lowerCAmelCase : Any = batch_size __lowerCAmelCase : Any = seq_length __lowerCAmelCase : Optional[Any] = is_training __lowerCAmelCase : Any = use_input_mask __lowerCAmelCase : Any = use_token_type_ids __lowerCAmelCase : Tuple = use_labels __lowerCAmelCase : Optional[Any] = vocab_size __lowerCAmelCase : Tuple = hidden_size __lowerCAmelCase : str = rotary_dim __lowerCAmelCase : Union[str, Any] = num_hidden_layers __lowerCAmelCase : Union[str, Any] = num_attention_heads __lowerCAmelCase : int = intermediate_size __lowerCAmelCase : List[str] = hidden_act __lowerCAmelCase : int = hidden_dropout_prob __lowerCAmelCase : Any = attention_probs_dropout_prob __lowerCAmelCase : List[Any] = max_position_embeddings __lowerCAmelCase : Optional[Any] = initializer_range __lowerCAmelCase : Tuple = None __lowerCAmelCase : int = vocab_size - 1 __lowerCAmelCase : Dict = vocab_size - 1 __lowerCAmelCase : int = vocab_size - 1 def __lowerCamelCase ( self ): __lowerCAmelCase : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __lowerCAmelCase : List[str] = None if self.use_input_mask: __lowerCAmelCase : Dict = random_attention_mask([self.batch_size, self.seq_length] ) __lowerCAmelCase : Optional[int] = GPTJConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , use_cache=_SCREAMING_SNAKE_CASE , bos_token_id=self.bos_token_id , eos_token_id=self.eos_token_id , pad_token_id=self.pad_token_id , rotary_dim=self.rotary_dim , ) return (config, input_ids, input_mask) def __lowerCamelCase ( self ): __lowerCAmelCase : Optional[int] = self.prepare_config_and_inputs() __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase : Any = config_and_inputs __lowerCAmelCase : Dict = {'input_ids': input_ids, 'attention_mask': attention_mask} return config, inputs_dict def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : List[str] = 20 __lowerCAmelCase : List[str] = model_class_name(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = model.init_cache(input_ids.shape[0] , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = jnp.ones((input_ids.shape[0], max_decoder_length) , dtype='i4' ) __lowerCAmelCase : Optional[Any] = jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1 )[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1) ) __lowerCAmelCase : Any = model( input_ids[:, :-1] , attention_mask=_SCREAMING_SNAKE_CASE , past_key_values=_SCREAMING_SNAKE_CASE , position_ids=_SCREAMING_SNAKE_CASE , ) __lowerCAmelCase : Any = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype='i4' ) __lowerCAmelCase : int = model( input_ids[:, -1:] , attention_mask=_SCREAMING_SNAKE_CASE , past_key_values=outputs_cache.past_key_values , position_ids=_SCREAMING_SNAKE_CASE , ) __lowerCAmelCase : Any = model(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=f"Max diff is {diff}" ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Tuple = 20 __lowerCAmelCase : List[str] = model_class_name(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Union[str, Any] = jnp.concatenate( [attention_mask, jnp.zeros((attention_mask.shape[0], max_decoder_length - attention_mask.shape[1]) )] , axis=-1 , ) __lowerCAmelCase : List[str] = model.init_cache(input_ids.shape[0] , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : str = jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1 )[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1) ) __lowerCAmelCase : Optional[Any] = model( input_ids[:, :-1] , attention_mask=_SCREAMING_SNAKE_CASE , past_key_values=_SCREAMING_SNAKE_CASE , position_ids=_SCREAMING_SNAKE_CASE , ) __lowerCAmelCase : str = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype='i4' ) __lowerCAmelCase : Tuple = model( input_ids[:, -1:] , past_key_values=outputs_cache.past_key_values , attention_mask=_SCREAMING_SNAKE_CASE , position_ids=_SCREAMING_SNAKE_CASE , ) __lowerCAmelCase : Union[str, Any] = model(_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=f"Max diff is {diff}" ) @require_flax class A__ ( _lowerCamelCase , _lowerCamelCase , unittest.TestCase): A_ : Tuple = (FlaxGPTJModel, FlaxGPTJForCausalLM) if is_flax_available() else () A_ : str = (FlaxGPTJForCausalLM,) if is_flax_available() else () def __lowerCamelCase ( self ): __lowerCAmelCase : int = FlaxGPTJModelTester(self ) def __lowerCamelCase ( self ): for model_class_name in self.all_model_classes: __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): for model_class_name in self.all_model_classes: __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward_with_attn_mask( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @tooslow def __lowerCamelCase ( self ): __lowerCAmelCase : Tuple = GPTaTokenizer.from_pretrained('gpt2' , pad_token='<|endoftext|>' , padding_side='left' ) __lowerCAmelCase : Optional[int] = tokenizer(['Hello this is a long string', 'Hey'] , return_tensors='np' , padding=_SCREAMING_SNAKE_CASE , truncation=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : int = FlaxGPTJForCausalLM.from_pretrained('EleutherAI/gpt-j-6B' ) __lowerCAmelCase : Any = False __lowerCAmelCase : Any = model.config.eos_token_id __lowerCAmelCase : Union[str, Any] = jax.jit(model.generate ) __lowerCAmelCase : Optional[Any] = jit_generate( inputs['input_ids'] , attention_mask=inputs['attention_mask'] , pad_token_id=tokenizer.pad_token_id ).sequences __lowerCAmelCase : str = tokenizer.batch_decode(_SCREAMING_SNAKE_CASE , skip_special_tokens=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = [ 'Hello this is a long string of text.\n\nI\'m trying to get the text of the', 'Hey, I\'m a little late to the party. I\'m going to', ] self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @is_pt_flax_cross_test def __lowerCamelCase ( self ): __lowerCAmelCase , __lowerCAmelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): # prepare inputs __lowerCAmelCase : str = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Union[str, Any] = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class __lowerCAmelCase : Dict = model_class.__name__[4:] # Skip the "Flax" at the beginning __lowerCAmelCase : Optional[int] = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase , __lowerCAmelCase : List[Any] = pt_inputs['input_ids'].shape __lowerCAmelCase : int = np.random.randint(0 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(_SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Tuple = 0 __lowerCAmelCase : Tuple = 1 __lowerCAmelCase : List[str] = 0 __lowerCAmelCase : Any = 1 __lowerCAmelCase : Optional[Any] = pt_model_class(_SCREAMING_SNAKE_CASE ).eval() __lowerCAmelCase : Any = model_class(_SCREAMING_SNAKE_CASE , dtype=jnp.floataa ) __lowerCAmelCase : int = convert_pytorch_state_dict_to_flax(pt_model.state_dict() , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : str = fx_state with torch.no_grad(): __lowerCAmelCase : Union[str, Any] = pt_model(**_SCREAMING_SNAKE_CASE ).to_tuple() __lowerCAmelCase : str = fx_model(**_SCREAMING_SNAKE_CASE ).to_tuple() self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , len(_SCREAMING_SNAKE_CASE ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output, pt_output in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) with tempfile.TemporaryDirectory() as tmpdirname: pt_model.save_pretrained(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Tuple = model_class.from_pretrained(_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = fx_model_loaded(**_SCREAMING_SNAKE_CASE ).to_tuple() self.assertEqual( len(_SCREAMING_SNAKE_CASE ) , len(_SCREAMING_SNAKE_CASE ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output_loaded, pt_output in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): self.assert_almost_equals(fx_output_loaded[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) @is_pt_flax_cross_test def __lowerCamelCase ( self ): __lowerCAmelCase , __lowerCAmelCase : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): # prepare inputs __lowerCAmelCase : List[str] = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class __lowerCAmelCase : Dict = model_class.__name__[4:] # Skip the "Flax" at the beginning __lowerCAmelCase : str = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = pt_model_class(_SCREAMING_SNAKE_CASE ).eval() __lowerCAmelCase : Tuple = model_class(_SCREAMING_SNAKE_CASE , dtype=jnp.floataa ) __lowerCAmelCase : List[str] = load_flax_weights_in_pytorch_model(_SCREAMING_SNAKE_CASE , fx_model.params ) __lowerCAmelCase , __lowerCAmelCase : int = pt_inputs['input_ids'].shape __lowerCAmelCase : List[str] = np.random.randint(0 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(_SCREAMING_SNAKE_CASE ): __lowerCAmelCase : str = 0 __lowerCAmelCase : Optional[Any] = 1 __lowerCAmelCase : Optional[int] = 0 __lowerCAmelCase : Optional[Any] = 1 # make sure weights are tied in PyTorch pt_model.tie_weights() with torch.no_grad(): __lowerCAmelCase : List[str] = pt_model(**_SCREAMING_SNAKE_CASE ).to_tuple() __lowerCAmelCase : Optional[int] = fx_model(**_SCREAMING_SNAKE_CASE ).to_tuple() self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , len(_SCREAMING_SNAKE_CASE ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output, pt_output in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) with tempfile.TemporaryDirectory() as tmpdirname: fx_model.save_pretrained(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = pt_model_class.from_pretrained(_SCREAMING_SNAKE_CASE , from_flax=_SCREAMING_SNAKE_CASE ) with torch.no_grad(): __lowerCAmelCase : Any = pt_model_loaded(**_SCREAMING_SNAKE_CASE ).to_tuple() self.assertEqual( len(_SCREAMING_SNAKE_CASE ) , len(_SCREAMING_SNAKE_CASE ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output, pt_output in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) @tooslow def __lowerCamelCase ( self ): for model_class_name in self.all_model_classes: __lowerCAmelCase : Optional[int] = model_class_name.from_pretrained('EleutherAI/gpt-j-6B' ) __lowerCAmelCase : List[Any] = model(np.ones((1, 1) ) ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE )
86
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices A: Optional[int] = logging.get_logger(__name__) A: Tuple = { "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 SCREAMING_SNAKE_CASE__ ( UpperCAmelCase__ , UpperCAmelCase__ ): __lowerCAmelCase : Any = 'nat' __lowerCAmelCase : Any = { 'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers', } def __init__( self , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=64 , _SCREAMING_SNAKE_CASE=[3, 4, 6, 5] , _SCREAMING_SNAKE_CASE=[2, 4, 8, 16] , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=3.0 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE=1E-5 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE , ) -> Tuple: '''simple docstring''' super().__init__(**_SCREAMING_SNAKE_CASE ) UpperCAmelCase : Optional[Any] = patch_size UpperCAmelCase : Dict = num_channels UpperCAmelCase : Tuple = embed_dim UpperCAmelCase : List[Any] = depths UpperCAmelCase : Optional[Any] = len(_SCREAMING_SNAKE_CASE ) UpperCAmelCase : Tuple = num_heads UpperCAmelCase : Any = kernel_size UpperCAmelCase : Dict = mlp_ratio UpperCAmelCase : List[Any] = qkv_bias UpperCAmelCase : List[str] = hidden_dropout_prob UpperCAmelCase : Any = attention_probs_dropout_prob UpperCAmelCase : Union[str, Any] = drop_path_rate UpperCAmelCase : List[str] = hidden_act UpperCAmelCase : List[Any] = layer_norm_eps UpperCAmelCase : Dict = 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 UpperCAmelCase : Union[str, Any] = int(embed_dim * 2 ** (len(_SCREAMING_SNAKE_CASE ) - 1) ) UpperCAmelCase : Tuple = layer_scale_init_value UpperCAmelCase : Optional[Any] = ["""stem"""] + [F"stage{idx}" for idx in range(1 , len(_SCREAMING_SNAKE_CASE ) + 1 )] UpperCAmelCase , UpperCAmelCase : Dict = get_aligned_output_features_output_indices( out_features=_SCREAMING_SNAKE_CASE , out_indices=_SCREAMING_SNAKE_CASE , stage_names=self.stage_names )
109
"""simple docstring""" 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 , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=13 , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=99 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=37 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=5_12 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=None , ): __lowerCAmelCase : Tuple = parent __lowerCAmelCase : Optional[int] = 13 __lowerCAmelCase : List[Any] = 7 __lowerCAmelCase : int = True __lowerCAmelCase : Optional[int] = True __lowerCAmelCase : List[Any] = True __lowerCAmelCase : Optional[int] = True __lowerCAmelCase : Optional[Any] = 99 __lowerCAmelCase : int = 3_84 __lowerCAmelCase : Union[str, Any] = 2 __lowerCAmelCase : Tuple = 4 __lowerCAmelCase : str = 37 __lowerCAmelCase : Any = 'gelu' __lowerCAmelCase : List[str] = 0.1 __lowerCAmelCase : Any = 0.1 __lowerCAmelCase : Union[str, Any] = 5_12 __lowerCAmelCase : int = 16 __lowerCAmelCase : Union[str, Any] = 2 __lowerCAmelCase : int = 0.02 __lowerCAmelCase : Dict = 3 __lowerCAmelCase : Tuple = 4 __lowerCAmelCase : Tuple = 1_28 __lowerCAmelCase : Optional[int] = 2 __lowerCAmelCase : List[str] = 9 __lowerCAmelCase : int = 1 __lowerCAmelCase : int = None def __lowerCamelCase ( self ): __lowerCAmelCase : Any = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __lowerCAmelCase : Optional[int] = None if self.use_input_mask: __lowerCAmelCase : str = random_attention_mask([self.batch_size, self.seq_length] ) __lowerCAmelCase : Tuple = None if self.use_token_type_ids: __lowerCAmelCase : Dict = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __lowerCAmelCase : Optional[Any] = None __lowerCAmelCase : Dict = None __lowerCAmelCase : Union[str, Any] = None if self.use_labels: __lowerCAmelCase : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCAmelCase : Dict = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __lowerCAmelCase : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) __lowerCAmelCase : Union[str, 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=_SCREAMING_SNAKE_CASE , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Optional[int] = TFConvBertModel(config=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids} __lowerCAmelCase : Tuple = [input_ids, input_mask] __lowerCAmelCase : Any = model(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Any = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Any = TFConvBertForMaskedLM(config=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } __lowerCAmelCase : Optional[Any] = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Tuple = self.num_labels __lowerCAmelCase : Optional[Any] = TFConvBertForSequenceClassification(config=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : int = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } __lowerCAmelCase : Union[str, Any] = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : int = self.num_choices __lowerCAmelCase : List[str] = TFConvBertForMultipleChoice(config=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = tf.tile(tf.expand_dims(_SCREAMING_SNAKE_CASE , 1 ) , (1, self.num_choices, 1) ) __lowerCAmelCase : Dict = tf.tile(tf.expand_dims(_SCREAMING_SNAKE_CASE , 1 ) , (1, self.num_choices, 1) ) __lowerCAmelCase : Union[str, Any] = tf.tile(tf.expand_dims(_SCREAMING_SNAKE_CASE , 1 ) , (1, self.num_choices, 1) ) __lowerCAmelCase : Tuple = { 'input_ids': multiple_choice_inputs_ids, 'attention_mask': multiple_choice_input_mask, 'token_type_ids': multiple_choice_token_type_ids, } __lowerCAmelCase : str = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : str = self.num_labels __lowerCAmelCase : Any = TFConvBertForTokenClassification(config=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } __lowerCAmelCase : Union[str, Any] = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : str = TFConvBertForQuestionAnswering(config=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Union[str, Any] = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } __lowerCAmelCase : Optional[int] = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __lowerCamelCase ( self ): __lowerCAmelCase : Union[str, Any] = self.prepare_config_and_inputs() ( ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ) : List[str] = config_and_inputs __lowerCAmelCase : Any = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_tf class A__ ( _lowerCamelCase , _lowerCamelCase , unittest.TestCase): A_ : List[str] = ( ( TFConvBertModel, TFConvBertForMaskedLM, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertForMultipleChoice, ) if is_tf_available() else () ) A_ : str = ( { 'feature-extraction': TFConvBertModel, 'fill-mask': TFConvBertForMaskedLM, 'question-answering': TFConvBertForQuestionAnswering, 'text-classification': TFConvBertForSequenceClassification, 'token-classification': TFConvBertForTokenClassification, 'zero-shot': TFConvBertForSequenceClassification, } if is_tf_available() else {} ) A_ : List[Any] = False A_ : str = False A_ : List[Any] = False def __lowerCamelCase ( self ): __lowerCAmelCase : Dict = TFConvBertModelTester(self ) __lowerCAmelCase : Any = ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , hidden_size=37 ) def __lowerCamelCase ( self ): self.config_tester.run_common_tests() def __lowerCamelCase ( self ): __lowerCAmelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_SCREAMING_SNAKE_CASE ) @slow def __lowerCamelCase ( self ): __lowerCAmelCase , __lowerCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() __lowerCAmelCase : Any = True __lowerCAmelCase : Dict = True if hasattr(_SCREAMING_SNAKE_CASE , 'use_cache' ): __lowerCAmelCase : int = True __lowerCAmelCase : List[str] = getattr(self.model_tester , 'encoder_seq_length' , self.model_tester.seq_length ) __lowerCAmelCase : str = getattr(self.model_tester , 'key_length' , _SCREAMING_SNAKE_CASE ) for model_class in self.all_model_classes: __lowerCAmelCase : str = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : str = model_class(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = len(model(_SCREAMING_SNAKE_CASE ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(_SCREAMING_SNAKE_CASE , saved_model=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = os.path.join(_SCREAMING_SNAKE_CASE , 'saved_model' , '1' ) __lowerCAmelCase : int = tf.keras.models.load_model(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = model(_SCREAMING_SNAKE_CASE ) if self.is_encoder_decoder: __lowerCAmelCase : List[str] = outputs['encoder_hidden_states'] __lowerCAmelCase : Tuple = outputs['encoder_attentions'] else: __lowerCAmelCase : Optional[int] = outputs['hidden_states'] __lowerCAmelCase : Tuple = outputs['attentions'] self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Union[str, Any] = getattr( self.model_tester , 'expected_num_hidden_layers' , self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) self.assertListEqual( list(output_hidden_states[0].shape[-2:] ) , [self.model_tester.seq_length, self.model_tester.hidden_size] , ) self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , 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 __lowerCamelCase ( self ): __lowerCAmelCase : Tuple = TFConvBertModel.from_pretrained('YituTech/conv-bert-base' ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase , __lowerCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs_for_common() __lowerCAmelCase : Optional[Any] = True __lowerCAmelCase : List[Any] = getattr(self.model_tester , 'decoder_seq_length' , self.model_tester.seq_length ) __lowerCAmelCase : str = getattr(self.model_tester , 'encoder_seq_length' , self.model_tester.seq_length ) __lowerCAmelCase : Tuple = getattr(self.model_tester , 'key_length' , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = getattr(self.model_tester , 'key_length' , _SCREAMING_SNAKE_CASE ) def check_decoder_attentions_output(_SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Union[str, Any] = len(_SCREAMING_SNAKE_CASE ) self.assertEqual(out_len % 2 , 0 ) __lowerCAmelCase : Optional[Any] = outputs.decoder_attentions self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , 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(_SCREAMING_SNAKE_CASE ): __lowerCAmelCase : str = [ t.numpy() for t in (outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions) ] self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , 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: __lowerCAmelCase : List[str] = True __lowerCAmelCase : Optional[int] = False __lowerCAmelCase : List[Any] = model_class(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = model(self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) __lowerCAmelCase : Tuple = len(_SCREAMING_SNAKE_CASE ) self.assertEqual(config.output_hidden_states , _SCREAMING_SNAKE_CASE ) check_encoder_attentions_output(_SCREAMING_SNAKE_CASE ) if self.is_encoder_decoder: __lowerCAmelCase : Any = model_class(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = model(self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) self.assertEqual(config.output_hidden_states , _SCREAMING_SNAKE_CASE ) check_decoder_attentions_output(_SCREAMING_SNAKE_CASE ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] __lowerCAmelCase : Optional[Any] = True __lowerCAmelCase : str = model_class(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = model(self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) self.assertEqual(config.output_hidden_states , _SCREAMING_SNAKE_CASE ) check_encoder_attentions_output(_SCREAMING_SNAKE_CASE ) # Check attention is always last and order is fine __lowerCAmelCase : Dict = True __lowerCAmelCase : Optional[Any] = True __lowerCAmelCase : List[Any] = model_class(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = model(self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(_SCREAMING_SNAKE_CASE ) ) self.assertEqual(model.config.output_hidden_states , _SCREAMING_SNAKE_CASE ) check_encoder_attentions_output(_SCREAMING_SNAKE_CASE ) @require_tf class A__ ( unittest.TestCase): @slow def __lowerCamelCase ( self ): __lowerCAmelCase : Dict = TFConvBertModel.from_pretrained('YituTech/conv-bert-base' ) __lowerCAmelCase : int = tf.constant([[0, 1, 2, 3, 4, 5]] ) __lowerCAmelCase : Tuple = model(_SCREAMING_SNAKE_CASE )[0] __lowerCAmelCase : Tuple = [1, 6, 7_68] self.assertEqual(output.shape , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = tf.constant( [ [ [-0.0347_5493, -0.468_6034, -0.3063_8832], [0.2263_7248, -0.2698_8646, -0.742_3424], [0.1032_4868, -0.4501_3508, -0.5828_0784], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 )
86
0
import gc import unittest from diffusers import FlaxStableDiffusionInpaintPipeline from diffusers.utils import is_flax_available, load_image, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard @slow @require_flax class _a ( unittest.TestCase ): def lowerCamelCase_ ( self: Optional[int] ) -> Dict: """simple docstring""" super().tearDown() gc.collect() def lowerCamelCase_ ( self: List[str] ) -> Union[str, Any]: """simple docstring""" lowercase__ = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/sd2-inpaint/init_image.png''' ) lowercase__ = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png''' ) lowercase__ = '''xvjiarui/stable-diffusion-2-inpainting''' lowercase__ , lowercase__ = FlaxStableDiffusionInpaintPipeline.from_pretrained(UpperCamelCase_ , safety_checker=UpperCamelCase_ ) lowercase__ = '''Face of a yellow cat, high resolution, sitting on a park bench''' lowercase__ = jax.random.PRNGKey(0 ) lowercase__ = 50 lowercase__ = jax.device_count() lowercase__ = num_samples * [prompt] lowercase__ = num_samples * [init_image] lowercase__ = num_samples * [mask_image] lowercase__ , lowercase__ , lowercase__ = pipeline.prepare_inputs(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) # shard inputs and rng lowercase__ = replicate(UpperCamelCase_ ) lowercase__ = jax.random.split(UpperCamelCase_ , jax.device_count() ) lowercase__ = shard(UpperCamelCase_ ) lowercase__ = shard(UpperCamelCase_ ) lowercase__ = shard(UpperCamelCase_ ) lowercase__ = pipeline( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , jit=UpperCamelCase_ ) lowercase__ = output.images.reshape(UpperCamelCase_ , 512 , 512 , 3 ) lowercase__ = images[0, 253:256, 253:256, -1] lowercase__ = jnp.asarray(jax.device_get(image_slice.flatten() ) ) lowercase__ = jnp.array( [0.3611307, 0.37649736, 0.3757408, 0.38213953, 0.39295167, 0.3841631, 0.41554978, 0.4137475, 0.4217084] ) print(f'output_slice: {output_slice}' ) assert jnp.abs(output_slice - expected_slice ).max() < 1E-2
110
"""simple docstring""" 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 DetrImageProcessor class A__ ( unittest.TestCase): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=30 , _SCREAMING_SNAKE_CASE=4_00 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=1 / 2_55 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , _SCREAMING_SNAKE_CASE=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __lowerCAmelCase : Any = size if size is not None else {'shortest_edge': 18, 'longest_edge': 13_33} __lowerCAmelCase : Optional[int] = parent __lowerCAmelCase : int = batch_size __lowerCAmelCase : str = num_channels __lowerCAmelCase : Optional[int] = min_resolution __lowerCAmelCase : List[Any] = max_resolution __lowerCAmelCase : Union[str, Any] = do_resize __lowerCAmelCase : Optional[Any] = size __lowerCAmelCase : Dict = do_rescale __lowerCAmelCase : Optional[Any] = rescale_factor __lowerCAmelCase : Any = do_normalize __lowerCAmelCase : List[str] = image_mean __lowerCAmelCase : Union[str, Any] = image_std __lowerCAmelCase : Optional[int] = do_pad def __lowerCamelCase ( self ): return { "do_resize": self.do_resize, "size": self.size, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_pad": self.do_pad, } def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ): if not batched: __lowerCAmelCase : str = image_inputs[0] if isinstance(_SCREAMING_SNAKE_CASE , Image.Image ): __lowerCAmelCase , __lowerCAmelCase : Optional[int] = image.size else: __lowerCAmelCase , __lowerCAmelCase : Union[str, Any] = image.shape[1], image.shape[2] if w < h: __lowerCAmelCase : str = int(self.size['shortest_edge'] * h / w ) __lowerCAmelCase : Optional[int] = self.size['shortest_edge'] elif w > h: __lowerCAmelCase : str = self.size['shortest_edge'] __lowerCAmelCase : Union[str, Any] = int(self.size['shortest_edge'] * w / h ) else: __lowerCAmelCase : str = self.size['shortest_edge'] __lowerCAmelCase : Optional[Any] = self.size['shortest_edge'] else: __lowerCAmelCase : str = [] for image in image_inputs: __lowerCAmelCase , __lowerCAmelCase : List[Any] = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __lowerCAmelCase : Any = max(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : item[0] )[0] __lowerCAmelCase : Dict = max(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class A__ ( _lowerCamelCase , unittest.TestCase): A_ : List[str] = DetrImageProcessor if is_vision_available() else None def __lowerCamelCase ( self ): __lowerCAmelCase : List[Any] = DetrImageProcessingTester(self ) @property def __lowerCamelCase ( self ): return self.image_processor_tester.prepare_image_processor_dict() def __lowerCamelCase ( self ): __lowerCAmelCase : Dict = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'image_mean' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'image_std' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_normalize' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_rescale' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'rescale_factor' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_resize' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'size' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_pad' ) ) def __lowerCamelCase ( self ): __lowerCAmelCase : Optional[Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'shortest_edge': 18, 'longest_edge': 13_33} ) self.assertEqual(image_processor.do_pad , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=_SCREAMING_SNAKE_CASE ) self.assertEqual(image_processor.size , {'shortest_edge': 42, 'longest_edge': 84} ) self.assertEqual(image_processor.do_pad , _SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): pass def __lowerCamelCase ( self ): # Initialize image_processing __lowerCAmelCase : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __lowerCAmelCase : str = 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 __lowerCAmelCase : int = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values __lowerCAmelCase , __lowerCAmelCase : List[Any] = self.image_processor_tester.get_expected_values(_SCREAMING_SNAKE_CASE ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __lowerCAmelCase , __lowerCAmelCase : int = self.image_processor_tester.get_expected_values(_SCREAMING_SNAKE_CASE , batched=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Union[str, Any] = image_processing(_SCREAMING_SNAKE_CASE , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __lowerCamelCase ( self ): # Initialize image_processing __lowerCAmelCase : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __lowerCAmelCase : str = 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 __lowerCAmelCase : Tuple = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values __lowerCAmelCase , __lowerCAmelCase : Tuple = self.image_processor_tester.get_expected_values(_SCREAMING_SNAKE_CASE ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __lowerCAmelCase : Union[str, Any] = image_processing(_SCREAMING_SNAKE_CASE , return_tensors='pt' ).pixel_values __lowerCAmelCase , __lowerCAmelCase : List[Any] = self.image_processor_tester.get_expected_values(_SCREAMING_SNAKE_CASE , batched=_SCREAMING_SNAKE_CASE ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __lowerCamelCase ( self ): # Initialize image_processing __lowerCAmelCase : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __lowerCAmelCase : int = 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 __lowerCAmelCase : Any = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values __lowerCAmelCase , __lowerCAmelCase : Dict = self.image_processor_tester.get_expected_values(_SCREAMING_SNAKE_CASE ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __lowerCAmelCase : Tuple = image_processing(_SCREAMING_SNAKE_CASE , return_tensors='pt' ).pixel_values __lowerCAmelCase , __lowerCAmelCase : Any = self.image_processor_tester.get_expected_values(_SCREAMING_SNAKE_CASE , batched=_SCREAMING_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 __lowerCamelCase ( self ): # prepare image and target __lowerCAmelCase : Union[str, Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' , 'r' ) as f: __lowerCAmelCase : Any = json.loads(f.read() ) __lowerCAmelCase : Tuple = {'image_id': 3_97_69, 'annotations': target} # encode them __lowerCAmelCase : Dict = DetrImageProcessor.from_pretrained('facebook/detr-resnet-50' ) __lowerCAmelCase : int = image_processing(images=_SCREAMING_SNAKE_CASE , annotations=_SCREAMING_SNAKE_CASE , return_tensors='pt' ) # verify pixel values __lowerCAmelCase : str = torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding['pixel_values'].shape , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : int = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 ) ) # verify area __lowerCAmelCase : List[str] = torch.tensor([5887.9600, 1_1250.2061, 48_9353.8438, 83_7122.7500, 14_7967.5156, 16_5732.3438] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , _SCREAMING_SNAKE_CASE ) ) # verify boxes __lowerCAmelCase : Tuple = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : str = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , _SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # verify image_id __lowerCAmelCase : Dict = torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , _SCREAMING_SNAKE_CASE ) ) # verify is_crowd __lowerCAmelCase : Optional[int] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , _SCREAMING_SNAKE_CASE ) ) # verify class_labels __lowerCAmelCase : Union[str, Any] = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , _SCREAMING_SNAKE_CASE ) ) # verify orig_size __lowerCAmelCase : int = torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , _SCREAMING_SNAKE_CASE ) ) # verify size __lowerCAmelCase : List[Any] = torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , _SCREAMING_SNAKE_CASE ) ) @slow def __lowerCamelCase ( self ): # prepare image, target and masks_path __lowerCAmelCase : Optional[int] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' , 'r' ) as f: __lowerCAmelCase : Optional[int] = json.loads(f.read() ) __lowerCAmelCase : Optional[int] = {'file_name': '000000039769.png', 'image_id': 3_97_69, 'segments_info': target} __lowerCAmelCase : Union[str, Any] = pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic' ) # encode them __lowerCAmelCase : Optional[int] = DetrImageProcessor.from_pretrained('facebook/detr-resnet-50-panoptic' ) __lowerCAmelCase : Optional[Any] = image_processing(images=_SCREAMING_SNAKE_CASE , annotations=_SCREAMING_SNAKE_CASE , masks_path=_SCREAMING_SNAKE_CASE , return_tensors='pt' ) # verify pixel values __lowerCAmelCase : str = torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding['pixel_values'].shape , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 ) ) # verify area __lowerCAmelCase : int = torch.tensor([14_7979.6875, 16_5527.0469, 48_4638.5938, 1_1292.9375, 5879.6562, 7634.1147] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , _SCREAMING_SNAKE_CASE ) ) # verify boxes __lowerCAmelCase : Optional[int] = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , _SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # verify image_id __lowerCAmelCase : str = torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , _SCREAMING_SNAKE_CASE ) ) # verify is_crowd __lowerCAmelCase : Optional[int] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , _SCREAMING_SNAKE_CASE ) ) # verify class_labels __lowerCAmelCase : str = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , _SCREAMING_SNAKE_CASE ) ) # verify masks __lowerCAmelCase : Dict = 82_28_73 self.assertEqual(encoding['labels'][0]['masks'].sum().item() , _SCREAMING_SNAKE_CASE ) # verify orig_size __lowerCAmelCase : str = torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , _SCREAMING_SNAKE_CASE ) ) # verify size __lowerCAmelCase : List[Any] = torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , _SCREAMING_SNAKE_CASE ) )
86
0
from manim import * class __lowercase (_lowerCamelCase ): def UpperCamelCase__ ( self ) ->Union[str, Any]: '''simple docstring''' __lowerCAmelCase : Optional[int] = Rectangle(height=0.5 , width=0.5 ) __lowerCAmelCase : str = Rectangle(height=0.25 , width=0.25 ) __lowerCAmelCase : List[Any] = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 ) __lowerCAmelCase : Optional[int] = [mem.copy() for i in range(6 )] __lowerCAmelCase : Optional[int] = [mem.copy() for i in range(6 )] __lowerCAmelCase : List[Any] = VGroup(*_SCREAMING_SNAKE_CASE ).arrange(_SCREAMING_SNAKE_CASE , buff=0 ) __lowerCAmelCase : str = VGroup(*_SCREAMING_SNAKE_CASE ).arrange(_SCREAMING_SNAKE_CASE , buff=0 ) __lowerCAmelCase : str = VGroup(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).arrange(_SCREAMING_SNAKE_CASE , buff=0 ) __lowerCAmelCase : int = Text('''CPU''' , font_size=24 ) __lowerCAmelCase : Optional[int] = Group(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).arrange(_SCREAMING_SNAKE_CASE , buff=0.5 , aligned_edge=_SCREAMING_SNAKE_CASE ) cpu.move_to([-2.5, -0.5, 0] ) self.add(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = [mem.copy() for i in range(4 )] __lowerCAmelCase : Dict = VGroup(*_SCREAMING_SNAKE_CASE ).arrange(_SCREAMING_SNAKE_CASE , buff=0 ) __lowerCAmelCase : int = Text('''GPU''' , font_size=24 ) __lowerCAmelCase : int = Group(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).arrange(_SCREAMING_SNAKE_CASE , buff=0.5 , aligned_edge=_SCREAMING_SNAKE_CASE ) gpu.move_to([-1, -1, 0] ) self.add(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = [mem.copy() for i in range(6 )] __lowerCAmelCase : Optional[Any] = VGroup(*_SCREAMING_SNAKE_CASE ).arrange(_SCREAMING_SNAKE_CASE , buff=0 ) __lowerCAmelCase : str = Text('''Model''' , font_size=24 ) __lowerCAmelCase : List[str] = Group(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).arrange(_SCREAMING_SNAKE_CASE , buff=0.5 , aligned_edge=_SCREAMING_SNAKE_CASE ) model.move_to([3, -1.0, 0] ) self.add(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : str = [] __lowerCAmelCase : Dict = [] __lowerCAmelCase : List[str] = [] for i, rect in enumerate(_SCREAMING_SNAKE_CASE ): rect.set_stroke(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = Rectangle(height=0.46 / 4 , width=0.46 / 3 ).set_stroke(width=0.0 ).set_fill(_SCREAMING_SNAKE_CASE , opacity=0.7 ) if i == 0: cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.02 , direction=_SCREAMING_SNAKE_CASE ) cpu_target.set_x(cpu_target.get_x() + 0.1 ) elif i == 3: cpu_target.next_to(model_cpu_arr[0] , direction=_SCREAMING_SNAKE_CASE , buff=0.0 ) else: cpu_target.next_to(model_cpu_arr[i - 1] , direction=_SCREAMING_SNAKE_CASE , buff=0.0 ) self.add(_SCREAMING_SNAKE_CASE ) model_cpu_arr.append(_SCREAMING_SNAKE_CASE ) self.add(*_SCREAMING_SNAKE_CASE , *_SCREAMING_SNAKE_CASE , *_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : int = [mem.copy() for i in range(6 )] __lowerCAmelCase : Union[str, Any] = VGroup(*_SCREAMING_SNAKE_CASE ).arrange(_SCREAMING_SNAKE_CASE , buff=0 ) __lowerCAmelCase : Optional[int] = Text('''Loaded Checkpoint''' , font_size=24 ) __lowerCAmelCase : Union[str, Any] = Group(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).arrange(_SCREAMING_SNAKE_CASE , buff=0.5 , aligned_edge=_SCREAMING_SNAKE_CASE ) checkpoint.move_to([3, 0.5, 0] ) self.add(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Any = [] __lowerCAmelCase : Optional[int] = [] for i, rect in enumerate(_SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Any = fill.copy().set_fill(_SCREAMING_SNAKE_CASE , opacity=0.7 ) target.move_to(_SCREAMING_SNAKE_CASE ) ckpt_arr.append(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = target.copy() if i < 5: cpu_target.move_to(cpu_left_col_base[i + 1] ) else: cpu_target.move_to(cpu_right_col_base[i - 5] ) ckpt_cpu_arr.append(_SCREAMING_SNAKE_CASE ) self.add(*_SCREAMING_SNAKE_CASE , *_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : str = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) __lowerCAmelCase : Optional[int] = MarkupText( f"""<b>Key:</b>\n\n<span fgcolor='{YELLOW}'>●</span> Empty Model""" , font_size=18 , ) key_text.move_to([-5, 2.4, 0] ) self.add(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = MarkupText( f"""<span fgcolor='{BLUE}'>●</span> Checkpoint""" , font_size=18 , ) blue_text.next_to(_SCREAMING_SNAKE_CASE , DOWN * 2.4 , aligned_edge=key_text.get_left() ) self.add(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : int = MarkupText( f"""Based on the passed in configuration, weights are stored in\na variety of np.memmaps on disk or to a particular device.""" , font_size=24 , ) step_a.move_to([2, 2, 0] ) __lowerCAmelCase : List[Any] = [meta_mem.copy() for i in range(6 )] __lowerCAmelCase : Any = [meta_mem.copy() for i in range(6 )] __lowerCAmelCase : Any = VGroup(*_SCREAMING_SNAKE_CASE ).arrange(_SCREAMING_SNAKE_CASE , buff=0 ) __lowerCAmelCase : Optional[int] = VGroup(*_SCREAMING_SNAKE_CASE ).arrange(_SCREAMING_SNAKE_CASE , buff=0 ) __lowerCAmelCase : Optional[Any] = VGroup(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).arrange(_SCREAMING_SNAKE_CASE , buff=0 ) __lowerCAmelCase : List[Any] = Text('''Disk''' , font_size=24 ) __lowerCAmelCase : Optional[Any] = Group(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).arrange(_SCREAMING_SNAKE_CASE , buff=0.5 , aligned_edge=_SCREAMING_SNAKE_CASE ) disk.move_to([-4.0, -1.25, 0] ) self.play(Write(_SCREAMING_SNAKE_CASE , run_time=3 ) , Write(_SCREAMING_SNAKE_CASE , run_time=1 ) , Create(_SCREAMING_SNAKE_CASE , run_time=1 ) ) __lowerCAmelCase : List[Any] = [] for i, rect in enumerate(_SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Union[str, Any] = rect.copy() target.generate_target() target.target.move_to(disk_left_col_base[i] ).scale(0.5 ) animations.append(MoveToTarget(_SCREAMING_SNAKE_CASE , run_time=1.5 ) ) self.play(*_SCREAMING_SNAKE_CASE ) self.play(FadeOut(_SCREAMING_SNAKE_CASE ) ) __lowerCAmelCase : Union[str, Any] = MarkupText(f"""Then, the checkpoint is removed from memory\nthrough garbage collection.""" , font_size=24 ) step_a.move_to([2, 2, 0] ) self.play(Write(_SCREAMING_SNAKE_CASE , run_time=3 ) ) self.play( FadeOut(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , *_SCREAMING_SNAKE_CASE , *_SCREAMING_SNAKE_CASE ) , ) self.wait()
275
"""simple docstring""" import numpy as np def __lowerCAmelCase (_UpperCamelCase ): return 1 / (1 + np.exp(-vector )) def __lowerCAmelCase (_UpperCamelCase ): return vector * sigmoid(_UpperCamelCase ) if __name__ == "__main__": import doctest doctest.testmod()
86
0
import argparse import torch from transformers import YosoConfig, YosoForMaskedLM def _A ( SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" if "model" in orig_key: a__ : str =orig_key.replace("model." , "" ) if "norm1" in orig_key: a__ : List[str] =orig_key.replace("norm1" , "attention.output.LayerNorm" ) if "norm2" in orig_key: a__ : Tuple =orig_key.replace("norm2" , "output.LayerNorm" ) if "norm" in orig_key: a__ : Tuple =orig_key.replace("norm" , "LayerNorm" ) if "transformer" in orig_key: a__ : Dict =orig_key.split("." )[0].split("_" )[-1] a__ : Any =orig_key.replace(f'''transformer_{layer_num}''' , f'''encoder.layer.{layer_num}''' ) if "mha.attn" in orig_key: a__ : Union[str, Any] =orig_key.replace("mha.attn" , "attention.self" ) if "mha" in orig_key: a__ : Tuple =orig_key.replace("mha" , "attention" ) if "W_q" in orig_key: a__ : Union[str, Any] =orig_key.replace("W_q" , "self.query" ) if "W_k" in orig_key: a__ : Union[str, Any] =orig_key.replace("W_k" , "self.key" ) if "W_v" in orig_key: a__ : List[str] =orig_key.replace("W_v" , "self.value" ) if "ff1" in orig_key: a__ : Any =orig_key.replace("ff1" , "intermediate.dense" ) if "ff2" in orig_key: a__ : List[Any] =orig_key.replace("ff2" , "output.dense" ) if "ff" in orig_key: a__ : Any =orig_key.replace("ff" , "output.dense" ) if "mlm_class" in orig_key: a__ : Dict =orig_key.replace("mlm.mlm_class" , "cls.predictions.decoder" ) if "mlm" in orig_key: a__ : Optional[Any] =orig_key.replace("mlm" , "cls.predictions.transform" ) if "cls" not in orig_key: a__ : str ='yoso.' + orig_key return orig_key def _A ( SCREAMING_SNAKE_CASE : Tuple , SCREAMING_SNAKE_CASE : Any ): """simple docstring""" for key in orig_state_dict.copy().keys(): a__ : Optional[Any] =orig_state_dict.pop(_UpperCamelCase ) if ("pooler" in key) or ("sen_class" in key): continue else: a__ : Tuple =val a__ : Tuple =orig_state_dict['cls.predictions.decoder.bias'] a__ : List[Any] =torch.arange(_UpperCamelCase ).expand((1, -1) ) + 2 return orig_state_dict def _A ( SCREAMING_SNAKE_CASE : Union[str, Any] , SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" a__ : int =torch.load(_UpperCamelCase , map_location="cpu" )['model_state_dict'] a__ : List[str] =YosoConfig.from_json_file(_UpperCamelCase ) a__ : Optional[Any] =YosoForMaskedLM(_UpperCamelCase ) a__ : Optional[int] =convert_checkpoint_helper(config.max_position_embeddings , _UpperCamelCase ) print(model.load_state_dict(_UpperCamelCase ) ) model.eval() model.save_pretrained(_UpperCamelCase ) print(f'''Checkpoint successfuly converted. Model saved at {pytorch_dump_path}''' ) if __name__ == "__main__": UpperCAmelCase : Any = argparse.ArgumentParser() # Required parameters parser.add_argument( """--pytorch_model_path""", default=None, type=str, required=True, help="""Path to YOSO pytorch checkpoint.""" ) parser.add_argument( """--config_file""", default=None, type=str, required=True, help="""The json file for YOSO model config.""", ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) UpperCAmelCase : Optional[Any] = parser.parse_args() convert_yoso_checkpoint(args.pytorch_model_path, args.config_file, args.pytorch_dump_path)
95
"""simple docstring""" import unittest from transformers import MobileBertConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, MobileBertForMaskedLM, MobileBertForMultipleChoice, MobileBertForNextSentencePrediction, MobileBertForPreTraining, MobileBertForQuestionAnswering, MobileBertForSequenceClassification, MobileBertForTokenClassification, MobileBertModel, ) class A__ : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=13 , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=99 , _SCREAMING_SNAKE_CASE=64 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=37 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=5_12 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=None , ): __lowerCAmelCase : Optional[int] = parent __lowerCAmelCase : Union[str, Any] = batch_size __lowerCAmelCase : Dict = seq_length __lowerCAmelCase : Dict = is_training __lowerCAmelCase : List[str] = use_input_mask __lowerCAmelCase : int = use_token_type_ids __lowerCAmelCase : Optional[int] = use_labels __lowerCAmelCase : List[Any] = vocab_size __lowerCAmelCase : Dict = hidden_size __lowerCAmelCase : Tuple = embedding_size __lowerCAmelCase : List[Any] = num_hidden_layers __lowerCAmelCase : Tuple = num_attention_heads __lowerCAmelCase : Union[str, Any] = intermediate_size __lowerCAmelCase : Optional[Any] = hidden_act __lowerCAmelCase : Optional[int] = hidden_dropout_prob __lowerCAmelCase : Dict = attention_probs_dropout_prob __lowerCAmelCase : Any = max_position_embeddings __lowerCAmelCase : Any = type_vocab_size __lowerCAmelCase : Union[str, Any] = type_sequence_label_size __lowerCAmelCase : List[str] = initializer_range __lowerCAmelCase : str = num_labels __lowerCAmelCase : int = num_choices __lowerCAmelCase : Union[str, Any] = scope def __lowerCamelCase ( self ): __lowerCAmelCase : Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __lowerCAmelCase : Optional[int] = None if self.use_input_mask: __lowerCAmelCase : Optional[int] = random_attention_mask([self.batch_size, self.seq_length] ) __lowerCAmelCase : str = None if self.use_token_type_ids: __lowerCAmelCase : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __lowerCAmelCase : Union[str, Any] = None __lowerCAmelCase : Optional[int] = None __lowerCAmelCase : Union[str, Any] = None if self.use_labels: __lowerCAmelCase : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCAmelCase : Dict = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __lowerCAmelCase : Dict = ids_tensor([self.batch_size] , self.num_choices ) __lowerCAmelCase : str = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowerCamelCase ( self ): return MobileBertConfig( 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 , embedding_size=self.embedding_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=_SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : str = MobileBertModel(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() __lowerCAmelCase : Optional[Any] = model(_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = model(_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : int = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Union[str, Any] = MobileBertForMaskedLM(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() __lowerCAmelCase : Any = model(_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Optional[Any] = MobileBertForNextSentencePrediction(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() __lowerCAmelCase : Dict = model( _SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : List[Any] = MobileBertForPreTraining(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() __lowerCAmelCase : List[Any] = model( _SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE , next_sentence_label=_SCREAMING_SNAKE_CASE , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Optional[int] = MobileBertForQuestionAnswering(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() __lowerCAmelCase : List[str] = model( _SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_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 __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Optional[int] = self.num_labels __lowerCAmelCase : Tuple = MobileBertForSequenceClassification(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() __lowerCAmelCase : str = model(_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Optional[Any] = self.num_labels __lowerCAmelCase : int = MobileBertForTokenClassification(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() __lowerCAmelCase : Optional[Any] = model(_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Optional[int] = self.num_choices __lowerCAmelCase : List[str] = MobileBertForMultipleChoice(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() __lowerCAmelCase : str = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __lowerCAmelCase : List[Any] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __lowerCAmelCase : List[Any] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __lowerCAmelCase : List[str] = model( _SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __lowerCamelCase ( self ): __lowerCAmelCase : Optional[Any] = self.prepare_config_and_inputs() ( ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ) : Optional[Any] = config_and_inputs __lowerCAmelCase : List[str] = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class A__ ( _lowerCamelCase , _lowerCamelCase , unittest.TestCase): A_ : str = ( ( MobileBertModel, MobileBertForMaskedLM, MobileBertForMultipleChoice, MobileBertForNextSentencePrediction, MobileBertForPreTraining, MobileBertForQuestionAnswering, MobileBertForSequenceClassification, MobileBertForTokenClassification, ) if is_torch_available() else () ) A_ : List[str] = ( { 'feature-extraction': MobileBertModel, 'fill-mask': MobileBertForMaskedLM, 'question-answering': MobileBertForQuestionAnswering, 'text-classification': MobileBertForSequenceClassification, 'token-classification': MobileBertForTokenClassification, 'zero-shot': MobileBertForSequenceClassification, } if is_torch_available() else {} ) A_ : Dict = True def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ): __lowerCAmelCase : List[str] = super()._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) if return_labels: if model_class in get_values(_SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Tuple = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=_SCREAMING_SNAKE_CASE ) return inputs_dict def __lowerCamelCase ( self ): __lowerCAmelCase : Optional[Any] = MobileBertModelTester(self ) __lowerCAmelCase : str = ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , hidden_size=37 ) def __lowerCamelCase ( self ): self.config_tester.run_common_tests() def __lowerCamelCase ( self ): __lowerCAmelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_model(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_masked_lm(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_multiple_choice(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_next_sequence_prediction(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_pretraining(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_question_answering(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_sequence_classification(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_token_classification(*_SCREAMING_SNAKE_CASE ) def __lowerCAmelCase (_UpperCamelCase ): return torch.tensor( _UpperCamelCase , dtype=torch.long , device=_UpperCamelCase , ) lowerCamelCase__ = 1E-3 @require_torch @require_sentencepiece @require_tokenizers class A__ ( unittest.TestCase): @slow def __lowerCamelCase ( self ): __lowerCAmelCase : Union[str, Any] = MobileBertModel.from_pretrained('google/mobilebert-uncased' ).to(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = _long_tensor([[1_01, 71_10, 10_05, 10_56, 20_23, 1_13_33, 1_74_13, 10_29, 1_02]] ) with torch.no_grad(): __lowerCAmelCase : int = model(_SCREAMING_SNAKE_CASE )[0] __lowerCAmelCase : Dict = torch.Size((1, 9, 5_12) ) self.assertEqual(output.shape , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = torch.tensor( [ [ [-2.4_73_65_26E07, 8.2_69_16_56E04, 1.6_52_18_38E05], [-5.7_54_17_04E-01, 3.9_05_60_22E00, 4.4_01_15_07E00], [2.6_04_73_59E00, 1.5_67_76_52E00, -1.7_32_41_88E-01], ] ] , device=_SCREAMING_SNAKE_CASE , ) # MobileBERT results range from 10e0 to 10e8. Even a 0.0000001% difference with a value of 10e8 results in a # ~1 difference, it's therefore not a good idea to measure using addition. # Here, we instead divide the expected result with the result in order to obtain ~1. We then check that the # result is held between bounds: 1 - TOLERANCE < expected_result / result < 1 + TOLERANCE __lowerCAmelCase : Tuple = torch.all((expected_slice / output[..., :3, :3]) >= 1 - TOLERANCE ) __lowerCAmelCase : Union[str, Any] = torch.all((expected_slice / output[..., :3, :3]) <= 1 + TOLERANCE ) self.assertTrue(lower_bound and upper_bound )
86
0
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import KandinskyPipeline, KandinskyPriorPipeline else: from .pipeline_kandinsky import KandinskyPipeline from .pipeline_kandinsky_imgaimg import KandinskyImgaImgPipeline from .pipeline_kandinsky_inpaint import KandinskyInpaintPipeline from .pipeline_kandinsky_prior import KandinskyPriorPipeline, KandinskyPriorPipelineOutput from .text_encoder import MultilingualCLIP
329
"""simple docstring""" import re import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class A__ ( _lowerCamelCase): A_ : Any = ['image_processor', 'tokenizer'] A_ : Optional[Any] = 'AutoImageProcessor' A_ : str = 'AutoTokenizer' def __init__( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Union[str, Any] = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , _SCREAMING_SNAKE_CASE , ) __lowerCAmelCase : Any = kwargs.pop('feature_extractor' ) __lowerCAmelCase : str = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.' ) if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.' ) super().__init__(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Any = self.image_processor __lowerCAmelCase : Tuple = False def __call__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = kwargs.pop('images' , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Any = kwargs.pop('text' , _SCREAMING_SNAKE_CASE ) if len(_SCREAMING_SNAKE_CASE ) > 0: __lowerCAmelCase : Dict = args[0] __lowerCAmelCase : Union[str, Any] = args[1:] if images is None and text is None: raise ValueError('You need to specify either an `images` or `text` input to process.' ) if images is not None: __lowerCAmelCase : Union[str, Any] = self.image_processor(_SCREAMING_SNAKE_CASE , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) if text is not None: __lowerCAmelCase : Dict = self.tokenizer(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) if text is None: return inputs elif images is None: return encodings else: __lowerCAmelCase : Union[str, Any] = encodings['input_ids'] return inputs def __lowerCamelCase ( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ): return self.tokenizer.batch_decode(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ): return self.tokenizer.decode(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @contextmanager def __lowerCamelCase ( self ): 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 images inputs, or in a separate call.' ) __lowerCAmelCase : Any = True __lowerCAmelCase : Dict = self.tokenizer yield __lowerCAmelCase : Optional[int] = self.image_processor __lowerCAmelCase : Optional[Any] = False def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=None ): if added_vocab is None: __lowerCAmelCase : str = self.tokenizer.get_added_vocab() __lowerCAmelCase : List[Any] = {} while tokens: __lowerCAmelCase : int = re.search(R'<s_(.*?)>' , _SCREAMING_SNAKE_CASE , re.IGNORECASE ) if start_token is None: break __lowerCAmelCase : Union[str, Any] = start_token.group(1 ) __lowerCAmelCase : Tuple = re.search(Rf"</s_{key}>" , _SCREAMING_SNAKE_CASE , re.IGNORECASE ) __lowerCAmelCase : str = start_token.group() if end_token is None: __lowerCAmelCase : Optional[int] = tokens.replace(_SCREAMING_SNAKE_CASE , '' ) else: __lowerCAmelCase : Optional[Any] = end_token.group() __lowerCAmelCase : Tuple = re.escape(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Tuple = re.escape(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = re.search(f"{start_token_escaped}(.*?){end_token_escaped}" , _SCREAMING_SNAKE_CASE , re.IGNORECASE ) if content is not None: __lowerCAmelCase : List[str] = content.group(1 ).strip() if r"<s_" in content and r"</s_" in content: # non-leaf node __lowerCAmelCase : int = self.tokenajson(_SCREAMING_SNAKE_CASE , is_inner_value=_SCREAMING_SNAKE_CASE , added_vocab=_SCREAMING_SNAKE_CASE ) if value: if len(_SCREAMING_SNAKE_CASE ) == 1: __lowerCAmelCase : Tuple = value[0] __lowerCAmelCase : Tuple = value else: # leaf nodes __lowerCAmelCase : Any = [] for leaf in content.split(R'<sep/>' ): __lowerCAmelCase : List[Any] = leaf.strip() if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>": __lowerCAmelCase : Dict = leaf[1:-2] # for categorical special tokens output[key].append(_SCREAMING_SNAKE_CASE ) if len(output[key] ) == 1: __lowerCAmelCase : str = output[key][0] __lowerCAmelCase : Dict = tokens[tokens.find(_SCREAMING_SNAKE_CASE ) + len(_SCREAMING_SNAKE_CASE ) :].strip() if tokens[:6] == r"<sep/>": # non-leaf nodes return [output] + self.tokenajson(tokens[6:] , is_inner_value=_SCREAMING_SNAKE_CASE , added_vocab=_SCREAMING_SNAKE_CASE ) if len(_SCREAMING_SNAKE_CASE ): return [output] if is_inner_value else output else: return [] if is_inner_value else {"text_sequence": tokens} @property def __lowerCamelCase ( self ): warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , _SCREAMING_SNAKE_CASE , ) return self.image_processor_class @property def __lowerCamelCase ( self ): warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , _SCREAMING_SNAKE_CASE , ) return self.image_processor
86
0
"""simple docstring""" import functools from typing import Any def _A ( UpperCamelCase_ : Dict, UpperCamelCase_ : str) -> Optional[Any]: '''simple docstring''' if not isinstance(_UpperCamelCase, _UpperCamelCase) or len(_UpperCamelCase) == 0: raise ValueError("the string should be not empty string") if not isinstance(_UpperCamelCase, _UpperCamelCase) or not all( isinstance(_UpperCamelCase, _UpperCamelCase) and len(_UpperCamelCase) > 0 for item in words): raise ValueError("the words should be a list of non-empty strings") # Build trie __lowercase = {} __lowercase = 'WORD_KEEPER' for word in words: __lowercase = trie for c in word: if c not in trie_node: __lowercase = {} __lowercase = trie_node[c] __lowercase = True __lowercase = len(_UpperCamelCase) # Dynamic programming method @functools.cache def is_breakable(UpperCamelCase_ : Optional[Any]) -> bool: if index == len_string: return True __lowercase = trie for i in range(_UpperCamelCase, _UpperCamelCase): __lowercase = trie_node.get(string[i], _UpperCamelCase) if trie_node is None: return False if trie_node.get(_UpperCamelCase, _UpperCamelCase) and is_breakable(i + 1): return True return False return is_breakable(0) if __name__ == "__main__": import doctest doctest.testmod()
17
"""simple docstring""" def __lowerCAmelCase (_UpperCamelCase ): __lowerCAmelCase : Tuple = 0 while num > 0: digit_sum += num % 10 num //= 10 return digit_sum def __lowerCAmelCase (_UpperCamelCase = 100 ): __lowerCAmelCase : Optional[int] = 1 __lowerCAmelCase : Optional[Any] = 2 for i in range(2 , max_n + 1 ): __lowerCAmelCase : Any = pre_numerator __lowerCAmelCase : Union[str, Any] = 2 * i // 3 if i % 3 == 0 else 1 __lowerCAmelCase : int = cur_numerator __lowerCAmelCase : Dict = e_cont * pre_numerator + temp return sum_digits(_UpperCamelCase ) if __name__ == "__main__": print(f'{solution() = }')
86
0
"""simple docstring""" from collections import defaultdict class _UpperCAmelCase : def __init__( self : List[Any] , lowercase_ : Dict , lowercase_ : Optional[int] ): snake_case_ : Any = total # total no of tasks (N) # DP table will have a dimension of (2^M)*N # initially all values are set to -1 snake_case_ : Optional[int] = [ [-1 for i in range(total + 1 )] for j in range(2 ** len(_SCREAMING_SNAKE_CASE ) ) ] snake_case_ : int = defaultdict(_SCREAMING_SNAKE_CASE ) # stores the list of persons for each task # final_mask is used to check if all persons are included by setting all bits # to 1 snake_case_ : Dict = (1 << len(_SCREAMING_SNAKE_CASE )) - 1 def _snake_case ( self : int , lowercase_ : List[str] , lowercase_ : Union[str, Any] ): # if mask == self.finalmask all persons are distributed tasks, return 1 if mask == self.final_mask: return 1 # if not everyone gets the task and no more tasks are available, return 0 if task_no > self.total_tasks: return 0 # if case already considered if self.dp[mask][task_no] != -1: return self.dp[mask][task_no] # Number of ways when we don't this task in the arrangement snake_case_ : int = self.count_ways_until(_SCREAMING_SNAKE_CASE , task_no + 1 ) # now assign the tasks one by one to all possible persons and recursively # assign for the remaining tasks. if task_no in self.task: for p in self.task[task_no]: # if p is already given a task if mask & (1 << p): continue # assign this task to p and change the mask value. And recursively # assign tasks with the new mask value. total_ways_util += self.count_ways_until(mask | (1 << p) , task_no + 1 ) # save the value. snake_case_ : Dict = total_ways_util return self.dp[mask][task_no] def _snake_case ( self : Union[str, Any] , lowercase_ : List[Any] ): # Store the list of persons for each task for i in range(len(_SCREAMING_SNAKE_CASE ) ): for j in task_performed[i]: self.task[j].append(_SCREAMING_SNAKE_CASE ) # call the function to fill the DP table, final answer is stored in dp[0][1] return self.count_ways_until(0 , 1 ) if __name__ == "__main__": lowercase__ : Optional[int] = 5 # total no of tasks (the value of N) # the list of tasks that can be done by M persons. lowercase__ : str = [[1, 3, 4], [1, 2, 5], [3, 4]] print( AssignmentUsingBitmask(task_performed, total_tasks).count_no_of_ways( task_performed ) )
264
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { """microsoft/markuplm-base""": """https://huggingface.co/microsoft/markuplm-base/resolve/main/config.json""", """microsoft/markuplm-large""": """https://huggingface.co/microsoft/markuplm-large/resolve/main/config.json""", } class A__ ( _lowerCamelCase): A_ : List[Any] = 'markuplm' def __init__( self , _SCREAMING_SNAKE_CASE=3_05_22 , _SCREAMING_SNAKE_CASE=7_68 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=30_72 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=5_12 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE=1E-12 , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=2_56 , _SCREAMING_SNAKE_CASE=10_24 , _SCREAMING_SNAKE_CASE=2_16 , _SCREAMING_SNAKE_CASE=10_01 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=50 , _SCREAMING_SNAKE_CASE="absolute" , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE , ): super().__init__( pad_token_id=_SCREAMING_SNAKE_CASE , bos_token_id=_SCREAMING_SNAKE_CASE , eos_token_id=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) __lowerCAmelCase : Union[str, Any] = vocab_size __lowerCAmelCase : Any = hidden_size __lowerCAmelCase : List[Any] = num_hidden_layers __lowerCAmelCase : Tuple = num_attention_heads __lowerCAmelCase : Union[str, Any] = hidden_act __lowerCAmelCase : List[Any] = intermediate_size __lowerCAmelCase : List[str] = hidden_dropout_prob __lowerCAmelCase : List[str] = attention_probs_dropout_prob __lowerCAmelCase : Optional[int] = max_position_embeddings __lowerCAmelCase : int = type_vocab_size __lowerCAmelCase : Tuple = initializer_range __lowerCAmelCase : int = layer_norm_eps __lowerCAmelCase : List[str] = position_embedding_type __lowerCAmelCase : List[Any] = use_cache __lowerCAmelCase : Optional[Any] = classifier_dropout # additional properties __lowerCAmelCase : Optional[int] = max_depth __lowerCAmelCase : List[str] = max_xpath_tag_unit_embeddings __lowerCAmelCase : Optional[Any] = max_xpath_subs_unit_embeddings __lowerCAmelCase : Any = tag_pad_id __lowerCAmelCase : Union[str, Any] = subs_pad_id __lowerCAmelCase : int = xpath_unit_hidden_size
86
0
from typing import Optional import pyspark from .. import Features, NamedSplit from ..download import DownloadMode from ..packaged_modules.spark.spark import Spark from .abc import AbstractDatasetReader class __lowerCAmelCase ( _lowerCamelCase ): """simple docstring""" def __init__( self , lowerCamelCase__ , lowerCamelCase__ = None , lowerCamelCase__ = None , lowerCamelCase__ = True , lowerCamelCase__ = None , lowerCamelCase__ = False , lowerCamelCase__ = None , lowerCamelCase__ = True , lowerCamelCase__ = "arrow" , **lowerCamelCase__ , ) -> Optional[int]: '''simple docstring''' super().__init__( split=_SCREAMING_SNAKE_CASE , features=_SCREAMING_SNAKE_CASE , cache_dir=_SCREAMING_SNAKE_CASE , keep_in_memory=_SCREAMING_SNAKE_CASE , streaming=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) __lowerCamelCase = load_from_cache_file __lowerCamelCase = file_format __lowerCamelCase = Spark( df=_SCREAMING_SNAKE_CASE , features=_SCREAMING_SNAKE_CASE , cache_dir=_SCREAMING_SNAKE_CASE , working_dir=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) def lowercase_ ( self ) -> int: '''simple docstring''' if self.streaming: return self.builder.as_streaming_dataset(split=self.split ) __lowerCamelCase = None if self._load_from_cache_file else DownloadMode.FORCE_REDOWNLOAD self.builder.download_and_prepare( download_mode=_SCREAMING_SNAKE_CASE , file_format=self._file_format , ) return self.builder.as_dataset(split=self.split )
90
"""simple docstring""" import argparse import torch # Step 1. clone https://github.com/microsoft/unilm # Step 2. git checkout to https://github.com/microsoft/unilm/commit/b94ec76c36f02fb2b0bf0dcb0b8554a2185173cd # Step 3. cd unilm # Step 4. ln -s $(realpath wavlm/modules.py) ./ # create simlink # import classes from unilm.wavlm.WavLM import WavLM as WavLMOrig from unilm.wavlm.WavLM import WavLMConfig as WavLMConfigOrig from transformers import WavLMConfig, WavLMModel, logging logging.set_verbosity_info() lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { """post_extract_proj""": """feature_projection.projection""", """encoder.pos_conv.0""": """encoder.pos_conv_embed.conv""", """self_attn.k_proj""": """encoder.layers.*.attention.k_proj""", """self_attn.v_proj""": """encoder.layers.*.attention.v_proj""", """self_attn.q_proj""": """encoder.layers.*.attention.q_proj""", """self_attn.out_proj""": """encoder.layers.*.attention.out_proj""", """self_attn.grep_linear""": """encoder.layers.*.attention.gru_rel_pos_linear""", """self_attn.relative_attention_bias""": """encoder.layers.*.attention.rel_attn_embed""", """self_attn.grep_a""": """encoder.layers.*.attention.gru_rel_pos_const""", """self_attn_layer_norm""": """encoder.layers.*.layer_norm""", """fc1""": """encoder.layers.*.feed_forward.intermediate_dense""", """fc2""": """encoder.layers.*.feed_forward.output_dense""", """final_layer_norm""": """encoder.layers.*.final_layer_norm""", """encoder.layer_norm""": """encoder.layer_norm""", """w2v_model.layer_norm""": """feature_projection.layer_norm""", """quantizer.weight_proj""": """quantizer.weight_proj""", """quantizer.vars""": """quantizer.codevectors""", """project_q""": """project_q""", """final_proj""": """project_hid""", """w2v_encoder.proj""": """ctc_proj""", """mask_emb""": """masked_spec_embed""", } lowerCamelCase__ = [ """ctc_proj""", """quantizer.weight_proj""", """quantizer.codevectors""", """project_q""", """project_hid""", ] def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): for attribute in key.split('.' ): __lowerCAmelCase : str = getattr(_UpperCamelCase , _UpperCamelCase ) if weight_type is not None: __lowerCAmelCase : Tuple = getattr(_UpperCamelCase , _UpperCamelCase ).shape else: __lowerCAmelCase : Dict = hf_pointer.shape assert hf_shape == value.shape, ( F"Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be" F" {value.shape} for {full_name}" ) if weight_type == "weight": __lowerCAmelCase : Union[str, Any] = value elif weight_type == "weight_g": __lowerCAmelCase : List[Any] = value elif weight_type == "weight_v": __lowerCAmelCase : Any = value elif weight_type == "bias": __lowerCAmelCase : List[str] = value else: __lowerCAmelCase : List[Any] = value logger.info(F"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}." ) def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase ): __lowerCAmelCase : Any = [] __lowerCAmelCase : Optional[int] = fairseq_model.state_dict() __lowerCAmelCase : Union[str, Any] = hf_model.feature_extractor for name, value in fairseq_dict.items(): __lowerCAmelCase : Union[str, Any] = False if "conv_layers" in name: load_conv_layer( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , hf_model.config.feat_extract_norm == 'group' , ) __lowerCAmelCase : str = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]: __lowerCAmelCase : int = True if "*" in mapped_key: __lowerCAmelCase : List[str] = name.split(_UpperCamelCase )[0].split('.' )[-2] __lowerCAmelCase : Optional[Any] = mapped_key.replace('*' , _UpperCamelCase ) if "weight_g" in name: __lowerCAmelCase : Union[str, Any] = 'weight_g' elif "weight_v" in name: __lowerCAmelCase : int = 'weight_v' elif "bias" in name and "relative_attention_bias" not in name: __lowerCAmelCase : Optional[Any] = 'bias' elif "weight" in name: # TODO: don't match quantizer.weight_proj __lowerCAmelCase : List[str] = 'weight' else: __lowerCAmelCase : Optional[Any] = None set_recursively(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) continue if not is_used: unused_weights.append(_UpperCamelCase ) logger.warning(F"Unused weights: {unused_weights}" ) def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): __lowerCAmelCase : List[Any] = full_name.split('conv_layers.' )[-1] __lowerCAmelCase : Any = name.split('.' ) __lowerCAmelCase : List[Any] = int(items[0] ) __lowerCAmelCase : Tuple = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( F"{full_name} has size {value.shape}, but" F" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found." ) __lowerCAmelCase : Tuple = value logger.info(F"Feat extract conv layer {layer_id} was initialized from {full_name}." ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( F"{full_name} has size {value.shape}, but" F" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found." ) __lowerCAmelCase : int = value logger.info(F"Feat extract conv layer {layer_id} was initialized from {full_name}." ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( F"{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was" " found." ) __lowerCAmelCase : Optional[Any] = value logger.info(F"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( F"{full_name} has size {value.shape}, but" F" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found." ) __lowerCAmelCase : Any = value logger.info(F"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) else: unused_weights.append(_UpperCamelCase ) @torch.no_grad() def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase=None ): # load the pre-trained checkpoints __lowerCAmelCase : Any = torch.load(_UpperCamelCase ) __lowerCAmelCase : List[str] = WavLMConfigOrig(checkpoint['cfg'] ) __lowerCAmelCase : Optional[Any] = WavLMOrig(_UpperCamelCase ) model.load_state_dict(checkpoint['model'] ) model.eval() if config_path is not None: __lowerCAmelCase : Dict = WavLMConfig.from_pretrained(_UpperCamelCase ) else: __lowerCAmelCase : List[str] = WavLMConfig() __lowerCAmelCase : List[str] = WavLMModel(_UpperCamelCase ) recursively_load_weights(_UpperCamelCase , _UpperCamelCase ) hf_wavlm.save_pretrained(_UpperCamelCase ) if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to fairseq checkpoint""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") lowerCamelCase__ = parser.parse_args() convert_wavlm_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
86
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) __lowercase = {'''configuration_fnet''': ['''FNET_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''FNetConfig''']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase = ['''FNetTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase = ['''FNetTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase = [ '''FNET_PRETRAINED_MODEL_ARCHIVE_LIST''', '''FNetForMaskedLM''', '''FNetForMultipleChoice''', '''FNetForNextSentencePrediction''', '''FNetForPreTraining''', '''FNetForQuestionAnswering''', '''FNetForSequenceClassification''', '''FNetForTokenClassification''', '''FNetLayer''', '''FNetModel''', '''FNetPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_fnet import FNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet import FNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet_fast import FNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_fnet import ( FNET_PRETRAINED_MODEL_ARCHIVE_LIST, FNetForMaskedLM, FNetForMultipleChoice, FNetForNextSentencePrediction, FNetForPreTraining, FNetForQuestionAnswering, FNetForSequenceClassification, FNetForTokenClassification, FNetLayer, FNetModel, FNetPreTrainedModel, ) else: import sys __lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
272
"""simple docstring""" import os import pytest from attr import dataclass lowerCamelCase__ = """us-east-1""" # defaults region @dataclass class A__ : A_ : str A_ : Union[str, Any] = 'arn:aws:iam::558105141721:role/sagemaker_execution_role' A_ : Optional[int] = { 'task_name': 'mnli', 'per_device_train_batch_size': 1_6, 'per_device_eval_batch_size': 1_6, 'do_train': True, 'do_eval': True, 'do_predict': True, 'output_dir': '/opt/ml/model', 'overwrite_output_dir': True, 'max_steps': 5_0_0, 'save_steps': 5_5_0_0, } A_ : List[Any] = {**hyperparameters, 'max_steps': 1_0_0_0} @property def __lowerCamelCase ( self ): if self.framework == "pytorch": return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"eval_accuracy.*=\D*(.*?)$"}, {"Name": "eval_loss", "Regex": r"eval_loss.*=\D*(.*?)$"}, ] else: return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"loss.*=\D*(.*?)]?$"}, {"Name": "eval_loss", "Regex": r"sparse_categorical_accuracy.*=\D*(.*?)]?$"}, ] @property def __lowerCamelCase ( self ): return f"{self.framework}-transfromers-test" @property def __lowerCamelCase ( self ): return f"./tests/sagemaker/scripts/{self.framework}" @property def __lowerCamelCase ( self ): if self.framework == "pytorch": return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-pytorch-training:1.7.1-transformers4.6.1-gpu-py36-cu110-ubuntu18.04" else: return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-tensorflow-training:2.4.1-transformers4.6.1-gpu-py37-cu110-ubuntu18.04" @pytest.fixture(scope='class' ) def __lowerCAmelCase (_UpperCamelCase ): __lowerCAmelCase : str = SageMakerTestEnvironment(framework=request.cls.framework )
86
0
import re import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class snake_case ( _lowerCamelCase ): '''simple docstring''' snake_case_ : Any = ['image_processor', 'tokenizer'] snake_case_ : Optional[Any] = 'AutoImageProcessor' snake_case_ : str = 'AutoTokenizer' def __init__( self : Union[str, Any] , lowerCAmelCase : Optional[Any]=None , lowerCAmelCase : List[str]=None , **lowerCAmelCase : List[str]) -> Optional[int]: """simple docstring""" _snake_case : Union[str, Any] = None if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""" , _SCREAMING_SNAKE_CASE , ) _snake_case : Any = kwargs.pop("""feature_extractor""") _snake_case : str = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("""You need to specify an `image_processor`.""") if tokenizer is None: raise ValueError("""You need to specify a `tokenizer`.""") super().__init__(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE) _snake_case : Any = self.image_processor _snake_case : Tuple = False def __call__( self : Optional[int] , *lowerCAmelCase : List[str] , **lowerCAmelCase : Dict) -> Optional[Any]: """simple docstring""" if self._in_target_context_manager: return self.current_processor(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE) _snake_case : List[Any] = kwargs.pop("""images""" , _SCREAMING_SNAKE_CASE) _snake_case : Any = kwargs.pop("""text""" , _SCREAMING_SNAKE_CASE) if len(_SCREAMING_SNAKE_CASE) > 0: _snake_case : Dict = args[0] _snake_case : Union[str, Any] = args[1:] if images is None and text is None: raise ValueError("""You need to specify either an `images` or `text` input to process.""") if images is not None: _snake_case : Union[str, Any] = self.image_processor(_SCREAMING_SNAKE_CASE , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE) if text is not None: _snake_case : Dict = self.tokenizer(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE) if text is None: return inputs elif images is None: return encodings else: _snake_case : Union[str, Any] = encodings['input_ids'] return inputs def UpperCamelCase_ ( self : Union[str, Any] , *lowerCAmelCase : int , **lowerCAmelCase : Tuple) -> Optional[int]: """simple docstring""" return self.tokenizer.batch_decode(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self : Optional[int] , *lowerCAmelCase : Any , **lowerCAmelCase : List[str]) -> Union[str, Any]: """simple docstring""" return self.tokenizer.decode(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE) @contextmanager def UpperCamelCase_ ( self : int) -> Any: """simple docstring""" 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 images inputs, or in a separate call.""") _snake_case : Any = True _snake_case : Dict = self.tokenizer yield _snake_case : Optional[int] = self.image_processor _snake_case : Optional[Any] = False def UpperCamelCase_ ( self : Optional[Any] , lowerCAmelCase : Dict , lowerCAmelCase : Dict=False , lowerCAmelCase : Dict=None) -> int: """simple docstring""" if added_vocab is None: _snake_case : str = self.tokenizer.get_added_vocab() _snake_case : List[Any] = {} while tokens: _snake_case : int = re.search(r"""<s_(.*?)>""" , _SCREAMING_SNAKE_CASE , re.IGNORECASE) if start_token is None: break _snake_case : Union[str, Any] = start_token.group(1) _snake_case : Tuple = re.search(rF'''</s_{key}>''' , _SCREAMING_SNAKE_CASE , re.IGNORECASE) _snake_case : str = start_token.group() if end_token is None: _snake_case : Optional[int] = tokens.replace(_SCREAMING_SNAKE_CASE , """""") else: _snake_case : Optional[Any] = end_token.group() _snake_case : Tuple = re.escape(_SCREAMING_SNAKE_CASE) _snake_case : Tuple = re.escape(_SCREAMING_SNAKE_CASE) _snake_case : Dict = re.search(F'''{start_token_escaped}(.*?){end_token_escaped}''' , _SCREAMING_SNAKE_CASE , re.IGNORECASE) if content is not None: _snake_case : List[str] = content.group(1).strip() if r"<s_" in content and r"</s_" in content: # non-leaf node _snake_case : int = self.tokenajson(_SCREAMING_SNAKE_CASE , is_inner_value=_SCREAMING_SNAKE_CASE , added_vocab=_SCREAMING_SNAKE_CASE) if value: if len(_SCREAMING_SNAKE_CASE) == 1: _snake_case : Tuple = value[0] _snake_case : Tuple = value else: # leaf nodes _snake_case : Any = [] for leaf in content.split(r"""<sep/>"""): _snake_case : List[Any] = leaf.strip() if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>": _snake_case : Dict = leaf[1:-2] # for categorical special tokens output[key].append(_SCREAMING_SNAKE_CASE) if len(output[key]) == 1: _snake_case : str = output[key][0] _snake_case : Dict = tokens[tokens.find(_SCREAMING_SNAKE_CASE) + len(_SCREAMING_SNAKE_CASE) :].strip() if tokens[:6] == r"<sep/>": # non-leaf nodes return [output] + self.tokenajson(tokens[6:] , is_inner_value=_SCREAMING_SNAKE_CASE , added_vocab=_SCREAMING_SNAKE_CASE) if len(_SCREAMING_SNAKE_CASE): return [output] if is_inner_value else output else: return [] if is_inner_value else {"text_sequence": tokens} @property def UpperCamelCase_ ( self : Dict) -> str: """simple docstring""" warnings.warn( """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.""" , _SCREAMING_SNAKE_CASE , ) return self.image_processor_class @property def UpperCamelCase_ ( self : Union[str, Any]) -> List[str]: """simple docstring""" warnings.warn( """`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.""" , _SCREAMING_SNAKE_CASE , ) return self.image_processor
317
"""simple docstring""" from __future__ import annotations lowerCamelCase__ = list[tuple[int, int]] lowerCamelCase__ = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] lowerCamelCase__ = ([-1, 0], [0, -1], [1, 0], [0, 1]) # up, left, down, right class A__ : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , ): __lowerCAmelCase : int = pos_x __lowerCAmelCase : Optional[Any] = pos_y __lowerCAmelCase : Optional[int] = (pos_y, pos_x) __lowerCAmelCase : Union[str, Any] = goal_x __lowerCAmelCase : Any = goal_y __lowerCAmelCase : Optional[Any] = g_cost __lowerCAmelCase : Any = parent __lowerCAmelCase : Union[str, Any] = self.calculate_heuristic() def __lowerCamelCase ( self ): __lowerCAmelCase : str = abs(self.pos_x - self.goal_x ) __lowerCAmelCase : str = abs(self.pos_y - self.goal_y ) return dx + dy def __lt__( self , _SCREAMING_SNAKE_CASE ): return self.f_cost < other.f_cost class A__ : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Optional[int] = Node(start[1] , start[0] , goal[1] , goal[0] , 0 , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Any = Node(goal[1] , goal[0] , goal[1] , goal[0] , 9_99_99 , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Tuple = [self.start] __lowerCAmelCase : list[Node] = [] __lowerCAmelCase : str = False def __lowerCamelCase ( self ): while self.open_nodes: # Open Nodes are sorted using __lt__ self.open_nodes.sort() __lowerCAmelCase : Optional[int] = self.open_nodes.pop(0 ) if current_node.pos == self.target.pos: __lowerCAmelCase : Union[str, Any] = True return self.retrace_path(_SCREAMING_SNAKE_CASE ) self.closed_nodes.append(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = self.get_successors(_SCREAMING_SNAKE_CASE ) for child_node in successors: if child_node in self.closed_nodes: continue if child_node not in self.open_nodes: self.open_nodes.append(_SCREAMING_SNAKE_CASE ) else: # retrieve the best current path __lowerCAmelCase : Optional[Any] = self.open_nodes.pop(self.open_nodes.index(_SCREAMING_SNAKE_CASE ) ) if child_node.g_cost < better_node.g_cost: self.open_nodes.append(_SCREAMING_SNAKE_CASE ) else: self.open_nodes.append(_SCREAMING_SNAKE_CASE ) if not self.reached: return [self.start.pos] return None def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Dict = [] for action in delta: __lowerCAmelCase : Optional[int] = parent.pos_x + action[1] __lowerCAmelCase : Union[str, Any] = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(_SCREAMING_SNAKE_CASE ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , self.target.pos_y , self.target.pos_x , parent.g_cost + 1 , _SCREAMING_SNAKE_CASE , ) ) return successors def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Union[str, Any] = node __lowerCAmelCase : Optional[int] = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) __lowerCAmelCase : int = current_node.parent path.reverse() return path if __name__ == "__main__": lowerCamelCase__ = (0, 0) lowerCamelCase__ = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) print("""------""") lowerCamelCase__ = GreedyBestFirst(init, goal) lowerCamelCase__ = greedy_bf.search() if path: for pos_x, pos_y in path: lowerCamelCase__ = 2 for elem in grid: print(elem)
86
0
'''simple docstring''' from __future__ import annotations from collections.abc import Iterator from typing import Generic, TypeVar lowerCAmelCase : Optional[int] =TypeVar('''T''') class a_ ( Generic[T] ): def __init__( self : Tuple , lowercase : Any ): """simple docstring""" lowercase_ :List[Any] = data lowercase_ :Node[T] | None = None def __str__( self : Union[str, Any] ): """simple docstring""" return F'{self.data}' class a_ ( Generic[T] ): def __init__( self : List[str] ): """simple docstring""" lowercase_ :Node[T] | None = None def __iter__( self : Dict ): """simple docstring""" lowercase_ :Tuple = self.top while node: yield node.data lowercase_ :Optional[int] = node.next def __str__( self : str ): """simple docstring""" return "->".join([str(_SCREAMING_SNAKE_CASE ) for item in self] ) def __len__( self : List[Any] ): """simple docstring""" return len(tuple(iter(self ) ) ) def lowercase__ ( self : Optional[Any] ): """simple docstring""" return self.top is None def lowercase__ ( self : str , lowercase : Tuple ): """simple docstring""" lowercase_ :int = Node(_SCREAMING_SNAKE_CASE ) if not self.is_empty(): lowercase_ :Union[str, Any] = self.top lowercase_ :Optional[int] = node def lowercase__ ( self : Any ): """simple docstring""" if self.is_empty(): raise IndexError("pop from empty stack" ) assert isinstance(self.top , _SCREAMING_SNAKE_CASE ) lowercase_ :Dict = self.top lowercase_ :int = self.top.next return pop_node.data def lowercase__ ( self : Dict ): """simple docstring""" if self.is_empty(): raise IndexError("peek from empty stack" ) assert self.top is not None return self.top.data def lowercase__ ( self : Dict ): """simple docstring""" lowercase_ :Optional[int] = None if __name__ == "__main__": from doctest import testmod testmod()
223
"""simple docstring""" def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): return round(float(moles / volume ) * nfactor ) def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): return round(float((moles * 0.0821 * temperature) / (volume) ) ) def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): return round(float((moles * 0.0821 * temperature) / (pressure) ) ) def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): return round(float((pressure * volume) / (0.0821 * moles) ) ) if __name__ == "__main__": import doctest doctest.testmod()
86
0
def UpperCAmelCase ( lowercase , lowercase ): """simple docstring""" def get_matched_characters(lowercase , lowercase ) -> str: __lowercase = [] __lowercase = min(len(_stra ) , len(_stra ) ) // 2 for i, l in enumerate(_stra ): __lowercase = int(max(0 , i - limit ) ) __lowercase = int(min(i + limit + 1 , len(_stra ) ) ) if l in _stra[left:right]: matched.append(_UpperCamelCase ) __lowercase = F"{_stra[0:_stra.index(_UpperCamelCase )]} {_stra[_stra.index(_UpperCamelCase ) + 1:]}" return "".join(_UpperCamelCase ) # matching characters __lowercase = get_matched_characters(_UpperCamelCase , _UpperCamelCase ) __lowercase = get_matched_characters(_UpperCamelCase , _UpperCamelCase ) __lowercase = len(_UpperCamelCase ) # transposition __lowercase = ( len([(ca, ca) for ca, ca in zip(_UpperCamelCase , _UpperCamelCase ) if ca != ca] ) // 2 ) if not match_count: __lowercase = 0.0 else: __lowercase = ( 1 / 3 * ( match_count / len(_UpperCamelCase ) + match_count / len(_UpperCamelCase ) + (match_count - transpositions) / match_count ) ) # common prefix up to 4 characters __lowercase = 0 for ca, ca in zip(stra[:4] , stra[:4] ): if ca == ca: prefix_len += 1 else: break return jaro + 0.1 * prefix_len * (1 - jaro) if __name__ == "__main__": import doctest doctest.testmod() print(jaro_winkler("""hello""", """world"""))
210
"""simple docstring""" import enum import warnings from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING from ..utils import add_end_docstrings, is_tf_available from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf class A__ ( enum.Enum): A_ : List[Any] = 0 A_ : Dict = 1 A_ : Union[str, Any] = 2 @add_end_docstrings(_lowerCamelCase) class A__ ( _lowerCamelCase): A_ : str = '\n In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The\n voice of Nicholas\'s young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western\n Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision\n and denounces one of the men as a horse thief. Although his father initially slaps him for making such an\n accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of\n the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop,\n begging for his blessing. <eod> </s> <eos>\n ' def __init__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ): super().__init__(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) self.check_model_type( TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == 'tf' else MODEL_FOR_CAUSAL_LM_MAPPING ) if "prefix" not in self._preprocess_params: # This is very specific. The logic is quite complex and needs to be done # as a "default". # It also defines both some preprocess_kwargs and generate_kwargs # which is why we cannot put them in their respective methods. __lowerCAmelCase : Any = None if self.model.config.prefix is not None: __lowerCAmelCase : str = self.model.config.prefix if prefix is None and self.model.__class__.__name__ in [ "XLNetLMHeadModel", "TransfoXLLMHeadModel", "TFXLNetLMHeadModel", "TFTransfoXLLMHeadModel", ]: # For XLNet and TransformerXL we add an article to the prompt to give more state to the model. __lowerCAmelCase : Tuple = self.XL_PREFIX if prefix is not None: # Recalculate some generate_kwargs linked to prefix. __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase : Union[str, Any] = self._sanitize_parameters(prefix=_SCREAMING_SNAKE_CASE , **self._forward_params ) __lowerCAmelCase : List[str] = {**self._preprocess_params, **preprocess_params} __lowerCAmelCase : List[str] = {**self._forward_params, **forward_params} def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE , ): __lowerCAmelCase : Optional[int] = {} if prefix is not None: __lowerCAmelCase : Union[str, Any] = prefix if prefix: __lowerCAmelCase : Dict = self.tokenizer( _SCREAMING_SNAKE_CASE , padding=_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE , return_tensors=self.framework ) __lowerCAmelCase : List[Any] = prefix_inputs['input_ids'].shape[-1] if handle_long_generation is not None: if handle_long_generation not in {"hole"}: raise ValueError( f"{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected" ' [None, \'hole\']' ) __lowerCAmelCase : int = handle_long_generation preprocess_params.update(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : int = generate_kwargs __lowerCAmelCase : List[Any] = {} if return_full_text is not None and return_type is None: if return_text is not None: raise ValueError('`return_text` is mutually exclusive with `return_full_text`' ) if return_tensors is not None: raise ValueError('`return_full_text` is mutually exclusive with `return_tensors`' ) __lowerCAmelCase : Optional[Any] = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT if return_tensors is not None and return_type is None: if return_text is not None: raise ValueError('`return_text` is mutually exclusive with `return_tensors`' ) __lowerCAmelCase : List[Any] = ReturnType.TENSORS if return_type is not None: __lowerCAmelCase : Optional[Any] = return_type if clean_up_tokenization_spaces is not None: __lowerCAmelCase : Tuple = clean_up_tokenization_spaces if stop_sequence is not None: __lowerCAmelCase : Union[str, Any] = self.tokenizer.encode(_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE ) if len(_SCREAMING_SNAKE_CASE ) > 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.' ) __lowerCAmelCase : Optional[Any] = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def __lowerCamelCase ( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ): # Parse arguments if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]: kwargs.update({'add_space_before_punct_symbol': True} ) return super()._parse_and_tokenize(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def __call__( self , _SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ): return super().__call__(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE="" , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Any = self.tokenizer( prefix + prompt_text , padding=_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE , return_tensors=self.framework ) __lowerCAmelCase : Optional[Any] = prompt_text if handle_long_generation == "hole": __lowerCAmelCase : str = inputs['input_ids'].shape[-1] if "max_new_tokens" in generate_kwargs: __lowerCAmelCase : Union[str, Any] = generate_kwargs['max_new_tokens'] else: __lowerCAmelCase : Any = generate_kwargs.get('max_length' , self.model.config.max_length ) - cur_len if new_tokens < 0: raise ValueError('We cannot infer how many new tokens are expected' ) if cur_len + new_tokens > self.tokenizer.model_max_length: __lowerCAmelCase : Any = self.tokenizer.model_max_length - new_tokens if keep_length <= 0: raise ValueError( 'We cannot use `hole` to handle this generation the number of desired tokens exceeds the' ' models max length' ) __lowerCAmelCase : int = inputs['input_ids'][:, -keep_length:] if "attention_mask" in inputs: __lowerCAmelCase : List[Any] = inputs['attention_mask'][:, -keep_length:] return inputs def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ): __lowerCAmelCase : str = model_inputs['input_ids'] __lowerCAmelCase : List[Any] = model_inputs.get('attention_mask' , _SCREAMING_SNAKE_CASE ) # Allow empty prompts if input_ids.shape[1] == 0: __lowerCAmelCase : Dict = None __lowerCAmelCase : str = None __lowerCAmelCase : Tuple = 1 else: __lowerCAmelCase : Any = input_ids.shape[0] __lowerCAmelCase : Union[str, Any] = model_inputs.pop('prompt_text' ) # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline. __lowerCAmelCase : Optional[int] = generate_kwargs.pop('prefix_length' , 0 ) if prefix_length > 0: __lowerCAmelCase : Any = 'max_new_tokens' in generate_kwargs or ( 'generation_config' in generate_kwargs and generate_kwargs['generation_config'].max_new_tokens is not None ) if not has_max_new_tokens: __lowerCAmelCase : List[str] = generate_kwargs.get('max_length' ) or self.model.config.max_length generate_kwargs["max_length"] += prefix_length __lowerCAmelCase : Dict = 'min_new_tokens' in generate_kwargs or ( 'generation_config' in generate_kwargs and generate_kwargs['generation_config'].min_new_tokens is not None ) if not has_min_new_tokens and "min_length" in generate_kwargs: generate_kwargs["min_length"] += prefix_length # BS x SL __lowerCAmelCase : Optional[int] = self.model.generate(input_ids=_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = generated_sequence.shape[0] if self.framework == "pt": __lowerCAmelCase : Dict = generated_sequence.reshape(_SCREAMING_SNAKE_CASE , out_b // in_b , *generated_sequence.shape[1:] ) elif self.framework == "tf": __lowerCAmelCase : Any = tf.reshape(_SCREAMING_SNAKE_CASE , (in_b, out_b // in_b, *generated_sequence.shape[1:]) ) return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text} def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=ReturnType.FULL_TEXT , _SCREAMING_SNAKE_CASE=True ): __lowerCAmelCase : Any = model_outputs['generated_sequence'][0] __lowerCAmelCase : Tuple = model_outputs['input_ids'] __lowerCAmelCase : Any = model_outputs['prompt_text'] __lowerCAmelCase : int = generated_sequence.numpy().tolist() __lowerCAmelCase : Union[str, Any] = [] for sequence in generated_sequence: if return_type == ReturnType.TENSORS: __lowerCAmelCase : int = {'generated_token_ids': sequence} elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}: # Decode text __lowerCAmelCase : Any = self.tokenizer.decode( _SCREAMING_SNAKE_CASE , skip_special_tokens=_SCREAMING_SNAKE_CASE , clean_up_tokenization_spaces=_SCREAMING_SNAKE_CASE , ) # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used if input_ids is None: __lowerCAmelCase : Optional[Any] = 0 else: __lowerCAmelCase : Any = len( self.tokenizer.decode( input_ids[0] , skip_special_tokens=_SCREAMING_SNAKE_CASE , clean_up_tokenization_spaces=_SCREAMING_SNAKE_CASE , ) ) if return_type == ReturnType.FULL_TEXT: __lowerCAmelCase : Union[str, Any] = prompt_text + text[prompt_length:] else: __lowerCAmelCase : int = text[prompt_length:] __lowerCAmelCase : Dict = {'generated_text': all_text} records.append(_SCREAMING_SNAKE_CASE ) return records
86
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __a = { 'configuration_instructblip': [ 'INSTRUCTBLIP_PRETRAINED_CONFIG_ARCHIVE_MAP', 'InstructBlipConfig', 'InstructBlipQFormerConfig', 'InstructBlipVisionConfig', ], 'processing_instructblip': ['InstructBlipProcessor'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __a = [ 'INSTRUCTBLIP_PRETRAINED_MODEL_ARCHIVE_LIST', 'InstructBlipQFormerModel', 'InstructBlipPreTrainedModel', 'InstructBlipForConditionalGeneration', 'InstructBlipVisionModel', ] if TYPE_CHECKING: from .configuration_instructblip import ( INSTRUCTBLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, InstructBlipConfig, InstructBlipQFormerConfig, InstructBlipVisionConfig, ) from .processing_instructblip import InstructBlipProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_instructblip import ( INSTRUCTBLIP_PRETRAINED_MODEL_ARCHIVE_LIST, InstructBlipForConditionalGeneration, InstructBlipPreTrainedModel, InstructBlipQFormerModel, InstructBlipVisionModel, ) else: import sys __a = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
145
"""simple docstring""" from __future__ import annotations import bisect def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase = 0 , _UpperCamelCase = -1 ): if hi < 0: __lowerCAmelCase : Tuple = len(_UpperCamelCase ) while lo < hi: __lowerCAmelCase : Optional[int] = lo + (hi - lo) // 2 if sorted_collection[mid] < item: __lowerCAmelCase : int = mid + 1 else: __lowerCAmelCase : List[str] = mid return lo def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase = 0 , _UpperCamelCase = -1 ): if hi < 0: __lowerCAmelCase : List[Any] = len(_UpperCamelCase ) while lo < hi: __lowerCAmelCase : Union[str, Any] = lo + (hi - lo) // 2 if sorted_collection[mid] <= item: __lowerCAmelCase : Dict = mid + 1 else: __lowerCAmelCase : str = mid return lo def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase = 0 , _UpperCamelCase = -1 ): sorted_collection.insert(bisect_left(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) , _UpperCamelCase ) def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase = 0 , _UpperCamelCase = -1 ): sorted_collection.insert(bisect_right(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) , _UpperCamelCase ) def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase ): __lowerCAmelCase : List[Any] = 0 __lowerCAmelCase : int = len(_UpperCamelCase ) - 1 while left <= right: __lowerCAmelCase : List[Any] = left + (right - left) // 2 __lowerCAmelCase : Union[str, Any] = sorted_collection[midpoint] if current_item == item: return midpoint elif item < current_item: __lowerCAmelCase : Tuple = midpoint - 1 else: __lowerCAmelCase : str = midpoint + 1 return None def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase ): __lowerCAmelCase : Union[str, Any] = bisect.bisect_left(_UpperCamelCase , _UpperCamelCase ) if index != len(_UpperCamelCase ) and sorted_collection[index] == item: return index return None def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): if right < left: return None __lowerCAmelCase : List[str] = left + (right - left) // 2 if sorted_collection[midpoint] == item: return midpoint elif sorted_collection[midpoint] > item: return binary_search_by_recursion(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , midpoint - 1 ) else: return binary_search_by_recursion(_UpperCamelCase , _UpperCamelCase , midpoint + 1 , _UpperCamelCase ) if __name__ == "__main__": lowerCamelCase__ = input("""Enter numbers separated by comma:\n""").strip() lowerCamelCase__ = sorted(int(item) for item in user_input.split(""",""")) lowerCamelCase__ = int(input("""Enter a single number to be found in the list:\n""")) lowerCamelCase__ = binary_search(collection, target) if result is None: print(f'{target} was not found in {collection}.') else: print(f'{target} was found at position {result} in {collection}.')
86
0
import numpy as np import torch from ..models.clipseg import CLIPSegForImageSegmentation from ..utils import is_vision_available, requires_backends from .base import PipelineTool if is_vision_available(): from PIL import Image class __lowercase (_lowerCamelCase ): _UpperCamelCase = ( 'This is a tool that creates a segmentation mask of an image according to a label. It cannot create an image.' 'It takes two arguments named `image` which should be the original image, and `label` which should be a text ' 'describing the elements what should be identified in the segmentation mask. The tool returns the mask.' ) _UpperCamelCase = 'CIDAS/clipseg-rd64-refined' _UpperCamelCase = 'image_segmenter' _UpperCamelCase = CLIPSegForImageSegmentation _UpperCamelCase = ['image', 'text'] _UpperCamelCase = ['image'] def __init__( self , *A_ , **A_ ) ->int: '''simple docstring''' requires_backends(self , ['''vision'''] ) super().__init__(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def UpperCamelCase__ ( self , A_ , A_ ) ->List[str]: '''simple docstring''' return self.pre_processor(text=[label] , images=[image] , padding=_SCREAMING_SNAKE_CASE , return_tensors='''pt''' ) def UpperCamelCase__ ( self , A_ ) ->int: '''simple docstring''' with torch.no_grad(): __lowerCAmelCase : Union[str, Any] = self.model(**_SCREAMING_SNAKE_CASE ).logits return logits def UpperCamelCase__ ( self , A_ ) ->int: '''simple docstring''' __lowerCAmelCase : Optional[Any] = outputs.cpu().detach().numpy() __lowerCAmelCase : int = 0 __lowerCAmelCase : Optional[int] = 1 return Image.fromarray((array * 255).astype(np.uinta ) )
275
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available, is_torch_available from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, is_pt_tf_cross_test, slow if is_tf_available(): from transformers import ( AutoConfig, BertConfig, GPTaConfig, TaConfig, TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSeqaSeqLM, TFAutoModelForSequenceClassification, TFAutoModelWithLMHead, TFBertForMaskedLM, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertModel, TFGPTaLMHeadModel, TFRobertaForMaskedLM, TFTaForConditionalGeneration, ) from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST if is_torch_available(): from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForPreTraining, AutoModelForQuestionAnswering, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoModelWithLMHead, BertForMaskedLM, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, BertModel, GPTaLMHeadModel, RobertaForMaskedLM, TaForConditionalGeneration, ) @is_pt_tf_cross_test class A__ ( unittest.TestCase): @slow def __lowerCamelCase ( self ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __lowerCAmelCase : Tuple = AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = TFAutoModel.from_pretrained(_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = AutoModel.from_pretrained(_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @slow def __lowerCamelCase ( self ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __lowerCAmelCase : int = AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Tuple = TFAutoModelForPreTraining.from_pretrained(_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : str = AutoModelForPreTraining.from_pretrained(_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @slow def __lowerCamelCase ( self ): for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCAmelCase : Dict = AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = TFAutoModelForCausalLM.from_pretrained(_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase , __lowerCAmelCase : List[str] = TFAutoModelForCausalLM.from_pretrained( _SCREAMING_SNAKE_CASE , output_loading_info=_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Any = AutoModelForCausalLM.from_pretrained(_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase , __lowerCAmelCase : List[Any] = AutoModelForCausalLM.from_pretrained( _SCREAMING_SNAKE_CASE , output_loading_info=_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @slow def __lowerCamelCase ( self ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCAmelCase : Dict = AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : int = TFAutoModelWithLMHead.from_pretrained(_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = AutoModelWithLMHead.from_pretrained(_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @slow def __lowerCamelCase ( self ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCAmelCase : Optional[Any] = AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = TFAutoModelForMaskedLM.from_pretrained(_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase , __lowerCAmelCase : int = TFAutoModelForMaskedLM.from_pretrained( _SCREAMING_SNAKE_CASE , output_loading_info=_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Union[str, Any] = AutoModelForMaskedLM.from_pretrained(_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase , __lowerCAmelCase : str = AutoModelForMaskedLM.from_pretrained( _SCREAMING_SNAKE_CASE , output_loading_info=_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @slow def __lowerCamelCase ( self ): for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCAmelCase : Optional[int] = AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Tuple = TFAutoModelForSeqaSeqLM.from_pretrained(_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase , __lowerCAmelCase : Tuple = TFAutoModelForSeqaSeqLM.from_pretrained( _SCREAMING_SNAKE_CASE , output_loading_info=_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : int = AutoModelForSeqaSeqLM.from_pretrained(_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase , __lowerCAmelCase : Dict = AutoModelForSeqaSeqLM.from_pretrained( _SCREAMING_SNAKE_CASE , output_loading_info=_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @slow def __lowerCamelCase ( self ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __lowerCAmelCase : Dict = AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = TFAutoModelForSequenceClassification.from_pretrained(_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Union[str, Any] = AutoModelForSequenceClassification.from_pretrained(_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @slow def __lowerCamelCase ( self ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __lowerCAmelCase : Union[str, Any] = AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = TFAutoModelForQuestionAnswering.from_pretrained(_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Union[str, Any] = AutoModelForQuestionAnswering.from_pretrained(_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : List[Any] = TFAutoModelWithLMHead.from_pretrained(_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) self.assertEqual(model.num_parameters() , 1_44_10 ) self.assertEqual(model.num_parameters(only_trainable=_SCREAMING_SNAKE_CASE ) , 1_44_10 ) __lowerCAmelCase : Tuple = AutoModelWithLMHead.from_pretrained(_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) self.assertEqual(model.num_parameters() , 1_44_10 ) self.assertEqual(model.num_parameters(only_trainable=_SCREAMING_SNAKE_CASE ) , 1_44_10 ) def __lowerCamelCase ( self ): __lowerCAmelCase : int = TFAutoModelWithLMHead.from_pretrained(_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) self.assertEqual(model.num_parameters() , 1_44_10 ) self.assertEqual(model.num_parameters(only_trainable=_SCREAMING_SNAKE_CASE ) , 1_44_10 ) __lowerCAmelCase : Tuple = AutoModelWithLMHead.from_pretrained(_SCREAMING_SNAKE_CASE , from_tf=_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) self.assertEqual(model.num_parameters() , 1_44_10 ) self.assertEqual(model.num_parameters(only_trainable=_SCREAMING_SNAKE_CASE ) , 1_44_10 )
86
0
import collections import inspect import unittest from typing import Dict, List, Tuple from transformers import MaskFormerSwinConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, torch_device from transformers.utils import is_torch_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import MaskFormerSwinBackbone from transformers.models.maskformer import MaskFormerSwinModel class __lowerCAmelCase : def __init__( self , lowerCAmelCase__ , lowerCAmelCase__=1_3 , lowerCAmelCase__=3_2 , lowerCAmelCase__=2 , lowerCAmelCase__=3 , lowerCAmelCase__=1_6 , lowerCAmelCase__=[1, 2, 1] , lowerCAmelCase__=[2, 2, 4] , lowerCAmelCase__=2 , lowerCAmelCase__=2.0 , lowerCAmelCase__=True , lowerCAmelCase__=0.0 , lowerCAmelCase__=0.0 , lowerCAmelCase__=0.1 , lowerCAmelCase__="gelu" , lowerCAmelCase__=False , lowerCAmelCase__=True , lowerCAmelCase__=0.02 , lowerCAmelCase__=1E-5 , lowerCAmelCase__=True , lowerCAmelCase__=None , lowerCAmelCase__=True , lowerCAmelCase__=1_0 , lowerCAmelCase__=8 , lowerCAmelCase__=["stage1", "stage2", "stage3"] , lowerCAmelCase__=[1, 2, 3] , ) -> Optional[Any]: '''simple docstring''' a__ : List[str] =parent a__ : Tuple =batch_size a__ : str =image_size a__ : Any =patch_size a__ : str =num_channels a__ : str =embed_dim a__ : Optional[Any] =depths a__ : Tuple =num_heads a__ : int =window_size a__ : List[str] =mlp_ratio a__ : Tuple =qkv_bias a__ : Union[str, Any] =hidden_dropout_prob a__ : List[str] =attention_probs_dropout_prob a__ : str =drop_path_rate a__ : Any =hidden_act a__ : Any =use_absolute_embeddings a__ : Dict =patch_norm a__ : int =layer_norm_eps a__ : Any =initializer_range a__ : Tuple =is_training a__ : Tuple =scope a__ : Dict =use_labels a__ : Tuple =type_sequence_label_size a__ : List[str] =encoder_stride a__ : int =out_features a__ : List[str] =out_indices def _lowercase ( self ) -> Dict: '''simple docstring''' a__ : str =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) a__ : List[Any] =None if self.use_labels: a__ : Any =ids_tensor([self.batch_size] , self.type_sequence_label_size ) a__ : str =self.get_config() return config, pixel_values, labels def _lowercase ( self ) -> str: '''simple docstring''' return MaskFormerSwinConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , out_features=self.out_features , out_indices=self.out_indices , ) def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> Dict: '''simple docstring''' a__ : List[Any] =MaskFormerSwinModel(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() a__ : Tuple =model(_SCREAMING_SNAKE_CASE ) a__ : Optional[int] =((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) a__ : Union[str, Any] =int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) ) def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> Optional[Any]: '''simple docstring''' a__ : Optional[int] =MaskFormerSwinBackbone(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() a__ : List[str] =model(_SCREAMING_SNAKE_CASE ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [1_3, 1_6, 1_6, 1_6] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , [1_6, 3_2, 6_4] ) # verify ValueError with self.parent.assertRaises(_SCREAMING_SNAKE_CASE ): a__ : List[Any] =['stem'] a__ : Any =MaskFormerSwinBackbone(config=_SCREAMING_SNAKE_CASE ) def _lowercase ( self ) -> Union[str, Any]: '''simple docstring''' a__ : List[str] =self.prepare_config_and_inputs() a__ : Union[str, Any] =config_and_inputs a__ : Dict ={'pixel_values': pixel_values} return config, inputs_dict @require_torch class __lowerCAmelCase ( _lowerCamelCase , _lowerCamelCase , unittest.TestCase): _lowercase : List[Any] = ( ( MaskFormerSwinModel, MaskFormerSwinBackbone, ) if is_torch_available() else () ) _lowercase : Union[str, Any] = {'feature-extraction': MaskFormerSwinModel} if is_torch_available() else {} _lowercase : str = False _lowercase : Union[str, Any] = False _lowercase : Optional[Any] = False _lowercase : Optional[int] = False _lowercase : Optional[int] = False def _lowercase ( self ) -> Tuple: '''simple docstring''' a__ : str =MaskFormerSwinModelTester(self ) a__ : Optional[int] =ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , embed_dim=3_7 ) @require_torch_multi_gpu @unittest.skip( reason=( "`MaskFormerSwinModel` outputs `hidden_states_spatial_dimensions` which doesn\'t work well with" " `nn.DataParallel`" ) ) def _lowercase ( self ) -> Optional[Any]: '''simple docstring''' pass def _lowercase ( self ) -> List[str]: '''simple docstring''' self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _lowercase ( self ) -> str: '''simple docstring''' return def _lowercase ( self ) -> List[str]: '''simple docstring''' a__ : Tuple =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE ) def _lowercase ( self ) -> int: '''simple docstring''' a__ : List[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*_SCREAMING_SNAKE_CASE ) @unittest.skip("Swin does not use inputs_embeds" ) def _lowercase ( self ) -> Any: '''simple docstring''' pass @unittest.skip("Swin does not support feedforward chunking" ) def _lowercase ( self ) -> Dict: '''simple docstring''' pass def _lowercase ( self ) -> List[Any]: '''simple docstring''' a__ : Optional[Any] =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a__ : List[str] =model_class(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) a__ : Any =model.get_output_embeddings() self.assertTrue(x is None or isinstance(_SCREAMING_SNAKE_CASE , nn.Linear ) ) def _lowercase ( self ) -> List[str]: '''simple docstring''' a__ : Optional[int] =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a__ : Any =model_class(_SCREAMING_SNAKE_CASE ) a__ : Optional[Any] =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic a__ : Union[str, Any] =[*signature.parameters.keys()] a__ : Optional[int] =['pixel_values'] self.assertListEqual(arg_names[:1] , _SCREAMING_SNAKE_CASE ) @unittest.skip(reason="MaskFormerSwin is only used as backbone and doesn\'t support output_attentions" ) def _lowercase ( self ) -> Union[str, Any]: '''simple docstring''' pass @unittest.skip(reason="MaskFormerSwin is only used as an internal backbone" ) def _lowercase ( self ) -> Optional[int]: '''simple docstring''' pass def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> int: '''simple docstring''' a__ : Any =model_class(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): a__ : str =model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) a__ : Dict =outputs.hidden_states a__ : str =getattr( self.model_tester , "expected_num_hidden_layers" , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) # Swin has a different seq_length a__ : Dict =( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) a__ : List[str] =(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) def _lowercase ( self ) -> Optional[Any]: '''simple docstring''' a__ : List[str] =self.model_tester.prepare_config_and_inputs_for_common() a__ : Union[str, Any] =( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes: a__ : List[str] =True self.check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] a__ : Optional[Any] =True self.check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def _lowercase ( self ) -> Tuple: '''simple docstring''' a__ : List[Any] =self.model_tester.prepare_config_and_inputs_for_common() a__ : Optional[Any] =3 a__ : Union[str, Any] =( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) a__ : str =( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) a__ : str =image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) a__ : Optional[Any] =image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: a__ : Optional[Any] =True self.check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] a__ : Any =True self.check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , (padded_height, padded_width) ) @unittest.skip(reason="MaskFormerSwin doesn\'t have pretrained checkpoints" ) def _lowercase ( self ) -> Optional[Any]: '''simple docstring''' pass @unittest.skip(reason="This will be fixed once MaskFormerSwin is replaced by native Swin" ) def _lowercase ( self ) -> Optional[int]: '''simple docstring''' pass @unittest.skip(reason="This will be fixed once MaskFormerSwin is replaced by native Swin" ) def _lowercase ( self ) -> List[Any]: '''simple docstring''' pass def _lowercase ( self ) -> List[str]: '''simple docstring''' a__ : List[str] =self.model_tester.prepare_config_and_inputs_for_common() def set_nan_tensor_to_zero(lowerCAmelCase__ ): a__ : Any =0 return t def check_equivalence(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__={} ): with torch.no_grad(): a__ : str =model(**_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) a__ : Optional[Any] =model(**_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ).to_tuple() def recursive_check(lowerCAmelCase__ , lowerCAmelCase__ ): if isinstance(_SCREAMING_SNAKE_CASE , (List, Tuple) ): for tuple_iterable_value, dict_iterable_value in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): recursive_check(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): for tuple_iterable_value, dict_iterable_value in zip( tuple_object.values() , dict_object.values() ): recursive_check(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif tuple_object is None: return else: self.assertTrue( torch.allclose( set_nan_tensor_to_zero(_SCREAMING_SNAKE_CASE ) , set_nan_tensor_to_zero(_SCREAMING_SNAKE_CASE ) , atol=1E-5 ) , msg=( "Tuple and dict output are not equal. Difference:" F''' {torch.max(torch.abs(tuple_object - dict_object ) )}. Tuple has `nan`:''' F''' {torch.isnan(_SCREAMING_SNAKE_CASE ).any()} and `inf`: {torch.isinf(_SCREAMING_SNAKE_CASE )}. Dict has''' F''' `nan`: {torch.isnan(_SCREAMING_SNAKE_CASE ).any()} and `inf`: {torch.isinf(_SCREAMING_SNAKE_CASE )}.''' ) , ) recursive_check(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for model_class in self.all_model_classes: a__ : int =model_class(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() a__ : Dict =self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) a__ : Optional[int] =self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) check_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) a__ : Optional[Any] =self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) a__ : Optional[Any] =self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) check_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) a__ : Optional[Any] =self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) a__ : Dict =self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) check_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , {"output_hidden_states": True} ) a__ : Optional[int] =self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) a__ : List[Any] =self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) check_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , {"output_hidden_states": True} ) @require_torch class __lowerCAmelCase ( unittest.TestCase , _lowerCamelCase): _lowercase : Tuple = (MaskFormerSwinBackbone,) if is_torch_available() else () _lowercase : Union[str, Any] = MaskFormerSwinConfig def _lowercase ( self ) -> Tuple: '''simple docstring''' a__ : Tuple =MaskFormerSwinModelTester(self ) def _lowercase ( self ) -> List[str]: '''simple docstring''' a__ : Dict =self.model_tester.prepare_config_and_inputs_for_common() a__ : Any =inputs_dict['pixel_values'].shape[0] for backbone_class in self.all_model_classes: a__ : int =backbone_class(_SCREAMING_SNAKE_CASE ) backbone.to(_SCREAMING_SNAKE_CASE ) backbone.eval() a__ : Union[str, Any] =backbone(**_SCREAMING_SNAKE_CASE ) # Test default outputs and verify feature maps self.assertIsInstance(outputs.feature_maps , _SCREAMING_SNAKE_CASE ) self.assertTrue(len(outputs.feature_maps ) == len(backbone.channels ) ) for feature_map, n_channels in zip(outputs.feature_maps , backbone.channels ): self.assertTrue(feature_map.shape[:2] , (batch_size, n_channels) ) self.assertIsNone(outputs.hidden_states ) self.assertIsNone(outputs.attentions ) # Test output_hidden_states=True a__ : Tuple =backbone(**_SCREAMING_SNAKE_CASE , output_hidden_states=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(outputs.hidden_states ) self.assertTrue(len(outputs.hidden_states ) , len(backbone.stage_names ) ) # We skip the stem layer for hidden_states, n_channels in zip(outputs.hidden_states[1:] , backbone.channels ): for hidden_state in hidden_states: # Hidden states are in the format (batch_size, (height * width), n_channels) a__ : Optional[int] =hidden_state.shape self.assertTrue((h_batch_size, h_n_channels) , (batch_size, n_channels) ) # Test output_attentions=True if self.has_attentions: a__ : str =backbone(**_SCREAMING_SNAKE_CASE , output_attentions=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(outputs.attentions )
95
"""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 lowerCamelCase__ = logging.get_logger(__name__) # pylint: disable=invalid-name lowerCamelCase__ = """ 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 (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase=8 ): __lowerCAmelCase : Dict = h // scale_factor**2 if h % scale_factor**2 != 0: new_h += 1 __lowerCAmelCase : List[str] = w // scale_factor**2 if w % scale_factor**2 != 0: new_w += 1 return new_h * scale_factor, new_w * scale_factor class A__ ( _lowerCamelCase): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , ): super().__init__() self.register_modules( text_encoder=_SCREAMING_SNAKE_CASE , tokenizer=_SCREAMING_SNAKE_CASE , unet=_SCREAMING_SNAKE_CASE , scheduler=_SCREAMING_SNAKE_CASE , movq=_SCREAMING_SNAKE_CASE , ) __lowerCAmelCase : Dict = 2 ** (len(self.movq.config.block_out_channels ) - 1) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): if latents is None: __lowerCAmelCase : Tuple = randn_tensor(_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , device=_SCREAMING_SNAKE_CASE , dtype=_SCREAMING_SNAKE_CASE ) else: if latents.shape != shape: raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}" ) __lowerCAmelCase : Any = latents.to(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = latents * scheduler.init_noise_sigma return latents def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , ): __lowerCAmelCase : Tuple = len(_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else 1 # get prompt text embeddings __lowerCAmelCase : Dict = self.tokenizer( _SCREAMING_SNAKE_CASE , padding='max_length' , truncation=_SCREAMING_SNAKE_CASE , max_length=77 , return_attention_mask=_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE , return_tensors='pt' , ) __lowerCAmelCase : Tuple = text_inputs.input_ids __lowerCAmelCase : Union[str, Any] = self.tokenizer(_SCREAMING_SNAKE_CASE , padding='longest' , return_tensors='pt' ).input_ids if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : List[Any] = 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}" ) __lowerCAmelCase : Dict = text_input_ids.to(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = text_inputs.attention_mask.to(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase , __lowerCAmelCase : str = self.text_encoder( input_ids=_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Any = prompt_embeds.repeat_interleave(_SCREAMING_SNAKE_CASE , dim=0 ) __lowerCAmelCase : Dict = text_encoder_hidden_states.repeat_interleave(_SCREAMING_SNAKE_CASE , dim=0 ) __lowerCAmelCase : Optional[int] = text_mask.repeat_interleave(_SCREAMING_SNAKE_CASE , dim=0 ) if do_classifier_free_guidance: __lowerCAmelCase : List[str] if negative_prompt is None: __lowerCAmelCase : Union[str, Any] = [''] * batch_size elif type(_SCREAMING_SNAKE_CASE ) is not type(_SCREAMING_SNAKE_CASE ): raise TypeError( f"`negative_prompt` should be the same type to `prompt`, but got {type(_SCREAMING_SNAKE_CASE )} !=" f" {type(_SCREAMING_SNAKE_CASE )}." ) elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Optional[int] = [negative_prompt] elif batch_size != len(_SCREAMING_SNAKE_CASE ): raise ValueError( f"`negative_prompt`: {negative_prompt} has batch size {len(_SCREAMING_SNAKE_CASE )}, but `prompt`:" f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" ' the batch size of `prompt`.' ) else: __lowerCAmelCase : Optional[int] = negative_prompt __lowerCAmelCase : Tuple = self.tokenizer( _SCREAMING_SNAKE_CASE , padding='max_length' , max_length=77 , truncation=_SCREAMING_SNAKE_CASE , return_attention_mask=_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE , return_tensors='pt' , ) __lowerCAmelCase : Union[str, Any] = uncond_input.input_ids.to(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = uncond_input.attention_mask.to(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase , __lowerCAmelCase : Any = self.text_encoder( input_ids=_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE ) # duplicate unconditional embeddings for each generation per prompt, using mps friendly method __lowerCAmelCase : List[str] = negative_prompt_embeds.shape[1] __lowerCAmelCase : Any = negative_prompt_embeds.repeat(1 , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = negative_prompt_embeds.view(batch_size * num_images_per_prompt , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : int = uncond_text_encoder_hidden_states.shape[1] __lowerCAmelCase : List[Any] = uncond_text_encoder_hidden_states.repeat(1 , _SCREAMING_SNAKE_CASE , 1 ) __lowerCAmelCase : Optional[int] = uncond_text_encoder_hidden_states.view( batch_size * num_images_per_prompt , _SCREAMING_SNAKE_CASE , -1 ) __lowerCAmelCase : Optional[Any] = uncond_text_mask.repeat_interleave(_SCREAMING_SNAKE_CASE , 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 __lowerCAmelCase : Tuple = torch.cat([negative_prompt_embeds, prompt_embeds] ) __lowerCAmelCase : Tuple = torch.cat([uncond_text_encoder_hidden_states, text_encoder_hidden_states] ) __lowerCAmelCase : int = torch.cat([uncond_text_mask, text_mask] ) return prompt_embeds, text_encoder_hidden_states, text_mask def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE=0 ): if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('Please install accelerate via `pip install accelerate`' ) __lowerCAmelCase : Union[str, Any] = torch.device(f"cuda:{gpu_id}" ) __lowerCAmelCase : List[Any] = [ self.unet, self.text_encoder, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE=0 ): 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.' ) __lowerCAmelCase : str = torch.device(f"cuda:{gpu_id}" ) if self.device.type != "cpu": self.to('cpu' , silence_dtype_warnings=_SCREAMING_SNAKE_CASE ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) __lowerCAmelCase : Any = None for cpu_offloaded_model in [self.text_encoder, self.unet, self.movq]: __lowerCAmelCase , __lowerCAmelCase : Any = cpu_offload_with_hook(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , prev_module_hook=_SCREAMING_SNAKE_CASE ) if self.safety_checker is not None: __lowerCAmelCase , __lowerCAmelCase : Dict = cpu_offload_with_hook(self.safety_checker , _SCREAMING_SNAKE_CASE , prev_module_hook=_SCREAMING_SNAKE_CASE ) # We'll offload the last model manually. __lowerCAmelCase : Optional[Any] = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def __lowerCamelCase ( self ): if not hasattr(self.unet , '_hf_hook' ): return self.device for module in self.unet.modules(): if ( hasattr(_SCREAMING_SNAKE_CASE , '_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(_SCREAMING_SNAKE_CASE ) def __call__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 5_12 , _SCREAMING_SNAKE_CASE = 5_12 , _SCREAMING_SNAKE_CASE = 1_00 , _SCREAMING_SNAKE_CASE = 4.0 , _SCREAMING_SNAKE_CASE = 1 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = "pil" , _SCREAMING_SNAKE_CASE = True , ): if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : List[str] = 1 elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Optional[int] = len(_SCREAMING_SNAKE_CASE ) else: raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(_SCREAMING_SNAKE_CASE )}" ) __lowerCAmelCase : Dict = self._execution_device __lowerCAmelCase : Optional[Any] = batch_size * num_images_per_prompt __lowerCAmelCase : Optional[int] = guidance_scale > 1.0 __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase : int = self._encode_prompt( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : int = torch.cat(_SCREAMING_SNAKE_CASE , dim=0 ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Dict = torch.cat(_SCREAMING_SNAKE_CASE , dim=0 ) if do_classifier_free_guidance: __lowerCAmelCase : Optional[Any] = image_embeds.repeat_interleave(_SCREAMING_SNAKE_CASE , dim=0 ) __lowerCAmelCase : int = negative_image_embeds.repeat_interleave(_SCREAMING_SNAKE_CASE , dim=0 ) __lowerCAmelCase : Any = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to( dtype=prompt_embeds.dtype , device=_SCREAMING_SNAKE_CASE ) self.scheduler.set_timesteps(_SCREAMING_SNAKE_CASE , device=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = self.scheduler.timesteps __lowerCAmelCase : int = self.unet.config.in_channels __lowerCAmelCase , __lowerCAmelCase : Any = get_new_h_w(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , self.movq_scale_factor ) # create initial latent __lowerCAmelCase : str = self.prepare_latents( (batch_size, num_channels_latents, height, width) , text_encoder_hidden_states.dtype , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , self.scheduler , ) for i, t in enumerate(self.progress_bar(_SCREAMING_SNAKE_CASE ) ): # expand the latents if we are doing classifier free guidance __lowerCAmelCase : List[str] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents __lowerCAmelCase : Union[str, Any] = {'text_embeds': prompt_embeds, 'image_embeds': image_embeds} __lowerCAmelCase : Optional[Any] = self.unet( sample=_SCREAMING_SNAKE_CASE , timestep=_SCREAMING_SNAKE_CASE , encoder_hidden_states=_SCREAMING_SNAKE_CASE , added_cond_kwargs=_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , )[0] if do_classifier_free_guidance: __lowerCAmelCase , __lowerCAmelCase : Dict = noise_pred.split(latents.shape[1] , dim=1 ) __lowerCAmelCase , __lowerCAmelCase : Optional[Any] = noise_pred.chunk(2 ) __lowerCAmelCase , __lowerCAmelCase : int = variance_pred.chunk(2 ) __lowerCAmelCase : Dict = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) __lowerCAmelCase : 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"] ): __lowerCAmelCase , __lowerCAmelCase : Union[str, Any] = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 __lowerCAmelCase : List[str] = self.scheduler.step( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , ).prev_sample # post-processing __lowerCAmelCase : Tuple = self.movq.decode(_SCREAMING_SNAKE_CASE , force_not_quantize=_SCREAMING_SNAKE_CASE )['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"]: __lowerCAmelCase : List[str] = image * 0.5 + 0.5 __lowerCAmelCase : Dict = image.clamp(0 , 1 ) __lowerCAmelCase : Dict = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": __lowerCAmelCase : Union[str, Any] = self.numpy_to_pil(_SCREAMING_SNAKE_CASE ) if not return_dict: return (image,) return ImagePipelineOutput(images=_SCREAMING_SNAKE_CASE )
86
0
import logging import os import sys from dataclasses import dataclass, field from typing import Optional import numpy as np import torch from datasets import load_dataset from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING, AutoConfig, AutoImageProcessor, AutoModelForMaskedImageModeling, HfArgumentParser, Trainer, TrainingArguments, ) 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 lowerCAmelCase__ :List[str] = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version('''4.31.0''') require_version('''datasets>=1.8.0''', '''To fix: pip install -r examples/pytorch/image-pretraining/requirements.txt''') lowerCAmelCase__ :Dict = list(MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING.keys()) lowerCAmelCase__ :Optional[int] = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class __a : _a : Optional[str] = field( default='cifar10' , metadata={'help': 'Name of a dataset from the datasets package'} ) _a : Optional[str] = field( default=_lowerCamelCase , metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'} ) _a : Optional[str] = field( default=_lowerCamelCase , metadata={'help': 'The column name of the images in the files. If not set, will try to use \'image\' or \'img\'.'} , ) _a : Optional[str] = field(default=_lowerCamelCase , metadata={'help': 'A folder containing the training data.'} ) _a : Optional[str] = field(default=_lowerCamelCase , metadata={'help': 'A folder containing the validation data.'} ) _a : Optional[float] = field( default=0.1_5 , metadata={'help': 'Percent to split off of train for validation.'} ) _a : int = field(default=32 , metadata={'help': 'The size of the square patches to use for masking.'} ) _a : float = field( default=0.6 , metadata={'help': 'Percentage of patches to mask.'} , ) _a : Optional[int] = field( default=_lowerCamelCase , metadata={ 'help': ( 'For debugging purposes or quicker training, truncate the number of training examples to this ' 'value if set.' ) } , ) _a : Optional[int] = field( default=_lowerCamelCase , metadata={ 'help': ( 'For debugging purposes or quicker training, truncate the number of evaluation examples to this ' 'value if set.' ) } , ) def UpperCAmelCase__ ( self ) -> List[Any]: """simple docstring""" _UpperCAmelCase = {} if self.train_dir is not None: _UpperCAmelCase = self.train_dir if self.validation_dir is not None: _UpperCAmelCase = self.validation_dir _UpperCAmelCase = data_files if data_files else None @dataclass class __a : _a : str = field( default=_lowerCamelCase , metadata={ 'help': ( 'The model checkpoint for weights initialization. Can be a local path to a pytorch_model.bin or a ' 'checkpoint identifier on the hub. ' 'Don\'t set if you want to train a model from scratch.' ) } , ) _a : Optional[str] = field( default=_lowerCamelCase , metadata={'help': 'If training from scratch, pass a model type from the list: ' + ', '.join(_lowerCamelCase )} , ) _a : Optional[str] = field( default=_lowerCamelCase , metadata={'help': 'Pretrained config name or path if not the same as model_name'} ) _a : Optional[str] = field( default=_lowerCamelCase , metadata={ 'help': ( 'Override some existing default config settings when a model is trained from scratch. Example: ' 'n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index' ) } , ) _a : Optional[str] = field( default=_lowerCamelCase , metadata={'help': 'Where do you want to store (cache) the pretrained models/datasets downloaded from the hub'} , ) _a : str = field( default='main' , metadata={'help': 'The specific model version to use (can be a branch name, tag name or commit id).'} , ) _a : str = field(default=_lowerCamelCase , metadata={'help': 'Name or path of preprocessor config.'} ) _a : bool = field( default=_lowerCamelCase , metadata={ 'help': ( 'Will use the token generated when running `huggingface-cli login` (necessary to use this script ' 'with private models).' ) } , ) _a : Optional[int] = field( default=_lowerCamelCase , metadata={ 'help': ( 'The size (resolution) of each image. If not specified, will use `image_size` of the configuration.' ) } , ) _a : Optional[int] = field( default=_lowerCamelCase , metadata={ 'help': ( 'The size (resolution) of each patch. If not specified, will use `patch_size` of the configuration.' ) } , ) _a : Optional[int] = field( default=_lowerCamelCase , metadata={'help': 'Stride to use for the encoder.'} , ) class __a : def __init__( self , _SCREAMING_SNAKE_CASE=192 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=0.6 ) -> List[str]: """simple docstring""" _UpperCAmelCase = input_size _UpperCAmelCase = mask_patch_size _UpperCAmelCase = model_patch_size _UpperCAmelCase = mask_ratio if self.input_size % self.mask_patch_size != 0: raise ValueError('Input size must be divisible by mask patch size' ) if self.mask_patch_size % self.model_patch_size != 0: raise ValueError('Mask patch size must be divisible by model patch size' ) _UpperCAmelCase = self.input_size // self.mask_patch_size _UpperCAmelCase = self.mask_patch_size // self.model_patch_size _UpperCAmelCase = self.rand_size**2 _UpperCAmelCase = int(np.ceil(self.token_count * self.mask_ratio ) ) def __call__( self ) -> Optional[int]: """simple docstring""" _UpperCAmelCase = np.random.permutation(self.token_count )[: self.mask_count] _UpperCAmelCase = np.zeros(self.token_count , dtype=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = 1 _UpperCAmelCase = mask.reshape((self.rand_size, self.rand_size) ) _UpperCAmelCase = mask.repeat(self.scale , axis=0 ).repeat(self.scale , axis=1 ) return torch.tensor(mask.flatten() ) def lowerCAmelCase__ ( a__: Optional[int] ) -> Tuple: '''simple docstring''' _UpperCAmelCase = torch.stack([example['pixel_values'] for example in examples] ) _UpperCAmelCase = torch.stack([example['mask'] for example in examples] ) return {"pixel_values": pixel_values, "bool_masked_pos": mask} def lowerCAmelCase__ ( ) -> int: '''simple docstring''' _UpperCAmelCase = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('.json' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. _UpperCAmelCase = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _UpperCAmelCase = 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_mim' , _UpperCamelCase , _UpperCamelCase ) # Setup logging logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() _UpperCAmelCase = training_args.get_process_log_level() logger.setLevel(_UpperCamelCase ) transformers.utils.logging.set_verbosity(_UpperCamelCase ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}''' + F'''distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}''' ) logger.info(F'''Training/evaluation parameters {training_args}''' ) # Detecting last checkpoint. _UpperCAmelCase = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: _UpperCAmelCase = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F'''Output directory ({training_args.output_dir}) already exists and is not empty. ''' 'Use --overwrite_output_dir to overcome.' ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( F'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ''' 'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.' ) # Initialize our dataset. _UpperCAmelCase = load_dataset( data_args.dataset_name , data_args.dataset_config_name , data_files=data_args.data_files , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) # If we don't have a validation split, split off a percentage of train as validation. _UpperCAmelCase = None if 'validation' in ds.keys() else data_args.train_val_split if isinstance(data_args.train_val_split , _UpperCamelCase ) and data_args.train_val_split > 0.0: _UpperCAmelCase = ds['train'].train_test_split(data_args.train_val_split ) _UpperCAmelCase = split['train'] _UpperCAmelCase = split['test'] # Create config # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. _UpperCAmelCase = { 'cache_dir': model_args.cache_dir, 'revision': model_args.model_revision, 'use_auth_token': True if model_args.use_auth_token else None, } if model_args.config_name_or_path: _UpperCAmelCase = AutoConfig.from_pretrained(model_args.config_name_or_path , **_UpperCamelCase ) elif model_args.model_name_or_path: _UpperCAmelCase = AutoConfig.from_pretrained(model_args.model_name_or_path , **_UpperCamelCase ) else: _UpperCAmelCase = CONFIG_MAPPING[model_args.model_type]() logger.warning('You are instantiating a new config instance from scratch.' ) if model_args.config_overrides is not None: logger.info(F'''Overriding config: {model_args.config_overrides}''' ) config.update_from_string(model_args.config_overrides ) logger.info(F'''New config: {config}''' ) # make sure the decoder_type is "simmim" (only relevant for BEiT) if hasattr(_UpperCamelCase , 'decoder_type' ): _UpperCAmelCase = 'simmim' # adapt config _UpperCAmelCase = model_args.image_size if model_args.image_size is not None else config.image_size _UpperCAmelCase = model_args.patch_size if model_args.patch_size is not None else config.patch_size _UpperCAmelCase = ( model_args.encoder_stride if model_args.encoder_stride is not None else config.encoder_stride ) config.update( { 'image_size': model_args.image_size, 'patch_size': model_args.patch_size, 'encoder_stride': model_args.encoder_stride, } ) # create image processor if model_args.image_processor_name: _UpperCAmelCase = AutoImageProcessor.from_pretrained(model_args.image_processor_name , **_UpperCamelCase ) elif model_args.model_name_or_path: _UpperCAmelCase = AutoImageProcessor.from_pretrained(model_args.model_name_or_path , **_UpperCamelCase ) else: _UpperCAmelCase = { conf.model_type: image_processor_class for conf, image_processor_class in IMAGE_PROCESSOR_MAPPING.items() } _UpperCAmelCase = IMAGE_PROCESSOR_TYPES[model_args.model_type]() # create model if model_args.model_name_or_path: _UpperCAmelCase = AutoModelForMaskedImageModeling.from_pretrained( model_args.model_name_or_path , from_tf=bool('.ckpt' in model_args.model_name_or_path ) , config=_UpperCamelCase , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) else: logger.info('Training new model from scratch' ) _UpperCAmelCase = AutoModelForMaskedImageModeling.from_config(_UpperCamelCase ) if training_args.do_train: _UpperCAmelCase = ds['train'].column_names else: _UpperCAmelCase = ds['validation'].column_names if data_args.image_column_name is not None: _UpperCAmelCase = data_args.image_column_name elif "image" in column_names: _UpperCAmelCase = 'image' elif "img" in column_names: _UpperCAmelCase = 'img' else: _UpperCAmelCase = column_names[0] # transformations as done in original SimMIM paper # source: https://github.com/microsoft/SimMIM/blob/main/data/data_simmim.py _UpperCAmelCase = Compose( [ Lambda(lambda a__ : img.convert('RGB' ) if img.mode != "RGB" else img ), RandomResizedCrop(model_args.image_size , scale=(0.67, 1.0) , ratio=(3.0 / 4.0, 4.0 / 3.0) ), RandomHorizontalFlip(), ToTensor(), Normalize(mean=image_processor.image_mean , std=image_processor.image_std ), ] ) # create mask generator _UpperCAmelCase = MaskGenerator( input_size=model_args.image_size , mask_patch_size=data_args.mask_patch_size , model_patch_size=model_args.patch_size , mask_ratio=data_args.mask_ratio , ) def preprocess_images(a__: List[Any] ): _UpperCAmelCase = [transforms(_UpperCamelCase ) for image in examples[image_column_name]] _UpperCAmelCase = [mask_generator() for i in range(len(examples[image_column_name] ) )] return examples if training_args.do_train: if "train" not in ds: raise ValueError('--do_train requires a train dataset' ) if data_args.max_train_samples is not None: _UpperCAmelCase = ds['train'].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) # Set the training transforms ds["train"].set_transform(_UpperCamelCase ) if training_args.do_eval: if "validation" not in ds: raise ValueError('--do_eval requires a validation dataset' ) if data_args.max_eval_samples is not None: _UpperCAmelCase = ( ds['validation'].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms ds["validation"].set_transform(_UpperCamelCase ) # Initialize our trainer _UpperCAmelCase = Trainer( model=_UpperCamelCase , args=_UpperCamelCase , train_dataset=ds['train'] if training_args.do_train else None , eval_dataset=ds['validation'] if training_args.do_eval else None , tokenizer=_UpperCamelCase , data_collator=_UpperCamelCase , ) # Training if training_args.do_train: _UpperCAmelCase = None if training_args.resume_from_checkpoint is not None: _UpperCAmelCase = training_args.resume_from_checkpoint elif last_checkpoint is not None: _UpperCAmelCase = last_checkpoint _UpperCAmelCase = trainer.train(resume_from_checkpoint=_UpperCamelCase ) trainer.save_model() trainer.log_metrics('train' , train_result.metrics ) trainer.save_metrics('train' , train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: _UpperCAmelCase = trainer.evaluate() trainer.log_metrics('eval' , _UpperCamelCase ) trainer.save_metrics('eval' , _UpperCamelCase ) # Write model card and (optionally) push to hub _UpperCAmelCase = { 'finetuned_from': model_args.model_name_or_path, 'tasks': 'masked-image-modeling', 'dataset': data_args.dataset_name, 'tags': ['masked-image-modeling'], } if training_args.push_to_hub: trainer.push_to_hub(**_UpperCamelCase ) else: trainer.create_model_card(**_UpperCamelCase ) if __name__ == "__main__": main()
329
"""simple docstring""" import unittest from transformers import BarthezTokenizer, BarthezTokenizerFast, BatchEncoding from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers @require_sentencepiece @slow # see https://github.com/huggingface/transformers/issues/11457 class A__ ( _lowerCamelCase , unittest.TestCase): A_ : Union[str, Any] = BarthezTokenizer A_ : Tuple = BarthezTokenizerFast A_ : Dict = True A_ : List[str] = True def __lowerCamelCase ( self ): super().setUp() __lowerCAmelCase : str = BarthezTokenizerFast.from_pretrained('moussaKam/mbarthez' ) tokenizer.save_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname , legacy_format=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Any = tokenizer def __lowerCamelCase ( self ): __lowerCAmelCase : Optional[Any] = '<pad>' __lowerCAmelCase : Union[str, Any] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : List[Any] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<s>' ) self.assertEqual(vocab_keys[1] , '<pad>' ) self.assertEqual(vocab_keys[-1] , '<mask>' ) self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , 10_11_22 ) def __lowerCamelCase ( self ): self.assertEqual(self.get_tokenizer().vocab_size , 10_11_22 ) @require_torch def __lowerCamelCase ( self ): __lowerCAmelCase : List[str] = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] __lowerCAmelCase : Optional[Any] = [0, 57, 30_18, 7_03_07, 91, 2] __lowerCAmelCase : Optional[int] = self.tokenizer( _SCREAMING_SNAKE_CASE , max_length=len(_SCREAMING_SNAKE_CASE ) , padding=_SCREAMING_SNAKE_CASE , truncation=_SCREAMING_SNAKE_CASE , return_tensors='pt' ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) self.assertEqual((2, 6) , batch.input_ids.shape ) self.assertEqual((2, 6) , batch.attention_mask.shape ) __lowerCAmelCase : List[str] = batch.input_ids.tolist()[0] self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): if not self.test_rust_tokenizer: return __lowerCAmelCase : Tuple = self.get_tokenizer() __lowerCAmelCase : Optional[int] = self.get_rust_tokenizer() __lowerCAmelCase : List[str] = 'I was born in 92000, and this is falsé.' __lowerCAmelCase : Optional[int] = tokenizer.tokenize(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Union[str, Any] = rust_tokenizer.tokenize(_SCREAMING_SNAKE_CASE ) self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = tokenizer.encode(_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = rust_tokenizer.encode(_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE ) self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = self.get_rust_tokenizer() __lowerCAmelCase : List[Any] = tokenizer.encode(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = rust_tokenizer.encode(_SCREAMING_SNAKE_CASE ) self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @slow def __lowerCamelCase ( self ): # fmt: off __lowerCAmelCase : str = {'input_ids': [[0, 4_90, 1_43_28, 45_07, 3_54, 47, 4_36_69, 95, 25, 7_81_17, 2_02_15, 1_97_79, 1_90, 22, 4_00, 4, 3_53_43, 8_03_10, 6_03, 86, 2_49_37, 1_05, 3_34_38, 9_47_62, 1_96, 3_96_42, 7, 15, 1_59_33, 1_73, 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], [0, 1_05_34, 87, 25, 66, 33_58, 1_96, 5_52_89, 8, 8_29_61, 81, 22_04, 7_52_03, 7, 15, 7_63, 1_29_56, 2_16, 1_78, 1_43_28, 95_95, 13_77, 6_96_93, 7, 4_48, 7_10_21, 1_96, 1_81_06, 14_37, 1_39_74, 1_08, 90_83, 4, 4_93_15, 7, 39, 86, 13_26, 27_93, 4_63_33, 4, 4_48, 1_96, 7_45_88, 7, 4_93_15, 7, 39, 21, 8_22, 3_84_70, 74, 21, 6_67_23, 6_24_80, 8, 2_20_50, 5, 2]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on # moussaKam/mbarthez is a french model. So we also use french texts. __lowerCAmelCase : Union[str, Any] = [ 'Le transformeur est un modèle d\'apprentissage profond introduit en 2017, ' 'utilisé principalement dans le domaine du traitement automatique des langues (TAL).', 'À l\'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus ' 'pour gérer des données séquentielles, telles que le langage naturel, pour des tâches ' 'telles que la traduction et la synthèse de texte.', ] self.tokenizer_integration_test_util( expected_encoding=_SCREAMING_SNAKE_CASE , model_name='moussaKam/mbarthez' , revision='c2e4ecbca5e3cd2c37fe1ac285ca4fbdf1366fb6' , sequences=_SCREAMING_SNAKE_CASE , )
86
0
"""simple docstring""" import numpy as np from transformers import BatchFeature from transformers.testing_utils import require_tf, require_torch from .test_feature_extraction_common import FeatureExtractionSavingTestMixin class _lowerCAmelCase ( _lowerCamelCase ): """simple docstring""" __UpperCAmelCase : Tuple = None __UpperCAmelCase : Any = None @property def _lowercase ( self : Tuple ): return self.feat_extract_tester.prepare_feat_extract_dict() def _lowercase ( self : Optional[Any] ): __lowercase = self.feature_extraction_class(**self.feat_extract_dict ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE, "feature_size" ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE, "sampling_rate" ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE, "padding_value" ) ) def _lowercase ( self : Optional[Any] ): __lowercase = self.feat_extract_tester.prepare_inputs_for_common() __lowercase = self.feature_extraction_class(**self.feat_extract_dict ) __lowercase = feat_extract.model_input_names[0] __lowercase = BatchFeature({input_name: speech_inputs} ) self.assertTrue(all(len(_SCREAMING_SNAKE_CASE ) == len(_SCREAMING_SNAKE_CASE ) for x, y in zip(_SCREAMING_SNAKE_CASE, processed_features[input_name] ) ) ) __lowercase = self.feat_extract_tester.prepare_inputs_for_common(equal_length=_SCREAMING_SNAKE_CASE ) __lowercase = BatchFeature({input_name: speech_inputs}, tensor_type="np" ) __lowercase = processed_features[input_name] if len(batch_features_input.shape ) < 3: __lowercase = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) @require_torch def _lowercase ( self : int ): __lowercase = self.feat_extract_tester.prepare_inputs_for_common(equal_length=_SCREAMING_SNAKE_CASE ) __lowercase = self.feature_extraction_class(**self.feat_extract_dict ) __lowercase = feat_extract.model_input_names[0] __lowercase = BatchFeature({input_name: speech_inputs}, tensor_type="pt" ) __lowercase = processed_features[input_name] if len(batch_features_input.shape ) < 3: __lowercase = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) @require_tf def _lowercase ( self : int ): __lowercase = self.feat_extract_tester.prepare_inputs_for_common(equal_length=_SCREAMING_SNAKE_CASE ) __lowercase = self.feature_extraction_class(**self.feat_extract_dict ) __lowercase = feat_extract.model_input_names[0] __lowercase = BatchFeature({input_name: speech_inputs}, tensor_type="tf" ) __lowercase = processed_features[input_name] if len(batch_features_input.shape ) < 3: __lowercase = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) def _lowercase ( self : Any, UpperCAmelCase__ : int=False ): def _inputs_have_equal_length(UpperCAmelCase__ : Optional[Any] ): __lowercase = len(input[0] ) for input_slice in input[1:]: if len(_SCREAMING_SNAKE_CASE ) != length: return False return True def _inputs_are_equal(UpperCAmelCase__ : List[Any], UpperCAmelCase__ : List[Any] ): if len(_SCREAMING_SNAKE_CASE ) != len(_SCREAMING_SNAKE_CASE ): return False for input_slice_a, input_slice_a in zip(_SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE ): if not np.allclose(np.asarray(_SCREAMING_SNAKE_CASE ), np.asarray(_SCREAMING_SNAKE_CASE ), atol=1E-3 ): return False return True __lowercase = self.feature_extraction_class(**self.feat_extract_dict ) __lowercase = self.feat_extract_tester.prepare_inputs_for_common(numpify=_SCREAMING_SNAKE_CASE ) __lowercase = feat_extract.model_input_names[0] __lowercase = BatchFeature({input_name: speech_inputs} ) __lowercase = self.feat_extract_tester.seq_length_diff __lowercase = self.feat_extract_tester.max_seq_length + pad_diff __lowercase = self.feat_extract_tester.min_seq_length __lowercase = self.feat_extract_tester.batch_size __lowercase = self.feat_extract_tester.feature_size # test padding for List[int] + numpy __lowercase = feat_extract.pad(_SCREAMING_SNAKE_CASE, padding=_SCREAMING_SNAKE_CASE ) __lowercase = input_a[input_name] __lowercase = feat_extract.pad(_SCREAMING_SNAKE_CASE, padding="longest" ) __lowercase = input_a[input_name] __lowercase = feat_extract.pad(_SCREAMING_SNAKE_CASE, padding="max_length", max_length=len(speech_inputs[-1] ) ) __lowercase = input_a[input_name] __lowercase = feat_extract.pad(_SCREAMING_SNAKE_CASE, padding="longest", return_tensors="np" ) __lowercase = input_a[input_name] # max_length parameter has to be provided when setting `padding="max_length"` with self.assertRaises(_SCREAMING_SNAKE_CASE ): feat_extract.pad(_SCREAMING_SNAKE_CASE, padding="max_length" )[input_name] __lowercase = feat_extract.pad( _SCREAMING_SNAKE_CASE, padding="max_length", max_length=_SCREAMING_SNAKE_CASE, return_tensors="np" ) __lowercase = input_a[input_name] self.assertFalse(_inputs_have_equal_length(_SCREAMING_SNAKE_CASE ) ) self.assertTrue(_inputs_have_equal_length(_SCREAMING_SNAKE_CASE ) ) self.assertTrue(_inputs_have_equal_length(_SCREAMING_SNAKE_CASE ) ) self.assertTrue(_inputs_are_equal(_SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE ) ) self.assertTrue(len(input_a[0] ) == pad_min_length ) self.assertTrue(len(input_a[1] ) == pad_min_length + pad_diff ) self.assertTrue(input_a.shape[:2] == (batch_size, len(input_a[0] )) ) self.assertTrue(input_a.shape[:2] == (batch_size, pad_max_length) ) if feature_size > 1: self.assertTrue(input_a.shape[2] == input_a.shape[2] == feature_size ) # test padding for `pad_to_multiple_of` for List[int] + numpy __lowercase = feat_extract.pad(_SCREAMING_SNAKE_CASE, pad_to_multiple_of=1_0 ) __lowercase = input_a[input_name] __lowercase = feat_extract.pad(_SCREAMING_SNAKE_CASE, padding="longest", pad_to_multiple_of=1_0 ) __lowercase = input_a[input_name] __lowercase = feat_extract.pad( _SCREAMING_SNAKE_CASE, padding="max_length", pad_to_multiple_of=1_0, max_length=_SCREAMING_SNAKE_CASE ) __lowercase = input_a[input_name] __lowercase = feat_extract.pad( _SCREAMING_SNAKE_CASE, padding="max_length", pad_to_multiple_of=1_0, max_length=_SCREAMING_SNAKE_CASE, return_tensors="np", ) __lowercase = input_a[input_name] self.assertTrue(all(len(_SCREAMING_SNAKE_CASE ) % 1_0 == 0 for x in input_a ) ) self.assertTrue(_inputs_are_equal(_SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE ) ) __lowercase = pad_max_length if pad_max_length % 1_0 == 0 else (pad_max_length // 1_0 + 1) * 1_0 self.assertTrue(all(len(_SCREAMING_SNAKE_CASE ) == expected_mult_pad_length for x in input_a ) ) self.assertEqual(input_a.shape[:2], (batch_size, expected_mult_pad_length) ) if feature_size > 1: self.assertTrue(input_a.shape[2] == feature_size ) # Check padding value is correct __lowercase = (np.ones(self.feat_extract_tester.feature_size ) * feat_extract.padding_value).sum() self.assertTrue( abs(np.asarray(input_a[0] )[pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length) ) < 1E-3 ) self.assertTrue( abs( np.asarray(input_a[1] )[pad_min_length + pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - pad_diff) ) < 1E-3 ) self.assertTrue( abs( np.asarray(input_a[2] )[pad_min_length + 2 * pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - 2 * pad_diff) ) < 1E-3 ) self.assertTrue( abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length) ) < 1E-3 ) self.assertTrue( abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (expected_mult_pad_length - pad_min_length) ) < 1E-3 ) def _lowercase ( self : int, UpperCAmelCase__ : Union[str, Any]=False ): def _inputs_have_equal_length(UpperCAmelCase__ : Optional[Any] ): __lowercase = len(input[0] ) for input_slice in input[1:]: if len(_SCREAMING_SNAKE_CASE ) != length: return False return True def _inputs_are_equal(UpperCAmelCase__ : int, UpperCAmelCase__ : Union[str, Any] ): if len(_SCREAMING_SNAKE_CASE ) != len(_SCREAMING_SNAKE_CASE ): return False for input_slice_a, input_slice_a in zip(_SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE ): if not np.allclose(np.asarray(_SCREAMING_SNAKE_CASE ), np.asarray(_SCREAMING_SNAKE_CASE ), atol=1E-3 ): return False return True __lowercase = self.feature_extraction_class(**self.feat_extract_dict ) __lowercase = self.feat_extract_tester.prepare_inputs_for_common(numpify=_SCREAMING_SNAKE_CASE ) __lowercase = feat_extract.model_input_names[0] __lowercase = BatchFeature({input_name: speech_inputs} ) # truncate to smallest __lowercase = feat_extract.pad( _SCREAMING_SNAKE_CASE, padding="max_length", max_length=len(speech_inputs[0] ), truncation=_SCREAMING_SNAKE_CASE ) __lowercase = input_a[input_name] __lowercase = feat_extract.pad(_SCREAMING_SNAKE_CASE, padding="max_length", max_length=len(speech_inputs[0] ) ) __lowercase = input_a[input_name] self.assertTrue(_inputs_have_equal_length(_SCREAMING_SNAKE_CASE ) ) self.assertFalse(_inputs_have_equal_length(_SCREAMING_SNAKE_CASE ) ) # truncate to smallest with np __lowercase = feat_extract.pad( _SCREAMING_SNAKE_CASE, padding="max_length", max_length=len(speech_inputs[0] ), return_tensors="np", truncation=_SCREAMING_SNAKE_CASE, ) __lowercase = input_a[input_name] __lowercase = feat_extract.pad( _SCREAMING_SNAKE_CASE, padding="max_length", max_length=len(speech_inputs[0] ), return_tensors="np" ) __lowercase = input_a[input_name] self.assertTrue(_inputs_have_equal_length(_SCREAMING_SNAKE_CASE ) ) self.assertTrue(input_a.shape[1] == len(speech_inputs[0] ) ) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(_SCREAMING_SNAKE_CASE ) ) # truncate to middle __lowercase = feat_extract.pad( _SCREAMING_SNAKE_CASE, padding="max_length", max_length=len(speech_inputs[1] ), truncation=_SCREAMING_SNAKE_CASE, return_tensors="np", ) __lowercase = input_a[input_name] __lowercase = feat_extract.pad( _SCREAMING_SNAKE_CASE, padding="max_length", max_length=len(speech_inputs[1] ), truncation=_SCREAMING_SNAKE_CASE ) __lowercase = input_a[input_name] __lowercase = feat_extract.pad( _SCREAMING_SNAKE_CASE, padding="max_length", max_length=len(speech_inputs[1] ), return_tensors="np" ) __lowercase = input_a[input_name] self.assertTrue(input_a.shape[1] == len(speech_inputs[1] ) ) self.assertTrue(_inputs_have_equal_length(_SCREAMING_SNAKE_CASE ) ) self.assertTrue(_inputs_have_equal_length(_SCREAMING_SNAKE_CASE ) ) self.assertTrue(_inputs_are_equal(_SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE ) ) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(_SCREAMING_SNAKE_CASE ) ) self.assertTrue(len(input_a[-1] ) == len(speech_inputs[-1] ) ) # padding has to be max_length when setting `truncation=True` with self.assertRaises(_SCREAMING_SNAKE_CASE ): feat_extract.pad(_SCREAMING_SNAKE_CASE, truncation=_SCREAMING_SNAKE_CASE )[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(_SCREAMING_SNAKE_CASE ): feat_extract.pad(_SCREAMING_SNAKE_CASE, padding="longest", truncation=_SCREAMING_SNAKE_CASE )[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(_SCREAMING_SNAKE_CASE ): feat_extract.pad(_SCREAMING_SNAKE_CASE, padding="longest", truncation=_SCREAMING_SNAKE_CASE )[input_name] # max_length parameter has to be provided when setting `truncation=True` and padding="max_length" with self.assertRaises(_SCREAMING_SNAKE_CASE ): feat_extract.pad(_SCREAMING_SNAKE_CASE, padding="max_length", truncation=_SCREAMING_SNAKE_CASE )[input_name] # test truncation for `pad_to_multiple_of` for List[int] + numpy __lowercase = 1_2 __lowercase = feat_extract.pad( _SCREAMING_SNAKE_CASE, padding="max_length", max_length=len(speech_inputs[0] ), pad_to_multiple_of=_SCREAMING_SNAKE_CASE, truncation=_SCREAMING_SNAKE_CASE, ) __lowercase = input_a[input_name] __lowercase = feat_extract.pad( _SCREAMING_SNAKE_CASE, padding="max_length", max_length=len(speech_inputs[0] ), pad_to_multiple_of=_SCREAMING_SNAKE_CASE, ) __lowercase = input_a[input_name] # retrieve expected_length as multiple of pad_to_multiple_of __lowercase = len(speech_inputs[0] ) if expected_length % pad_to_multiple_of != 0: __lowercase = ((len(speech_inputs[0] ) // pad_to_multiple_of) + 1) * pad_to_multiple_of self.assertTrue(len(input_a[0] ) == expected_length ) self.assertTrue(_inputs_have_equal_length(_SCREAMING_SNAKE_CASE ) ) self.assertFalse(_inputs_have_equal_length(_SCREAMING_SNAKE_CASE ) ) def _lowercase ( self : Dict ): self._check_padding(numpify=_SCREAMING_SNAKE_CASE ) def _lowercase ( self : str ): self._check_padding(numpify=_SCREAMING_SNAKE_CASE ) def _lowercase ( self : Union[str, Any] ): self._check_truncation(numpify=_SCREAMING_SNAKE_CASE ) def _lowercase ( self : Union[str, Any] ): self._check_truncation(numpify=_SCREAMING_SNAKE_CASE ) @require_torch def _lowercase ( self : Optional[Any] ): __lowercase = self.feature_extraction_class(**self.feat_extract_dict ) __lowercase = self.feat_extract_tester.prepare_inputs_for_common() __lowercase = feat_extract.model_input_names[0] __lowercase = BatchFeature({input_name: speech_inputs} ) __lowercase = feat_extract.pad(_SCREAMING_SNAKE_CASE, padding="longest", return_tensors="np" )[input_name] __lowercase = feat_extract.pad(_SCREAMING_SNAKE_CASE, padding="longest", return_tensors="pt" )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_pt.numpy().astype(np.floataa ).sum() ) < 1E-2 ) @require_tf def _lowercase ( self : List[Any] ): __lowercase = self.feature_extraction_class(**self.feat_extract_dict ) __lowercase = self.feat_extract_tester.prepare_inputs_for_common() __lowercase = feat_extract.model_input_names[0] __lowercase = BatchFeature({input_name: speech_inputs} ) __lowercase = feat_extract.pad(_SCREAMING_SNAKE_CASE, padding="longest", return_tensors="np" )[input_name] __lowercase = feat_extract.pad(_SCREAMING_SNAKE_CASE, padding="longest", return_tensors="tf" )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_tf.numpy().astype(np.floataa ).sum() ) < 1E-2 ) def _lowercase ( self : Any ): __lowercase = self.feat_extract_dict __lowercase = True __lowercase = self.feature_extraction_class(**_SCREAMING_SNAKE_CASE ) __lowercase = self.feat_extract_tester.prepare_inputs_for_common() __lowercase = [len(_SCREAMING_SNAKE_CASE ) for x in speech_inputs] __lowercase = feat_extract.model_input_names[0] __lowercase = BatchFeature({input_name: speech_inputs} ) __lowercase = feat_extract.pad(_SCREAMING_SNAKE_CASE, padding="longest", return_tensors="np" ) self.assertIn("attention_mask", _SCREAMING_SNAKE_CASE ) self.assertListEqual(list(processed.attention_mask.shape ), list(processed[input_name].shape[:2] ) ) self.assertListEqual(processed.attention_mask.sum(-1 ).tolist(), _SCREAMING_SNAKE_CASE ) def _lowercase ( self : Union[str, Any] ): __lowercase = self.feat_extract_dict __lowercase = True __lowercase = self.feature_extraction_class(**_SCREAMING_SNAKE_CASE ) __lowercase = self.feat_extract_tester.prepare_inputs_for_common() __lowercase = [len(_SCREAMING_SNAKE_CASE ) for x in speech_inputs] __lowercase = feat_extract.model_input_names[0] __lowercase = BatchFeature({input_name: speech_inputs} ) __lowercase = min(_SCREAMING_SNAKE_CASE ) __lowercase = feat_extract.pad( _SCREAMING_SNAKE_CASE, padding="max_length", max_length=_SCREAMING_SNAKE_CASE, truncation=_SCREAMING_SNAKE_CASE, return_tensors="np" ) self.assertIn("attention_mask", _SCREAMING_SNAKE_CASE ) self.assertListEqual( list(processed_pad.attention_mask.shape ), [processed_pad[input_name].shape[0], max_length] ) self.assertListEqual( processed_pad.attention_mask[:, :max_length].sum(-1 ).tolist(), [max_length for x in speech_inputs] )
17
"""simple docstring""" 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__ = { """sail/poolformer_s12""": """https://huggingface.co/sail/poolformer_s12/resolve/main/config.json""", # See all PoolFormer models at https://huggingface.co/models?filter=poolformer } class A__ ( _lowerCamelCase): A_ : Optional[int] = 'poolformer' def __init__( self , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=4.0 , _SCREAMING_SNAKE_CASE=[2, 2, 6, 2] , _SCREAMING_SNAKE_CASE=[64, 1_28, 3_20, 5_12] , _SCREAMING_SNAKE_CASE=[7, 3, 3, 3] , _SCREAMING_SNAKE_CASE=[4, 2, 2, 2] , _SCREAMING_SNAKE_CASE=[2, 1, 1, 1] , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=1E-5 , _SCREAMING_SNAKE_CASE=0.02 , **_SCREAMING_SNAKE_CASE , ): __lowerCAmelCase : int = num_channels __lowerCAmelCase : str = patch_size __lowerCAmelCase : Optional[Any] = stride __lowerCAmelCase : Optional[int] = padding __lowerCAmelCase : List[Any] = pool_size __lowerCAmelCase : int = hidden_sizes __lowerCAmelCase : str = mlp_ratio __lowerCAmelCase : Optional[int] = depths __lowerCAmelCase : str = patch_sizes __lowerCAmelCase : str = strides __lowerCAmelCase : Optional[int] = num_encoder_blocks __lowerCAmelCase : Any = drop_path_rate __lowerCAmelCase : Any = hidden_act __lowerCAmelCase : Dict = use_layer_scale __lowerCAmelCase : Union[str, Any] = layer_scale_init_value __lowerCAmelCase : Dict = initializer_range super().__init__(**_SCREAMING_SNAKE_CASE ) class A__ ( _lowerCamelCase): A_ : List[str] = version.parse('1.11') @property def __lowerCamelCase ( self ): return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def __lowerCamelCase ( self ): return 2E-3
86
0
"""simple docstring""" import gc import unittest import numpy as np import torch from diffusers import AutoencoderKL, DDIMScheduler, DiTPipeline, DPMSolverMultistepScheduler, TransformeraDModel from diffusers.utils import is_xformers_available, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS, CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class _UpperCAmelCase ( _lowerCamelCase , unittest.TestCase): _lowerCAmelCase : Union[str, Any] = DiTPipeline _lowerCAmelCase : Union[str, Any] = CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS _lowerCAmelCase : List[Any] = PipelineTesterMixin.required_optional_params - { 'latents', 'num_images_per_prompt', 'callback', 'callback_steps', } _lowerCAmelCase : Optional[Any] = CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS _lowerCAmelCase : Tuple = False def _snake_case ( self : Optional[int] ): torch.manual_seed(0 ) snake_case_ : List[str] = TransformeraDModel( sample_size=16 , num_layers=2 , patch_size=4 , attention_head_dim=8 , num_attention_heads=2 , in_channels=4 , out_channels=8 , attention_bias=_SCREAMING_SNAKE_CASE , activation_fn='''gelu-approximate''' , num_embeds_ada_norm=1000 , norm_type='''ada_norm_zero''' , norm_elementwise_affine=_SCREAMING_SNAKE_CASE , ) snake_case_ : str = AutoencoderKL() snake_case_ : Union[str, Any] = DDIMScheduler() snake_case_ : Dict = {'transformer': transformer.eval(), 'vae': vae.eval(), 'scheduler': scheduler} return components def _snake_case ( self : int , lowercase_ : Dict , lowercase_ : Tuple=0 ): if str(_SCREAMING_SNAKE_CASE ).startswith('''mps''' ): snake_case_ : List[str] = torch.manual_seed(_SCREAMING_SNAKE_CASE ) else: snake_case_ : List[str] = torch.Generator(device=_SCREAMING_SNAKE_CASE ).manual_seed(_SCREAMING_SNAKE_CASE ) snake_case_ : Any = { 'class_labels': [1], 'generator': generator, 'num_inference_steps': 2, 'output_type': 'numpy', } return inputs def _snake_case ( self : List[Any] ): snake_case_ : List[str] = 'cpu' snake_case_ : Any = self.get_dummy_components() snake_case_ : Union[str, Any] = self.pipeline_class(**_SCREAMING_SNAKE_CASE ) pipe.to(_SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) snake_case_ : Tuple = self.get_dummy_inputs(_SCREAMING_SNAKE_CASE ) snake_case_ : List[str] = pipe(**_SCREAMING_SNAKE_CASE ).images snake_case_ : List[str] = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 16, 16, 3) ) snake_case_ : Optional[int] = np.array([0.29_46, 0.66_01, 0.43_29, 0.32_96, 0.41_44, 0.53_19, 0.72_73, 0.50_13, 0.44_57] ) snake_case_ : List[Any] = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(_SCREAMING_SNAKE_CASE , 1E-3 ) def _snake_case ( self : List[str] ): self._test_inference_batch_single_identical(relax_max_difference=_SCREAMING_SNAKE_CASE , expected_max_diff=1E-3 ) @unittest.skipIf( torch_device != '''cuda''' or not is_xformers_available() , reason='''XFormers attention is only available with CUDA and `xformers` installed''' , ) def _snake_case ( self : int ): self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 ) @require_torch_gpu @slow class _UpperCAmelCase ( unittest.TestCase): def _snake_case ( self : Union[str, Any] ): super().tearDown() gc.collect() torch.cuda.empty_cache() def _snake_case ( self : Optional[Any] ): snake_case_ : Dict = torch.manual_seed(0 ) snake_case_ : int = DiTPipeline.from_pretrained('''facebook/DiT-XL-2-256''' ) pipe.to('''cuda''' ) snake_case_ : Optional[Any] = ['vase', 'umbrella', 'white shark', 'white wolf'] snake_case_ : Optional[Any] = pipe.get_label_ids(_SCREAMING_SNAKE_CASE ) snake_case_ : Optional[Any] = pipe(_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , num_inference_steps=40 , output_type='''np''' ).images for word, image in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): snake_case_ : Tuple = load_numpy( f"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/dit/{word}.npy" ) assert np.abs((expected_image - image).max() ) < 1E-2 def _snake_case ( self : Optional[Any] ): snake_case_ : Any = DiTPipeline.from_pretrained('''facebook/DiT-XL-2-512''' ) snake_case_ : Union[str, Any] = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.to('''cuda''' ) snake_case_ : Dict = ['vase', 'umbrella'] snake_case_ : List[str] = pipe.get_label_ids(_SCREAMING_SNAKE_CASE ) snake_case_ : Any = torch.manual_seed(0 ) snake_case_ : Optional[Any] = pipe(_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , num_inference_steps=25 , output_type='''np''' ).images for word, image in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): snake_case_ : Dict = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' f"/dit/{word}_512.npy" ) assert np.abs((expected_image - image).max() ) < 1E-1
264
"""simple docstring""" import gc import unittest import numpy as np import torch from diffusers import AutoencoderKL, DDIMScheduler, DiTPipeline, DPMSolverMultistepScheduler, TransformeraDModel from diffusers.utils import is_xformers_available, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS, CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class A__ ( _lowerCamelCase , unittest.TestCase): A_ : Union[str, Any] = DiTPipeline A_ : Union[str, Any] = CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS A_ : List[Any] = PipelineTesterMixin.required_optional_params - { 'latents', 'num_images_per_prompt', 'callback', 'callback_steps', } A_ : Optional[Any] = CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS A_ : Tuple = False def __lowerCamelCase ( self ): torch.manual_seed(0 ) __lowerCAmelCase : List[str] = TransformeraDModel( sample_size=16 , num_layers=2 , patch_size=4 , attention_head_dim=8 , num_attention_heads=2 , in_channels=4 , out_channels=8 , attention_bias=_SCREAMING_SNAKE_CASE , activation_fn='gelu-approximate' , num_embeds_ada_norm=10_00 , norm_type='ada_norm_zero' , norm_elementwise_affine=_SCREAMING_SNAKE_CASE , ) __lowerCAmelCase : str = AutoencoderKL() __lowerCAmelCase : Union[str, Any] = DDIMScheduler() __lowerCAmelCase : Dict = {'transformer': transformer.eval(), 'vae': vae.eval(), 'scheduler': scheduler} return components def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=0 ): if str(_SCREAMING_SNAKE_CASE ).startswith('mps' ): __lowerCAmelCase : List[str] = torch.manual_seed(_SCREAMING_SNAKE_CASE ) else: __lowerCAmelCase : List[str] = torch.Generator(device=_SCREAMING_SNAKE_CASE ).manual_seed(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Any = { 'class_labels': [1], 'generator': generator, 'num_inference_steps': 2, 'output_type': 'numpy', } return inputs def __lowerCamelCase ( self ): __lowerCAmelCase : List[str] = 'cpu' __lowerCAmelCase : Any = self.get_dummy_components() __lowerCAmelCase : Union[str, Any] = self.pipeline_class(**_SCREAMING_SNAKE_CASE ) pipe.to(_SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Tuple = self.get_dummy_inputs(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = pipe(**_SCREAMING_SNAKE_CASE ).images __lowerCAmelCase : List[str] = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 16, 16, 3) ) __lowerCAmelCase : Optional[int] = np.array([0.2946, 0.6601, 0.4329, 0.3296, 0.4144, 0.5319, 0.7273, 0.5013, 0.4457] ) __lowerCAmelCase : List[Any] = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(_SCREAMING_SNAKE_CASE , 1E-3 ) def __lowerCamelCase ( self ): self._test_inference_batch_single_identical(relax_max_difference=_SCREAMING_SNAKE_CASE , expected_max_diff=1E-3 ) @unittest.skipIf( torch_device != 'cuda' or not is_xformers_available() , reason='XFormers attention is only available with CUDA and `xformers` installed' , ) def __lowerCamelCase ( self ): self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 ) @require_torch_gpu @slow class A__ ( unittest.TestCase): def __lowerCamelCase ( self ): super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCamelCase ( self ): __lowerCAmelCase : Dict = torch.manual_seed(0 ) __lowerCAmelCase : int = DiTPipeline.from_pretrained('facebook/DiT-XL-2-256' ) pipe.to('cuda' ) __lowerCAmelCase : Optional[Any] = ['vase', 'umbrella', 'white shark', 'white wolf'] __lowerCAmelCase : Optional[Any] = pipe.get_label_ids(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = pipe(_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , num_inference_steps=40 , output_type='np' ).images for word, image in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Tuple = load_numpy( f"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/dit/{word}.npy" ) assert np.abs((expected_image - image).max() ) < 1E-2 def __lowerCamelCase ( self ): __lowerCAmelCase : Any = DiTPipeline.from_pretrained('facebook/DiT-XL-2-512' ) __lowerCAmelCase : Union[str, Any] = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.to('cuda' ) __lowerCAmelCase : Dict = ['vase', 'umbrella'] __lowerCAmelCase : List[str] = pipe.get_label_ids(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Any = torch.manual_seed(0 ) __lowerCAmelCase : Optional[Any] = pipe(_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , num_inference_steps=25 , output_type='np' ).images for word, image in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Dict = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' f"/dit/{word}_512.npy" ) assert np.abs((expected_image - image).max() ) < 1E-1
86
0
import re import string import numpy as np import datasets __A = "\nReturns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.\n" __A = "\nArgs:\n predictions: List of predicted texts.\n references: List of reference texts.\n regexes_to_ignore: List, defaults to None. Regex expressions of characters to\n ignore when calculating the exact matches. Note: these regexes are removed\n from the input data before the changes based on the options below (e.g. ignore_case,\n ignore_punctuation, ignore_numbers) are applied.\n ignore_case: Boolean, defaults to False. If true, turns everything\n to lowercase so that capitalization differences are ignored.\n ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\n ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\nReturns:\n exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive.\nExamples:\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results[\"exact_match\"], 1))\n 25.0\n\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results[\"exact_match\"], 1))\n 50.0\n\n\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\", \"YELL\"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results[\"exact_match\"], 1))\n 75.0\n\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\", \"YELL\"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True)\n >>> print(round(results[\"exact_match\"], 1))\n 100.0\n\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"The cat sat on the mat.\", \"Theaters are great.\", \"It's like comparing oranges and apples.\"]\n >>> preds = [\"The cat sat on the mat?\", \"Theaters are great.\", \"It's like comparing apples and oranges.\"]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results[\"exact_match\"], 1))\n 33.3\n\n" __A = "\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __lowerCAmelCase ( datasets.Metric ): """simple docstring""" def lowercase_ ( self ) -> List[str]: '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('string' , id='sequence' ), 'references': datasets.Value('string' , id='sequence' ), } ) , reference_urls=[] , ) def lowercase_ ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=None , lowerCamelCase__=False , lowerCamelCase__=False , lowerCamelCase__=False , ) -> Any: '''simple docstring''' if regexes_to_ignore is not None: for s in regexes_to_ignore: __lowerCamelCase = np.array([re.sub(_SCREAMING_SNAKE_CASE , '' , _SCREAMING_SNAKE_CASE ) for x in predictions] ) __lowerCamelCase = np.array([re.sub(_SCREAMING_SNAKE_CASE , '' , _SCREAMING_SNAKE_CASE ) for x in references] ) else: __lowerCamelCase = np.asarray(_SCREAMING_SNAKE_CASE ) __lowerCamelCase = np.asarray(_SCREAMING_SNAKE_CASE ) if ignore_case: __lowerCamelCase = np.char.lower(_SCREAMING_SNAKE_CASE ) __lowerCamelCase = np.char.lower(_SCREAMING_SNAKE_CASE ) if ignore_punctuation: __lowerCamelCase = string.punctuation.maketrans('' , '' , string.punctuation ) __lowerCamelCase = np.char.translate(_SCREAMING_SNAKE_CASE , table=_SCREAMING_SNAKE_CASE ) __lowerCamelCase = np.char.translate(_SCREAMING_SNAKE_CASE , table=_SCREAMING_SNAKE_CASE ) if ignore_numbers: __lowerCamelCase = string.digits.maketrans('' , '' , string.digits ) __lowerCamelCase = np.char.translate(_SCREAMING_SNAKE_CASE , table=_SCREAMING_SNAKE_CASE ) __lowerCamelCase = np.char.translate(_SCREAMING_SNAKE_CASE , table=_SCREAMING_SNAKE_CASE ) __lowerCamelCase = predictions == references return {"exact_match": np.mean(_SCREAMING_SNAKE_CASE ) * 100}
90
"""simple docstring""" import gc import random import unittest import numpy as np import torch from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import floats_tensor, load_image, load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class A__ ( _lowerCamelCase , unittest.TestCase): A_ : str = ShapEImgaImgPipeline A_ : str = ['image'] A_ : int = ['image'] A_ : Tuple = [ 'num_images_per_prompt', 'num_inference_steps', 'generator', 'latents', 'guidance_scale', 'frame_size', 'output_type', 'return_dict', ] A_ : Tuple = False @property def __lowerCamelCase ( self ): return 32 @property def __lowerCamelCase ( self ): return 32 @property def __lowerCamelCase ( self ): return self.time_input_dim * 4 @property def __lowerCamelCase ( self ): return 8 @property def __lowerCamelCase ( self ): torch.manual_seed(0 ) __lowerCAmelCase : Any = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=64 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=1 , ) __lowerCAmelCase : Tuple = CLIPVisionModel(_SCREAMING_SNAKE_CASE ) return model @property def __lowerCamelCase ( self ): __lowerCAmelCase : Any = CLIPImageProcessor( crop_size=2_24 , do_center_crop=_SCREAMING_SNAKE_CASE , do_normalize=_SCREAMING_SNAKE_CASE , do_resize=_SCREAMING_SNAKE_CASE , image_mean=[0.4814_5466, 0.457_8275, 0.4082_1073] , image_std=[0.2686_2954, 0.2613_0258, 0.2757_7711] , resample=3 , size=2_24 , ) return image_processor @property def __lowerCamelCase ( self ): torch.manual_seed(0 ) __lowerCAmelCase : Optional[Any] = { 'num_attention_heads': 2, 'attention_head_dim': 16, 'embedding_dim': self.time_input_dim, 'num_embeddings': 32, 'embedding_proj_dim': self.text_embedder_hidden_size, 'time_embed_dim': self.time_embed_dim, 'num_layers': 1, 'clip_embed_dim': self.time_input_dim * 2, 'additional_embeddings': 0, 'time_embed_act_fn': 'gelu', 'norm_in_type': 'layer', 'embedding_proj_norm_type': 'layer', 'encoder_hid_proj_type': None, 'added_emb_type': None, } __lowerCAmelCase : List[Any] = PriorTransformer(**_SCREAMING_SNAKE_CASE ) return model @property def __lowerCamelCase ( self ): torch.manual_seed(0 ) __lowerCAmelCase : Dict = { 'param_shapes': ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), 'd_latent': self.time_input_dim, 'd_hidden': self.renderer_dim, 'n_output': 12, 'background': ( 0.1, 0.1, 0.1, ), } __lowerCAmelCase : int = ShapERenderer(**_SCREAMING_SNAKE_CASE ) return model def __lowerCamelCase ( self ): __lowerCAmelCase : Any = self.dummy_prior __lowerCAmelCase : List[Any] = self.dummy_image_encoder __lowerCAmelCase : int = self.dummy_image_processor __lowerCAmelCase : Any = self.dummy_renderer __lowerCAmelCase : Any = HeunDiscreteScheduler( beta_schedule='exp' , num_train_timesteps=10_24 , prediction_type='sample' , use_karras_sigmas=_SCREAMING_SNAKE_CASE , clip_sample=_SCREAMING_SNAKE_CASE , clip_sample_range=1.0 , ) __lowerCAmelCase : Tuple = { 'prior': prior, 'image_encoder': image_encoder, 'image_processor': image_processor, 'renderer': renderer, 'scheduler': scheduler, } return components def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=0 ): __lowerCAmelCase : Optional[Any] = floats_tensor((1, 3, 64, 64) , rng=random.Random(_SCREAMING_SNAKE_CASE ) ).to(_SCREAMING_SNAKE_CASE ) if str(_SCREAMING_SNAKE_CASE ).startswith('mps' ): __lowerCAmelCase : int = torch.manual_seed(_SCREAMING_SNAKE_CASE ) else: __lowerCAmelCase : str = torch.Generator(device=_SCREAMING_SNAKE_CASE ).manual_seed(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = { 'image': input_image, 'generator': generator, 'num_inference_steps': 1, 'frame_size': 32, 'output_type': 'np', } return inputs def __lowerCamelCase ( self ): __lowerCAmelCase : str = 'cpu' __lowerCAmelCase : Dict = self.get_dummy_components() __lowerCAmelCase : Optional[int] = self.pipeline_class(**_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = pipe.to(_SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = pipe(**self.get_dummy_inputs(_SCREAMING_SNAKE_CASE ) ) __lowerCAmelCase : Any = output.images[0] __lowerCAmelCase : Optional[Any] = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) __lowerCAmelCase : List[Any] = np.array( [ 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def __lowerCamelCase ( self ): # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def __lowerCamelCase ( self ): __lowerCAmelCase : str = torch_device == 'cpu' __lowerCAmelCase : Optional[Any] = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=_SCREAMING_SNAKE_CASE , relax_max_difference=_SCREAMING_SNAKE_CASE , ) def __lowerCamelCase ( self ): __lowerCAmelCase : str = self.get_dummy_components() __lowerCAmelCase : List[str] = self.pipeline_class(**_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = pipe.to(_SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = 1 __lowerCAmelCase : List[str] = 2 __lowerCAmelCase : Union[str, Any] = self.get_dummy_inputs(_SCREAMING_SNAKE_CASE ) for key in inputs.keys(): if key in self.batch_params: __lowerCAmelCase : Optional[Any] = batch_size * [inputs[key]] __lowerCAmelCase : List[str] = pipe(**_SCREAMING_SNAKE_CASE , num_images_per_prompt=_SCREAMING_SNAKE_CASE )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class A__ ( unittest.TestCase): def __lowerCamelCase ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCamelCase ( self ): __lowerCAmelCase : int = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/shap_e/corgi.png' ) __lowerCAmelCase : Any = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/shap_e/test_shap_e_img2img_out.npy' ) __lowerCAmelCase : Union[str, Any] = ShapEImgaImgPipeline.from_pretrained('openai/shap-e-img2img' ) __lowerCAmelCase : Dict = pipe.to(_SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Tuple = torch.Generator(device=_SCREAMING_SNAKE_CASE ).manual_seed(0 ) __lowerCAmelCase : int = pipe( _SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , guidance_scale=3.0 , num_inference_steps=64 , frame_size=64 , output_type='np' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
86
0
'''simple docstring''' from __future__ import annotations from math import pi, sqrt def snake_case__ ( _A: Tuple , _A: Dict ) -> int: '''simple docstring''' if inductance <= 0: raise ValueError("""Inductance cannot be 0 or negative""" ) elif capacitance <= 0: raise ValueError("""Capacitance cannot be 0 or negative""" ) else: return ( "Resonant frequency", float(1 / (2 * pi * (sqrt(inductance * capacitance ))) ), ) if __name__ == "__main__": import doctest doctest.testmod()
272
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase__ = {"""configuration_fnet""": ["""FNET_PRETRAINED_CONFIG_ARCHIVE_MAP""", """FNetConfig"""]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = ["""FNetTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = ["""FNetTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ """FNET_PRETRAINED_MODEL_ARCHIVE_LIST""", """FNetForMaskedLM""", """FNetForMultipleChoice""", """FNetForNextSentencePrediction""", """FNetForPreTraining""", """FNetForQuestionAnswering""", """FNetForSequenceClassification""", """FNetForTokenClassification""", """FNetLayer""", """FNetModel""", """FNetPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_fnet import FNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet import FNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet_fast import FNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_fnet import ( FNET_PRETRAINED_MODEL_ARCHIVE_LIST, FNetForMaskedLM, FNetForMultipleChoice, FNetForNextSentencePrediction, FNetForPreTraining, FNetForQuestionAnswering, FNetForSequenceClassification, FNetForTokenClassification, FNetLayer, FNetModel, FNetPreTrainedModel, ) else: import sys lowerCamelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
86
0
from __future__ import annotations class snake_case : '''simple docstring''' def __init__( self : int , lowerCAmelCase : Any) -> Optional[int]: """simple docstring""" _snake_case : Any = order # a_{0} ... a_{k} _snake_case : Optional[int] = [1.0] + [0.0] * order # b_{0} ... b_{k} _snake_case : Dict = [1.0] + [0.0] * order # x[n-1] ... x[n-k] _snake_case : Union[str, Any] = [0.0] * self.order # y[n-1] ... y[n-k] _snake_case : List[Any] = [0.0] * self.order def UpperCamelCase_ ( self : List[str] , lowerCAmelCase : Any , lowerCAmelCase : List[str]) -> Tuple: """simple docstring""" if len(_SCREAMING_SNAKE_CASE) < self.order: _snake_case : int = [1.0, *a_coeffs] if len(_SCREAMING_SNAKE_CASE) != self.order + 1: _snake_case : Any = ( F'''Expected a_coeffs to have {self.order + 1} elements ''' F'''for {self.order}-order filter, got {len(_SCREAMING_SNAKE_CASE)}''' ) raise ValueError(_SCREAMING_SNAKE_CASE) if len(_SCREAMING_SNAKE_CASE) != self.order + 1: _snake_case : int = ( F'''Expected b_coeffs to have {self.order + 1} elements ''' F'''for {self.order}-order filter, got {len(_SCREAMING_SNAKE_CASE)}''' ) raise ValueError(_SCREAMING_SNAKE_CASE) _snake_case : Tuple = a_coeffs _snake_case : Optional[int] = b_coeffs def UpperCamelCase_ ( self : Dict , lowerCAmelCase : Any) -> Optional[Any]: """simple docstring""" _snake_case : Dict = 0.0 # Start at index 1 and do index 0 at the end. for i in range(1 , self.order + 1): result += ( self.b_coeffs[i] * self.input_history[i - 1] - self.a_coeffs[i] * self.output_history[i - 1] ) _snake_case : Union[str, Any] = (result + self.b_coeffs[0] * sample) / self.a_coeffs[0] _snake_case : str = self.input_history[:-1] _snake_case : int = self.output_history[:-1] _snake_case : List[Any] = sample _snake_case : str = result return result
317
"""simple docstring""" import math import sys def __lowerCAmelCase (_UpperCamelCase ): if number != int(_UpperCamelCase ): raise ValueError('the value of input must be a natural number' ) if number < 0: raise ValueError('the value of input must not be a negative number' ) if number == 0: return 1 __lowerCAmelCase : Any = [-1] * (number + 1) __lowerCAmelCase : List[Any] = 0 for i in range(1 , number + 1 ): __lowerCAmelCase : List[Any] = sys.maxsize __lowerCAmelCase : Optional[int] = int(math.sqrt(_UpperCamelCase ) ) for j in range(1 , root + 1 ): __lowerCAmelCase : Optional[Any] = 1 + answers[i - (j**2)] __lowerCAmelCase : Any = min(_UpperCamelCase , _UpperCamelCase ) __lowerCAmelCase : List[str] = answer return answers[number] if __name__ == "__main__": import doctest doctest.testmod()
86
0
'''simple docstring''' from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def UpperCAmelCase_ ( __lowerCamelCase : Union[str, Any] ,__lowerCamelCase : str ,__lowerCamelCase : List[str] ,__lowerCamelCase : Any ,): lowercase_ :str = coefficient_matrix.shape lowercase_ :Dict = constant_matrix.shape if rowsa != colsa: lowercase_ :Tuple = F'Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}' raise ValueError(_UpperCamelCase ) if colsa != 1: lowercase_ :int = F'Constant matrix must be nx1 but received {rowsa}x{colsa}' raise ValueError(_UpperCamelCase ) if rowsa != rowsa: lowercase_ :Union[str, Any] = ( 'Coefficient and constant matrices dimensions must be nxn and nx1 but ' F'received {rowsa}x{colsa} and {rowsa}x{colsa}' ) raise ValueError(_UpperCamelCase ) if len(_UpperCamelCase ) != rowsa: lowercase_ :str = ( 'Number of initial values must be equal to number of rows in coefficient ' F'matrix but received {len(_UpperCamelCase )} and {rowsa}' ) raise ValueError(_UpperCamelCase ) if iterations <= 0: raise ValueError("Iterations must be at least 1" ) lowercase_ :NDArray[floataa] = np.concatenate( (coefficient_matrix, constant_matrix) ,axis=1 ) lowercase_ :str = table.shape strictly_diagonally_dominant(_UpperCamelCase ) # Iterates the whole matrix for given number of times for _ in range(_UpperCamelCase ): lowercase_ :Tuple = [] for row in range(_UpperCamelCase ): lowercase_ :Tuple = 0 for col in range(_UpperCamelCase ): if col == row: lowercase_ :Optional[Any] = table[row][col] elif col == cols - 1: lowercase_ :Tuple = table[row][col] else: temp += (-1) * table[row][col] * init_val[col] lowercase_ :Tuple = (temp + val) / denom new_val.append(_UpperCamelCase ) lowercase_ :Tuple = new_val return [float(_UpperCamelCase ) for i in new_val] def UpperCAmelCase_ ( __lowerCamelCase : str ): lowercase_ :int = table.shape lowercase_ :Tuple = True for i in range(0 ,_UpperCamelCase ): lowercase_ :Tuple = 0 for j in range(0 ,cols - 1 ): if i == j: continue else: total += table[i][j] if table[i][i] <= total: raise ValueError("Coefficient matrix is not strictly diagonally dominant" ) return is_diagonally_dominant # Test Cases if __name__ == "__main__": import doctest doctest.testmod()
223
"""simple docstring""" import tempfile import unittest import numpy as np import transformers from transformers import GPTaTokenizer, GPTJConfig, is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax, tooslow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax import jax.numpy as jnp from transformers.modeling_flax_pytorch_utils import ( convert_pytorch_state_dict_to_flax, load_flax_weights_in_pytorch_model, ) from transformers.models.gptj.modeling_flax_gptj import FlaxGPTJForCausalLM, FlaxGPTJModel if is_torch_available(): import torch class A__ : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=14 , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=99 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=37 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=5_12 , _SCREAMING_SNAKE_CASE=0.02 , ): __lowerCAmelCase : Union[str, Any] = parent __lowerCAmelCase : Any = batch_size __lowerCAmelCase : Any = seq_length __lowerCAmelCase : Optional[Any] = is_training __lowerCAmelCase : Any = use_input_mask __lowerCAmelCase : Any = use_token_type_ids __lowerCAmelCase : Tuple = use_labels __lowerCAmelCase : Optional[Any] = vocab_size __lowerCAmelCase : Tuple = hidden_size __lowerCAmelCase : str = rotary_dim __lowerCAmelCase : Union[str, Any] = num_hidden_layers __lowerCAmelCase : Union[str, Any] = num_attention_heads __lowerCAmelCase : int = intermediate_size __lowerCAmelCase : List[str] = hidden_act __lowerCAmelCase : int = hidden_dropout_prob __lowerCAmelCase : Any = attention_probs_dropout_prob __lowerCAmelCase : List[Any] = max_position_embeddings __lowerCAmelCase : Optional[Any] = initializer_range __lowerCAmelCase : Tuple = None __lowerCAmelCase : int = vocab_size - 1 __lowerCAmelCase : Dict = vocab_size - 1 __lowerCAmelCase : int = vocab_size - 1 def __lowerCamelCase ( self ): __lowerCAmelCase : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __lowerCAmelCase : List[str] = None if self.use_input_mask: __lowerCAmelCase : Dict = random_attention_mask([self.batch_size, self.seq_length] ) __lowerCAmelCase : Optional[int] = GPTJConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , use_cache=_SCREAMING_SNAKE_CASE , bos_token_id=self.bos_token_id , eos_token_id=self.eos_token_id , pad_token_id=self.pad_token_id , rotary_dim=self.rotary_dim , ) return (config, input_ids, input_mask) def __lowerCamelCase ( self ): __lowerCAmelCase : Optional[int] = self.prepare_config_and_inputs() __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase : Any = config_and_inputs __lowerCAmelCase : Dict = {'input_ids': input_ids, 'attention_mask': attention_mask} return config, inputs_dict def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : List[str] = 20 __lowerCAmelCase : List[str] = model_class_name(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = model.init_cache(input_ids.shape[0] , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = jnp.ones((input_ids.shape[0], max_decoder_length) , dtype='i4' ) __lowerCAmelCase : Optional[Any] = jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1 )[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1) ) __lowerCAmelCase : Any = model( input_ids[:, :-1] , attention_mask=_SCREAMING_SNAKE_CASE , past_key_values=_SCREAMING_SNAKE_CASE , position_ids=_SCREAMING_SNAKE_CASE , ) __lowerCAmelCase : Any = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype='i4' ) __lowerCAmelCase : int = model( input_ids[:, -1:] , attention_mask=_SCREAMING_SNAKE_CASE , past_key_values=outputs_cache.past_key_values , position_ids=_SCREAMING_SNAKE_CASE , ) __lowerCAmelCase : Any = model(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=f"Max diff is {diff}" ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Tuple = 20 __lowerCAmelCase : List[str] = model_class_name(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Union[str, Any] = jnp.concatenate( [attention_mask, jnp.zeros((attention_mask.shape[0], max_decoder_length - attention_mask.shape[1]) )] , axis=-1 , ) __lowerCAmelCase : List[str] = model.init_cache(input_ids.shape[0] , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : str = jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1 )[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1) ) __lowerCAmelCase : Optional[Any] = model( input_ids[:, :-1] , attention_mask=_SCREAMING_SNAKE_CASE , past_key_values=_SCREAMING_SNAKE_CASE , position_ids=_SCREAMING_SNAKE_CASE , ) __lowerCAmelCase : str = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype='i4' ) __lowerCAmelCase : Tuple = model( input_ids[:, -1:] , past_key_values=outputs_cache.past_key_values , attention_mask=_SCREAMING_SNAKE_CASE , position_ids=_SCREAMING_SNAKE_CASE , ) __lowerCAmelCase : Union[str, Any] = model(_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=f"Max diff is {diff}" ) @require_flax class A__ ( _lowerCamelCase , _lowerCamelCase , unittest.TestCase): A_ : Tuple = (FlaxGPTJModel, FlaxGPTJForCausalLM) if is_flax_available() else () A_ : str = (FlaxGPTJForCausalLM,) if is_flax_available() else () def __lowerCamelCase ( self ): __lowerCAmelCase : int = FlaxGPTJModelTester(self ) def __lowerCamelCase ( self ): for model_class_name in self.all_model_classes: __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): for model_class_name in self.all_model_classes: __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward_with_attn_mask( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @tooslow def __lowerCamelCase ( self ): __lowerCAmelCase : Tuple = GPTaTokenizer.from_pretrained('gpt2' , pad_token='<|endoftext|>' , padding_side='left' ) __lowerCAmelCase : Optional[int] = tokenizer(['Hello this is a long string', 'Hey'] , return_tensors='np' , padding=_SCREAMING_SNAKE_CASE , truncation=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : int = FlaxGPTJForCausalLM.from_pretrained('EleutherAI/gpt-j-6B' ) __lowerCAmelCase : Any = False __lowerCAmelCase : Any = model.config.eos_token_id __lowerCAmelCase : Union[str, Any] = jax.jit(model.generate ) __lowerCAmelCase : Optional[Any] = jit_generate( inputs['input_ids'] , attention_mask=inputs['attention_mask'] , pad_token_id=tokenizer.pad_token_id ).sequences __lowerCAmelCase : str = tokenizer.batch_decode(_SCREAMING_SNAKE_CASE , skip_special_tokens=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = [ 'Hello this is a long string of text.\n\nI\'m trying to get the text of the', 'Hey, I\'m a little late to the party. I\'m going to', ] self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @is_pt_flax_cross_test def __lowerCamelCase ( self ): __lowerCAmelCase , __lowerCAmelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): # prepare inputs __lowerCAmelCase : str = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Union[str, Any] = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class __lowerCAmelCase : Dict = model_class.__name__[4:] # Skip the "Flax" at the beginning __lowerCAmelCase : Optional[int] = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase , __lowerCAmelCase : List[Any] = pt_inputs['input_ids'].shape __lowerCAmelCase : int = np.random.randint(0 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(_SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Tuple = 0 __lowerCAmelCase : Tuple = 1 __lowerCAmelCase : List[str] = 0 __lowerCAmelCase : Any = 1 __lowerCAmelCase : Optional[Any] = pt_model_class(_SCREAMING_SNAKE_CASE ).eval() __lowerCAmelCase : Any = model_class(_SCREAMING_SNAKE_CASE , dtype=jnp.floataa ) __lowerCAmelCase : int = convert_pytorch_state_dict_to_flax(pt_model.state_dict() , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : str = fx_state with torch.no_grad(): __lowerCAmelCase : Union[str, Any] = pt_model(**_SCREAMING_SNAKE_CASE ).to_tuple() __lowerCAmelCase : str = fx_model(**_SCREAMING_SNAKE_CASE ).to_tuple() self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , len(_SCREAMING_SNAKE_CASE ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output, pt_output in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) with tempfile.TemporaryDirectory() as tmpdirname: pt_model.save_pretrained(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Tuple = model_class.from_pretrained(_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = fx_model_loaded(**_SCREAMING_SNAKE_CASE ).to_tuple() self.assertEqual( len(_SCREAMING_SNAKE_CASE ) , len(_SCREAMING_SNAKE_CASE ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output_loaded, pt_output in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): self.assert_almost_equals(fx_output_loaded[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) @is_pt_flax_cross_test def __lowerCamelCase ( self ): __lowerCAmelCase , __lowerCAmelCase : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): # prepare inputs __lowerCAmelCase : List[str] = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class __lowerCAmelCase : Dict = model_class.__name__[4:] # Skip the "Flax" at the beginning __lowerCAmelCase : str = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = pt_model_class(_SCREAMING_SNAKE_CASE ).eval() __lowerCAmelCase : Tuple = model_class(_SCREAMING_SNAKE_CASE , dtype=jnp.floataa ) __lowerCAmelCase : List[str] = load_flax_weights_in_pytorch_model(_SCREAMING_SNAKE_CASE , fx_model.params ) __lowerCAmelCase , __lowerCAmelCase : int = pt_inputs['input_ids'].shape __lowerCAmelCase : List[str] = np.random.randint(0 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(_SCREAMING_SNAKE_CASE ): __lowerCAmelCase : str = 0 __lowerCAmelCase : Optional[Any] = 1 __lowerCAmelCase : Optional[int] = 0 __lowerCAmelCase : Optional[Any] = 1 # make sure weights are tied in PyTorch pt_model.tie_weights() with torch.no_grad(): __lowerCAmelCase : List[str] = pt_model(**_SCREAMING_SNAKE_CASE ).to_tuple() __lowerCAmelCase : Optional[int] = fx_model(**_SCREAMING_SNAKE_CASE ).to_tuple() self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , len(_SCREAMING_SNAKE_CASE ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output, pt_output in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) with tempfile.TemporaryDirectory() as tmpdirname: fx_model.save_pretrained(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = pt_model_class.from_pretrained(_SCREAMING_SNAKE_CASE , from_flax=_SCREAMING_SNAKE_CASE ) with torch.no_grad(): __lowerCAmelCase : Any = pt_model_loaded(**_SCREAMING_SNAKE_CASE ).to_tuple() self.assertEqual( len(_SCREAMING_SNAKE_CASE ) , len(_SCREAMING_SNAKE_CASE ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output, pt_output in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) @tooslow def __lowerCamelCase ( self ): for model_class_name in self.all_model_classes: __lowerCAmelCase : Optional[int] = model_class_name.from_pretrained('EleutherAI/gpt-j-6B' ) __lowerCAmelCase : List[Any] = model(np.ones((1, 1) ) ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE )
86
0
import requests from bsa import BeautifulSoup def UpperCAmelCase ( lowercase = "https://www.worldometers.info/coronavirus" ): """simple docstring""" __lowercase = BeautifulSoup(requests.get(_UpperCamelCase ).text , '''html.parser''' ) __lowercase = soup.findAll('''h1''' ) __lowercase = soup.findAll('''div''' , {'''class''': '''maincounter-number'''} ) keys += soup.findAll('''span''' , {'''class''': '''panel-title'''} ) values += soup.findAll('''div''' , {'''class''': '''number-table-main'''} ) return {key.text.strip(): value.text.strip() for key, value in zip(_UpperCamelCase , _UpperCamelCase )} if __name__ == "__main__": print("""\033[1m""" + """COVID-19 Status of the World""" + """\033[0m\n""") for key, value in world_covidaa_stats().items(): print(F'''{key}\n{value}\n''')
210
"""simple docstring""" 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 , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=13 , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=99 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=37 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=5_12 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=None , ): __lowerCAmelCase : Tuple = parent __lowerCAmelCase : Optional[int] = 13 __lowerCAmelCase : List[Any] = 7 __lowerCAmelCase : int = True __lowerCAmelCase : Optional[int] = True __lowerCAmelCase : List[Any] = True __lowerCAmelCase : Optional[int] = True __lowerCAmelCase : Optional[Any] = 99 __lowerCAmelCase : int = 3_84 __lowerCAmelCase : Union[str, Any] = 2 __lowerCAmelCase : Tuple = 4 __lowerCAmelCase : str = 37 __lowerCAmelCase : Any = 'gelu' __lowerCAmelCase : List[str] = 0.1 __lowerCAmelCase : Any = 0.1 __lowerCAmelCase : Union[str, Any] = 5_12 __lowerCAmelCase : int = 16 __lowerCAmelCase : Union[str, Any] = 2 __lowerCAmelCase : int = 0.02 __lowerCAmelCase : Dict = 3 __lowerCAmelCase : Tuple = 4 __lowerCAmelCase : Tuple = 1_28 __lowerCAmelCase : Optional[int] = 2 __lowerCAmelCase : List[str] = 9 __lowerCAmelCase : int = 1 __lowerCAmelCase : int = None def __lowerCamelCase ( self ): __lowerCAmelCase : Any = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __lowerCAmelCase : Optional[int] = None if self.use_input_mask: __lowerCAmelCase : str = random_attention_mask([self.batch_size, self.seq_length] ) __lowerCAmelCase : Tuple = None if self.use_token_type_ids: __lowerCAmelCase : Dict = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __lowerCAmelCase : Optional[Any] = None __lowerCAmelCase : Dict = None __lowerCAmelCase : Union[str, Any] = None if self.use_labels: __lowerCAmelCase : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCAmelCase : Dict = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __lowerCAmelCase : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) __lowerCAmelCase : Union[str, 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=_SCREAMING_SNAKE_CASE , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Optional[int] = TFConvBertModel(config=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids} __lowerCAmelCase : Tuple = [input_ids, input_mask] __lowerCAmelCase : Any = model(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Any = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Any = TFConvBertForMaskedLM(config=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } __lowerCAmelCase : Optional[Any] = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Tuple = self.num_labels __lowerCAmelCase : Optional[Any] = TFConvBertForSequenceClassification(config=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : int = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } __lowerCAmelCase : Union[str, Any] = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : int = self.num_choices __lowerCAmelCase : List[str] = TFConvBertForMultipleChoice(config=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = tf.tile(tf.expand_dims(_SCREAMING_SNAKE_CASE , 1 ) , (1, self.num_choices, 1) ) __lowerCAmelCase : Dict = tf.tile(tf.expand_dims(_SCREAMING_SNAKE_CASE , 1 ) , (1, self.num_choices, 1) ) __lowerCAmelCase : Union[str, Any] = tf.tile(tf.expand_dims(_SCREAMING_SNAKE_CASE , 1 ) , (1, self.num_choices, 1) ) __lowerCAmelCase : Tuple = { 'input_ids': multiple_choice_inputs_ids, 'attention_mask': multiple_choice_input_mask, 'token_type_ids': multiple_choice_token_type_ids, } __lowerCAmelCase : str = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : str = self.num_labels __lowerCAmelCase : Any = TFConvBertForTokenClassification(config=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } __lowerCAmelCase : Union[str, Any] = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : str = TFConvBertForQuestionAnswering(config=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Union[str, Any] = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } __lowerCAmelCase : Optional[int] = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __lowerCamelCase ( self ): __lowerCAmelCase : Union[str, Any] = self.prepare_config_and_inputs() ( ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ) : List[str] = config_and_inputs __lowerCAmelCase : Any = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_tf class A__ ( _lowerCamelCase , _lowerCamelCase , unittest.TestCase): A_ : List[str] = ( ( TFConvBertModel, TFConvBertForMaskedLM, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertForMultipleChoice, ) if is_tf_available() else () ) A_ : str = ( { 'feature-extraction': TFConvBertModel, 'fill-mask': TFConvBertForMaskedLM, 'question-answering': TFConvBertForQuestionAnswering, 'text-classification': TFConvBertForSequenceClassification, 'token-classification': TFConvBertForTokenClassification, 'zero-shot': TFConvBertForSequenceClassification, } if is_tf_available() else {} ) A_ : List[Any] = False A_ : str = False A_ : List[Any] = False def __lowerCamelCase ( self ): __lowerCAmelCase : Dict = TFConvBertModelTester(self ) __lowerCAmelCase : Any = ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , hidden_size=37 ) def __lowerCamelCase ( self ): self.config_tester.run_common_tests() def __lowerCamelCase ( self ): __lowerCAmelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_SCREAMING_SNAKE_CASE ) @slow def __lowerCamelCase ( self ): __lowerCAmelCase , __lowerCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() __lowerCAmelCase : Any = True __lowerCAmelCase : Dict = True if hasattr(_SCREAMING_SNAKE_CASE , 'use_cache' ): __lowerCAmelCase : int = True __lowerCAmelCase : List[str] = getattr(self.model_tester , 'encoder_seq_length' , self.model_tester.seq_length ) __lowerCAmelCase : str = getattr(self.model_tester , 'key_length' , _SCREAMING_SNAKE_CASE ) for model_class in self.all_model_classes: __lowerCAmelCase : str = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : str = model_class(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = len(model(_SCREAMING_SNAKE_CASE ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(_SCREAMING_SNAKE_CASE , saved_model=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = os.path.join(_SCREAMING_SNAKE_CASE , 'saved_model' , '1' ) __lowerCAmelCase : int = tf.keras.models.load_model(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = model(_SCREAMING_SNAKE_CASE ) if self.is_encoder_decoder: __lowerCAmelCase : List[str] = outputs['encoder_hidden_states'] __lowerCAmelCase : Tuple = outputs['encoder_attentions'] else: __lowerCAmelCase : Optional[int] = outputs['hidden_states'] __lowerCAmelCase : Tuple = outputs['attentions'] self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Union[str, Any] = getattr( self.model_tester , 'expected_num_hidden_layers' , self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) self.assertListEqual( list(output_hidden_states[0].shape[-2:] ) , [self.model_tester.seq_length, self.model_tester.hidden_size] , ) self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , 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 __lowerCamelCase ( self ): __lowerCAmelCase : Tuple = TFConvBertModel.from_pretrained('YituTech/conv-bert-base' ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase , __lowerCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs_for_common() __lowerCAmelCase : Optional[Any] = True __lowerCAmelCase : List[Any] = getattr(self.model_tester , 'decoder_seq_length' , self.model_tester.seq_length ) __lowerCAmelCase : str = getattr(self.model_tester , 'encoder_seq_length' , self.model_tester.seq_length ) __lowerCAmelCase : Tuple = getattr(self.model_tester , 'key_length' , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = getattr(self.model_tester , 'key_length' , _SCREAMING_SNAKE_CASE ) def check_decoder_attentions_output(_SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Union[str, Any] = len(_SCREAMING_SNAKE_CASE ) self.assertEqual(out_len % 2 , 0 ) __lowerCAmelCase : Optional[Any] = outputs.decoder_attentions self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , 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(_SCREAMING_SNAKE_CASE ): __lowerCAmelCase : str = [ t.numpy() for t in (outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions) ] self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , 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: __lowerCAmelCase : List[str] = True __lowerCAmelCase : Optional[int] = False __lowerCAmelCase : List[Any] = model_class(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = model(self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) __lowerCAmelCase : Tuple = len(_SCREAMING_SNAKE_CASE ) self.assertEqual(config.output_hidden_states , _SCREAMING_SNAKE_CASE ) check_encoder_attentions_output(_SCREAMING_SNAKE_CASE ) if self.is_encoder_decoder: __lowerCAmelCase : Any = model_class(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = model(self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) self.assertEqual(config.output_hidden_states , _SCREAMING_SNAKE_CASE ) check_decoder_attentions_output(_SCREAMING_SNAKE_CASE ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] __lowerCAmelCase : Optional[Any] = True __lowerCAmelCase : str = model_class(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = model(self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) self.assertEqual(config.output_hidden_states , _SCREAMING_SNAKE_CASE ) check_encoder_attentions_output(_SCREAMING_SNAKE_CASE ) # Check attention is always last and order is fine __lowerCAmelCase : Dict = True __lowerCAmelCase : Optional[Any] = True __lowerCAmelCase : List[Any] = model_class(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = model(self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(_SCREAMING_SNAKE_CASE ) ) self.assertEqual(model.config.output_hidden_states , _SCREAMING_SNAKE_CASE ) check_encoder_attentions_output(_SCREAMING_SNAKE_CASE ) @require_tf class A__ ( unittest.TestCase): @slow def __lowerCamelCase ( self ): __lowerCAmelCase : Dict = TFConvBertModel.from_pretrained('YituTech/conv-bert-base' ) __lowerCAmelCase : int = tf.constant([[0, 1, 2, 3, 4, 5]] ) __lowerCAmelCase : Tuple = model(_SCREAMING_SNAKE_CASE )[0] __lowerCAmelCase : Tuple = [1, 6, 7_68] self.assertEqual(output.shape , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = tf.constant( [ [ [-0.0347_5493, -0.468_6034, -0.3063_8832], [0.2263_7248, -0.2698_8646, -0.742_3424], [0.1032_4868, -0.4501_3508, -0.5828_0784], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 )
86
0
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging __a = logging.get_logger(__name__) if is_vision_available(): import PIL class A__ ( _lowerCamelCase ): """simple docstring""" UpperCamelCase_ : Optional[Any] = ['pixel_values'] def __init__( self : List[Any] , lowerCAmelCase__ : List[str] = True , lowerCAmelCase__ : List[str] = None , lowerCAmelCase__ : int = PILImageResampling.BICUBIC , lowerCAmelCase__ : List[Any] = True , lowerCAmelCase__ : Optional[Any] = None , lowerCAmelCase__ : Union[str, Any] = True , lowerCAmelCase__ : Dict = 1 / 2_5_5 , lowerCAmelCase__ : List[Any] = True , lowerCAmelCase__ : str = None , lowerCAmelCase__ : Dict = None , lowerCAmelCase__ : str = True , **lowerCAmelCase__ : int , ) -> Union[str, Any]: """simple docstring""" super().__init__(**_SCREAMING_SNAKE_CASE ) _UpperCAmelCase : str = size if size is not None else {'shortest_edge': 2_2_4} _UpperCAmelCase : List[str] = get_size_dict(_SCREAMING_SNAKE_CASE , default_to_square=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase : Any = crop_size if crop_size is not None else {'height': 2_2_4, 'width': 2_2_4} _UpperCAmelCase : Optional[int] = get_size_dict(_SCREAMING_SNAKE_CASE , default_to_square=_SCREAMING_SNAKE_CASE , param_name="crop_size" ) _UpperCAmelCase : Tuple = do_resize _UpperCAmelCase : Union[str, Any] = size _UpperCAmelCase : str = resample _UpperCAmelCase : Optional[int] = do_center_crop _UpperCAmelCase : List[Any] = crop_size _UpperCAmelCase : Any = do_rescale _UpperCAmelCase : List[str] = rescale_factor _UpperCAmelCase : Tuple = do_normalize _UpperCAmelCase : Dict = image_mean if image_mean is not None else OPENAI_CLIP_MEAN _UpperCAmelCase : Optional[Any] = image_std if image_std is not None else OPENAI_CLIP_STD _UpperCAmelCase : str = do_convert_rgb def _lowerCAmelCase ( self : Optional[int] , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : str , lowerCAmelCase__ : List[str] = PILImageResampling.BICUBIC , lowerCAmelCase__ : Any = None , **lowerCAmelCase__ : Any , ) -> List[Any]: """simple docstring""" _UpperCAmelCase : str = get_size_dict(_SCREAMING_SNAKE_CASE , default_to_square=_SCREAMING_SNAKE_CASE ) if "shortest_edge" not in size: raise ValueError(F"""The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}""" ) _UpperCAmelCase : List[Any] = get_resize_output_image_size(_SCREAMING_SNAKE_CASE , size=size["shortest_edge"] , default_to_square=_SCREAMING_SNAKE_CASE ) return resize(_SCREAMING_SNAKE_CASE , size=_SCREAMING_SNAKE_CASE , resample=_SCREAMING_SNAKE_CASE , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _lowerCAmelCase ( self : Optional[Any] , lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Tuple = None , **lowerCAmelCase__ : List[Any] , ) -> List[str]: """simple docstring""" _UpperCAmelCase : Dict = get_size_dict(_SCREAMING_SNAKE_CASE ) if "height" not in size or "width" not in size: raise ValueError(F"""The `size` parameter must contain the keys (height, width). Got {size.keys()}""" ) return center_crop(_SCREAMING_SNAKE_CASE , size=(size["height"], size["width"]) , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _lowerCAmelCase ( self : Tuple , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Dict , lowerCAmelCase__ : Optional[Any] = None , **lowerCAmelCase__ : Tuple , ) -> Dict: """simple docstring""" return rescale(_SCREAMING_SNAKE_CASE , scale=_SCREAMING_SNAKE_CASE , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _lowerCAmelCase ( self : Dict , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Dict , lowerCAmelCase__ : List[str] , lowerCAmelCase__ : List[str] = None , **lowerCAmelCase__ : Tuple , ) -> List[Any]: """simple docstring""" return normalize(_SCREAMING_SNAKE_CASE , mean=_SCREAMING_SNAKE_CASE , std=_SCREAMING_SNAKE_CASE , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _lowerCAmelCase ( self : int , lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Any = None , lowerCAmelCase__ : Tuple = None , lowerCAmelCase__ : Dict = None , lowerCAmelCase__ : Any = None , lowerCAmelCase__ : Union[str, Any] = None , lowerCAmelCase__ : Optional[int] = None , lowerCAmelCase__ : int = None , lowerCAmelCase__ : Dict = None , lowerCAmelCase__ : Optional[Any] = None , lowerCAmelCase__ : Tuple = None , lowerCAmelCase__ : Dict = None , lowerCAmelCase__ : List[str] = None , lowerCAmelCase__ : Tuple = ChannelDimension.FIRST , **lowerCAmelCase__ : Union[str, Any] , ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase : List[str] = do_resize if do_resize is not None else self.do_resize _UpperCAmelCase : Dict = size if size is not None else self.size _UpperCAmelCase : Optional[int] = get_size_dict(_SCREAMING_SNAKE_CASE , param_name="size" , default_to_square=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase : str = resample if resample is not None else self.resample _UpperCAmelCase : Dict = do_center_crop if do_center_crop is not None else self.do_center_crop _UpperCAmelCase : Optional[Any] = crop_size if crop_size is not None else self.crop_size _UpperCAmelCase : Any = get_size_dict(_SCREAMING_SNAKE_CASE , param_name="crop_size" , default_to_square=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase : Any = do_rescale if do_rescale is not None else self.do_rescale _UpperCAmelCase : int = rescale_factor if rescale_factor is not None else self.rescale_factor _UpperCAmelCase : Optional[int] = do_normalize if do_normalize is not None else self.do_normalize _UpperCAmelCase : List[str] = image_mean if image_mean is not None else self.image_mean _UpperCAmelCase : int = image_std if image_std is not None else self.image_std _UpperCAmelCase : str = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb _UpperCAmelCase : Optional[Any] = make_list_of_images(_SCREAMING_SNAKE_CASE ) if not valid_images(_SCREAMING_SNAKE_CASE ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None: raise ValueError("Size must be specified if do_resize is True." ) if do_center_crop and crop_size is None: raise ValueError("Crop size must be specified if do_center_crop is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # PIL RGBA images are converted to RGB if do_convert_rgb: _UpperCAmelCase : Union[str, Any] = [convert_to_rgb(_SCREAMING_SNAKE_CASE ) for image in images] # All transformations expect numpy arrays. _UpperCAmelCase : Dict = [to_numpy_array(_SCREAMING_SNAKE_CASE ) for image in images] if do_resize: _UpperCAmelCase : int = [self.resize(image=_SCREAMING_SNAKE_CASE , size=_SCREAMING_SNAKE_CASE , resample=_SCREAMING_SNAKE_CASE ) for image in images] if do_center_crop: _UpperCAmelCase : Any = [self.center_crop(image=_SCREAMING_SNAKE_CASE , size=_SCREAMING_SNAKE_CASE ) for image in images] if do_rescale: _UpperCAmelCase : str = [self.rescale(image=_SCREAMING_SNAKE_CASE , scale=_SCREAMING_SNAKE_CASE ) for image in images] if do_normalize: _UpperCAmelCase : List[Any] = [self.normalize(image=_SCREAMING_SNAKE_CASE , mean=_SCREAMING_SNAKE_CASE , std=_SCREAMING_SNAKE_CASE ) for image in images] _UpperCAmelCase : Dict = [to_channel_dimension_format(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for image in images] _UpperCAmelCase : Tuple = {'pixel_values': images} return BatchFeature(data=_SCREAMING_SNAKE_CASE , tensor_type=_SCREAMING_SNAKE_CASE )
145
"""simple docstring""" 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 DetrImageProcessor class A__ ( unittest.TestCase): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=30 , _SCREAMING_SNAKE_CASE=4_00 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=1 / 2_55 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , _SCREAMING_SNAKE_CASE=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __lowerCAmelCase : Any = size if size is not None else {'shortest_edge': 18, 'longest_edge': 13_33} __lowerCAmelCase : Optional[int] = parent __lowerCAmelCase : int = batch_size __lowerCAmelCase : str = num_channels __lowerCAmelCase : Optional[int] = min_resolution __lowerCAmelCase : List[Any] = max_resolution __lowerCAmelCase : Union[str, Any] = do_resize __lowerCAmelCase : Optional[Any] = size __lowerCAmelCase : Dict = do_rescale __lowerCAmelCase : Optional[Any] = rescale_factor __lowerCAmelCase : Any = do_normalize __lowerCAmelCase : List[str] = image_mean __lowerCAmelCase : Union[str, Any] = image_std __lowerCAmelCase : Optional[int] = do_pad def __lowerCamelCase ( self ): return { "do_resize": self.do_resize, "size": self.size, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_pad": self.do_pad, } def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ): if not batched: __lowerCAmelCase : str = image_inputs[0] if isinstance(_SCREAMING_SNAKE_CASE , Image.Image ): __lowerCAmelCase , __lowerCAmelCase : Optional[int] = image.size else: __lowerCAmelCase , __lowerCAmelCase : Union[str, Any] = image.shape[1], image.shape[2] if w < h: __lowerCAmelCase : str = int(self.size['shortest_edge'] * h / w ) __lowerCAmelCase : Optional[int] = self.size['shortest_edge'] elif w > h: __lowerCAmelCase : str = self.size['shortest_edge'] __lowerCAmelCase : Union[str, Any] = int(self.size['shortest_edge'] * w / h ) else: __lowerCAmelCase : str = self.size['shortest_edge'] __lowerCAmelCase : Optional[Any] = self.size['shortest_edge'] else: __lowerCAmelCase : str = [] for image in image_inputs: __lowerCAmelCase , __lowerCAmelCase : List[Any] = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __lowerCAmelCase : Any = max(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : item[0] )[0] __lowerCAmelCase : Dict = max(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class A__ ( _lowerCamelCase , unittest.TestCase): A_ : List[str] = DetrImageProcessor if is_vision_available() else None def __lowerCamelCase ( self ): __lowerCAmelCase : List[Any] = DetrImageProcessingTester(self ) @property def __lowerCamelCase ( self ): return self.image_processor_tester.prepare_image_processor_dict() def __lowerCamelCase ( self ): __lowerCAmelCase : Dict = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'image_mean' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'image_std' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_normalize' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_rescale' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'rescale_factor' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_resize' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'size' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_pad' ) ) def __lowerCamelCase ( self ): __lowerCAmelCase : Optional[Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'shortest_edge': 18, 'longest_edge': 13_33} ) self.assertEqual(image_processor.do_pad , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=_SCREAMING_SNAKE_CASE ) self.assertEqual(image_processor.size , {'shortest_edge': 42, 'longest_edge': 84} ) self.assertEqual(image_processor.do_pad , _SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): pass def __lowerCamelCase ( self ): # Initialize image_processing __lowerCAmelCase : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __lowerCAmelCase : str = 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 __lowerCAmelCase : int = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values __lowerCAmelCase , __lowerCAmelCase : List[Any] = self.image_processor_tester.get_expected_values(_SCREAMING_SNAKE_CASE ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __lowerCAmelCase , __lowerCAmelCase : int = self.image_processor_tester.get_expected_values(_SCREAMING_SNAKE_CASE , batched=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Union[str, Any] = image_processing(_SCREAMING_SNAKE_CASE , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __lowerCamelCase ( self ): # Initialize image_processing __lowerCAmelCase : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __lowerCAmelCase : str = 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 __lowerCAmelCase : Tuple = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values __lowerCAmelCase , __lowerCAmelCase : Tuple = self.image_processor_tester.get_expected_values(_SCREAMING_SNAKE_CASE ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __lowerCAmelCase : Union[str, Any] = image_processing(_SCREAMING_SNAKE_CASE , return_tensors='pt' ).pixel_values __lowerCAmelCase , __lowerCAmelCase : List[Any] = self.image_processor_tester.get_expected_values(_SCREAMING_SNAKE_CASE , batched=_SCREAMING_SNAKE_CASE ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __lowerCamelCase ( self ): # Initialize image_processing __lowerCAmelCase : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __lowerCAmelCase : int = 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 __lowerCAmelCase : Any = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values __lowerCAmelCase , __lowerCAmelCase : Dict = self.image_processor_tester.get_expected_values(_SCREAMING_SNAKE_CASE ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __lowerCAmelCase : Tuple = image_processing(_SCREAMING_SNAKE_CASE , return_tensors='pt' ).pixel_values __lowerCAmelCase , __lowerCAmelCase : Any = self.image_processor_tester.get_expected_values(_SCREAMING_SNAKE_CASE , batched=_SCREAMING_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 __lowerCamelCase ( self ): # prepare image and target __lowerCAmelCase : Union[str, Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' , 'r' ) as f: __lowerCAmelCase : Any = json.loads(f.read() ) __lowerCAmelCase : Tuple = {'image_id': 3_97_69, 'annotations': target} # encode them __lowerCAmelCase : Dict = DetrImageProcessor.from_pretrained('facebook/detr-resnet-50' ) __lowerCAmelCase : int = image_processing(images=_SCREAMING_SNAKE_CASE , annotations=_SCREAMING_SNAKE_CASE , return_tensors='pt' ) # verify pixel values __lowerCAmelCase : str = torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding['pixel_values'].shape , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : int = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 ) ) # verify area __lowerCAmelCase : List[str] = torch.tensor([5887.9600, 1_1250.2061, 48_9353.8438, 83_7122.7500, 14_7967.5156, 16_5732.3438] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , _SCREAMING_SNAKE_CASE ) ) # verify boxes __lowerCAmelCase : Tuple = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : str = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , _SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # verify image_id __lowerCAmelCase : Dict = torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , _SCREAMING_SNAKE_CASE ) ) # verify is_crowd __lowerCAmelCase : Optional[int] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , _SCREAMING_SNAKE_CASE ) ) # verify class_labels __lowerCAmelCase : Union[str, Any] = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , _SCREAMING_SNAKE_CASE ) ) # verify orig_size __lowerCAmelCase : int = torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , _SCREAMING_SNAKE_CASE ) ) # verify size __lowerCAmelCase : List[Any] = torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , _SCREAMING_SNAKE_CASE ) ) @slow def __lowerCamelCase ( self ): # prepare image, target and masks_path __lowerCAmelCase : Optional[int] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' , 'r' ) as f: __lowerCAmelCase : Optional[int] = json.loads(f.read() ) __lowerCAmelCase : Optional[int] = {'file_name': '000000039769.png', 'image_id': 3_97_69, 'segments_info': target} __lowerCAmelCase : Union[str, Any] = pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic' ) # encode them __lowerCAmelCase : Optional[int] = DetrImageProcessor.from_pretrained('facebook/detr-resnet-50-panoptic' ) __lowerCAmelCase : Optional[Any] = image_processing(images=_SCREAMING_SNAKE_CASE , annotations=_SCREAMING_SNAKE_CASE , masks_path=_SCREAMING_SNAKE_CASE , return_tensors='pt' ) # verify pixel values __lowerCAmelCase : str = torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding['pixel_values'].shape , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 ) ) # verify area __lowerCAmelCase : int = torch.tensor([14_7979.6875, 16_5527.0469, 48_4638.5938, 1_1292.9375, 5879.6562, 7634.1147] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , _SCREAMING_SNAKE_CASE ) ) # verify boxes __lowerCAmelCase : Optional[int] = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , _SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # verify image_id __lowerCAmelCase : str = torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , _SCREAMING_SNAKE_CASE ) ) # verify is_crowd __lowerCAmelCase : Optional[int] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , _SCREAMING_SNAKE_CASE ) ) # verify class_labels __lowerCAmelCase : str = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , _SCREAMING_SNAKE_CASE ) ) # verify masks __lowerCAmelCase : Dict = 82_28_73 self.assertEqual(encoding['labels'][0]['masks'].sum().item() , _SCREAMING_SNAKE_CASE ) # verify orig_size __lowerCAmelCase : str = torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , _SCREAMING_SNAKE_CASE ) ) # verify size __lowerCAmelCase : List[Any] = torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , _SCREAMING_SNAKE_CASE ) )
86
0
import os import tempfile import unittest import uuid from pathlib import Path from transformers.testing_utils import get_tests_dir, require_soundfile, require_torch, require_vision from transformers.tools.agent_types import AgentAudio, AgentImage, AgentText from transformers.utils import is_soundfile_availble, is_torch_available, is_vision_available if is_torch_available(): import torch if is_soundfile_availble(): import soundfile as sf if is_vision_available(): from PIL import Image def _lowercase ( lowercase__="" ): __lowerCAmelCase : Optional[int] = tempfile.mkdtemp() return os.path.join(_UpperCamelCase , str(uuid.uuida() ) + suffix ) @require_soundfile @require_torch class __lowercase (unittest.TestCase ): def UpperCamelCase__ ( self ) ->Tuple: '''simple docstring''' __lowerCAmelCase : Dict = torch.rand(12 , dtype=torch.floataa ) - 0.5 __lowerCAmelCase : Optional[Any] = AgentAudio(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = str(agent_type.to_string() ) # Ensure that the tensor and the agent_type's tensor are the same self.assertTrue(torch.allclose(_SCREAMING_SNAKE_CASE , agent_type.to_raw() , atol=1e-4 ) ) del agent_type # Ensure the path remains even after the object deletion self.assertTrue(os.path.exists(_SCREAMING_SNAKE_CASE ) ) # Ensure that the file contains the same value as the original tensor __lowerCAmelCase : int = sf.read(_SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(_SCREAMING_SNAKE_CASE , torch.tensor(_SCREAMING_SNAKE_CASE ) , atol=1e-4 ) ) def UpperCamelCase__ ( self ) ->str: '''simple docstring''' __lowerCAmelCase : Optional[Any] = torch.rand(12 , dtype=torch.floataa ) - 0.5 __lowerCAmelCase : int = get_new_path(suffix='''.wav''' ) sf.write(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 1_6000 ) __lowerCAmelCase : int = AgentAudio(_SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(_SCREAMING_SNAKE_CASE , agent_type.to_raw() , atol=1e-4 ) ) self.assertEqual(agent_type.to_string() , _SCREAMING_SNAKE_CASE ) @require_vision @require_torch class __lowercase (unittest.TestCase ): def UpperCamelCase__ ( self ) ->Optional[Any]: '''simple docstring''' __lowerCAmelCase : Optional[Any] = torch.randint(0 , 256 , (64, 64, 3) ) __lowerCAmelCase : int = AgentImage(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = str(agent_type.to_string() ) # Ensure that the tensor and the agent_type's tensor are the same self.assertTrue(torch.allclose(_SCREAMING_SNAKE_CASE , agent_type._tensor , atol=1e-4 ) ) self.assertIsInstance(agent_type.to_raw() , Image.Image ) # Ensure the path remains even after the object deletion del agent_type self.assertTrue(os.path.exists(_SCREAMING_SNAKE_CASE ) ) def UpperCamelCase__ ( self ) ->Dict: '''simple docstring''' __lowerCAmelCase : Any = Path(get_tests_dir('''fixtures/tests_samples/COCO''' ) ) / '000000039769.png' __lowerCAmelCase : Tuple = Image.open(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = AgentImage(_SCREAMING_SNAKE_CASE ) self.assertTrue(path.samefile(agent_type.to_string() ) ) self.assertTrue(image == agent_type.to_raw() ) # Ensure the path remains even after the object deletion del agent_type self.assertTrue(os.path.exists(_SCREAMING_SNAKE_CASE ) ) def UpperCamelCase__ ( self ) ->Union[str, Any]: '''simple docstring''' __lowerCAmelCase : Any = Path(get_tests_dir('''fixtures/tests_samples/COCO''' ) ) / '000000039769.png' __lowerCAmelCase : Any = Image.open(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = AgentImage(_SCREAMING_SNAKE_CASE ) self.assertFalse(path.samefile(agent_type.to_string() ) ) self.assertTrue(image == agent_type.to_raw() ) # Ensure the path remains even after the object deletion del agent_type self.assertTrue(os.path.exists(_SCREAMING_SNAKE_CASE ) ) class __lowercase (unittest.TestCase ): def UpperCamelCase__ ( self ) ->List[str]: '''simple docstring''' __lowerCAmelCase : List[str] = 'Hey!' __lowerCAmelCase : Optional[Any] = AgentText(_SCREAMING_SNAKE_CASE ) self.assertEqual(_SCREAMING_SNAKE_CASE , agent_type.to_string() ) self.assertEqual(_SCREAMING_SNAKE_CASE , agent_type.to_raw() ) self.assertEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
275
"""simple docstring""" import numpy as np def __lowerCAmelCase (_UpperCamelCase ): return 1 / (1 + np.exp(-vector )) def __lowerCAmelCase (_UpperCamelCase ): return vector * sigmoid(_UpperCamelCase ) if __name__ == "__main__": import doctest doctest.testmod()
86
0
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 __lowerCAmelCase : def __init__( self , lowerCAmelCase__ , lowerCAmelCase__=1_3 , lowerCAmelCase__=7 , lowerCAmelCase__=True , lowerCAmelCase__=True , lowerCAmelCase__=True , lowerCAmelCase__=True , lowerCAmelCase__=9_9 , lowerCAmelCase__=3_2 , lowerCAmelCase__=2 , lowerCAmelCase__=4 , lowerCAmelCase__=3_7 , lowerCAmelCase__="gelu" , lowerCAmelCase__=0.1 , lowerCAmelCase__=0.1 , lowerCAmelCase__=5_1_2 , lowerCAmelCase__=1_6 , lowerCAmelCase__=2 , lowerCAmelCase__=0.02 , lowerCAmelCase__=3 , lowerCAmelCase__=4 , lowerCAmelCase__=None , ) -> List[str]: '''simple docstring''' a__ : Tuple =parent a__ : Optional[int] =1_3 a__ : List[Any] =7 a__ : int =True a__ : Optional[int] =True a__ : List[Any] =True a__ : Optional[int] =True a__ : Optional[Any] =9_9 a__ : int =3_8_4 a__ : Union[str, Any] =2 a__ : Tuple =4 a__ : str =3_7 a__ : Any ='gelu' a__ : List[str] =0.1 a__ : Any =0.1 a__ : Union[str, Any] =5_1_2 a__ : int =1_6 a__ : Union[str, Any] =2 a__ : int =0.02 a__ : Dict =3 a__ : Tuple =4 a__ : Tuple =1_2_8 a__ : Optional[int] =2 a__ : List[str] =9 a__ : int =1 a__ : int =None def _lowercase ( self ) -> Optional[int]: '''simple docstring''' a__ : Any =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a__ : Optional[int] =None if self.use_input_mask: a__ : str =random_attention_mask([self.batch_size, self.seq_length] ) a__ : Tuple =None if self.use_token_type_ids: a__ : Dict =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) a__ : Optional[Any] =None a__ : Dict =None a__ : Union[str, Any] =None if self.use_labels: a__ : List[Any] =ids_tensor([self.batch_size] , self.type_sequence_label_size ) a__ : Dict =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) a__ : List[Any] =ids_tensor([self.batch_size] , self.num_choices ) a__ : Union[str, 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=_SCREAMING_SNAKE_CASE , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> List[Any]: '''simple docstring''' a__ : Optional[int] =TFConvBertModel(config=_SCREAMING_SNAKE_CASE ) a__ : Optional[int] ={'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids} a__ : Tuple =[input_ids, input_mask] a__ : Any =model(_SCREAMING_SNAKE_CASE ) a__ : Any =model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> List[Any]: '''simple docstring''' a__ : Any =TFConvBertForMaskedLM(config=_SCREAMING_SNAKE_CASE ) a__ : Optional[int] ={ 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } a__ : Optional[Any] =model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> Optional[int]: '''simple docstring''' a__ : Tuple =self.num_labels a__ : Optional[Any] =TFConvBertForSequenceClassification(config=_SCREAMING_SNAKE_CASE ) a__ : int ={ 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } a__ : Union[str, Any] =model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> Union[str, Any]: '''simple docstring''' a__ : int =self.num_choices a__ : List[str] =TFConvBertForMultipleChoice(config=_SCREAMING_SNAKE_CASE ) a__ : Dict =tf.tile(tf.expand_dims(_SCREAMING_SNAKE_CASE , 1 ) , (1, self.num_choices, 1) ) a__ : Dict =tf.tile(tf.expand_dims(_SCREAMING_SNAKE_CASE , 1 ) , (1, self.num_choices, 1) ) a__ : Union[str, Any] =tf.tile(tf.expand_dims(_SCREAMING_SNAKE_CASE , 1 ) , (1, self.num_choices, 1) ) a__ : Tuple ={ 'input_ids': multiple_choice_inputs_ids, 'attention_mask': multiple_choice_input_mask, 'token_type_ids': multiple_choice_token_type_ids, } a__ : str =model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> Union[str, Any]: '''simple docstring''' a__ : str =self.num_labels a__ : Any =TFConvBertForTokenClassification(config=_SCREAMING_SNAKE_CASE ) a__ : Optional[int] ={ 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } a__ : Union[str, Any] =model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> Tuple: '''simple docstring''' a__ : str =TFConvBertForQuestionAnswering(config=_SCREAMING_SNAKE_CASE ) a__ : Union[str, Any] ={ 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } a__ : Optional[int] =model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def _lowercase ( self ) -> Dict: '''simple docstring''' a__ : Union[str, Any] =self.prepare_config_and_inputs() ( a__ ) : List[str] =config_and_inputs a__ : Any ={'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_tf class __lowerCAmelCase ( _lowerCamelCase , _lowerCamelCase , unittest.TestCase): _lowercase : List[str] = ( ( TFConvBertModel, TFConvBertForMaskedLM, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertForMultipleChoice, ) if is_tf_available() else () ) _lowercase : str = ( { 'feature-extraction': TFConvBertModel, 'fill-mask': TFConvBertForMaskedLM, 'question-answering': TFConvBertForQuestionAnswering, 'text-classification': TFConvBertForSequenceClassification, 'token-classification': TFConvBertForTokenClassification, 'zero-shot': TFConvBertForSequenceClassification, } if is_tf_available() else {} ) _lowercase : List[Any] = False _lowercase : str = False _lowercase : List[Any] = False def _lowercase ( self ) -> Optional[int]: '''simple docstring''' a__ : Dict =TFConvBertModelTester(self ) a__ : Any =ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , hidden_size=3_7 ) def _lowercase ( self ) -> Optional[int]: '''simple docstring''' self.config_tester.run_common_tests() def _lowercase ( self ) -> Union[str, Any]: '''simple docstring''' a__ : int =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE ) def _lowercase ( self ) -> Union[str, Any]: '''simple docstring''' a__ : str =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_SCREAMING_SNAKE_CASE ) def _lowercase ( self ) -> Any: '''simple docstring''' a__ : Tuple =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*_SCREAMING_SNAKE_CASE ) def _lowercase ( self ) -> Union[str, Any]: '''simple docstring''' a__ : Tuple =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*_SCREAMING_SNAKE_CASE ) def _lowercase ( self ) -> Optional[int]: '''simple docstring''' a__ : Union[str, Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*_SCREAMING_SNAKE_CASE ) def _lowercase ( self ) -> Optional[Any]: '''simple docstring''' a__ : Dict =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_SCREAMING_SNAKE_CASE ) @slow def _lowercase ( self ) -> List[Any]: '''simple docstring''' a__ : Optional[int] =self.model_tester.prepare_config_and_inputs_for_common() a__ : Any =True a__ : Dict =True if hasattr(_SCREAMING_SNAKE_CASE , "use_cache" ): a__ : int =True a__ : List[str] =getattr(self.model_tester , "encoder_seq_length" , self.model_tester.seq_length ) a__ : str =getattr(self.model_tester , "key_length" , _SCREAMING_SNAKE_CASE ) for model_class in self.all_model_classes: a__ : str =self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) a__ : str =model_class(_SCREAMING_SNAKE_CASE ) a__ : Optional[Any] =len(model(_SCREAMING_SNAKE_CASE ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(_SCREAMING_SNAKE_CASE , saved_model=_SCREAMING_SNAKE_CASE ) a__ : List[Any] =os.path.join(_SCREAMING_SNAKE_CASE , "saved_model" , "1" ) a__ : int =tf.keras.models.load_model(_SCREAMING_SNAKE_CASE ) a__ : Dict =model(_SCREAMING_SNAKE_CASE ) if self.is_encoder_decoder: a__ : List[str] =outputs['encoder_hidden_states'] a__ : Tuple =outputs['encoder_attentions'] else: a__ : Optional[int] =outputs['hidden_states'] a__ : Tuple =outputs['attentions'] self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) a__ : Union[str, Any] =getattr( self.model_tester , "expected_num_hidden_layers" , self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) self.assertListEqual( list(output_hidden_states[0].shape[-2:] ) , [self.model_tester.seq_length, self.model_tester.hidden_size] , ) self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , 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 _lowercase ( self ) -> List[Any]: '''simple docstring''' a__ : Tuple =TFConvBertModel.from_pretrained("YituTech/conv-bert-base" ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) def _lowercase ( self ) -> Dict: '''simple docstring''' a__ : List[str] =self.model_tester.prepare_config_and_inputs_for_common() a__ : Optional[Any] =True a__ : List[Any] =getattr(self.model_tester , "decoder_seq_length" , self.model_tester.seq_length ) a__ : str =getattr(self.model_tester , "encoder_seq_length" , self.model_tester.seq_length ) a__ : Tuple =getattr(self.model_tester , "key_length" , _SCREAMING_SNAKE_CASE ) a__ : Optional[Any] =getattr(self.model_tester , "key_length" , _SCREAMING_SNAKE_CASE ) def check_decoder_attentions_output(lowerCAmelCase__ ): a__ : Union[str, Any] =len(_SCREAMING_SNAKE_CASE ) self.assertEqual(out_len % 2 , 0 ) a__ : Optional[Any] =outputs.decoder_attentions self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , 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(lowerCAmelCase__ ): a__ : str =[ t.numpy() for t in (outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions) ] self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , 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: a__ : List[str] =True a__ : Optional[int] =False a__ : List[Any] =model_class(_SCREAMING_SNAKE_CASE ) a__ : Optional[int] =model(self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) a__ : Tuple =len(_SCREAMING_SNAKE_CASE ) self.assertEqual(config.output_hidden_states , _SCREAMING_SNAKE_CASE ) check_encoder_attentions_output(_SCREAMING_SNAKE_CASE ) if self.is_encoder_decoder: a__ : Any =model_class(_SCREAMING_SNAKE_CASE ) a__ : List[str] =model(self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) self.assertEqual(config.output_hidden_states , _SCREAMING_SNAKE_CASE ) check_decoder_attentions_output(_SCREAMING_SNAKE_CASE ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] a__ : Optional[Any] =True a__ : str =model_class(_SCREAMING_SNAKE_CASE ) a__ : Optional[int] =model(self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) self.assertEqual(config.output_hidden_states , _SCREAMING_SNAKE_CASE ) check_encoder_attentions_output(_SCREAMING_SNAKE_CASE ) # Check attention is always last and order is fine a__ : Dict =True a__ : Optional[Any] =True a__ : List[Any] =model_class(_SCREAMING_SNAKE_CASE ) a__ : Dict =model(self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(_SCREAMING_SNAKE_CASE ) ) self.assertEqual(model.config.output_hidden_states , _SCREAMING_SNAKE_CASE ) check_encoder_attentions_output(_SCREAMING_SNAKE_CASE ) @require_tf class __lowerCAmelCase ( unittest.TestCase): @slow def _lowercase ( self ) -> str: '''simple docstring''' a__ : Dict =TFConvBertModel.from_pretrained("YituTech/conv-bert-base" ) a__ : int =tf.constant([[0, 1, 2, 3, 4, 5]] ) a__ : Tuple =model(_SCREAMING_SNAKE_CASE )[0] a__ : Tuple =[1, 6, 7_6_8] self.assertEqual(output.shape , _SCREAMING_SNAKE_CASE ) a__ : List[Any] =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] , _SCREAMING_SNAKE_CASE , atol=1E-4 )
95
"""simple docstring""" import unittest from transformers import MobileBertConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, MobileBertForMaskedLM, MobileBertForMultipleChoice, MobileBertForNextSentencePrediction, MobileBertForPreTraining, MobileBertForQuestionAnswering, MobileBertForSequenceClassification, MobileBertForTokenClassification, MobileBertModel, ) class A__ : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=13 , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=99 , _SCREAMING_SNAKE_CASE=64 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=37 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=5_12 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=None , ): __lowerCAmelCase : Optional[int] = parent __lowerCAmelCase : Union[str, Any] = batch_size __lowerCAmelCase : Dict = seq_length __lowerCAmelCase : Dict = is_training __lowerCAmelCase : List[str] = use_input_mask __lowerCAmelCase : int = use_token_type_ids __lowerCAmelCase : Optional[int] = use_labels __lowerCAmelCase : List[Any] = vocab_size __lowerCAmelCase : Dict = hidden_size __lowerCAmelCase : Tuple = embedding_size __lowerCAmelCase : List[Any] = num_hidden_layers __lowerCAmelCase : Tuple = num_attention_heads __lowerCAmelCase : Union[str, Any] = intermediate_size __lowerCAmelCase : Optional[Any] = hidden_act __lowerCAmelCase : Optional[int] = hidden_dropout_prob __lowerCAmelCase : Dict = attention_probs_dropout_prob __lowerCAmelCase : Any = max_position_embeddings __lowerCAmelCase : Any = type_vocab_size __lowerCAmelCase : Union[str, Any] = type_sequence_label_size __lowerCAmelCase : List[str] = initializer_range __lowerCAmelCase : str = num_labels __lowerCAmelCase : int = num_choices __lowerCAmelCase : Union[str, Any] = scope def __lowerCamelCase ( self ): __lowerCAmelCase : Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __lowerCAmelCase : Optional[int] = None if self.use_input_mask: __lowerCAmelCase : Optional[int] = random_attention_mask([self.batch_size, self.seq_length] ) __lowerCAmelCase : str = None if self.use_token_type_ids: __lowerCAmelCase : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __lowerCAmelCase : Union[str, Any] = None __lowerCAmelCase : Optional[int] = None __lowerCAmelCase : Union[str, Any] = None if self.use_labels: __lowerCAmelCase : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCAmelCase : Dict = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __lowerCAmelCase : Dict = ids_tensor([self.batch_size] , self.num_choices ) __lowerCAmelCase : str = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowerCamelCase ( self ): return MobileBertConfig( 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 , embedding_size=self.embedding_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=_SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : str = MobileBertModel(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() __lowerCAmelCase : Optional[Any] = model(_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = model(_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : int = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Union[str, Any] = MobileBertForMaskedLM(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() __lowerCAmelCase : Any = model(_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Optional[Any] = MobileBertForNextSentencePrediction(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() __lowerCAmelCase : Dict = model( _SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : List[Any] = MobileBertForPreTraining(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() __lowerCAmelCase : List[Any] = model( _SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE , next_sentence_label=_SCREAMING_SNAKE_CASE , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Optional[int] = MobileBertForQuestionAnswering(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() __lowerCAmelCase : List[str] = model( _SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_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 __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Optional[int] = self.num_labels __lowerCAmelCase : Tuple = MobileBertForSequenceClassification(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() __lowerCAmelCase : str = model(_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Optional[Any] = self.num_labels __lowerCAmelCase : int = MobileBertForTokenClassification(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() __lowerCAmelCase : Optional[Any] = model(_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Optional[int] = self.num_choices __lowerCAmelCase : List[str] = MobileBertForMultipleChoice(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() __lowerCAmelCase : str = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __lowerCAmelCase : List[Any] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __lowerCAmelCase : List[Any] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __lowerCAmelCase : List[str] = model( _SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __lowerCamelCase ( self ): __lowerCAmelCase : Optional[Any] = self.prepare_config_and_inputs() ( ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ) : Optional[Any] = config_and_inputs __lowerCAmelCase : List[str] = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class A__ ( _lowerCamelCase , _lowerCamelCase , unittest.TestCase): A_ : str = ( ( MobileBertModel, MobileBertForMaskedLM, MobileBertForMultipleChoice, MobileBertForNextSentencePrediction, MobileBertForPreTraining, MobileBertForQuestionAnswering, MobileBertForSequenceClassification, MobileBertForTokenClassification, ) if is_torch_available() else () ) A_ : List[str] = ( { 'feature-extraction': MobileBertModel, 'fill-mask': MobileBertForMaskedLM, 'question-answering': MobileBertForQuestionAnswering, 'text-classification': MobileBertForSequenceClassification, 'token-classification': MobileBertForTokenClassification, 'zero-shot': MobileBertForSequenceClassification, } if is_torch_available() else {} ) A_ : Dict = True def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ): __lowerCAmelCase : List[str] = super()._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) if return_labels: if model_class in get_values(_SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Tuple = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=_SCREAMING_SNAKE_CASE ) return inputs_dict def __lowerCamelCase ( self ): __lowerCAmelCase : Optional[Any] = MobileBertModelTester(self ) __lowerCAmelCase : str = ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , hidden_size=37 ) def __lowerCamelCase ( self ): self.config_tester.run_common_tests() def __lowerCamelCase ( self ): __lowerCAmelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_model(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_masked_lm(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_multiple_choice(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_next_sequence_prediction(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_pretraining(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_question_answering(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_sequence_classification(*_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): __lowerCAmelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_token_classification(*_SCREAMING_SNAKE_CASE ) def __lowerCAmelCase (_UpperCamelCase ): return torch.tensor( _UpperCamelCase , dtype=torch.long , device=_UpperCamelCase , ) lowerCamelCase__ = 1E-3 @require_torch @require_sentencepiece @require_tokenizers class A__ ( unittest.TestCase): @slow def __lowerCamelCase ( self ): __lowerCAmelCase : Union[str, Any] = MobileBertModel.from_pretrained('google/mobilebert-uncased' ).to(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = _long_tensor([[1_01, 71_10, 10_05, 10_56, 20_23, 1_13_33, 1_74_13, 10_29, 1_02]] ) with torch.no_grad(): __lowerCAmelCase : int = model(_SCREAMING_SNAKE_CASE )[0] __lowerCAmelCase : Dict = torch.Size((1, 9, 5_12) ) self.assertEqual(output.shape , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = torch.tensor( [ [ [-2.4_73_65_26E07, 8.2_69_16_56E04, 1.6_52_18_38E05], [-5.7_54_17_04E-01, 3.9_05_60_22E00, 4.4_01_15_07E00], [2.6_04_73_59E00, 1.5_67_76_52E00, -1.7_32_41_88E-01], ] ] , device=_SCREAMING_SNAKE_CASE , ) # MobileBERT results range from 10e0 to 10e8. Even a 0.0000001% difference with a value of 10e8 results in a # ~1 difference, it's therefore not a good idea to measure using addition. # Here, we instead divide the expected result with the result in order to obtain ~1. We then check that the # result is held between bounds: 1 - TOLERANCE < expected_result / result < 1 + TOLERANCE __lowerCAmelCase : Tuple = torch.all((expected_slice / output[..., :3, :3]) >= 1 - TOLERANCE ) __lowerCAmelCase : Union[str, Any] = torch.all((expected_slice / output[..., :3, :3]) <= 1 + TOLERANCE ) self.assertTrue(lower_bound and upper_bound )
86
0
from __future__ import annotations import os from typing import Any import requests lowerCAmelCase__ :List[Any] = '''https://api.github.com''' # https://docs.github.com/en/free-pro-team@latest/rest/reference/users#get-the-authenticated-user lowerCAmelCase__ :List[Any] = BASE_URL + '''/user''' # https://github.com/settings/tokens lowerCAmelCase__ :List[Any] = os.environ.get('''USER_TOKEN''', '''''') def lowerCAmelCase__ ( a__: str ) -> List[str]: '''simple docstring''' _UpperCAmelCase = { 'Authorization': F'''token {auth_token}''', 'Accept': 'application/vnd.github.v3+json', } return requests.get(_UpperCamelCase , headers=_UpperCamelCase ).json() if __name__ == "__main__": # pragma: no cover if USER_TOKEN: for key, value in fetch_github_info(USER_TOKEN).items(): print(f'''{key}: {value}''') else: raise ValueError('''\'USER_TOKEN\' field cannot be empty.''')
329
"""simple docstring""" import re import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class A__ ( _lowerCamelCase): A_ : Any = ['image_processor', 'tokenizer'] A_ : Optional[Any] = 'AutoImageProcessor' A_ : str = 'AutoTokenizer' def __init__( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Union[str, Any] = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , _SCREAMING_SNAKE_CASE , ) __lowerCAmelCase : Any = kwargs.pop('feature_extractor' ) __lowerCAmelCase : str = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.' ) if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.' ) super().__init__(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Any = self.image_processor __lowerCAmelCase : Tuple = False def __call__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = kwargs.pop('images' , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Any = kwargs.pop('text' , _SCREAMING_SNAKE_CASE ) if len(_SCREAMING_SNAKE_CASE ) > 0: __lowerCAmelCase : Dict = args[0] __lowerCAmelCase : Union[str, Any] = args[1:] if images is None and text is None: raise ValueError('You need to specify either an `images` or `text` input to process.' ) if images is not None: __lowerCAmelCase : Union[str, Any] = self.image_processor(_SCREAMING_SNAKE_CASE , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) if text is not None: __lowerCAmelCase : Dict = self.tokenizer(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) if text is None: return inputs elif images is None: return encodings else: __lowerCAmelCase : Union[str, Any] = encodings['input_ids'] return inputs def __lowerCamelCase ( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ): return self.tokenizer.batch_decode(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ): return self.tokenizer.decode(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @contextmanager def __lowerCamelCase ( self ): 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 images inputs, or in a separate call.' ) __lowerCAmelCase : Any = True __lowerCAmelCase : Dict = self.tokenizer yield __lowerCAmelCase : Optional[int] = self.image_processor __lowerCAmelCase : Optional[Any] = False def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=None ): if added_vocab is None: __lowerCAmelCase : str = self.tokenizer.get_added_vocab() __lowerCAmelCase : List[Any] = {} while tokens: __lowerCAmelCase : int = re.search(R'<s_(.*?)>' , _SCREAMING_SNAKE_CASE , re.IGNORECASE ) if start_token is None: break __lowerCAmelCase : Union[str, Any] = start_token.group(1 ) __lowerCAmelCase : Tuple = re.search(Rf"</s_{key}>" , _SCREAMING_SNAKE_CASE , re.IGNORECASE ) __lowerCAmelCase : str = start_token.group() if end_token is None: __lowerCAmelCase : Optional[int] = tokens.replace(_SCREAMING_SNAKE_CASE , '' ) else: __lowerCAmelCase : Optional[Any] = end_token.group() __lowerCAmelCase : Tuple = re.escape(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Tuple = re.escape(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Dict = re.search(f"{start_token_escaped}(.*?){end_token_escaped}" , _SCREAMING_SNAKE_CASE , re.IGNORECASE ) if content is not None: __lowerCAmelCase : List[str] = content.group(1 ).strip() if r"<s_" in content and r"</s_" in content: # non-leaf node __lowerCAmelCase : int = self.tokenajson(_SCREAMING_SNAKE_CASE , is_inner_value=_SCREAMING_SNAKE_CASE , added_vocab=_SCREAMING_SNAKE_CASE ) if value: if len(_SCREAMING_SNAKE_CASE ) == 1: __lowerCAmelCase : Tuple = value[0] __lowerCAmelCase : Tuple = value else: # leaf nodes __lowerCAmelCase : Any = [] for leaf in content.split(R'<sep/>' ): __lowerCAmelCase : List[Any] = leaf.strip() if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>": __lowerCAmelCase : Dict = leaf[1:-2] # for categorical special tokens output[key].append(_SCREAMING_SNAKE_CASE ) if len(output[key] ) == 1: __lowerCAmelCase : str = output[key][0] __lowerCAmelCase : Dict = tokens[tokens.find(_SCREAMING_SNAKE_CASE ) + len(_SCREAMING_SNAKE_CASE ) :].strip() if tokens[:6] == r"<sep/>": # non-leaf nodes return [output] + self.tokenajson(tokens[6:] , is_inner_value=_SCREAMING_SNAKE_CASE , added_vocab=_SCREAMING_SNAKE_CASE ) if len(_SCREAMING_SNAKE_CASE ): return [output] if is_inner_value else output else: return [] if is_inner_value else {"text_sequence": tokens} @property def __lowerCamelCase ( self ): warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , _SCREAMING_SNAKE_CASE , ) return self.image_processor_class @property def __lowerCamelCase ( self ): warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , _SCREAMING_SNAKE_CASE , ) return self.image_processor
86
0
"""simple docstring""" import unittest from datasets import load_dataset from transformers import BloomTokenizerFast from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class _lowerCAmelCase ( _lowerCamelCase ,unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Optional[int] = None __UpperCAmelCase : int = BloomTokenizerFast __UpperCAmelCase : List[Any] = BloomTokenizerFast __UpperCAmelCase : Dict = True __UpperCAmelCase : str = False __UpperCAmelCase : str = 'tokenizer_file' __UpperCAmelCase : Any = {'bos_token': '<s>', 'eos_token': '</s>', 'unk_token': '<unk>', 'pad_token': '<pad>'} def _lowercase ( self : List[Any] ): super().setUp() __lowercase = BloomTokenizerFast.from_pretrained("bigscience/tokenizer" ) tokenizer.save_pretrained(self.tmpdirname ) def _lowercase ( self : Optional[Any], **UpperCAmelCase__ : List[str] ): kwargs.update(self.special_tokens_map ) return BloomTokenizerFast.from_pretrained(self.tmpdirname, **_SCREAMING_SNAKE_CASE ) def _lowercase ( self : Any ): __lowercase = self.get_rust_tokenizer() __lowercase = ['The quick brown fox</s>', 'jumps over the lazy dog</s>'] __lowercase = [[2_1_7_5, 2_3_7_1_4, 7_3_1_7_3, 1_4_4_2_5_2, 2], [7_7, 1_3_2_6_1_9, 3_4_7_8, 3_6_8, 1_0_9_5_8_6, 3_5_4_3_3, 2]] __lowercase = tokenizer.batch_encode_plus(_SCREAMING_SNAKE_CASE )['input_ids'] self.assertListEqual(_SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE ) __lowercase = tokenizer.batch_decode(_SCREAMING_SNAKE_CASE ) self.assertListEqual(_SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE ) def _lowercase ( self : str, UpperCAmelCase__ : Dict=6 ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __lowercase = self.rust_tokenizer_class.from_pretrained(_SCREAMING_SNAKE_CASE, **_SCREAMING_SNAKE_CASE ) # tokenizer_r.pad_token = None # Hotfixing padding = None # Simple input __lowercase = 'This is a simple input' __lowercase = ['This is a simple input 1', 'This is a simple input 2'] __lowercase = ('This is a simple input', 'This is a pair') __lowercase = [ ('This is a simple input 1', 'This is a simple input 2'), ('This is a simple pair 1', 'This is a simple pair 2'), ] # Simple input tests try: tokenizer_r.encode(_SCREAMING_SNAKE_CASE, max_length=_SCREAMING_SNAKE_CASE ) tokenizer_r.encode_plus(_SCREAMING_SNAKE_CASE, max_length=_SCREAMING_SNAKE_CASE ) tokenizer_r.batch_encode_plus(_SCREAMING_SNAKE_CASE, max_length=_SCREAMING_SNAKE_CASE ) tokenizer_r.encode(_SCREAMING_SNAKE_CASE, max_length=_SCREAMING_SNAKE_CASE ) tokenizer_r.batch_encode_plus(_SCREAMING_SNAKE_CASE, max_length=_SCREAMING_SNAKE_CASE ) except ValueError: self.fail("Bloom Tokenizer should be able to deal with padding" ) __lowercase = None # Hotfixing padding = None self.assertRaises(_SCREAMING_SNAKE_CASE, tokenizer_r.encode, _SCREAMING_SNAKE_CASE, max_length=_SCREAMING_SNAKE_CASE, padding="max_length" ) # Simple input self.assertRaises(_SCREAMING_SNAKE_CASE, tokenizer_r.encode_plus, _SCREAMING_SNAKE_CASE, max_length=_SCREAMING_SNAKE_CASE, padding="max_length" ) # Simple input self.assertRaises( _SCREAMING_SNAKE_CASE, tokenizer_r.batch_encode_plus, _SCREAMING_SNAKE_CASE, max_length=_SCREAMING_SNAKE_CASE, padding="max_length", ) # Pair input self.assertRaises(_SCREAMING_SNAKE_CASE, tokenizer_r.encode, _SCREAMING_SNAKE_CASE, max_length=_SCREAMING_SNAKE_CASE, padding="max_length" ) # Pair input self.assertRaises(_SCREAMING_SNAKE_CASE, tokenizer_r.encode_plus, _SCREAMING_SNAKE_CASE, max_length=_SCREAMING_SNAKE_CASE, padding="max_length" ) # Pair input self.assertRaises( _SCREAMING_SNAKE_CASE, tokenizer_r.batch_encode_plus, _SCREAMING_SNAKE_CASE, max_length=_SCREAMING_SNAKE_CASE, padding="max_length", ) def _lowercase ( self : Tuple ): __lowercase = self.get_rust_tokenizer() __lowercase = load_dataset("xnli", "all_languages", split="test", streaming=_SCREAMING_SNAKE_CASE ) __lowercase = next(iter(_SCREAMING_SNAKE_CASE ) )['premise'] # pick up one data __lowercase = list(sample_data.values() ) __lowercase = list(map(tokenizer.encode, _SCREAMING_SNAKE_CASE ) ) __lowercase = [tokenizer.decode(_SCREAMING_SNAKE_CASE, clean_up_tokenization_spaces=_SCREAMING_SNAKE_CASE ) for x in output_tokens] self.assertListEqual(_SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE ) def _lowercase ( self : Dict ): # The test has to be overriden because BLOOM uses ALiBi positional embeddings that does not have # any sequence length constraints. This test of the parent class will fail since it relies on the # maximum sequence length of the positoonal embeddings. self.assertGreaterEqual(len(self.tokenizer_class.pretrained_vocab_files_map ), 1 ) self.assertGreaterEqual(len(list(self.tokenizer_class.pretrained_vocab_files_map.values() )[0] ), 1 )
17
"""simple docstring""" def __lowerCAmelCase (_UpperCamelCase ): __lowerCAmelCase : Tuple = 0 while num > 0: digit_sum += num % 10 num //= 10 return digit_sum def __lowerCAmelCase (_UpperCamelCase = 100 ): __lowerCAmelCase : Optional[int] = 1 __lowerCAmelCase : Optional[Any] = 2 for i in range(2 , max_n + 1 ): __lowerCAmelCase : Any = pre_numerator __lowerCAmelCase : Union[str, Any] = 2 * i // 3 if i % 3 == 0 else 1 __lowerCAmelCase : int = cur_numerator __lowerCAmelCase : Dict = e_cont * pre_numerator + temp return sum_digits(_UpperCamelCase ) if __name__ == "__main__": print(f'{solution() = }')
86
0
"""simple docstring""" import argparse import os import re # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_dummies.py lowercase__ : Optional[Any] = '''src/diffusers''' # Matches is_xxx_available() lowercase__ : Optional[Any] = re.compile(r'''is\_([a-z_]*)_available\(\)''') # Matches from xxx import bla lowercase__ : Dict = re.compile(r'''\s+from\s+\S*\s+import\s+([^\(\s].*)\n''') lowercase__ : int = ''' {0} = None ''' lowercase__ : Optional[Any] = ''' class {0}(metaclass=DummyObject): _backends = {1} def __init__(self, *args, **kwargs): requires_backends(self, {1}) @classmethod def from_config(cls, *args, **kwargs): requires_backends(cls, {1}) @classmethod def from_pretrained(cls, *args, **kwargs): requires_backends(cls, {1}) ''' lowercase__ : int = ''' def {0}(*args, **kwargs): requires_backends({0}, {1}) ''' def __lowercase ( _a ): snake_case_ : List[str] = _re_backend.findall(_UpperCamelCase ) if len(_UpperCamelCase ) == 0: return None return "_and_".join(_UpperCamelCase ) def __lowercase ( ): with open(os.path.join(_UpperCamelCase , '''__init__.py''' ) , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: snake_case_ : Union[str, Any] = f.readlines() # Get to the point we do the actual imports for type checking snake_case_ : List[Any] = 0 snake_case_ : Dict = {} # Go through the end of the file while line_index < len(_UpperCamelCase ): # If the line contains is_backend_available, we grab all objects associated with the `else` block snake_case_ : Tuple = find_backend(lines[line_index] ) if backend is not None: while not lines[line_index].startswith('''else:''' ): line_index += 1 line_index += 1 snake_case_ : Any = [] # Until we unindent, add backend objects to the list while line_index < len(_UpperCamelCase ) and len(lines[line_index] ) > 1: snake_case_ : Optional[int] = lines[line_index] snake_case_ : Optional[int] = _re_single_line_import.search(_UpperCamelCase ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(''', ''' ) ) elif line.startswith(''' ''' * 8 ): objects.append(line[8:-2] ) line_index += 1 if len(_UpperCamelCase ) > 0: snake_case_ : List[Any] = objects else: line_index += 1 return backend_specific_objects def __lowercase ( _a , _a ): if name.isupper(): return DUMMY_CONSTANT.format(_UpperCamelCase ) elif name.islower(): return DUMMY_FUNCTION.format(_UpperCamelCase , _UpperCamelCase ) else: return DUMMY_CLASS.format(_UpperCamelCase , _UpperCamelCase ) def __lowercase ( _a=None ): if backend_specific_objects is None: snake_case_ : Dict = read_init() # For special correspondence backend to module name as used in the function requires_modulename snake_case_ : Any = {} for backend, objects in backend_specific_objects.items(): snake_case_ : List[Any] = '[' + ', '.join(f"\"{b}\"" for b in backend.split('''_and_''' ) ) + ']' snake_case_ : Optional[int] = '# This file is autogenerated by the command `make fix-copies`, do not edit.\n' dummy_file += "from ..utils import DummyObject, requires_backends\n\n" dummy_file += "\n".join([create_dummy_object(_UpperCamelCase , _UpperCamelCase ) for o in objects] ) snake_case_ : Optional[Any] = dummy_file return dummy_files def __lowercase ( _a=False ): snake_case_ : str = create_dummy_files() # For special correspondence backend to shortcut as used in utils/dummy_xxx_objects.py snake_case_ : Optional[Any] = {'torch': 'pt'} # Locate actual dummy modules and read their content. snake_case_ : Dict = os.path.join(_UpperCamelCase , '''utils''' ) snake_case_ : Dict = { backend: os.path.join(_UpperCamelCase , f"dummy_{short_names.get(_UpperCamelCase , _UpperCamelCase )}_objects.py" ) for backend in dummy_files.keys() } snake_case_ : str = {} for backend, file_path in dummy_file_paths.items(): if os.path.isfile(_UpperCamelCase ): with open(_UpperCamelCase , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: snake_case_ : Union[str, Any] = f.read() else: snake_case_ : List[str] = '' for backend in dummy_files.keys(): if dummy_files[backend] != actual_dummies[backend]: if overwrite: print( f"Updating diffusers.utils.dummy_{short_names.get(_UpperCamelCase , _UpperCamelCase )}_objects.py as the main " '''__init__ has new objects.''' ) with open(dummy_file_paths[backend] , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.write(dummy_files[backend] ) else: raise ValueError( '''The main __init__ has objects that are not present in ''' f"diffusers.utils.dummy_{short_names.get(_UpperCamelCase , _UpperCamelCase )}_objects.py. Run `make fix-copies` " '''to fix this.''' ) if __name__ == "__main__": lowercase__ : List[str] = argparse.ArgumentParser() parser.add_argument('''--fix_and_overwrite''', action='''store_true''', help='''Whether to fix inconsistencies.''') lowercase__ : List[str] = parser.parse_args() check_dummies(args.fix_and_overwrite)
264
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { """microsoft/markuplm-base""": """https://huggingface.co/microsoft/markuplm-base/resolve/main/config.json""", """microsoft/markuplm-large""": """https://huggingface.co/microsoft/markuplm-large/resolve/main/config.json""", } class A__ ( _lowerCamelCase): A_ : List[Any] = 'markuplm' def __init__( self , _SCREAMING_SNAKE_CASE=3_05_22 , _SCREAMING_SNAKE_CASE=7_68 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=30_72 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=5_12 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE=1E-12 , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=2_56 , _SCREAMING_SNAKE_CASE=10_24 , _SCREAMING_SNAKE_CASE=2_16 , _SCREAMING_SNAKE_CASE=10_01 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=50 , _SCREAMING_SNAKE_CASE="absolute" , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE , ): super().__init__( pad_token_id=_SCREAMING_SNAKE_CASE , bos_token_id=_SCREAMING_SNAKE_CASE , eos_token_id=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) __lowerCAmelCase : Union[str, Any] = vocab_size __lowerCAmelCase : Any = hidden_size __lowerCAmelCase : List[Any] = num_hidden_layers __lowerCAmelCase : Tuple = num_attention_heads __lowerCAmelCase : Union[str, Any] = hidden_act __lowerCAmelCase : List[Any] = intermediate_size __lowerCAmelCase : List[str] = hidden_dropout_prob __lowerCAmelCase : List[str] = attention_probs_dropout_prob __lowerCAmelCase : Optional[int] = max_position_embeddings __lowerCAmelCase : int = type_vocab_size __lowerCAmelCase : Tuple = initializer_range __lowerCAmelCase : int = layer_norm_eps __lowerCAmelCase : List[str] = position_embedding_type __lowerCAmelCase : List[Any] = use_cache __lowerCAmelCase : Optional[Any] = classifier_dropout # additional properties __lowerCAmelCase : Optional[int] = max_depth __lowerCAmelCase : List[str] = max_xpath_tag_unit_embeddings __lowerCAmelCase : Optional[Any] = max_xpath_subs_unit_embeddings __lowerCAmelCase : Any = tag_pad_id __lowerCAmelCase : Union[str, Any] = subs_pad_id __lowerCAmelCase : int = xpath_unit_hidden_size
86
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) __A = { "configuration_longformer": [ "LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "LongformerConfig", "LongformerOnnxConfig", ], "tokenization_longformer": ["LongformerTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["LongformerTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ "LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "LongformerForMaskedLM", "LongformerForMultipleChoice", "LongformerForQuestionAnswering", "LongformerForSequenceClassification", "LongformerForTokenClassification", "LongformerModel", "LongformerPreTrainedModel", "LongformerSelfAttention", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ "TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TFLongformerForMaskedLM", "TFLongformerForMultipleChoice", "TFLongformerForQuestionAnswering", "TFLongformerForSequenceClassification", "TFLongformerForTokenClassification", "TFLongformerModel", "TFLongformerPreTrainedModel", "TFLongformerSelfAttention", ] if TYPE_CHECKING: from .configuration_longformer import ( LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, LongformerConfig, LongformerOnnxConfig, ) from .tokenization_longformer import LongformerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_longformer_fast import LongformerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_longformer import ( LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, LongformerForMaskedLM, LongformerForMultipleChoice, LongformerForQuestionAnswering, LongformerForSequenceClassification, LongformerForTokenClassification, LongformerModel, LongformerPreTrainedModel, LongformerSelfAttention, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_longformer import ( TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFLongformerForMaskedLM, TFLongformerForMultipleChoice, TFLongformerForQuestionAnswering, TFLongformerForSequenceClassification, TFLongformerForTokenClassification, TFLongformerModel, TFLongformerPreTrainedModel, TFLongformerSelfAttention, ) else: import sys __A = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
90
"""simple docstring""" import argparse import torch # Step 1. clone https://github.com/microsoft/unilm # Step 2. git checkout to https://github.com/microsoft/unilm/commit/b94ec76c36f02fb2b0bf0dcb0b8554a2185173cd # Step 3. cd unilm # Step 4. ln -s $(realpath wavlm/modules.py) ./ # create simlink # import classes from unilm.wavlm.WavLM import WavLM as WavLMOrig from unilm.wavlm.WavLM import WavLMConfig as WavLMConfigOrig from transformers import WavLMConfig, WavLMModel, logging logging.set_verbosity_info() lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { """post_extract_proj""": """feature_projection.projection""", """encoder.pos_conv.0""": """encoder.pos_conv_embed.conv""", """self_attn.k_proj""": """encoder.layers.*.attention.k_proj""", """self_attn.v_proj""": """encoder.layers.*.attention.v_proj""", """self_attn.q_proj""": """encoder.layers.*.attention.q_proj""", """self_attn.out_proj""": """encoder.layers.*.attention.out_proj""", """self_attn.grep_linear""": """encoder.layers.*.attention.gru_rel_pos_linear""", """self_attn.relative_attention_bias""": """encoder.layers.*.attention.rel_attn_embed""", """self_attn.grep_a""": """encoder.layers.*.attention.gru_rel_pos_const""", """self_attn_layer_norm""": """encoder.layers.*.layer_norm""", """fc1""": """encoder.layers.*.feed_forward.intermediate_dense""", """fc2""": """encoder.layers.*.feed_forward.output_dense""", """final_layer_norm""": """encoder.layers.*.final_layer_norm""", """encoder.layer_norm""": """encoder.layer_norm""", """w2v_model.layer_norm""": """feature_projection.layer_norm""", """quantizer.weight_proj""": """quantizer.weight_proj""", """quantizer.vars""": """quantizer.codevectors""", """project_q""": """project_q""", """final_proj""": """project_hid""", """w2v_encoder.proj""": """ctc_proj""", """mask_emb""": """masked_spec_embed""", } lowerCamelCase__ = [ """ctc_proj""", """quantizer.weight_proj""", """quantizer.codevectors""", """project_q""", """project_hid""", ] def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): for attribute in key.split('.' ): __lowerCAmelCase : str = getattr(_UpperCamelCase , _UpperCamelCase ) if weight_type is not None: __lowerCAmelCase : Tuple = getattr(_UpperCamelCase , _UpperCamelCase ).shape else: __lowerCAmelCase : Dict = hf_pointer.shape assert hf_shape == value.shape, ( F"Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be" F" {value.shape} for {full_name}" ) if weight_type == "weight": __lowerCAmelCase : Union[str, Any] = value elif weight_type == "weight_g": __lowerCAmelCase : List[Any] = value elif weight_type == "weight_v": __lowerCAmelCase : Any = value elif weight_type == "bias": __lowerCAmelCase : List[str] = value else: __lowerCAmelCase : List[Any] = value logger.info(F"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}." ) def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase ): __lowerCAmelCase : Any = [] __lowerCAmelCase : Optional[int] = fairseq_model.state_dict() __lowerCAmelCase : Union[str, Any] = hf_model.feature_extractor for name, value in fairseq_dict.items(): __lowerCAmelCase : Union[str, Any] = False if "conv_layers" in name: load_conv_layer( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , hf_model.config.feat_extract_norm == 'group' , ) __lowerCAmelCase : str = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]: __lowerCAmelCase : int = True if "*" in mapped_key: __lowerCAmelCase : List[str] = name.split(_UpperCamelCase )[0].split('.' )[-2] __lowerCAmelCase : Optional[Any] = mapped_key.replace('*' , _UpperCamelCase ) if "weight_g" in name: __lowerCAmelCase : Union[str, Any] = 'weight_g' elif "weight_v" in name: __lowerCAmelCase : int = 'weight_v' elif "bias" in name and "relative_attention_bias" not in name: __lowerCAmelCase : Optional[Any] = 'bias' elif "weight" in name: # TODO: don't match quantizer.weight_proj __lowerCAmelCase : List[str] = 'weight' else: __lowerCAmelCase : Optional[Any] = None set_recursively(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) continue if not is_used: unused_weights.append(_UpperCamelCase ) logger.warning(F"Unused weights: {unused_weights}" ) def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): __lowerCAmelCase : List[Any] = full_name.split('conv_layers.' )[-1] __lowerCAmelCase : Any = name.split('.' ) __lowerCAmelCase : List[Any] = int(items[0] ) __lowerCAmelCase : Tuple = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( F"{full_name} has size {value.shape}, but" F" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found." ) __lowerCAmelCase : Tuple = value logger.info(F"Feat extract conv layer {layer_id} was initialized from {full_name}." ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( F"{full_name} has size {value.shape}, but" F" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found." ) __lowerCAmelCase : int = value logger.info(F"Feat extract conv layer {layer_id} was initialized from {full_name}." ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( F"{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was" " found." ) __lowerCAmelCase : Optional[Any] = value logger.info(F"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( F"{full_name} has size {value.shape}, but" F" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found." ) __lowerCAmelCase : Any = value logger.info(F"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) else: unused_weights.append(_UpperCamelCase ) @torch.no_grad() def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase=None ): # load the pre-trained checkpoints __lowerCAmelCase : Any = torch.load(_UpperCamelCase ) __lowerCAmelCase : List[str] = WavLMConfigOrig(checkpoint['cfg'] ) __lowerCAmelCase : Optional[Any] = WavLMOrig(_UpperCamelCase ) model.load_state_dict(checkpoint['model'] ) model.eval() if config_path is not None: __lowerCAmelCase : Dict = WavLMConfig.from_pretrained(_UpperCamelCase ) else: __lowerCAmelCase : List[str] = WavLMConfig() __lowerCAmelCase : List[str] = WavLMModel(_UpperCamelCase ) recursively_load_weights(_UpperCamelCase , _UpperCamelCase ) hf_wavlm.save_pretrained(_UpperCamelCase ) if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to fairseq checkpoint""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") lowerCamelCase__ = parser.parse_args() convert_wavlm_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
86
0
'''simple docstring''' from typing import Any, Dict, List, Optional, Tuple, Union import torch from torch import nn from torch.utils.data import DistributedSampler, RandomSampler from transformers import PreTrainedModel, Trainer, logging from transformers.integrations import is_fairscale_available from transformers.models.fsmt.configuration_fsmt import FSMTConfig from transformers.optimization import ( Adafactor, AdamW, get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) from transformers.trainer_pt_utils import get_tpu_sampler from transformers.training_args import ParallelMode from transformers.utils import is_torch_tpu_available if is_fairscale_available(): from fairscale.optim import OSS __lowercase = logging.get_logger(__name__) __lowercase = { '''linear''': get_linear_schedule_with_warmup, '''cosine''': get_cosine_schedule_with_warmup, '''cosine_w_restarts''': get_cosine_with_hard_restarts_schedule_with_warmup, '''polynomial''': get_polynomial_decay_schedule_with_warmup, '''constant''': get_constant_schedule, '''constant_w_warmup''': get_constant_schedule_with_warmup, } class a__( _lowerCamelCase ): '''simple docstring''' def __init__( self , __lowerCAmelCase=None , __lowerCAmelCase=None , *__lowerCAmelCase , **__lowerCAmelCase): """simple docstring""" super().__init__(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE) if config is None: assert isinstance(self.model , _SCREAMING_SNAKE_CASE), ( "If no `config` is passed the model to be trained has to be of type `PreTrainedModel`, but is" f" {self.model.__class__}" ) lowerCAmelCase = self.model.config else: lowerCAmelCase = config lowerCAmelCase = data_args lowerCAmelCase = self.config.tgt_vocab_size if isinstance(self.config , _SCREAMING_SNAKE_CASE) else self.config.vocab_size if self.args.label_smoothing != 0 or (self.data_args is not None and self.data_args.ignore_pad_token_for_loss): assert self.config.pad_token_id is not None, ( "Make sure that `config.pad_token_id` is correcly defined when ignoring `pad_token` for loss" " calculation or doing label smoothing." ) if self.config.pad_token_id is None and self.config.eos_token_id is not None: logger.warning( f"The `config.pad_token_id` is `None`. Using `config.eos_token_id` = {self.config.eos_token_id} for" """ padding..""") if self.args.label_smoothing == 0: lowerCAmelCase = torch.nn.CrossEntropyLoss(ignore_index=self.config.pad_token_id) else: # dynamically import label_smoothed_nll_loss from utils import label_smoothed_nll_loss lowerCAmelCase = label_smoothed_nll_loss def a_ ( self , __lowerCAmelCase): """simple docstring""" if self.optimizer is None: lowerCAmelCase = ['bias', 'LayerNorm.weight'] lowerCAmelCase = [ { 'params': [p for n, p in self.model.named_parameters() if not any(nd in n for nd in no_decay)], 'weight_decay': self.args.weight_decay, }, { 'params': [p for n, p in self.model.named_parameters() if any(nd in n for nd in no_decay)], 'weight_decay': 0.0, }, ] lowerCAmelCase = Adafactor if self.args.adafactor else AdamW if self.args.adafactor: lowerCAmelCase = Adafactor lowerCAmelCase = {'scale_parameter': False, 'relative_step': False} else: lowerCAmelCase = AdamW lowerCAmelCase = { 'betas': (self.args.adam_betaa, self.args.adam_betaa), 'eps': self.args.adam_epsilon, } lowerCAmelCase = self.args.learning_rate if self.sharded_ddp: lowerCAmelCase = OSS( params=_SCREAMING_SNAKE_CASE , optim=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) else: lowerCAmelCase = optimizer_cls(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE) if self.lr_scheduler is None: lowerCAmelCase = self._get_lr_scheduler(_SCREAMING_SNAKE_CASE) else: # ignoring --lr_scheduler logger.warning("""scheduler is passed to `Seq2SeqTrainer`, `--lr_scheduler` arg is ignored.""") def a_ ( self , __lowerCAmelCase): """simple docstring""" lowerCAmelCase = arg_to_scheduler[self.args.lr_scheduler] if self.args.lr_scheduler == "constant": lowerCAmelCase = schedule_func(self.optimizer) elif self.args.lr_scheduler == "constant_w_warmup": lowerCAmelCase = schedule_func(self.optimizer , num_warmup_steps=self.args.warmup_steps) else: lowerCAmelCase = schedule_func( self.optimizer , num_warmup_steps=self.args.warmup_steps , num_training_steps=_SCREAMING_SNAKE_CASE) return scheduler def a_ ( self): """simple docstring""" if isinstance(self.train_dataset , torch.utils.data.IterableDataset): return None elif is_torch_tpu_available(): return get_tpu_sampler(self.train_dataset) else: if self.args.sortish_sampler: self.train_dataset.make_sortish_sampler( self.args.per_device_train_batch_size , distributed=(self.args.parallel_mode == ParallelMode.DISTRIBUTED) , ) return ( RandomSampler(self.train_dataset) if self.args.local_rank == -1 else DistributedSampler(self.train_dataset) ) def a_ ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase): """simple docstring""" if self.args.label_smoothing == 0: if self.data_args is not None and self.data_args.ignore_pad_token_for_loss: # force training to ignore pad token lowerCAmelCase = model(**_SCREAMING_SNAKE_CASE , use_cache=_SCREAMING_SNAKE_CASE)[0] lowerCAmelCase = self.loss_fn(logits.view(-1 , logits.shape[-1]) , labels.view(-1)) else: # compute usual loss via models lowerCAmelCase = model(**_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE , use_cache=_SCREAMING_SNAKE_CASE)[:2] else: # compute label smoothed loss lowerCAmelCase = model(**_SCREAMING_SNAKE_CASE , use_cache=_SCREAMING_SNAKE_CASE)[0] lowerCAmelCase = torch.nn.functional.log_softmax(_SCREAMING_SNAKE_CASE , dim=-1) lowerCAmelCase = self.loss_fn(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , self.args.label_smoothing , ignore_index=self.config.pad_token_id) return loss, logits def a_ ( self , __lowerCAmelCase , __lowerCAmelCase): """simple docstring""" lowerCAmelCase = inputs.pop("""labels""") lowerCAmelCase = self._compute_loss(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE) return loss def a_ ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = None , ): """simple docstring""" lowerCAmelCase = self._prepare_inputs(_SCREAMING_SNAKE_CASE) lowerCAmelCase = { 'max_length': self.data_args.val_max_target_length if self.data_args is not None else self.config.max_length, 'num_beams': self.data_args.eval_beams if self.data_args is not None else self.config.num_beams, } if self.args.predict_with_generate and not self.args.prediction_loss_only: lowerCAmelCase = self.model.generate( inputs["""input_ids"""] , attention_mask=inputs["""attention_mask"""] , **_SCREAMING_SNAKE_CASE , ) # in case the batch is shorter than max length, the output should be padded if generated_tokens.shape[-1] < gen_kwargs["max_length"]: lowerCAmelCase = self._pad_tensors_to_max_len(_SCREAMING_SNAKE_CASE , gen_kwargs["""max_length"""]) lowerCAmelCase = inputs.pop("""labels""") with torch.no_grad(): # compute loss on predict data lowerCAmelCase = self._compute_loss(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE) lowerCAmelCase = loss.mean().detach() if self.args.prediction_loss_only: return (loss, None, None) lowerCAmelCase = generated_tokens if self.args.predict_with_generate else logits if labels.shape[-1] < gen_kwargs["max_length"]: lowerCAmelCase = self._pad_tensors_to_max_len(_SCREAMING_SNAKE_CASE , gen_kwargs["""max_length"""]) return (loss, logits, labels) def a_ ( self , __lowerCAmelCase , __lowerCAmelCase): """simple docstring""" lowerCAmelCase = self.config.pad_token_id if self.config.pad_token_id is not None else self.config.eos_token_id if pad_token_id is None: raise ValueError( """Make sure that either `config.pad_token_id` or `config.eos_token_id` is defined if tensor has to be""" f" padded to `max_length`={max_length}") lowerCAmelCase = pad_token_id * torch.ones( (tensor.shape[0], max_length) , dtype=tensor.dtype , device=tensor.device) lowerCAmelCase = tensor return padded_tensor
272
"""simple docstring""" import os import pytest from attr import dataclass lowerCamelCase__ = """us-east-1""" # defaults region @dataclass class A__ : A_ : str A_ : Union[str, Any] = 'arn:aws:iam::558105141721:role/sagemaker_execution_role' A_ : Optional[int] = { 'task_name': 'mnli', 'per_device_train_batch_size': 1_6, 'per_device_eval_batch_size': 1_6, 'do_train': True, 'do_eval': True, 'do_predict': True, 'output_dir': '/opt/ml/model', 'overwrite_output_dir': True, 'max_steps': 5_0_0, 'save_steps': 5_5_0_0, } A_ : List[Any] = {**hyperparameters, 'max_steps': 1_0_0_0} @property def __lowerCamelCase ( self ): if self.framework == "pytorch": return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"eval_accuracy.*=\D*(.*?)$"}, {"Name": "eval_loss", "Regex": r"eval_loss.*=\D*(.*?)$"}, ] else: return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"loss.*=\D*(.*?)]?$"}, {"Name": "eval_loss", "Regex": r"sparse_categorical_accuracy.*=\D*(.*?)]?$"}, ] @property def __lowerCamelCase ( self ): return f"{self.framework}-transfromers-test" @property def __lowerCamelCase ( self ): return f"./tests/sagemaker/scripts/{self.framework}" @property def __lowerCamelCase ( self ): if self.framework == "pytorch": return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-pytorch-training:1.7.1-transformers4.6.1-gpu-py36-cu110-ubuntu18.04" else: return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-tensorflow-training:2.4.1-transformers4.6.1-gpu-py37-cu110-ubuntu18.04" @pytest.fixture(scope='class' ) def __lowerCAmelCase (_UpperCamelCase ): __lowerCAmelCase : str = SageMakerTestEnvironment(framework=request.cls.framework )
86
0
import argparse import re import torch from CLAP import create_model from transformers import AutoFeatureExtractor, ClapConfig, ClapModel a__ = { """text_branch""": """text_model""", """audio_branch""": """audio_model.audio_encoder""", """attn""": """attention.self""", """self.proj""": """output.dense""", """attention.self_mask""": """attn_mask""", """mlp.fc1""": """intermediate.dense""", """mlp.fc2""": """output.dense""", """norm1""": """layernorm_before""", """norm2""": """layernorm_after""", """bn0""": """batch_norm""", } a__ = AutoFeatureExtractor.from_pretrained("""laion/clap-htsat-unfused""", truncation="""rand_trunc""") def lowercase ( SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Union[str, Any]=False ) -> Optional[Any]: _snake_case : List[str] = create_model( """HTSAT-tiny""" , """roberta""" , _UpperCamelCase , precision="""fp32""" , device="""cuda:0""" if torch.cuda.is_available() else """cpu""" , enable_fusion=_UpperCamelCase , fusion_type="""aff_2d""" if enable_fusion else None , ) return model, model_cfg def lowercase ( SCREAMING_SNAKE_CASE__ : Dict ) -> int: _snake_case : Optional[int] = {} _snake_case : str = r'.*sequential.(\d+).*' _snake_case : int = r'.*_projection.(\d+).*' for key, value in state_dict.items(): # check if any key needs to be modified for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items(): if key_to_modify in key: _snake_case : Union[str, Any] = key.replace(_UpperCamelCase , _UpperCamelCase ) if re.match(_UpperCamelCase , _UpperCamelCase ): # replace sequential layers with list _snake_case : List[str] = re.match(_UpperCamelCase , _UpperCamelCase ).group(1 ) _snake_case : Tuple = key.replace(F'''sequential.{sequential_layer}.''' , F'''layers.{int(_UpperCamelCase )//3}.linear.''' ) elif re.match(_UpperCamelCase , _UpperCamelCase ): _snake_case : Dict = int(re.match(_UpperCamelCase , _UpperCamelCase ).group(1 ) ) # Because in CLAP they use `nn.Sequential`... _snake_case : Tuple = 1 if projecton_layer == 0 else 2 _snake_case : List[str] = key.replace(F'''_projection.{projecton_layer}.''' , F'''_projection.linear{transformers_projection_layer}.''' ) if "audio" and "qkv" in key: # split qkv into query key and value _snake_case : int = value _snake_case : Union[str, Any] = mixed_qkv.size(0 ) // 3 _snake_case : Optional[int] = mixed_qkv[:qkv_dim] _snake_case : Optional[Any] = mixed_qkv[qkv_dim : qkv_dim * 2] _snake_case : Optional[int] = mixed_qkv[qkv_dim * 2 :] _snake_case : Optional[Any] = query_layer _snake_case : Dict = key_layer _snake_case : str = value_layer else: _snake_case : Dict = value return model_state_dict def lowercase ( SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any]=False ) -> str: _snake_case : List[str] = init_clap(_UpperCamelCase , enable_fusion=_UpperCamelCase ) clap_model.eval() _snake_case : Optional[int] = clap_model.state_dict() _snake_case : Dict = rename_state_dict(_UpperCamelCase ) _snake_case : List[str] = ClapConfig() _snake_case : List[str] = enable_fusion _snake_case : Dict = ClapModel(_UpperCamelCase ) # ignore the spectrogram embedding layer model.load_state_dict(_UpperCamelCase , strict=_UpperCamelCase ) model.save_pretrained(_UpperCamelCase ) transformers_config.save_pretrained(_UpperCamelCase ) if __name__ == "__main__": a__ = argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to fairseq checkpoint""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") parser.add_argument("""--enable_fusion""", action="""store_true""", help="""Whether to enable fusion or not""") a__ = parser.parse_args() convert_clap_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.enable_fusion)
317
"""simple docstring""" from __future__ import annotations lowerCamelCase__ = list[tuple[int, int]] lowerCamelCase__ = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] lowerCamelCase__ = ([-1, 0], [0, -1], [1, 0], [0, 1]) # up, left, down, right class A__ : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , ): __lowerCAmelCase : int = pos_x __lowerCAmelCase : Optional[Any] = pos_y __lowerCAmelCase : Optional[int] = (pos_y, pos_x) __lowerCAmelCase : Union[str, Any] = goal_x __lowerCAmelCase : Any = goal_y __lowerCAmelCase : Optional[Any] = g_cost __lowerCAmelCase : Any = parent __lowerCAmelCase : Union[str, Any] = self.calculate_heuristic() def __lowerCamelCase ( self ): __lowerCAmelCase : str = abs(self.pos_x - self.goal_x ) __lowerCAmelCase : str = abs(self.pos_y - self.goal_y ) return dx + dy def __lt__( self , _SCREAMING_SNAKE_CASE ): return self.f_cost < other.f_cost class A__ : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Optional[int] = Node(start[1] , start[0] , goal[1] , goal[0] , 0 , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Any = Node(goal[1] , goal[0] , goal[1] , goal[0] , 9_99_99 , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Tuple = [self.start] __lowerCAmelCase : list[Node] = [] __lowerCAmelCase : str = False def __lowerCamelCase ( self ): while self.open_nodes: # Open Nodes are sorted using __lt__ self.open_nodes.sort() __lowerCAmelCase : Optional[int] = self.open_nodes.pop(0 ) if current_node.pos == self.target.pos: __lowerCAmelCase : Union[str, Any] = True return self.retrace_path(_SCREAMING_SNAKE_CASE ) self.closed_nodes.append(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = self.get_successors(_SCREAMING_SNAKE_CASE ) for child_node in successors: if child_node in self.closed_nodes: continue if child_node not in self.open_nodes: self.open_nodes.append(_SCREAMING_SNAKE_CASE ) else: # retrieve the best current path __lowerCAmelCase : Optional[Any] = self.open_nodes.pop(self.open_nodes.index(_SCREAMING_SNAKE_CASE ) ) if child_node.g_cost < better_node.g_cost: self.open_nodes.append(_SCREAMING_SNAKE_CASE ) else: self.open_nodes.append(_SCREAMING_SNAKE_CASE ) if not self.reached: return [self.start.pos] return None def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Dict = [] for action in delta: __lowerCAmelCase : Optional[int] = parent.pos_x + action[1] __lowerCAmelCase : Union[str, Any] = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(_SCREAMING_SNAKE_CASE ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , self.target.pos_y , self.target.pos_x , parent.g_cost + 1 , _SCREAMING_SNAKE_CASE , ) ) return successors def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Union[str, Any] = node __lowerCAmelCase : Optional[int] = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) __lowerCAmelCase : int = current_node.parent path.reverse() return path if __name__ == "__main__": lowerCamelCase__ = (0, 0) lowerCamelCase__ = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) print("""------""") lowerCamelCase__ = GreedyBestFirst(init, goal) lowerCamelCase__ = greedy_bf.search() if path: for pos_x, pos_y in path: lowerCamelCase__ = 2 for elem in grid: print(elem)
86
0