code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
from collections import UserDict from typing import Union import numpy as np import requests from ..utils import ( add_end_docstrings, logging, ) from .audio_classification import ffmpeg_read from .base import PIPELINE_INIT_ARGS, Pipeline __snake_case :List[Any] = logging.get_logger(__name__) @add_end_docstrings(__UpperCAmelCase ) class _A ( __UpperCAmelCase ): def __init__( self : Any , **__SCREAMING_SNAKE_CASE : Union[str, Any]): '''simple docstring''' super().__init__(**__SCREAMING_SNAKE_CASE) if self.framework != "pt": raise ValueError(F'The {self.__class__} is only available in PyTorch.') # No specific FOR_XXX available yet def __call__( self : Tuple , __SCREAMING_SNAKE_CASE : Union[np.ndarray, bytes, str] , **__SCREAMING_SNAKE_CASE : int): '''simple docstring''' return super().__call__(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE) def _lowerCamelCase ( self : Tuple , **__SCREAMING_SNAKE_CASE : Any): '''simple docstring''' __a = {} if "candidate_labels" in kwargs: __a = kwargs['''candidate_labels'''] if "hypothesis_template" in kwargs: __a = kwargs['''hypothesis_template'''] return preprocess_params, {}, {} def _lowerCamelCase ( self : List[Any] , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : List[str]=None , __SCREAMING_SNAKE_CASE : Tuple="This is a sound of {}."): '''simple docstring''' if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE): if audio.startswith('''http://''') or audio.startswith('''https://'''): # We need to actually check for a real protocol, otherwise it's impossible to use a local file # like http_huggingface_co.png __a = requests.get(__SCREAMING_SNAKE_CASE).content else: with open(__SCREAMING_SNAKE_CASE , '''rb''') as f: __a = f.read() if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE): __a = ffmpeg_read(__SCREAMING_SNAKE_CASE , self.feature_extractor.sampling_rate) if not isinstance(__SCREAMING_SNAKE_CASE , np.ndarray): raise ValueError('''We expect a numpy ndarray as input''') if len(audio.shape) != 1: raise ValueError('''We expect a single channel audio input for ZeroShotAudioClassificationPipeline''') __a = self.feature_extractor( [audio] , sampling_rate=self.feature_extractor.sampling_rate , return_tensors='''pt''') __a = candidate_labels __a = [hypothesis_template.format(__SCREAMING_SNAKE_CASE) for x in candidate_labels] __a = self.tokenizer(__SCREAMING_SNAKE_CASE , return_tensors=self.framework , padding=__SCREAMING_SNAKE_CASE) __a = [text_inputs] return inputs def _lowerCamelCase ( self : List[Any] , __SCREAMING_SNAKE_CASE : Optional[int]): '''simple docstring''' __a = model_inputs.pop('''candidate_labels''') __a = model_inputs.pop('''text_inputs''') if isinstance(text_inputs[0] , __SCREAMING_SNAKE_CASE): __a = text_inputs[0] else: # Batching case. __a = text_inputs[0][0] __a = self.model(**__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE) __a = { '''candidate_labels''': candidate_labels, '''logits''': outputs.logits_per_audio, } return model_outputs def _lowerCamelCase ( self : Optional[int] , __SCREAMING_SNAKE_CASE : Optional[int]): '''simple docstring''' __a = model_outputs.pop('''candidate_labels''') __a = model_outputs['''logits'''][0] if self.framework == "pt": __a = logits.softmax(dim=0) __a = probs.tolist() else: raise ValueError('''`tf` framework not supported.''') __a = [ {'''score''': score, '''label''': candidate_label} for score, candidate_label in sorted(zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) , key=lambda __SCREAMING_SNAKE_CASE: -x[0]) ] return result
49
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __lowerCAmelCase = {'''configuration_swin''': ['''SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''SwinConfig''', '''SwinOnnxConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase = [ '''SWIN_PRETRAINED_MODEL_ARCHIVE_LIST''', '''SwinForImageClassification''', '''SwinForMaskedImageModeling''', '''SwinModel''', '''SwinPreTrainedModel''', '''SwinBackbone''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase = [ '''TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFSwinForImageClassification''', '''TFSwinForMaskedImageModeling''', '''TFSwinModel''', '''TFSwinPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_swin import SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP, SwinConfig, SwinOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_swin import ( SWIN_PRETRAINED_MODEL_ARCHIVE_LIST, SwinBackbone, SwinForImageClassification, SwinForMaskedImageModeling, SwinModel, SwinPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_swin import ( TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST, TFSwinForImageClassification, TFSwinForMaskedImageModeling, TFSwinModel, TFSwinPreTrainedModel, ) else: import sys __lowerCAmelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
89
0
import argparse import re from flax.traverse_util import flatten_dict, unflatten_dict from tax import checkpoints from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration from transformers.modeling_flax_pytorch_utils import load_flax_weights_in_pytorch_model from transformers.utils import logging logging.set_verbosity_info() # should not include what is already done by the `from_pt` argument lowercase_ = { '/attention/': '/0/SelfAttention/', '/self_attention/': '/0/SelfAttention/', '/encoder_decoder_attention/': '/1/EncDecAttention/', 'value': 'v', 'query': 'q', 'key': 'k', 'out': 'o', 'pre_self_attention_layer_norm': '0/layer_norm', 'pre_cross_attention_layer_norm': '1/layer_norm', 'pre_attention_layer_norm': '0/layer_norm', # previously 1, but seems wrong 'token_embedder': 'shared', 'encoder_norm': 'final_layer_norm', 'decoder_norm': 'final_layer_norm', 'relpos_bias/rel_embedding': 'block/0/layer/0/SelfAttention/relative_attention_bias/weight', 'router/router_weights/w/': 'router/classifier/', 'roer/roer_weights/w/': 'router/classifier/', 'logits_dense': 'lm_head', } def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): # 1. in HF T5, we have block.{x}.layer.{y}. which corresponds to layer.{x} in # the original model __lowerCamelCase : List[Any] = list(s_dict.keys() ) for key in keys: __lowerCamelCase : int = r'.*/layers_(\d+)' __lowerCamelCase : List[str] = key if re.match(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Union[str, Any] = re.sub(r'layers_(\d+)' , r'block/\1/layer' , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : List[Any] = r'(encoder|decoder)\/' if re.match(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Dict = re.match(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ).groups() if groups[0] == "encoder": __lowerCamelCase : Union[str, Any] = re.sub(r'/mlp/' , r'/1/mlp/' , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : str = re.sub(r'/pre_mlp_layer_norm/' , r'/1/layer_norm/' , SCREAMING_SNAKE_CASE__ ) elif groups[0] == "decoder": __lowerCamelCase : Tuple = re.sub(r'/mlp/' , r'/2/mlp/' , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : List[str] = re.sub(r'/pre_mlp_layer_norm/' , r'/2/layer_norm/' , SCREAMING_SNAKE_CASE__ ) # 2. Convert other classic mappings for old_key, temp_key in MOE_LAYER_NAME_MAPPING.items(): if old_key in new_key: __lowerCamelCase : Union[str, Any] = new_key.replace(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) print(f'{key} -> {new_key}' ) __lowerCamelCase : Optional[int] = s_dict.pop(SCREAMING_SNAKE_CASE__ ) if "encoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight" in s_dict: __lowerCamelCase : Optional[int] = s_dict[ 'encoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight' ].T if "decoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight" in s_dict: __lowerCamelCase : Optional[int] = s_dict[ 'decoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight' ].T # 3. Take extra care of the EXPERTS layer for key in list(s_dict.keys() ): if "expert" in key: __lowerCamelCase : Any = s_dict[key].shape[0] __lowerCamelCase : List[str] = s_dict[key] for idx in range(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Optional[int] = expert_weihts[idx] print(f'{key} -> {key.replace("expert/" , "nested fstring" )}' ) s_dict.pop(SCREAMING_SNAKE_CASE__ ) return s_dict lowercase_ = { 'NUM_ENCODER_LAYERS': 'num_layers', 'NUM_DECODER_LAYERS': 'num_decoder_layers', 'NUM_HEADS': 'num_heads', 'HEAD_DIM': 'd_kv', 'EMBED_DIM': 'd_model', 'MLP_DIM': 'd_ff', 'NUM_SELECTED_EXPERTS': 'num_selected_experts', 'NUM_ENCODER_SPARSE_LAYERS': 'num_sparse_encoder_layers', 'NUM_DECODER_SPARSE_LAYERS': 'num_sparse_decoder_layers', 'dense.MlpBlock.activations': 'feed_forward_proj', } def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): # Convert a google style config to the hugging face fromat import regex as re with open(SCREAMING_SNAKE_CASE__ , 'r' ) as f: __lowerCamelCase : Optional[Any] = f.read() __lowerCamelCase : str = re.findall(r'(.*) = ([0-9.]*)' , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : List[Any] = {} for param, value in regex_match: if param in GIN_TO_CONFIG_MAPPING and value != "": __lowerCamelCase : Dict = float(SCREAMING_SNAKE_CASE__ ) if '.' in value else int(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Tuple = re.findall(r'(.*activations) = \(\'(.*)\',\)' , SCREAMING_SNAKE_CASE__ )[0] __lowerCamelCase : Union[str, Any] = str(activation[1] ) __lowerCamelCase : List[str] = num_experts __lowerCamelCase : Union[str, Any] = SwitchTransformersConfig(**SCREAMING_SNAKE_CASE__ ) return config def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__="./" , SCREAMING_SNAKE_CASE__=8 ): # Initialise PyTorch model print(f'Loading flax weights from : {flax_checkpoint_path}' ) __lowerCamelCase : Tuple = checkpoints.load_tax_checkpoint(SCREAMING_SNAKE_CASE__ ) if gin_file is not None: __lowerCamelCase : Optional[Any] = convert_gin_to_config(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else: __lowerCamelCase : Any = SwitchTransformersConfig.from_pretrained(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Union[str, Any] = SwitchTransformersForConditionalGeneration(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : int = flax_params['target'] __lowerCamelCase : List[Any] = flatten_dict(SCREAMING_SNAKE_CASE__ , sep='/' ) __lowerCamelCase : Optional[int] = rename_keys(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : List[str] = unflatten_dict(SCREAMING_SNAKE_CASE__ , sep='/' ) # Load the flax params in the PT model load_flax_weights_in_pytorch_model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) print(f'Save PyTorch model to {pytorch_dump_path}' ) pt_model.save_pretrained(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--switch_t5x_checkpoint_path', default=None, type=str, required=True, help=( 'The config json file corresponding to the pre-trained SwitchTransformers model. \nThis specifies the' ' model architecture. If not provided, a `gin_file` has to be provided.' ), ) parser.add_argument( '--gin_file', default=None, type=str, required=False, help='Path to the gin config file. If not provided, a `config_file` has to be passed ', ) parser.add_argument( '--config_name', default=None, type=str, required=False, help='Config name of SwitchTransformers model.' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output pytorch model.' ) parser.add_argument('--num_experts', default=8, type=int, required=False, help='Number of experts') lowercase_ = parser.parse_args() convert_flax_checkpoint_to_pytorch( args.switch_tax_checkpoint_path, args.config_name, args.gin_file, args.pytorch_dump_folder_path, args.num_experts, )
357
import inspect from typing import Optional, Union import numpy as np import PIL import torch from torch.nn import functional as F from torchvision import transforms from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, DPMSolverMultistepScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput from diffusers.utils import ( PIL_INTERPOLATION, randn_tensor, ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if isinstance(SCREAMING_SNAKE_CASE__ , torch.Tensor ): return image elif isinstance(SCREAMING_SNAKE_CASE__ , PIL.Image.Image ): __lowerCamelCase : Union[str, Any] = [image] if isinstance(image[0] , PIL.Image.Image ): __lowerCamelCase : Any = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION['lanczos'] ) )[None, :] for i in image] __lowerCamelCase : Optional[int] = np.concatenate(SCREAMING_SNAKE_CASE__ , axis=0 ) __lowerCamelCase : str = np.array(SCREAMING_SNAKE_CASE__ ).astype(np.floataa ) / 255.0 __lowerCamelCase : List[str] = image.transpose(0 , 3 , 1 , 2 ) __lowerCamelCase : Union[str, Any] = 2.0 * image - 1.0 __lowerCamelCase : Tuple = torch.from_numpy(SCREAMING_SNAKE_CASE__ ) elif isinstance(image[0] , torch.Tensor ): __lowerCamelCase : str = torch.cat(SCREAMING_SNAKE_CASE__ , dim=0 ) return image def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=0.9_995 ): if not isinstance(SCREAMING_SNAKE_CASE__ , np.ndarray ): __lowerCamelCase : List[str] = True __lowerCamelCase : str = va.device __lowerCamelCase : int = va.cpu().numpy() __lowerCamelCase : List[str] = va.cpu().numpy() __lowerCamelCase : str = np.sum(va * va / (np.linalg.norm(SCREAMING_SNAKE_CASE__ ) * np.linalg.norm(SCREAMING_SNAKE_CASE__ )) ) if np.abs(SCREAMING_SNAKE_CASE__ ) > DOT_THRESHOLD: __lowerCamelCase : Union[str, Any] = (1 - t) * va + t * va else: __lowerCamelCase : List[Any] = np.arccos(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Dict = np.sin(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : str = theta_a * t __lowerCamelCase : List[Any] = np.sin(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : str = np.sin(theta_a - theta_t ) / sin_theta_a __lowerCamelCase : List[Any] = sin_theta_t / sin_theta_a __lowerCamelCase : Union[str, Any] = sa * va + sa * va if inputs_are_torch: __lowerCamelCase : str = torch.from_numpy(SCREAMING_SNAKE_CASE__ ).to(SCREAMING_SNAKE_CASE__ ) return va def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : List[Any] = F.normalize(SCREAMING_SNAKE_CASE__ , dim=-1 ) __lowerCamelCase : Union[str, Any] = F.normalize(SCREAMING_SNAKE_CASE__ , dim=-1 ) return (x - y).norm(dim=-1 ).div(2 ).arcsin().pow(2 ).mul(2 ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): for param in model.parameters(): __lowerCamelCase : Any = value class A_ ( __UpperCamelCase ): '''simple docstring''' def __init__( self: Any , a: AutoencoderKL , a: CLIPTextModel , a: CLIPModel , a: CLIPTokenizer , a: UNetaDConditionModel , a: Union[PNDMScheduler, LMSDiscreteScheduler, DDIMScheduler, DPMSolverMultistepScheduler] , a: CLIPFeatureExtractor , a: Union[str, Any]=None , a: Union[str, Any]=None , a: Union[str, Any]=None , ): super().__init__() self.register_modules( vae=a , text_encoder=a , clip_model=a , tokenizer=a , unet=a , scheduler=a , feature_extractor=a , coca_model=a , coca_tokenizer=a , coca_transform=a , ) __lowerCamelCase : Tuple = ( feature_extractor.size if isinstance(feature_extractor.size , a ) else feature_extractor.size['shortest_edge'] ) __lowerCamelCase : List[Any] = transforms.Normalize(mean=feature_extractor.image_mean , std=feature_extractor.image_std ) set_requires_grad(self.text_encoder , a ) set_requires_grad(self.clip_model , a ) def _snake_case ( self: Optional[Any] , a: Optional[Union[str, int]] = "auto" ): if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory __lowerCamelCase : Any = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(a ) def _snake_case ( self: Dict ): self.enable_attention_slicing(a ) def _snake_case ( self: Optional[Any] ): set_requires_grad(self.vae , a ) def _snake_case ( self: List[Any] ): set_requires_grad(self.vae , a ) def _snake_case ( self: int ): set_requires_grad(self.unet , a ) def _snake_case ( self: int ): set_requires_grad(self.unet , a ) def _snake_case ( self: Optional[Any] , a: Union[str, Any] , a: List[str] , a: List[Any] ): # get the original timestep using init_timestep __lowerCamelCase : List[Any] = min(int(num_inference_steps * strength ) , a ) __lowerCamelCase : str = max(num_inference_steps - init_timestep , 0 ) __lowerCamelCase : List[Any] = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def _snake_case ( self: Union[str, Any] , a: Optional[Any] , a: Any , a: Optional[int] , a: Optional[Any] , a: Union[str, Any] , a: List[str]=None ): if not isinstance(a , torch.Tensor ): raise ValueError(F'`image` has to be of type `torch.Tensor` but is {type(a )}' ) __lowerCamelCase : Union[str, Any] = image.to(device=a , dtype=a ) if isinstance(a , a ): __lowerCamelCase : str = [ self.vae.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(a ) ] __lowerCamelCase : Tuple = torch.cat(a , dim=0 ) else: __lowerCamelCase : List[Any] = self.vae.encode(a ).latent_dist.sample(a ) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor __lowerCamelCase : List[str] = 0.1_8_2_1_5 * init_latents __lowerCamelCase : Union[str, Any] = init_latents.repeat_interleave(a , dim=0 ) __lowerCamelCase : Optional[int] = randn_tensor(init_latents.shape , generator=a , device=a , dtype=a ) # get latents __lowerCamelCase : Union[str, Any] = self.scheduler.add_noise(a , a , a ) __lowerCamelCase : int = init_latents return latents def _snake_case ( self: Optional[int] , a: Any ): __lowerCamelCase : List[Any] = self.coca_transform(a ).unsqueeze(0 ) with torch.no_grad(), torch.cuda.amp.autocast(): __lowerCamelCase : Any = self.coca_model.generate(transformed_image.to(device=self.device , dtype=self.coca_model.dtype ) ) __lowerCamelCase : str = self.coca_tokenizer.decode(generated[0].cpu().numpy() ) return generated.split('<end_of_text>' )[0].replace('<start_of_text>' , '' ).rstrip(' .,' ) def _snake_case ( self: Any , a: Tuple , a: Tuple ): __lowerCamelCase : Dict = self.feature_extractor.preprocess(a ) __lowerCamelCase : Dict = torch.from_numpy(clip_image_input['pixel_values'][0] ).unsqueeze(0 ).to(self.device ).half() __lowerCamelCase : List[str] = self.clip_model.get_image_features(a ) __lowerCamelCase : Optional[Any] = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=a ) __lowerCamelCase : Tuple = image_embeddings_clip.repeat_interleave(a , dim=0 ) return image_embeddings_clip @torch.enable_grad() def _snake_case ( self: str , a: str , a: int , a: List[Any] , a: str , a: List[Any] , a: Dict , a: int , ): __lowerCamelCase : Optional[Any] = latents.detach().requires_grad_() __lowerCamelCase : str = self.scheduler.scale_model_input(a , a ) # predict the noise residual __lowerCamelCase : Optional[int] = self.unet(a , a , encoder_hidden_states=a ).sample if isinstance(self.scheduler , (PNDMScheduler, DDIMScheduler, DPMSolverMultistepScheduler) ): __lowerCamelCase : str = self.scheduler.alphas_cumprod[timestep] __lowerCamelCase : Dict = 1 - alpha_prod_t # compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf __lowerCamelCase : Optional[int] = (latents - beta_prod_t ** 0.5 * noise_pred) / alpha_prod_t ** 0.5 __lowerCamelCase : Optional[int] = torch.sqrt(a ) __lowerCamelCase : int = pred_original_sample * (fac) + latents * (1 - fac) elif isinstance(self.scheduler , a ): __lowerCamelCase : str = self.scheduler.sigmas[index] __lowerCamelCase : List[Any] = latents - sigma * noise_pred else: raise ValueError(F'scheduler type {type(self.scheduler )} not supported' ) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor __lowerCamelCase : Optional[int] = 1 / 0.1_8_2_1_5 * sample __lowerCamelCase : Optional[Any] = self.vae.decode(a ).sample __lowerCamelCase : Tuple = (image / 2 + 0.5).clamp(0 , 1 ) __lowerCamelCase : Any = transforms.Resize(self.feature_extractor_size )(a ) __lowerCamelCase : Union[str, Any] = self.normalize(a ).to(latents.dtype ) __lowerCamelCase : Tuple = self.clip_model.get_image_features(a ) __lowerCamelCase : List[str] = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=a ) __lowerCamelCase : List[str] = spherical_dist_loss(a , a ).mean() * clip_guidance_scale __lowerCamelCase : Tuple = -torch.autograd.grad(a , a )[0] if isinstance(self.scheduler , a ): __lowerCamelCase : Optional[int] = latents.detach() + grads * (sigma**2) __lowerCamelCase : List[Any] = noise_pred_original else: __lowerCamelCase : str = noise_pred_original - torch.sqrt(a ) * grads return noise_pred, latents @torch.no_grad() def __call__( self: Any , a: Union[torch.FloatTensor, PIL.Image.Image] , a: Union[torch.FloatTensor, PIL.Image.Image] , a: Optional[str] = None , a: Optional[str] = None , a: Optional[int] = 512 , a: Optional[int] = 512 , a: float = 0.6 , a: Optional[int] = 50 , a: Optional[float] = 7.5 , a: Optional[int] = 1 , a: float = 0.0 , a: Optional[float] = 100 , a: Optional[torch.Generator] = None , a: Optional[str] = "pil" , a: bool = True , a: float = 0.8 , a: float = 0.1 , a: float = 0.1 , ): if isinstance(a , a ) and len(a ) != batch_size: raise ValueError(F'You have passed {batch_size} batch_size, but only {len(a )} generators.' ) if height % 8 != 0 or width % 8 != 0: raise ValueError(F'`height` and `width` have to be divisible by 8 but are {height} and {width}.' ) if isinstance(a , torch.Generator ) and batch_size > 1: __lowerCamelCase : List[Any] = [generator] + [None] * (batch_size - 1) __lowerCamelCase : Dict = [ ('model', self.coca_model is None), ('tokenizer', self.coca_tokenizer is None), ('transform', self.coca_transform is None), ] __lowerCamelCase : Any = [x[0] for x in coca_is_none if x[1]] __lowerCamelCase : str = ', '.join(a ) # generate prompts with coca model if prompt is None if content_prompt is None: if len(a ): raise ValueError( F'Content prompt is None and CoCa [{coca_is_none_str}] is None.' F'Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.' ) __lowerCamelCase : Any = self.get_image_description(a ) if style_prompt is None: if len(a ): raise ValueError( F'Style prompt is None and CoCa [{coca_is_none_str}] is None.' F' Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.' ) __lowerCamelCase : Tuple = self.get_image_description(a ) # get prompt text embeddings for content and style __lowerCamelCase : int = self.tokenizer( a , padding='max_length' , max_length=self.tokenizer.model_max_length , truncation=a , return_tensors='pt' , ) __lowerCamelCase : Dict = self.text_encoder(content_text_input.input_ids.to(self.device ) )[0] __lowerCamelCase : Union[str, Any] = self.tokenizer( a , padding='max_length' , max_length=self.tokenizer.model_max_length , truncation=a , return_tensors='pt' , ) __lowerCamelCase : Any = self.text_encoder(style_text_input.input_ids.to(self.device ) )[0] __lowerCamelCase : List[Any] = slerp(a , a , a ) # duplicate text embeddings for each generation per prompt __lowerCamelCase : Any = text_embeddings.repeat_interleave(a , dim=0 ) # set timesteps __lowerCamelCase : List[Any] = 'offset' in set(inspect.signature(self.scheduler.set_timesteps ).parameters.keys() ) __lowerCamelCase : Union[str, Any] = {} if accepts_offset: __lowerCamelCase : Dict = 1 self.scheduler.set_timesteps(a , **a ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand self.scheduler.timesteps.to(self.device ) __lowerCamelCase , __lowerCamelCase : Dict = self.get_timesteps(a , a , self.device ) __lowerCamelCase : Tuple = timesteps[:1].repeat(a ) # Preprocess image __lowerCamelCase : Any = preprocess(a , a , a ) __lowerCamelCase : str = self.prepare_latents( a , a , a , text_embeddings.dtype , self.device , a ) __lowerCamelCase : Dict = preprocess(a , a , a ) __lowerCamelCase : Optional[int] = self.prepare_latents( a , a , a , text_embeddings.dtype , self.device , a ) __lowerCamelCase : int = slerp(a , a , a ) if clip_guidance_scale > 0: __lowerCamelCase : List[str] = self.get_clip_image_embeddings(a , a ) __lowerCamelCase : Union[str, Any] = self.get_clip_image_embeddings(a , a ) __lowerCamelCase : Union[str, Any] = slerp( a , a , a ) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. __lowerCamelCase : Tuple = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: __lowerCamelCase : Optional[int] = content_text_input.input_ids.shape[-1] __lowerCamelCase : int = self.tokenizer([''] , padding='max_length' , max_length=a , return_tensors='pt' ) __lowerCamelCase : List[Any] = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt __lowerCamelCase : List[Any] = uncond_embeddings.repeat_interleave(a , dim=0 ) # 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 : int = torch.cat([uncond_embeddings, text_embeddings] ) # get the initial random noise unless the user supplied it # Unlike in other pipelines, latents need to be generated in the target device # for 1-to-1 results reproducibility with the CompVis implementation. # However this currently doesn't work in `mps`. __lowerCamelCase : str = (batch_size, self.unet.config.in_channels, height // 8, width // 8) __lowerCamelCase : List[str] = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not work reproducibly on mps __lowerCamelCase : Tuple = torch.randn(a , generator=a , device='cpu' , dtype=a ).to( self.device ) else: __lowerCamelCase : List[Any] = torch.randn(a , generator=a , device=self.device , dtype=a ) else: if latents.shape != latents_shape: raise ValueError(F'Unexpected latents shape, got {latents.shape}, expected {latents_shape}' ) __lowerCamelCase : List[str] = latents.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler __lowerCamelCase : str = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] __lowerCamelCase : int = 'eta' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) __lowerCamelCase : Dict = {} if accepts_eta: __lowerCamelCase : List[str] = eta # check if the scheduler accepts generator __lowerCamelCase : Optional[int] = 'generator' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) if accepts_generator: __lowerCamelCase : Optional[Any] = generator with self.progress_bar(total=a ): for i, t in enumerate(a ): # expand the latents if we are doing classifier free guidance __lowerCamelCase : Optional[int] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents __lowerCamelCase : Union[str, Any] = self.scheduler.scale_model_input(a , a ) # predict the noise residual __lowerCamelCase : Tuple = self.unet(a , a , encoder_hidden_states=a ).sample # perform classifier free guidance if do_classifier_free_guidance: __lowerCamelCase , __lowerCamelCase : str = noise_pred.chunk(2 ) __lowerCamelCase : List[str] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # perform clip guidance if clip_guidance_scale > 0: __lowerCamelCase : str = ( text_embeddings.chunk(2 )[1] if do_classifier_free_guidance else text_embeddings ) __lowerCamelCase , __lowerCamelCase : int = self.cond_fn( a , a , a , a , a , a , a , ) # compute the previous noisy sample x_t -> x_t-1 __lowerCamelCase : Tuple = self.scheduler.step(a , a , a , **a ).prev_sample # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor __lowerCamelCase : List[Any] = 1 / 0.1_8_2_1_5 * latents __lowerCamelCase : Union[str, Any] = self.vae.decode(a ).sample __lowerCamelCase : Optional[int] = (image / 2 + 0.5).clamp(0 , 1 ) __lowerCamelCase : Any = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": __lowerCamelCase : Union[str, Any] = self.numpy_to_pil(a ) if not return_dict: return (image, None) return StableDiffusionPipelineOutput(images=a , nsfw_content_detected=a )
194
0
"""simple docstring""" import warnings from typing import List import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import is_flax_available, is_tf_available, is_torch_available class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): lowercase = ["image_processor", "tokenizer"] lowercase = "OwlViTImageProcessor" lowercase = ("CLIPTokenizer", "CLIPTokenizerFast") def __init__( self , __UpperCAmelCase=None , __UpperCAmelCase=None , **__UpperCAmelCase ): '''simple docstring''' __UpperCamelCase = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , __UpperCAmelCase , ) __UpperCamelCase = kwargs.pop('feature_extractor' ) __UpperCamelCase = 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__(__UpperCAmelCase , __UpperCAmelCase ) def __call__( self , __UpperCAmelCase=None , __UpperCAmelCase=None , __UpperCAmelCase=None , __UpperCAmelCase="max_length" , __UpperCAmelCase="np" , **__UpperCAmelCase ): '''simple docstring''' if text is None and query_images is None and images is None: raise ValueError( 'You have to specify at least one text or query image or image. All three cannot be none.' ) if text is not None: if isinstance(__UpperCAmelCase , __UpperCAmelCase ) or (isinstance(__UpperCAmelCase , __UpperCAmelCase ) and not isinstance(text[0] , __UpperCAmelCase )): __UpperCamelCase = [self.tokenizer(__UpperCAmelCase , padding=__UpperCAmelCase , return_tensors=__UpperCAmelCase , **__UpperCAmelCase )] elif isinstance(__UpperCAmelCase , __UpperCAmelCase ) and isinstance(text[0] , __UpperCAmelCase ): __UpperCamelCase = [] # Maximum number of queries across batch __UpperCamelCase = max([len(__UpperCAmelCase ) for t in text] ) # Pad all batch samples to max number of text queries for t in text: if len(__UpperCAmelCase ) != max_num_queries: __UpperCamelCase = t + [' '] * (max_num_queries - len(__UpperCAmelCase )) __UpperCamelCase = self.tokenizer(__UpperCAmelCase , padding=__UpperCAmelCase , return_tensors=__UpperCAmelCase , **__UpperCAmelCase ) encodings.append(__UpperCAmelCase ) else: raise TypeError('Input text should be a string, a list of strings or a nested list of strings' ) if return_tensors == "np": __UpperCamelCase = np.concatenate([encoding['input_ids'] for encoding in encodings] , axis=0 ) __UpperCamelCase = np.concatenate([encoding['attention_mask'] for encoding in encodings] , axis=0 ) elif return_tensors == "jax" and is_flax_available(): import jax.numpy as jnp __UpperCamelCase = jnp.concatenate([encoding['input_ids'] for encoding in encodings] , axis=0 ) __UpperCamelCase = jnp.concatenate([encoding['attention_mask'] for encoding in encodings] , axis=0 ) elif return_tensors == "pt" and is_torch_available(): import torch __UpperCamelCase = torch.cat([encoding['input_ids'] for encoding in encodings] , dim=0 ) __UpperCamelCase = torch.cat([encoding['attention_mask'] for encoding in encodings] , dim=0 ) elif return_tensors == "tf" and is_tf_available(): import tensorflow as tf __UpperCamelCase = tf.stack([encoding['input_ids'] for encoding in encodings] , axis=0 ) __UpperCamelCase = tf.stack([encoding['attention_mask'] for encoding in encodings] , axis=0 ) else: raise ValueError('Target return tensor type could not be returned' ) __UpperCamelCase = BatchEncoding() __UpperCamelCase = input_ids __UpperCamelCase = attention_mask if query_images is not None: __UpperCamelCase = BatchEncoding() __UpperCamelCase = self.image_processor( __UpperCAmelCase , return_tensors=__UpperCAmelCase , **__UpperCAmelCase ).pixel_values __UpperCamelCase = query_pixel_values if images is not None: __UpperCamelCase = self.image_processor(__UpperCAmelCase , return_tensors=__UpperCAmelCase , **__UpperCAmelCase ) if text is not None and images is not None: __UpperCamelCase = image_features.pixel_values return encoding elif query_images is not None and images is not None: __UpperCamelCase = image_features.pixel_values return encoding elif text is not None or query_images is not None: return encoding else: return BatchEncoding(data=dict(**__UpperCAmelCase ) , tensor_type=__UpperCAmelCase ) def UpperCAmelCase ( self , *__UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' return self.image_processor.post_process(*__UpperCAmelCase , **__UpperCAmelCase ) def UpperCAmelCase ( self , *__UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' return self.image_processor.post_process_object_detection(*__UpperCAmelCase , **__UpperCAmelCase ) def UpperCAmelCase ( self , *__UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' return self.image_processor.post_process_image_guided_detection(*__UpperCAmelCase , **__UpperCAmelCase ) def UpperCAmelCase ( self , *__UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' return self.tokenizer.batch_decode(*__UpperCAmelCase , **__UpperCAmelCase ) def UpperCAmelCase ( self , *__UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' return self.tokenizer.decode(*__UpperCAmelCase , **__UpperCAmelCase ) @property def UpperCAmelCase ( self ): '''simple docstring''' warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , __UpperCAmelCase , ) return self.image_processor_class @property def UpperCAmelCase ( self ): '''simple docstring''' warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , __UpperCAmelCase , ) return self.image_processor
316
"""simple docstring""" import argparse import logging import os from pathlib import Path from typing import Any, Dict import pytorch_lightning as pl from pytorch_lightning.utilities import rank_zero_info from transformers import ( AdamW, AutoConfig, AutoModel, AutoModelForPreTraining, AutoModelForQuestionAnswering, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoModelForTokenClassification, AutoModelWithLMHead, AutoTokenizer, PretrainedConfig, PreTrainedTokenizer, ) from transformers.optimization import ( Adafactor, 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.utils.versions import require_version UpperCamelCase : Union[str, Any] = logging.getLogger(__name__) require_version("pytorch_lightning>=1.0.4") UpperCamelCase : int = { "base": AutoModel, "sequence-classification": AutoModelForSequenceClassification, "question-answering": AutoModelForQuestionAnswering, "pretraining": AutoModelForPreTraining, "token-classification": AutoModelForTokenClassification, "language-modeling": AutoModelWithLMHead, "summarization": AutoModelForSeqaSeqLM, "translation": AutoModelForSeqaSeqLM, } # update this and the import above to support new schedulers from transformers.optimization UpperCamelCase : Optional[Any] = { "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, # '': get_constant_schedule, # not supported for now # '': get_constant_schedule_with_warmup, # not supported for now } UpperCamelCase : str = sorted(arg_to_scheduler.keys()) UpperCamelCase : List[str] = "{" + ", ".join(arg_to_scheduler_choices) + "}" class __lowerCAmelCase ( pl.LightningModule ): def __init__( self , __UpperCAmelCase , __UpperCAmelCase=None , __UpperCAmelCase="base" , __UpperCAmelCase=None , __UpperCAmelCase=None , __UpperCAmelCase=None , **__UpperCAmelCase , ): '''simple docstring''' super().__init__() # TODO: move to self.save_hyperparameters() # self.save_hyperparameters() # can also expand arguments into trainer signature for easier reading self.save_hyperparameters(__UpperCAmelCase ) __UpperCamelCase = 0 __UpperCamelCase = Path(self.hparams.output_dir ) __UpperCamelCase = self.hparams.cache_dir if self.hparams.cache_dir else None if config is None: __UpperCamelCase = AutoConfig.from_pretrained( self.hparams.config_name if self.hparams.config_name else self.hparams.model_name_or_path , **({'num_labels': num_labels} if num_labels is not None else {}) , cache_dir=__UpperCAmelCase , **__UpperCAmelCase , ) else: __UpperCamelCase = config __UpperCamelCase = ('encoder_layerdrop', 'decoder_layerdrop', 'dropout', 'attention_dropout') for p in extra_model_params: if getattr(self.hparams , __UpperCAmelCase , __UpperCAmelCase ): assert hasattr(self.config , __UpperCAmelCase ), F'model config doesn\'t have a `{p}` attribute' setattr(self.config , __UpperCAmelCase , getattr(self.hparams , __UpperCAmelCase ) ) if tokenizer is None: __UpperCamelCase = AutoTokenizer.from_pretrained( self.hparams.tokenizer_name if self.hparams.tokenizer_name else self.hparams.model_name_or_path , cache_dir=__UpperCAmelCase , ) else: __UpperCamelCase = tokenizer __UpperCamelCase = MODEL_MODES[mode] if model is None: __UpperCamelCase = self.model_type.from_pretrained( self.hparams.model_name_or_path , from_tf=bool('.ckpt' in self.hparams.model_name_or_path ) , config=self.config , cache_dir=__UpperCAmelCase , ) else: __UpperCamelCase = model def UpperCAmelCase ( self , *__UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' __UpperCamelCase = self.model_type.from_pretrained(*__UpperCAmelCase , **__UpperCAmelCase ) def UpperCAmelCase ( self ): '''simple docstring''' __UpperCamelCase = arg_to_scheduler[self.hparams.lr_scheduler] __UpperCamelCase = get_schedule_func( self.opt , num_warmup_steps=self.hparams.warmup_steps , num_training_steps=self.total_steps() ) __UpperCamelCase = {'scheduler': scheduler, 'interval': 'step', 'frequency': 1} return scheduler def UpperCAmelCase ( self ): '''simple docstring''' __UpperCamelCase = self.model __UpperCamelCase = ['bias', 'LayerNorm.weight'] __UpperCamelCase = [ { 'params': [ p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay ) ], # check this named paramters 'weight_decay': self.hparams.weight_decay, }, { 'params': [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay )], 'weight_decay': 0.0, }, ] if self.hparams.adafactor: __UpperCamelCase = Adafactor( __UpperCAmelCase , lr=self.hparams.learning_rate , scale_parameter=__UpperCAmelCase , relative_step=__UpperCAmelCase ) else: __UpperCamelCase = AdamW( __UpperCAmelCase , lr=self.hparams.learning_rate , eps=self.hparams.adam_epsilon ) __UpperCamelCase = optimizer __UpperCamelCase = self.get_lr_scheduler() return [optimizer], [scheduler] def UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' return self.validation_step(__UpperCAmelCase , __UpperCAmelCase ) def UpperCAmelCase ( self , __UpperCAmelCase ): '''simple docstring''' return self.validation_end(__UpperCAmelCase ) def UpperCAmelCase ( self ): '''simple docstring''' __UpperCamelCase = max(1 , self.hparams.gpus ) # TODO: consider num_tpu_cores __UpperCamelCase = self.hparams.train_batch_size * self.hparams.accumulate_grad_batches * num_devices return (self.dataset_size / effective_batch_size) * self.hparams.max_epochs def UpperCAmelCase ( self , __UpperCAmelCase ): '''simple docstring''' if stage == "test": __UpperCamelCase = len(self.test_dataloader().dataset ) else: __UpperCamelCase = self.get_dataloader('train' , self.hparams.train_batch_size , shuffle=__UpperCAmelCase ) __UpperCamelCase = len(self.train_dataloader().dataset ) def UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = False ): '''simple docstring''' raise NotImplementedError('You must implement this for your task' ) def UpperCAmelCase ( self ): '''simple docstring''' return self.train_loader def UpperCAmelCase ( self ): '''simple docstring''' return self.get_dataloader('dev' , self.hparams.eval_batch_size , shuffle=__UpperCAmelCase ) def UpperCAmelCase ( self ): '''simple docstring''' return self.get_dataloader('test' , self.hparams.eval_batch_size , shuffle=__UpperCAmelCase ) def UpperCAmelCase ( self , __UpperCAmelCase ): '''simple docstring''' return os.path.join( self.hparams.data_dir , 'cached_{}_{}_{}'.format( __UpperCAmelCase , list(filter(__UpperCAmelCase , self.hparams.model_name_or_path.split('/' ) ) ).pop() , str(self.hparams.max_seq_length ) , ) , ) @pl.utilities.rank_zero_only def UpperCAmelCase ( self , __UpperCAmelCase ): '''simple docstring''' __UpperCamelCase = self.output_dir.joinpath('best_tfmr' ) __UpperCamelCase = self.step_count self.model.save_pretrained(__UpperCAmelCase ) self.tokenizer.save_pretrained(__UpperCAmelCase ) @staticmethod def UpperCAmelCase ( __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' parser.add_argument( '--model_name_or_path' , default=__UpperCAmelCase , type=__UpperCAmelCase , required=__UpperCAmelCase , help='Path to pretrained model or model identifier from huggingface.co/models' , ) parser.add_argument( '--config_name' , default='' , type=__UpperCAmelCase , help='Pretrained config name or path if not the same as model_name' ) parser.add_argument( '--tokenizer_name' , default=__UpperCAmelCase , type=__UpperCAmelCase , help='Pretrained tokenizer name or path if not the same as model_name' , ) parser.add_argument( '--cache_dir' , default=str(Path(__UpperCAmelCase ).parent / 'test_run' / 'cache' ) , type=__UpperCAmelCase , help='Where do you want to store the pre-trained models downloaded from huggingface.co' , ) parser.add_argument( '--encoder_layerdrop' , type=__UpperCAmelCase , help='Encoder layer dropout probability (Optional). Goes into model.config' , ) parser.add_argument( '--decoder_layerdrop' , type=__UpperCAmelCase , help='Decoder layer dropout probability (Optional). Goes into model.config' , ) parser.add_argument( '--dropout' , type=__UpperCAmelCase , help='Dropout probability (Optional). Goes into model.config' , ) parser.add_argument( '--attention_dropout' , type=__UpperCAmelCase , help='Attention dropout probability (Optional). Goes into model.config' , ) parser.add_argument('--learning_rate' , default=5E-5 , type=__UpperCAmelCase , help='The initial learning rate for Adam.' ) parser.add_argument( '--lr_scheduler' , default='linear' , choices=__UpperCAmelCase , metavar=__UpperCAmelCase , type=__UpperCAmelCase , help='Learning rate scheduler' , ) parser.add_argument('--weight_decay' , default=0.0 , type=__UpperCAmelCase , help='Weight decay if we apply some.' ) parser.add_argument('--adam_epsilon' , default=1E-8 , type=__UpperCAmelCase , help='Epsilon for Adam optimizer.' ) parser.add_argument('--warmup_steps' , default=0 , type=__UpperCAmelCase , help='Linear warmup over warmup_steps.' ) parser.add_argument('--num_workers' , default=4 , type=__UpperCAmelCase , help='kwarg passed to DataLoader' ) parser.add_argument('--num_train_epochs' , dest='max_epochs' , default=3 , type=__UpperCAmelCase ) parser.add_argument('--train_batch_size' , default=32 , type=__UpperCAmelCase ) parser.add_argument('--eval_batch_size' , default=32 , type=__UpperCAmelCase ) parser.add_argument('--adafactor' , action='store_true' ) class __lowerCAmelCase ( pl.Callback ): def UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' if ( trainer.is_global_zero and trainer.global_rank == 0 ): # we initialize the retriever only on master worker with RAY. In new pytorch-lightning accelorators are removed. pl_module.model.rag.retriever.init_retrieval() # better to use hook functions. class __lowerCAmelCase ( pl.Callback ): def UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' for name, param in pl_module.model.rag.named_parameters(): if param.grad is None: print(__UpperCAmelCase ) class __lowerCAmelCase ( pl.Callback ): def UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' __UpperCamelCase = trainer.lr_schedulers[0]['scheduler'] __UpperCamelCase = {F'lr_group_{i}': lr for i, lr in enumerate(lr_scheduler.get_lr() )} pl_module.logger.log_metrics(__UpperCAmelCase ) def UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' rank_zero_info('***** Validation results *****' ) __UpperCamelCase = trainer.callback_metrics # Log results for key in sorted(__UpperCAmelCase ): if key not in ["log", "progress_bar"]: rank_zero_info('{} = {}\n'.format(__UpperCAmelCase , str(metrics[key] ) ) ) def UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' rank_zero_info('***** Test results *****' ) __UpperCamelCase = trainer.callback_metrics # Log and save results to file __UpperCamelCase = os.path.join(pl_module.hparams.output_dir , 'test_results.txt' ) with open(__UpperCAmelCase , 'w' ) as writer: for key in sorted(__UpperCAmelCase ): if key not in ["log", "progress_bar"]: rank_zero_info('{} = {}\n'.format(__UpperCAmelCase , str(metrics[key] ) ) ) writer.write('{} = {}\n'.format(__UpperCAmelCase , str(metrics[key] ) ) ) def A ( snake_case :Any , snake_case :int ) -> None: # To allow all pl args uncomment the following line # parser = pl.Trainer.add_argparse_args(parser) parser.add_argument( '--output_dir' , default=str(Path(snake_case ).parent / 'test_run' / 'model_checkpoints' ) , type=snake_case , help='The output directory where the model predictions and checkpoints will be written.' , ) parser.add_argument( '--fp16' , action='store_true' , help='Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit' , ) parser.add_argument( '--fp16_opt_level' , type=snake_case , default='O2' , help=( 'For fp16: Apex AMP optimization level selected in [\'O0\', \'O1\', \'O2\', and \'O3\'].' 'See details at https://nvidia.github.io/apex/amp.html' ) , ) parser.add_argument('--n_tpu_cores' , dest='tpu_cores' , type=snake_case ) parser.add_argument('--max_grad_norm' , dest='gradient_clip_val' , default=1.0 , type=snake_case , help='Max gradient norm' ) parser.add_argument('--do_train' , action='store_true' , help='Whether to run training.' ) parser.add_argument('--do_predict' , action='store_true' , help='Whether to run predictions on the test set.' ) parser.add_argument( '--gradient_accumulation_steps' , dest='accumulate_grad_batches' , type=snake_case , default=1 , help='Number of updates steps to accumulate before performing a backward/update pass.' , ) parser.add_argument('--seed' , type=snake_case , default=4_2 , help='random seed for initialization' ) parser.add_argument( '--data_dir' , default=str(Path(snake_case ).parent / 'test_run' / 'dummy-train-data' ) , type=snake_case , help='The input data dir. Should contain the training files for the CoNLL-2003 NER task.' , ) def A ( snake_case :BaseTransformer , snake_case :argparse.Namespace , snake_case :Union[str, Any]=None , snake_case :Union[str, Any]=True , snake_case :Any=[] , snake_case :Tuple=None , snake_case :List[str]=None , **snake_case :Union[str, Any] , ) -> Optional[int]: pl.seed_everything(args.seed ) # init model __UpperCamelCase = Path(model.hparams.output_dir ) odir.mkdir(exist_ok=snake_case ) # add custom checkpoints if checkpoint_callback is None: __UpperCamelCase = pl.callbacks.ModelCheckpoint( filepath=args.output_dir , prefix='checkpoint' , monitor='val_loss' , mode='min' , save_top_k=1 ) if early_stopping_callback: extra_callbacks.append(snake_case ) if logging_callback is None: __UpperCamelCase = LoggingCallback() __UpperCamelCase = {} if args.fpaa: __UpperCamelCase = 1_6 if args.gpus > 1: __UpperCamelCase = 'auto' __UpperCamelCase = 'ddp' __UpperCamelCase = args.accumulate_grad_batches __UpperCamelCase = None __UpperCamelCase = 'auto' __UpperCamelCase = pl.Trainer.from_argparse_args( snake_case , weights_summary=snake_case , callbacks=[logging_callback] + extra_callbacks + [InitCallback()] + [checkpoint_callback] , logger=snake_case , val_check_interval=1 , num_sanity_val_steps=2 , **snake_case , ) if args.do_train: trainer.fit(snake_case ) else: print('RAG modeling tests with new set functions successfuly executed!' ) return trainer
316
1
def __snake_case ( __UpperCamelCase : Optional[Any] ,__UpperCamelCase : List[str] ): """simple docstring""" if a < 0 or b < 0: raise ValueError("the value of both inputs must be positive" ) A_ = str(bin(__UpperCamelCase ) )[2:] # remove the leading "0b" A_ = str(bin(__UpperCamelCase ) )[2:] # remove the leading "0b" A_ = max(len(__UpperCamelCase ) ,len(__UpperCamelCase ) ) return "0b" + "".join( str(int(char_a == "1" and char_b == "1" ) ) for char_a, char_b in zip(a_binary.zfill(__UpperCamelCase ) ,b_binary.zfill(__UpperCamelCase ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
360
import time from dataclasses import dataclass from multiprocessing import Pool from unittest import TestCase from unittest.mock import patch import multiprocess import numpy as np import pytest from datasets.utils.py_utils import ( NestedDataStructure, asdict, iflatmap_unordered, map_nested, temp_seed, temporary_assignment, zip_dict, ) from .utils import require_tf, require_torch def __snake_case ( __UpperCamelCase : Optional[int] ): # picklable for multiprocessing """simple docstring""" return x.sum() def __snake_case ( __UpperCamelCase : List[str] ): # picklable for multiprocessing """simple docstring""" return i + 1 @dataclass class _a : """simple docstring""" _lowerCamelCase : int _lowerCamelCase : str class _a ( snake_case_ ): """simple docstring""" def __A ( self : Dict ): A_ = {} A_ = [] A_ = 1 A_ = [1, 2] A_ = {"a": 1, "b": 2} A_ = {"a": [1, 2], "b": [3, 4]} A_ = {"a": {"1": 1}, "b": 2} A_ = {"a": 1, "b": 2, "c": 3, "d": 4} A_ = {} A_ = [] A_ = 2 A_ = [2, 3] A_ = {"a": 2, "b": 3} A_ = {"a": [2, 3], "b": [4, 5]} A_ = {"a": {"1": 2}, "b": 3} A_ = {"a": 2, "b": 3, "c": 4, "d": 5} self.assertEqual(map_nested(UpperCAmelCase , UpperCAmelCase ) , UpperCAmelCase ) self.assertEqual(map_nested(UpperCAmelCase , UpperCAmelCase ) , UpperCAmelCase ) self.assertEqual(map_nested(UpperCAmelCase , UpperCAmelCase ) , UpperCAmelCase ) self.assertEqual(map_nested(UpperCAmelCase , UpperCAmelCase ) , UpperCAmelCase ) self.assertEqual(map_nested(UpperCAmelCase , UpperCAmelCase ) , UpperCAmelCase ) self.assertEqual(map_nested(UpperCAmelCase , UpperCAmelCase ) , UpperCAmelCase ) self.assertEqual(map_nested(UpperCAmelCase , UpperCAmelCase ) , UpperCAmelCase ) self.assertEqual(map_nested(UpperCAmelCase , UpperCAmelCase ) , UpperCAmelCase ) A_ = 2 self.assertEqual(map_nested(UpperCAmelCase , UpperCAmelCase , num_proc=UpperCAmelCase ) , UpperCAmelCase ) self.assertEqual(map_nested(UpperCAmelCase , UpperCAmelCase , num_proc=UpperCAmelCase ) , UpperCAmelCase ) self.assertEqual(map_nested(UpperCAmelCase , UpperCAmelCase , num_proc=UpperCAmelCase ) , UpperCAmelCase ) self.assertEqual(map_nested(UpperCAmelCase , UpperCAmelCase , num_proc=UpperCAmelCase ) , UpperCAmelCase ) self.assertEqual(map_nested(UpperCAmelCase , UpperCAmelCase , num_proc=UpperCAmelCase ) , UpperCAmelCase ) self.assertEqual(map_nested(UpperCAmelCase , UpperCAmelCase , num_proc=UpperCAmelCase ) , UpperCAmelCase ) self.assertEqual(map_nested(UpperCAmelCase , UpperCAmelCase , num_proc=UpperCAmelCase ) , UpperCAmelCase ) self.assertEqual(map_nested(UpperCAmelCase , UpperCAmelCase , num_proc=UpperCAmelCase ) , UpperCAmelCase ) A_ = {"a": np.eye(2 ), "b": np.zeros(3 ), "c": np.ones(2 )} A_ = {"a": 2, "b": 0, "c": 2} A_ = { "a": np.eye(2 ).astype(UpperCAmelCase ), "b": np.zeros(3 ).astype(UpperCAmelCase ), "c": np.ones(2 ).astype(UpperCAmelCase ), } self.assertEqual(map_nested(UpperCAmelCase , UpperCAmelCase , map_numpy=UpperCAmelCase ) , UpperCAmelCase ) self.assertEqual( {k: v.tolist() for k, v in map_nested(UpperCAmelCase , UpperCAmelCase , map_numpy=UpperCAmelCase ).items()} , {k: v.tolist() for k, v in expected_map_nested_sna_int.items()} , ) self.assertEqual(map_nested(UpperCAmelCase , UpperCAmelCase , map_numpy=UpperCAmelCase , num_proc=UpperCAmelCase ) , UpperCAmelCase ) self.assertEqual( {k: v.tolist() for k, v in map_nested(UpperCAmelCase , UpperCAmelCase , map_numpy=UpperCAmelCase , num_proc=UpperCAmelCase ).items()} , {k: v.tolist() for k, v in expected_map_nested_sna_int.items()} , ) with self.assertRaises(UpperCAmelCase ): # can't pickle a local lambda map_nested(lambda UpperCAmelCase : x + 1 , UpperCAmelCase , num_proc=UpperCAmelCase ) def __A ( self : List[str] ): A_ = {"a": 1, "b": 2} A_ = {"a": 3, "b": 4} A_ = {"a": 5, "b": 6} A_ = sorted([("a", (1, 3, 5)), ("b", (2, 4, 6))] ) self.assertEqual(sorted(zip_dict(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) ) , UpperCAmelCase ) def __A ( self : Any ): class _a : """simple docstring""" _lowerCamelCase : int = 'bar' A_ = Foo() self.assertEqual(foo.my_attr , "bar" ) with temporary_assignment(UpperCAmelCase , "my_attr" , "BAR" ): self.assertEqual(foo.my_attr , "BAR" ) self.assertEqual(foo.my_attr , "bar" ) @pytest.mark.parametrize( "iterable_length, num_proc, expected_num_proc" ,[ (1, None, 1), (1, 1, 1), (2, None, 1), (2, 1, 1), (2, 2, 1), (2, 3, 1), (3, 2, 1), (16, 16, 16), (16, 17, 16), (17, 16, 16), ] ,) def __snake_case ( __UpperCamelCase : Optional[int] ,__UpperCamelCase : Tuple ,__UpperCamelCase : List[Any] ): """simple docstring""" with patch("datasets.utils.py_utils._single_map_nested" ) as mock_single_map_nested, patch( "datasets.parallel.parallel.Pool" ) as mock_multiprocessing_pool: A_ = {f'''{i}''': i for i in range(__UpperCamelCase )} A_ = map_nested(lambda __UpperCamelCase : x + 10 ,__UpperCamelCase ,num_proc=__UpperCamelCase ,parallel_min_length=16 ) if expected_num_proc == 1: assert mock_single_map_nested.called assert not mock_multiprocessing_pool.called else: assert not mock_single_map_nested.called assert mock_multiprocessing_pool.called assert mock_multiprocessing_pool.call_args[0][0] == expected_num_proc class _a ( snake_case_ ): """simple docstring""" @require_tf def __A ( self : Union[str, Any] ): import tensorflow as tf from tensorflow.keras import layers A_ = layers.Dense(2 ) def gen_random_output(): A_ = tf.random.uniform((1, 3) ) return model(UpperCAmelCase ).numpy() with temp_seed(42 , set_tensorflow=UpperCAmelCase ): A_ = gen_random_output() with temp_seed(42 , set_tensorflow=UpperCAmelCase ): A_ = gen_random_output() A_ = gen_random_output() np.testing.assert_equal(UpperCAmelCase , UpperCAmelCase ) self.assertGreater(np.abs(outa - outa ).sum() , 0 ) @require_torch def __A ( self : Optional[int] ): import torch def gen_random_output(): A_ = torch.nn.Linear(3 , 2 ) A_ = torch.rand(1 , 3 ) return model(UpperCAmelCase ).detach().numpy() with temp_seed(42 , set_pytorch=UpperCAmelCase ): A_ = gen_random_output() with temp_seed(42 , set_pytorch=UpperCAmelCase ): A_ = gen_random_output() A_ = gen_random_output() np.testing.assert_equal(UpperCAmelCase , UpperCAmelCase ) self.assertGreater(np.abs(outa - outa ).sum() , 0 ) def __A ( self : Any ): def gen_random_output(): return np.random.rand(1 , 3 ) with temp_seed(42 ): A_ = gen_random_output() with temp_seed(42 ): A_ = gen_random_output() A_ = gen_random_output() np.testing.assert_equal(UpperCAmelCase , UpperCAmelCase ) self.assertGreater(np.abs(outa - outa ).sum() , 0 ) @pytest.mark.parametrize("input_data" ,[{}] ) def __snake_case ( __UpperCamelCase : str ): """simple docstring""" A_ = NestedDataStructure(__UpperCamelCase ).data assert output_data == input_data @pytest.mark.parametrize( "data, expected_output" ,[ ({}, []), ([], []), ("foo", ["foo"]), (["foo", "bar"], ["foo", "bar"]), ([["foo", "bar"]], ["foo", "bar"]), ([[["foo"], ["bar"]]], ["foo", "bar"]), ([[["foo"], "bar"]], ["foo", "bar"]), ({"a": 1, "b": 2}, [1, 2]), ({"a": [1, 2], "b": [3, 4]}, [1, 2, 3, 4]), ({"a": [[1, 2]], "b": [[3, 4]]}, [1, 2, 3, 4]), ({"a": [[1, 2]], "b": [3, 4]}, [1, 2, 3, 4]), ({"a": [[[1], [2]]], "b": [[[3], [4]]]}, [1, 2, 3, 4]), ({"a": [[[1], [2]]], "b": [[3, 4]]}, [1, 2, 3, 4]), ({"a": [[[1], [2]]], "b": [3, 4]}, [1, 2, 3, 4]), ({"a": [[[1], [2]]], "b": [3, [4]]}, [1, 2, 3, 4]), ({"a": {"1": 1}, "b": 2}, [1, 2]), ({"a": {"1": [1]}, "b": 2}, [1, 2]), ({"a": {"1": [1]}, "b": [2]}, [1, 2]), ] ,) def __snake_case ( __UpperCamelCase : Dict ,__UpperCamelCase : Any ): """simple docstring""" A_ = NestedDataStructure(__UpperCamelCase ).flatten() assert output == expected_output def __snake_case ( ): """simple docstring""" A_ = A(x=1 ,y="foobar" ) A_ = {"x": 1, "y": "foobar"} assert asdict(__UpperCamelCase ) == expected_output A_ = {"a": {"b": A(x=10 ,y="foo" )}, "c": [A(x=20 ,y="bar" )]} A_ = {"a": {"b": {"x": 10, "y": "foo"}}, "c": [{"x": 20, "y": "bar"}]} assert asdict(__UpperCamelCase ) == expected_output with pytest.raises(__UpperCamelCase ): asdict([1, A(x=10 ,y="foo" )] ) def __snake_case ( __UpperCamelCase : str ): """simple docstring""" return text.split() def __snake_case ( __UpperCamelCase : List[Any] ): """simple docstring""" yield (time.time(), content) time.sleep(2 ) yield (time.time(), content) def __snake_case ( ): """simple docstring""" with Pool(2 ) as pool: A_ = list(iflatmap_unordered(__UpperCamelCase ,_split_text ,kwargs_iterable=[{"text": "hello there"}] * 10 ) ) assert out.count("hello" ) == 10 assert out.count("there" ) == 10 assert len(__UpperCamelCase ) == 20 # check multiprocess from pathos (uses dill for pickling) with multiprocess.Pool(2 ) as pool: A_ = list(iflatmap_unordered(__UpperCamelCase ,_split_text ,kwargs_iterable=[{"text": "hello there"}] * 10 ) ) assert out.count("hello" ) == 10 assert out.count("there" ) == 10 assert len(__UpperCamelCase ) == 20 # check that we get items as fast as possible with Pool(2 ) as pool: A_ = [] for yield_time, content in iflatmap_unordered( __UpperCamelCase ,_aseconds_generator_of_aitems_with_timing ,kwargs_iterable=[{"content": "a"}, {"content": "b"}] ): assert yield_time < time.time() + 0.1, "we should each item directly after it was yielded" out.append(__UpperCamelCase ) assert out.count("a" ) == 2 assert out.count("b" ) == 2 assert len(__UpperCamelCase ) == 4
329
0
"""simple docstring""" from typing import Any, Dict, List, Union from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): import torch from transformers.modeling_outputs import BaseModelOutput from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING _UpperCamelCase : Dict = logging.get_logger(__name__) @add_end_docstrings(_a) class UpperCAmelCase_ ( _a): def __init__( self , **a ) -> Dict: super().__init__(**a ) if self.framework == "tf": raise ValueError(f"""The {self.__class__} is only available in PyTorch.""" ) requires_backends(self , 'vision' ) self.check_model_type(a ) def __call__( self , a , a = None , **a , ) -> List[str]: if "text_queries" in kwargs: lowercase__ : Optional[Any] = kwargs.pop('text_queries' ) if isinstance(a , (str, Image.Image) ): lowercase__ : Optional[Any] = {'image': image, 'candidate_labels': candidate_labels} else: lowercase__ : List[str] = image lowercase__ : Optional[Any] = super().__call__(a , **a ) return results def _UpperCAmelCase ( self , **a ) -> Dict: lowercase__ : Optional[Any] = {} if "threshold" in kwargs: lowercase__ : Tuple = kwargs['threshold'] if "top_k" in kwargs: lowercase__ : List[Any] = kwargs['top_k'] return {}, {}, postprocess_params def _UpperCAmelCase ( self , a ) -> Dict: lowercase__ : Any = load_image(inputs['image'] ) lowercase__ : Optional[int] = inputs['candidate_labels'] if isinstance(a , a ): lowercase__ : Optional[int] = candidate_labels.split(',' ) lowercase__ : Optional[int] = torch.tensor([[image.height, image.width]] , dtype=torch.intaa ) for i, candidate_label in enumerate(a ): lowercase__ : List[str] = self.tokenizer(a , return_tensors=self.framework ) lowercase__ : List[Any] = self.image_processor(a , return_tensors=self.framework ) yield { "is_last": i == len(a ) - 1, "target_size": target_size, "candidate_label": candidate_label, **text_inputs, **image_features, } def _UpperCAmelCase ( self , a ) -> List[Any]: lowercase__ : List[Any] = model_inputs.pop('target_size' ) lowercase__ : Dict = model_inputs.pop('candidate_label' ) lowercase__ : Dict = model_inputs.pop('is_last' ) lowercase__ : Optional[int] = self.model(**a ) lowercase__ : Any = {'target_size': target_size, 'candidate_label': candidate_label, 'is_last': is_last, **outputs} return model_outputs def _UpperCAmelCase ( self , a , a=0.1 , a=None ) -> Union[str, Any]: lowercase__ : Dict = [] for model_output in model_outputs: lowercase__ : List[Any] = model_output['candidate_label'] lowercase__ : Optional[int] = BaseModelOutput(a ) lowercase__ : Any = self.image_processor.post_process_object_detection( outputs=a , threshold=a , target_sizes=model_output['target_size'] )[0] for index in outputs["scores"].nonzero(): lowercase__ : Union[str, Any] = outputs['scores'][index].item() lowercase__ : Tuple = self._get_bounding_box(outputs['boxes'][index][0] ) lowercase__ : Tuple = {'score': score, 'label': label, 'box': box} results.append(a ) lowercase__ : Dict = sorted(a , key=lambda a : x["score"] , reverse=a ) if top_k: lowercase__ : Dict = results[:top_k] return results def _UpperCAmelCase ( self , a ) -> Dict[str, int]: if self.framework != "pt": raise ValueError('The ZeroShotObjectDetectionPipeline is only available in PyTorch.' ) lowercase__ , lowercase__ , lowercase__ , lowercase__ : Tuple = box.int().tolist() lowercase__ : Any = { 'xmin': xmin, 'ymin': ymin, 'xmax': xmax, 'ymax': ymax, } return bbox
77
import collections import importlib.util import os import re from pathlib import Path lowercase = "src/transformers" # Matches is_xxx_available() lowercase = re.compile(r"is\_([a-z_]*)_available()") # Catches a one-line _import_struct = {xxx} lowercase = re.compile(r"^_import_structure\s+=\s+\{([^\}]+)\}") # Catches a line with a key-values pattern: "bla": ["foo", "bar"] lowercase = re.compile(r"\s+\"\S*\":\s+\[([^\]]*)\]") # Catches a line if not is_foo_available lowercase = re.compile(r"^\s*if\s+not\s+is\_[a-z_]*\_available\(\)") # Catches a line _import_struct["bla"].append("foo") lowercase = re.compile(r"^\s*_import_structure\[\"\S*\"\]\.append\(\"(\S*)\"\)") # Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"] lowercase = re.compile(r"^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]") # Catches a line with an object between quotes and a comma: "MyModel", lowercase = re.compile("^\s+\"([^\"]+)\",") # Catches a line with objects between brackets only: ["foo", "bar"], lowercase = re.compile("^\s+\[([^\]]+)\]") # Catches a line with from foo import bar, bla, boo lowercase = re.compile(r"\s+from\s+\S*\s+import\s+([^\(\s].*)\n") # Catches a line with try: lowercase = re.compile(r"^\s*try:") # Catches a line with else: lowercase = re.compile(r"^\s*else:") def __UpperCAmelCase ( a_): if _re_test_backend.search(a_) is None: return None snake_case_ = [b[0] for b in _re_backend.findall(a_)] backends.sort() return "_and_".join(a_) def __UpperCAmelCase ( a_): with open(a_ , 'r' , encoding='utf-8' , newline='\n') as f: snake_case_ = f.readlines() snake_case_ = 0 while line_index < len(a_) and not lines[line_index].startswith('_import_structure = {'): line_index += 1 # If this is a traditional init, just return. if line_index >= len(a_): return None # First grab the objects without a specific backend in _import_structure snake_case_ = [] while not lines[line_index].startswith('if TYPE_CHECKING') and find_backend(lines[line_index]) is None: snake_case_ = lines[line_index] # If we have everything on a single line, let's deal with it. if _re_one_line_import_struct.search(a_): snake_case_ = _re_one_line_import_struct.search(a_).groups()[0] snake_case_ = re.findall('\[([^\]]+)\]' , a_) for imp in imports: objects.extend([obj[1:-1] for obj in imp.split(', ')]) line_index += 1 continue snake_case_ = _re_import_struct_key_value.search(a_) if single_line_import_search is not None: snake_case_ = [obj[1:-1] for obj in single_line_import_search.groups()[0].split(', ') if len(a_) > 0] objects.extend(a_) elif line.startswith(' ' * 8 + '"'): objects.append(line[9:-3]) line_index += 1 snake_case_ = {'none': objects} # Let's continue with backend-specific objects in _import_structure while not lines[line_index].startswith('if TYPE_CHECKING'): # If the line is an if not is_backend_available, we grab all objects associated. snake_case_ = find_backend(lines[line_index]) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1]) is None: snake_case_ = None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index]) is None: line_index += 1 line_index += 1 snake_case_ = [] # Until we unindent, add backend objects to the list while len(lines[line_index]) <= 1 or lines[line_index].startswith(' ' * 4): snake_case_ = lines[line_index] if _re_import_struct_add_one.search(a_) is not None: objects.append(_re_import_struct_add_one.search(a_).groups()[0]) elif _re_import_struct_add_many.search(a_) is not None: snake_case_ = _re_import_struct_add_many.search(a_).groups()[0].split(', ') snake_case_ = [obj[1:-1] for obj in imports if len(a_) > 0] objects.extend(a_) elif _re_between_brackets.search(a_) is not None: snake_case_ = _re_between_brackets.search(a_).groups()[0].split(', ') snake_case_ = [obj[1:-1] for obj in imports if len(a_) > 0] objects.extend(a_) elif _re_quote_object.search(a_) is not None: objects.append(_re_quote_object.search(a_).groups()[0]) elif line.startswith(' ' * 8 + '"'): objects.append(line[9:-3]) elif line.startswith(' ' * 12 + '"'): objects.append(line[13:-3]) line_index += 1 snake_case_ = objects else: line_index += 1 # At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend snake_case_ = [] while ( line_index < len(a_) and find_backend(lines[line_index]) is None and not lines[line_index].startswith('else') ): snake_case_ = lines[line_index] snake_case_ = _re_import.search(a_) 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 snake_case_ = {'none': objects} # Let's continue with backend-specific objects while line_index < len(a_): # If the line is an if is_backend_available, we grab all objects associated. snake_case_ = find_backend(lines[line_index]) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1]) is None: snake_case_ = None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index]) is None: line_index += 1 line_index += 1 snake_case_ = [] # Until we unindent, add backend objects to the list while len(lines[line_index]) <= 1 or lines[line_index].startswith(' ' * 8): snake_case_ = lines[line_index] snake_case_ = _re_import.search(a_) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(', ')) elif line.startswith(' ' * 12): objects.append(line[12:-2]) line_index += 1 snake_case_ = objects else: line_index += 1 return import_dict_objects, type_hint_objects def __UpperCAmelCase ( a_ , a_): def find_duplicates(a_): return [k for k, v in collections.Counter(a_).items() if v > 1] if list(import_dict_objects.keys()) != list(type_hint_objects.keys()): return ["Both sides of the init do not have the same backends!"] snake_case_ = [] for key in import_dict_objects.keys(): snake_case_ = find_duplicates(import_dict_objects[key]) if duplicate_imports: errors.append(f'''Duplicate _import_structure definitions for: {duplicate_imports}''') snake_case_ = find_duplicates(type_hint_objects[key]) if duplicate_type_hints: errors.append(f'''Duplicate TYPE_CHECKING objects for: {duplicate_type_hints}''') if sorted(set(import_dict_objects[key])) != sorted(set(type_hint_objects[key])): snake_case_ = 'base imports' if key == 'none' else f'''{key} backend''' errors.append(f'''Differences for {name}:''') for a in type_hint_objects[key]: if a not in import_dict_objects[key]: errors.append(f''' {a} in TYPE_HINT but not in _import_structure.''') for a in import_dict_objects[key]: if a not in type_hint_objects[key]: errors.append(f''' {a} in _import_structure but not in TYPE_HINT.''') return errors def __UpperCAmelCase ( ): snake_case_ = [] for root, _, files in os.walk(a_): if "__init__.py" in files: snake_case_ = os.path.join(a_ , '__init__.py') snake_case_ = parse_init(a_) if objects is not None: snake_case_ = analyze_results(*a_) if len(a_) > 0: snake_case_ = f'''Problem in {fname}, both halves do not define the same objects.\n{errors[0]}''' failures.append('\n'.join(a_)) if len(a_) > 0: raise ValueError('\n\n'.join(a_)) def __UpperCAmelCase ( ): snake_case_ = [] for path, directories, files in os.walk(a_): for folder in directories: # Ignore private modules if folder.startswith('_'): directories.remove(a_) continue # Ignore leftovers from branches (empty folders apart from pycache) if len(list((Path(a_) / folder).glob('*.py'))) == 0: continue snake_case_ = str((Path(a_) / folder).relative_to(a_)) snake_case_ = short_path.replace(os.path.sep , '.') submodules.append(a_) for fname in files: if fname == "__init__.py": continue snake_case_ = str((Path(a_) / fname).relative_to(a_)) snake_case_ = short_path.replace('.py' , '').replace(os.path.sep , '.') if len(submodule.split('.')) == 1: submodules.append(a_) return submodules lowercase = [ "convert_pytorch_checkpoint_to_tf2", "modeling_flax_pytorch_utils", ] def __UpperCAmelCase ( ): # This is to make sure the transformers module imported is the one in the repo. snake_case_ = importlib.util.spec_from_file_location( 'transformers' , os.path.join(a_ , '__init__.py') , submodule_search_locations=[PATH_TO_TRANSFORMERS] , ) snake_case_ = spec.loader.load_module() snake_case_ = [ module for module in get_transformers_submodules() if module not in IGNORE_SUBMODULES and module not in transformers._import_structure.keys() ] if len(a_) > 0: snake_case_ = '\n'.join(f'''- {module}''' for module in module_not_registered) raise ValueError( 'The following submodules are not properly registered in the main init of Transformers:\n' f'''{list_of_modules}\n''' 'Make sure they appear somewhere in the keys of `_import_structure` with an empty list as value.') if __name__ == "__main__": check_all_inits() check_submodules()
178
0
def SCREAMING_SNAKE_CASE ( __UpperCamelCase : float , __UpperCamelCase : float ) -> float: if density <= 0: raise ValueError('''Impossible fluid density''' ) if bulk_modulus <= 0: raise ValueError('''Impossible bulk modulus''' ) return (bulk_modulus / density) ** 0.5 if __name__ == "__main__": import doctest doctest.testmod()
177
import baseaa def SCREAMING_SNAKE_CASE ( __UpperCamelCase : str ) -> bytes: return baseaa.baaencode(string.encode('''utf-8''' ) ) def SCREAMING_SNAKE_CASE ( __UpperCamelCase : bytes ) -> str: return baseaa.baadecode(__UpperCamelCase ).decode('''utf-8''' ) if __name__ == "__main__": _lowerCamelCase = 'Hello World!' _lowerCamelCase = baseaa_encode(test) print(encoded) _lowerCamelCase = baseaa_decode(encoded) print(decoded)
177
1
'''simple docstring''' import json import os from functools import lru_cache from typing import TYPE_CHECKING, List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation UpperCamelCase_ = logging.get_logger(__name__) UpperCamelCase_ = { "vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_config_file": "tokenizer_config.json", } UpperCamelCase_ = { "vocab_file": {"facebook/blenderbot-3B": "https://huggingface.co/facebook/blenderbot-3B/resolve/main/vocab.json"}, "merges_file": {"facebook/blenderbot-3B": "https://huggingface.co/facebook/blenderbot-3B/resolve/main/merges.txt"}, "tokenizer_config_file": { "facebook/blenderbot-3B": "https://huggingface.co/facebook/blenderbot-3B/resolve/main/tokenizer_config.json" }, } UpperCamelCase_ = {"facebook/blenderbot-3B": 1_2_8} @lru_cache() # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode def lowercase__( ): """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = ( list(range(ord('!' ) ,ord('~' ) + 1 ) ) + list(range(ord('¡' ) ,ord('¬' ) + 1 ) ) + list(range(ord('®' ) ,ord('ÿ' ) + 1 ) ) ) SCREAMING_SNAKE_CASE : Tuple = bs[:] SCREAMING_SNAKE_CASE : Union[str, Any] = 0 for b in range(2**8 ): if b not in bs: bs.append(__UpperCamelCase ) cs.append(2**8 + n ) n += 1 SCREAMING_SNAKE_CASE : Optional[int] = [chr(__UpperCamelCase ) for n in cs] return dict(zip(__UpperCamelCase ,__UpperCamelCase ) ) def lowercase__( __UpperCamelCase: List[Any] ): """simple docstring""" SCREAMING_SNAKE_CASE : str = set() SCREAMING_SNAKE_CASE : int = word[0] for char in word[1:]: pairs.add((prev_char, char) ) SCREAMING_SNAKE_CASE : str = char return pairs class _a ( SCREAMING_SNAKE_CASE ): '''simple docstring''' A : Optional[Any] = VOCAB_FILES_NAMES A : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP A : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A : Dict = ['''input_ids''', '''attention_mask'''] def __init__( self, A, A, A="replace", A="<s>", A="</s>", A="</s>", A="<s>", A="<unk>", A="<pad>", A="<mask>", A=False, **A, ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = AddedToken(A, lstrip=A, rstrip=A ) if isinstance(A, A ) else bos_token SCREAMING_SNAKE_CASE : Any = AddedToken(A, lstrip=A, rstrip=A ) if isinstance(A, A ) else eos_token SCREAMING_SNAKE_CASE : str = AddedToken(A, lstrip=A, rstrip=A ) if isinstance(A, A ) else sep_token SCREAMING_SNAKE_CASE : Union[str, Any] = AddedToken(A, lstrip=A, rstrip=A ) if isinstance(A, A ) else cls_token SCREAMING_SNAKE_CASE : List[Any] = AddedToken(A, lstrip=A, rstrip=A ) if isinstance(A, A ) else unk_token SCREAMING_SNAKE_CASE : Any = AddedToken(A, lstrip=A, rstrip=A ) if isinstance(A, A ) else pad_token # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE : Optional[Any] = AddedToken(A, lstrip=A, rstrip=A ) if isinstance(A, A ) else mask_token super().__init__( errors=A, bos_token=A, eos_token=A, unk_token=A, sep_token=A, cls_token=A, pad_token=A, mask_token=A, add_prefix_space=A, **A, ) with open(A, encoding='utf-8' ) as vocab_handle: SCREAMING_SNAKE_CASE : Tuple = json.load(A ) SCREAMING_SNAKE_CASE : Dict = {v: k for k, v in self.encoder.items()} SCREAMING_SNAKE_CASE : int = errors # how to handle errors in decoding SCREAMING_SNAKE_CASE : Any = bytes_to_unicode() SCREAMING_SNAKE_CASE : Tuple = {v: k for k, v in self.byte_encoder.items()} with open(A, encoding='utf-8' ) as merges_handle: SCREAMING_SNAKE_CASE : Any = merges_handle.read().split('\n' )[1:-1] SCREAMING_SNAKE_CASE : Optional[int] = [tuple(merge.split() ) for merge in bpe_merges] SCREAMING_SNAKE_CASE : Optional[Any] = dict(zip(A, range(len(A ) ) ) ) SCREAMING_SNAKE_CASE : List[Any] = {} SCREAMING_SNAKE_CASE : Union[str, Any] = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions SCREAMING_SNAKE_CASE : Dict = re.compile(r'\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+' ) @property # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.vocab_size with Roberta->Blenderbot, RoBERTa->Blenderbot def UpperCamelCase_ ( self ): '''simple docstring''' return len(self.encoder ) def UpperCamelCase_ ( self ): '''simple docstring''' return dict(self.encoder, **self.added_tokens_encoder ) def UpperCamelCase_ ( self, A ): '''simple docstring''' if token in self.cache: return self.cache[token] SCREAMING_SNAKE_CASE : Union[str, Any] = tuple(A ) SCREAMING_SNAKE_CASE : int = get_pairs(A ) if not pairs: return token while True: SCREAMING_SNAKE_CASE : Union[str, Any] = min(A, key=lambda A : self.bpe_ranks.get(A, float('inf' ) ) ) if bigram not in self.bpe_ranks: break SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : str = bigram SCREAMING_SNAKE_CASE : List[str] = [] SCREAMING_SNAKE_CASE : Optional[int] = 0 while i < len(A ): try: SCREAMING_SNAKE_CASE : List[str] = word.index(A, A ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) SCREAMING_SNAKE_CASE : Any = j if word[i] == first and i < len(A ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 SCREAMING_SNAKE_CASE : int = tuple(A ) SCREAMING_SNAKE_CASE : List[str] = new_word if len(A ) == 1: break else: SCREAMING_SNAKE_CASE : Dict = get_pairs(A ) SCREAMING_SNAKE_CASE : Optional[Any] = ' '.join(A ) SCREAMING_SNAKE_CASE : int = word return word def UpperCamelCase_ ( self, A ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = [] for token in re.findall(self.pat, A ): SCREAMING_SNAKE_CASE : List[Any] = ''.join( self.byte_encoder[b] for b in token.encode('utf-8' ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(A ).split(' ' ) ) return bpe_tokens def UpperCamelCase_ ( self, A ): '''simple docstring''' return self.encoder.get(A, self.encoder.get(self.unk_token ) ) def UpperCamelCase_ ( self, A ): '''simple docstring''' return self.decoder.get(A ) def UpperCamelCase_ ( self, A ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = ''.join(A ) SCREAMING_SNAKE_CASE : List[Any] = bytearray([self.byte_decoder[c] for c in text] ).decode('utf-8', errors=self.errors ) return text def UpperCamelCase_ ( self, A, A = None ): '''simple docstring''' if not os.path.isdir(A ): logger.error(F"Vocabulary path ({save_directory}) should be a directory" ) return SCREAMING_SNAKE_CASE : Optional[int] = os.path.join( A, (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) SCREAMING_SNAKE_CASE : str = os.path.join( A, (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['merges_file'] ) with open(A, 'w', encoding='utf-8' ) as f: f.write(json.dumps(self.encoder, indent=2, sort_keys=A, ensure_ascii=A ) + '\n' ) SCREAMING_SNAKE_CASE : str = 0 with open(A, 'w', encoding='utf-8' ) as writer: writer.write('#version: 0.2\n' ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda A : kv[1] ): if index != token_index: logger.warning( F"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive." ' Please check that the tokenizer is not corrupted!' ) SCREAMING_SNAKE_CASE : int = token_index writer.write(' '.join(A ) + '\n' ) index += 1 return vocab_file, merge_file def UpperCamelCase_ ( self, A, A = None, A = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=A, token_ids_a=A, already_has_special_tokens=A ) if token_ids_a is None: return [1] + ([0] * len(A )) + [1] return [1] + ([0] * len(A )) + [1, 1] + ([0] * len(A )) + [1] def UpperCamelCase_ ( self, A, A = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = [self.sep_token_id] SCREAMING_SNAKE_CASE : List[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 UpperCamelCase_ ( self, A, A=False, **A ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = kwargs.pop('add_prefix_space', self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(A ) > 0 and not text[0].isspace()): SCREAMING_SNAKE_CASE : Union[str, Any] = ' ' + text return (text, kwargs) def UpperCamelCase_ ( self, A, A = None ): '''simple docstring''' return token_ids_a + [self.eos_token_id] def UpperCamelCase_ ( self, A ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = [] for is_user, text in conversation.iter_texts(): if is_user: # We need to space prefix as it's being done within blenderbot inputs.append(' ' + text ) else: # Generated responses should contain them already. inputs.append(A ) SCREAMING_SNAKE_CASE : List[str] = ' '.join(A ) SCREAMING_SNAKE_CASE : Dict = self.encode(A ) if len(A ) > self.model_max_length: SCREAMING_SNAKE_CASE : Optional[Any] = input_ids[-self.model_max_length :] logger.warning(F"Trimmed input from conversation as it was longer than {self.model_max_length} tokens." ) return input_ids
251
'''simple docstring''' import math from enum import Enum from typing import Optional, Union from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR from .utils import logging UpperCamelCase_ = logging.get_logger(__name__) class _a ( SCREAMING_SNAKE_CASE ): '''simple docstring''' A : Union[str, Any] = '''linear''' A : int = '''cosine''' A : Optional[Any] = '''cosine_with_restarts''' A : Optional[int] = '''polynomial''' A : str = '''constant''' A : Union[str, Any] = '''constant_with_warmup''' A : Optional[Any] = '''piecewise_constant''' def lowercase__( __UpperCamelCase: Optimizer ,__UpperCamelCase: int = -1 ): """simple docstring""" return LambdaLR(__UpperCamelCase ,lambda __UpperCamelCase : 1 ,last_epoch=__UpperCamelCase ) def lowercase__( __UpperCamelCase: Optimizer ,__UpperCamelCase: int ,__UpperCamelCase: int = -1 ): """simple docstring""" def lr_lambda(__UpperCamelCase: int ): if current_step < num_warmup_steps: return float(__UpperCamelCase ) / float(max(1.0 ,__UpperCamelCase ) ) return 1.0 return LambdaLR(__UpperCamelCase ,__UpperCamelCase ,last_epoch=__UpperCamelCase ) def lowercase__( __UpperCamelCase: Optimizer ,__UpperCamelCase: str ,__UpperCamelCase: int = -1 ): """simple docstring""" SCREAMING_SNAKE_CASE : Dict = {} SCREAMING_SNAKE_CASE : Optional[Any] = step_rules.split(',' ) for rule_str in rule_list[:-1]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = rule_str.split(':' ) SCREAMING_SNAKE_CASE : int = int(__UpperCamelCase ) SCREAMING_SNAKE_CASE : Any = float(__UpperCamelCase ) SCREAMING_SNAKE_CASE : List[str] = value SCREAMING_SNAKE_CASE : Any = float(rule_list[-1] ) def create_rules_function(__UpperCamelCase: Union[str, Any] ,__UpperCamelCase: Optional[Any] ): def rule_func(__UpperCamelCase: int ) -> float: SCREAMING_SNAKE_CASE : Union[str, Any] = sorted(rules_dict.keys() ) for i, sorted_step in enumerate(__UpperCamelCase ): if steps < sorted_step: return rules_dict[sorted_steps[i]] return last_lr_multiple return rule_func SCREAMING_SNAKE_CASE : Any = create_rules_function(__UpperCamelCase ,__UpperCamelCase ) return LambdaLR(__UpperCamelCase ,__UpperCamelCase ,last_epoch=__UpperCamelCase ) def lowercase__( __UpperCamelCase: int ,__UpperCamelCase: List[Any] ,__UpperCamelCase: Dict ,__UpperCamelCase: int=-1 ): """simple docstring""" def lr_lambda(__UpperCamelCase: int ): if current_step < num_warmup_steps: return float(__UpperCamelCase ) / float(max(1 ,__UpperCamelCase ) ) return max( 0.0 ,float(num_training_steps - current_step ) / float(max(1 ,num_training_steps - num_warmup_steps ) ) ) return LambdaLR(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) def lowercase__( __UpperCamelCase: Optimizer ,__UpperCamelCase: int ,__UpperCamelCase: int ,__UpperCamelCase: float = 0.5 ,__UpperCamelCase: int = -1 ): """simple docstring""" def lr_lambda(__UpperCamelCase: Any ): if current_step < num_warmup_steps: return float(__UpperCamelCase ) / float(max(1 ,__UpperCamelCase ) ) SCREAMING_SNAKE_CASE : str = float(current_step - num_warmup_steps ) / float(max(1 ,num_training_steps - num_warmup_steps ) ) return max(0.0 ,0.5 * (1.0 + math.cos(math.pi * float(__UpperCamelCase ) * 2.0 * progress )) ) return LambdaLR(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) def lowercase__( __UpperCamelCase: Optimizer ,__UpperCamelCase: int ,__UpperCamelCase: int ,__UpperCamelCase: int = 1 ,__UpperCamelCase: int = -1 ): """simple docstring""" def lr_lambda(__UpperCamelCase: Dict ): if current_step < num_warmup_steps: return float(__UpperCamelCase ) / float(max(1 ,__UpperCamelCase ) ) SCREAMING_SNAKE_CASE : int = float(current_step - num_warmup_steps ) / float(max(1 ,num_training_steps - num_warmup_steps ) ) if progress >= 1.0: return 0.0 return max(0.0 ,0.5 * (1.0 + math.cos(math.pi * ((float(__UpperCamelCase ) * progress) % 1.0) )) ) return LambdaLR(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) def lowercase__( __UpperCamelCase: Optional[int] ,__UpperCamelCase: Any ,__UpperCamelCase: Optional[int] ,__UpperCamelCase: Optional[Any]=1e-7 ,__UpperCamelCase: Dict=1.0 ,__UpperCamelCase: Optional[Any]=-1 ): """simple docstring""" SCREAMING_SNAKE_CASE : Dict = optimizer.defaults['lr'] if not (lr_init > lr_end): raise ValueError(f"lr_end ({lr_end}) must be be smaller than initial lr ({lr_init})" ) def lr_lambda(__UpperCamelCase: int ): if current_step < num_warmup_steps: return float(__UpperCamelCase ) / float(max(1 ,__UpperCamelCase ) ) elif current_step > num_training_steps: return lr_end / lr_init # as LambdaLR multiplies by lr_init else: SCREAMING_SNAKE_CASE : List[str] = lr_init - lr_end SCREAMING_SNAKE_CASE : Optional[Any] = num_training_steps - num_warmup_steps SCREAMING_SNAKE_CASE : Union[str, Any] = 1 - (current_step - num_warmup_steps) / decay_steps SCREAMING_SNAKE_CASE : str = lr_range * pct_remaining**power + lr_end return decay / lr_init # as LambdaLR multiplies by lr_init return LambdaLR(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) UpperCamelCase_ = { SchedulerType.LINEAR: get_linear_schedule_with_warmup, SchedulerType.COSINE: get_cosine_schedule_with_warmup, SchedulerType.COSINE_WITH_RESTARTS: get_cosine_with_hard_restarts_schedule_with_warmup, SchedulerType.POLYNOMIAL: get_polynomial_decay_schedule_with_warmup, SchedulerType.CONSTANT: get_constant_schedule, SchedulerType.CONSTANT_WITH_WARMUP: get_constant_schedule_with_warmup, SchedulerType.PIECEWISE_CONSTANT: get_piecewise_constant_schedule, } def lowercase__( __UpperCamelCase: Union[str, SchedulerType] ,__UpperCamelCase: Optimizer ,__UpperCamelCase: Optional[str] = None ,__UpperCamelCase: Optional[int] = None ,__UpperCamelCase: Optional[int] = None ,__UpperCamelCase: int = 1 ,__UpperCamelCase: float = 1.0 ,__UpperCamelCase: int = -1 ,): """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = SchedulerType(__UpperCamelCase ) SCREAMING_SNAKE_CASE : str = TYPE_TO_SCHEDULER_FUNCTION[name] if name == SchedulerType.CONSTANT: return schedule_func(__UpperCamelCase ,last_epoch=__UpperCamelCase ) if name == SchedulerType.PIECEWISE_CONSTANT: return schedule_func(__UpperCamelCase ,step_rules=__UpperCamelCase ,last_epoch=__UpperCamelCase ) # All other schedulers require `num_warmup_steps` if num_warmup_steps is None: raise ValueError(f"{name} requires `num_warmup_steps`, please provide that argument." ) if name == SchedulerType.CONSTANT_WITH_WARMUP: return schedule_func(__UpperCamelCase ,num_warmup_steps=__UpperCamelCase ,last_epoch=__UpperCamelCase ) # All other schedulers require `num_training_steps` if num_training_steps is None: raise ValueError(f"{name} requires `num_training_steps`, please provide that argument." ) if name == SchedulerType.COSINE_WITH_RESTARTS: return schedule_func( __UpperCamelCase ,num_warmup_steps=__UpperCamelCase ,num_training_steps=__UpperCamelCase ,num_cycles=__UpperCamelCase ,last_epoch=__UpperCamelCase ,) if name == SchedulerType.POLYNOMIAL: return schedule_func( __UpperCamelCase ,num_warmup_steps=__UpperCamelCase ,num_training_steps=__UpperCamelCase ,power=__UpperCamelCase ,last_epoch=__UpperCamelCase ,) return schedule_func( __UpperCamelCase ,num_warmup_steps=__UpperCamelCase ,num_training_steps=__UpperCamelCase ,last_epoch=__UpperCamelCase )
251
1
'''simple docstring''' from ...utils import ( OptionalDependencyNotAvailable, is_flax_available, is_torch_available, is_transformers_available, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .multicontrolnet import MultiControlNetModel from .pipeline_controlnet import StableDiffusionControlNetPipeline from .pipeline_controlnet_imgaimg import StableDiffusionControlNetImgaImgPipeline from .pipeline_controlnet_inpaint import StableDiffusionControlNetInpaintPipeline if is_transformers_available() and is_flax_available(): from .pipeline_flax_controlnet import FlaxStableDiffusionControlNetPipeline
106
'''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() SCREAMING_SNAKE_CASE_: int =logging.get_logger(__name__) SCREAMING_SNAKE_CASE_: Dict ={ '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', } SCREAMING_SNAKE_CASE_: List[str] =[ 'lm_head', 'quantizer.weight_proj', 'quantizer.codevectors', 'project_q', 'project_hid', ] def lowerCAmelCase_ ( snake_case_ : str , snake_case_ : List[Any] , snake_case_ : Union[str, Any] , snake_case_ : int , snake_case_ : Any ) -> Optional[int]: '''simple docstring''' for attribute in key.split("." ): UpperCAmelCase_ = getattr(snake_case_ , snake_case_ ) if weight_type is not None: UpperCAmelCase_ = getattr(snake_case_ , snake_case_ ).shape else: UpperCAmelCase_ = 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_ = value elif weight_type == "weight_g": UpperCAmelCase_ = value elif weight_type == "weight_v": UpperCAmelCase_ = value elif weight_type == "bias": UpperCAmelCase_ = value else: UpperCAmelCase_ = value logger.info(f"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def lowerCAmelCase_ ( snake_case_ : List[Any] , snake_case_ : List[str] ) -> int: '''simple docstring''' UpperCAmelCase_ = [] UpperCAmelCase_ = fairseq_model.state_dict() UpperCAmelCase_ = hf_model.feature_extractor # if encoder has different dim to decoder -> use proj_weight UpperCAmelCase_ = None for name, value in fairseq_dict.items(): UpperCAmelCase_ = False if "conv_layers" in name: load_conv_layer( snake_case_ , snake_case_ , snake_case_ , snake_case_ , hf_model.config.feat_extract_norm == "group" , ) UpperCAmelCase_ = True elif name.split("." )[0] == "proj": UpperCAmelCase_ = fairseq_model.proj UpperCAmelCase_ = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split("w2v_model." )[-1] == name.split("." )[0]: UpperCAmelCase_ = True if "*" in mapped_key: UpperCAmelCase_ = name.split(snake_case_ )[0].split("." )[-2] UpperCAmelCase_ = mapped_key.replace("*" , snake_case_ ) if "weight_g" in name: UpperCAmelCase_ = "weight_g" elif "weight_v" in name: UpperCAmelCase_ = "weight_v" elif "bias" in name: UpperCAmelCase_ = "bias" elif "weight" in name: UpperCAmelCase_ = "weight" else: UpperCAmelCase_ = 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 lowerCAmelCase_ ( snake_case_ : Dict , snake_case_ : List[Any] , snake_case_ : str , snake_case_ : Any , snake_case_ : int ) -> Dict: '''simple docstring''' UpperCAmelCase_ = full_name.split("conv_layers." )[-1] UpperCAmelCase_ = name.split("." ) UpperCAmelCase_ = int(items[0] ) UpperCAmelCase_ = 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_ = 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_ = 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_ = 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_ = 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 lowerCAmelCase_ ( snake_case_ : Any ) -> Any: '''simple docstring''' UpperCAmelCase_ , UpperCAmelCase_ = emb.weight.shape UpperCAmelCase_ = nn.Linear(snake_case_ , snake_case_ , bias=snake_case_ ) UpperCAmelCase_ = emb.weight.data return lin_layer def lowerCAmelCase_ ( snake_case_ : int ) -> List[str]: '''simple docstring''' with open(snake_case_ , "r" , encoding="utf-8" ) as f: UpperCAmelCase_ = f.readlines() UpperCAmelCase_ = [line.split(" " )[0] for line in lines] UpperCAmelCase_ = len(snake_case_ ) UpperCAmelCase_ = { "<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 lowerCAmelCase_ ( snake_case_ : Dict , snake_case_ : Tuple , snake_case_ : List[str] , snake_case_ : Dict , snake_case_ : Union[str, Any] , snake_case_ : Tuple , snake_case_ : Any , ) -> Dict: '''simple docstring''' UpperCAmelCase_ = WavaVecaConfig.from_pretrained(snake_case_ ) UpperCAmelCase_ = SpeechaTextaConfig.from_pretrained( snake_case_ , vocab_size=snake_case_ , decoder_layers=snake_case_ , do_stable_layer_norm=snake_case_ ) UpperCAmelCase_ = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_60_00 , padding_value=0 , do_normalize=snake_case_ , return_attention_mask=snake_case_ , ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"data": "/".join(dict_path.split("/" )[:-1] )} ) UpperCAmelCase_ = model[0].eval() # set weights for wav2vec2 encoder UpperCAmelCase_ = WavaVecaModel(snake_case_ ) UpperCAmelCase_ = recursively_load_weights_wavaveca(model.encoder , snake_case_ ) UpperCAmelCase_ = SpeechaTextaForCausalLM(snake_case_ ) UpperCAmelCase_ , UpperCAmelCase_ = hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict() , strict=snake_case_ ) # set output linear layer unexpected_keys.remove("embed_out" ) UpperCAmelCase_ = 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}""" ) UpperCAmelCase_ = SpeechEncoderDecoderModel(encoder=snake_case_ , decoder=snake_case_ ) UpperCAmelCase_ = False # add projection layer UpperCAmelCase_ = nn.Parameter(projection_layer.weight ) UpperCAmelCase_ = nn.Parameter(projection_layer.bias ) UpperCAmelCase_ = create_vocab_dict(snake_case_ ) with open(os.path.join(snake_case_ , "vocab.json" ) , "w" ) as fp: json.dump(snake_case_ , snake_case_ ) UpperCAmelCase_ = SpeechaTextaTokenizer(os.path.join(snake_case_ , "vocab.json" ) ) tokenizer.save_pretrained(snake_case_ ) UpperCAmelCase_ = hf_wavavec.config.to_dict() UpperCAmelCase_ = tokenizer.pad_token_id UpperCAmelCase_ = tokenizer.bos_token_id UpperCAmelCase_ = tokenizer.eos_token_id UpperCAmelCase_ = "speech_to_text_2" UpperCAmelCase_ = "wav2vec2" UpperCAmelCase_ = SpeechEncoderDecoderConfig.from_dict(snake_case_ ) hf_wavavec.save_pretrained(snake_case_ ) feature_extractor.save_pretrained(snake_case_ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_: Optional[int] =argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint') parser.add_argument('--dict_path', default=None, type=str, help='Path to dict of fine-tuned model') parser.add_argument( '--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') SCREAMING_SNAKE_CASE_: Dict =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, )
106
1
import os import unittest from transformers.models.cpmant.tokenization_cpmant import VOCAB_FILES_NAMES, CpmAntTokenizer from transformers.testing_utils import require_jieba, tooslow from ...test_tokenization_common import TokenizerTesterMixin @require_jieba class SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): """simple docstring""" _snake_case = CpmAntTokenizer _snake_case = False def A__ ( self )-> str: '''simple docstring''' super().setUp() __UpperCamelCase = [ '''<d>''', '''</d>''', '''<s>''', '''</s>''', '''</_>''', '''<unk>''', '''<pad>''', '''</n>''', '''我''', '''是''', '''C''', '''P''', '''M''', '''A''', '''n''', '''t''', ] __UpperCamelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) @tooslow def A__ ( self )-> Any: '''simple docstring''' __UpperCamelCase = CpmAntTokenizer.from_pretrained('''openbmb/cpm-ant-10b''' ) __UpperCamelCase = '''今天天气真好!''' __UpperCamelCase = ['''今天''', '''天气''', '''真''', '''好''', '''!'''] __UpperCamelCase = tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) __UpperCamelCase = '''今天天气真好!''' __UpperCamelCase = [tokenizer.bos_token] + tokens __UpperCamelCase = [6, 9802, 14962, 2082, 831, 244] self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) __UpperCamelCase = tokenizer.decode(SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
328
import itertools from dataclasses import dataclass from typing import Any, Callable, Dict, List, Optional, Union import pandas as pd import pyarrow as pa import datasets import datasets.config from datasets.features.features import require_storage_cast from datasets.table import table_cast from datasets.utils.py_utils import Literal lowercase__ : Optional[int] = datasets.utils.logging.get_logger(__name__) lowercase__ : Optional[Any] = ["names", "prefix"] lowercase__ : List[Any] = ["warn_bad_lines", "error_bad_lines", "mangle_dupe_cols"] lowercase__ : Optional[Any] = ["encoding_errors", "on_bad_lines"] lowercase__ : List[str] = ["date_format"] @dataclass class SCREAMING_SNAKE_CASE__ ( datasets.BuilderConfig ): """simple docstring""" _snake_case = "," _snake_case = None _snake_case = "infer" _snake_case = None _snake_case = None _snake_case = None _snake_case = None _snake_case = None _snake_case = True _snake_case = None _snake_case = None _snake_case = None _snake_case = None _snake_case = False _snake_case = None _snake_case = None _snake_case = None _snake_case = True _snake_case = True _snake_case = False _snake_case = True _snake_case = None _snake_case = "." _snake_case = None _snake_case = '"' _snake_case = 0 _snake_case = None _snake_case = None _snake_case = None _snake_case = None _snake_case = True _snake_case = True _snake_case = 0 _snake_case = True _snake_case = False _snake_case = None _snake_case = 10000 _snake_case = None _snake_case = "strict" _snake_case = "error" _snake_case = None def A__ ( self )-> Any: '''simple docstring''' if self.delimiter is not None: __UpperCamelCase = self.delimiter if self.column_names is not None: __UpperCamelCase = self.column_names @property def A__ ( self )-> Any: '''simple docstring''' __UpperCamelCase = { '''sep''': self.sep, '''header''': self.header, '''names''': self.names, '''index_col''': self.index_col, '''usecols''': self.usecols, '''prefix''': self.prefix, '''mangle_dupe_cols''': self.mangle_dupe_cols, '''engine''': self.engine, '''converters''': self.converters, '''true_values''': self.true_values, '''false_values''': self.false_values, '''skipinitialspace''': self.skipinitialspace, '''skiprows''': self.skiprows, '''nrows''': self.nrows, '''na_values''': self.na_values, '''keep_default_na''': self.keep_default_na, '''na_filter''': self.na_filter, '''verbose''': self.verbose, '''skip_blank_lines''': self.skip_blank_lines, '''thousands''': self.thousands, '''decimal''': self.decimal, '''lineterminator''': self.lineterminator, '''quotechar''': self.quotechar, '''quoting''': self.quoting, '''escapechar''': self.escapechar, '''comment''': self.comment, '''encoding''': self.encoding, '''dialect''': self.dialect, '''error_bad_lines''': self.error_bad_lines, '''warn_bad_lines''': self.warn_bad_lines, '''skipfooter''': self.skipfooter, '''doublequote''': self.doublequote, '''memory_map''': self.memory_map, '''float_precision''': self.float_precision, '''chunksize''': self.chunksize, '''encoding_errors''': self.encoding_errors, '''on_bad_lines''': self.on_bad_lines, '''date_format''': self.date_format, } # some kwargs must not be passed if they don't have a default value # some others are deprecated and we can also not pass them if they are the default value for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS: if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig() , SCREAMING_SNAKE_CASE_ ): del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 2.0 new arguments if not (datasets.config.PANDAS_VERSION.major >= 2): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 1.3 new arguments if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] return pd_read_csv_kwargs class SCREAMING_SNAKE_CASE__ ( datasets.ArrowBasedBuilder ): """simple docstring""" _snake_case = CsvConfig def A__ ( self )-> Any: '''simple docstring''' return datasets.DatasetInfo(features=self.config.features ) def A__ ( self , SCREAMING_SNAKE_CASE_ )-> Optional[int]: '''simple docstring''' if not self.config.data_files: raise ValueError(F"At least one data file must be specified, but got data_files={self.config.data_files}" ) __UpperCamelCase = dl_manager.download_and_extract(self.config.data_files ) if isinstance(SCREAMING_SNAKE_CASE_ , (str, list, tuple) ): __UpperCamelCase = data_files if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): __UpperCamelCase = [files] __UpperCamelCase = [dl_manager.iter_files(SCREAMING_SNAKE_CASE_ ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'''files''': files} )] __UpperCamelCase = [] for split_name, files in data_files.items(): if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): __UpperCamelCase = [files] __UpperCamelCase = [dl_manager.iter_files(SCREAMING_SNAKE_CASE_ ) for file in files] splits.append(datasets.SplitGenerator(name=SCREAMING_SNAKE_CASE_ , gen_kwargs={'''files''': files} ) ) return splits def A__ ( self , SCREAMING_SNAKE_CASE_ )-> pa.Table: '''simple docstring''' if self.config.features is not None: __UpperCamelCase = self.config.features.arrow_schema if all(not require_storage_cast(SCREAMING_SNAKE_CASE_ ) for feature in self.config.features.values() ): # cheaper cast __UpperCamelCase = pa.Table.from_arrays([pa_table[field.name] for field in schema] , schema=SCREAMING_SNAKE_CASE_ ) else: # more expensive cast; allows str <-> int/float or str to Audio for example __UpperCamelCase = table_cast(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) return pa_table def A__ ( self , SCREAMING_SNAKE_CASE_ )-> str: '''simple docstring''' __UpperCamelCase = self.config.features.arrow_schema if self.config.features else None # dtype allows reading an int column as str __UpperCamelCase = ( { name: dtype.to_pandas_dtype() if not require_storage_cast(SCREAMING_SNAKE_CASE_ ) else object for name, dtype, feature in zip(schema.names , schema.types , self.config.features.values() ) } if schema is not None else None ) for file_idx, file in enumerate(itertools.chain.from_iterable(SCREAMING_SNAKE_CASE_ ) ): __UpperCamelCase = pd.read_csv(SCREAMING_SNAKE_CASE_ , iterator=SCREAMING_SNAKE_CASE_ , dtype=SCREAMING_SNAKE_CASE_ , **self.config.pd_read_csv_kwargs ) try: for batch_idx, df in enumerate(SCREAMING_SNAKE_CASE_ ): __UpperCamelCase = pa.Table.from_pandas(SCREAMING_SNAKE_CASE_ ) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(SCREAMING_SNAKE_CASE_ ) except ValueError as e: logger.error(F"Failed to read file '{file}' with error {type(SCREAMING_SNAKE_CASE_ )}: {e}" ) raise
328
1
import uuid from typing import Any, Dict, List, Optional, Union from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf if is_torch_available(): import torch UpperCamelCase = logging.get_logger(__name__) class __lowerCamelCase : """simple docstring""" def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : str = None , SCREAMING_SNAKE_CASE__ : uuid.UUID = None , SCREAMING_SNAKE_CASE__ : int=None , SCREAMING_SNAKE_CASE__ : Optional[int]=None ) -> Optional[Any]: if not conversation_id: lowerCAmelCase__ = uuid.uuida() if past_user_inputs is None: lowerCAmelCase__ = [] if generated_responses is None: lowerCAmelCase__ = [] lowerCAmelCase__ = conversation_id lowerCAmelCase__ = past_user_inputs lowerCAmelCase__ = generated_responses lowerCAmelCase__ = text def __eq__( self : List[str] , SCREAMING_SNAKE_CASE__ : Dict ) -> Dict: if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): return False if self.uuid == other.uuid: return True return ( self.new_user_input == other.new_user_input and self.past_user_inputs == other.past_user_inputs and self.generated_responses == other.generated_responses ) def a ( self : int , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : bool = False ) -> Tuple: if self.new_user_input: if overwrite: logger.warning( f'User input added while unprocessed input was existing: "{self.new_user_input}" was overwritten ' f'with: "{text}".' ) lowerCAmelCase__ = text else: logger.warning( f'User input added while unprocessed input was existing: "{self.new_user_input}" new input ' f'ignored: "{text}". Set `overwrite` to True to overwrite unprocessed user input' ) else: lowerCAmelCase__ = text def a ( self : str ) -> List[str]: if self.new_user_input: self.past_user_inputs.append(self.new_user_input ) lowerCAmelCase__ = None def a ( self : str , SCREAMING_SNAKE_CASE__ : str ) -> Union[str, Any]: self.generated_responses.append(SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] ) -> int: for user_input, generated_response in zip(self.past_user_inputs , self.generated_responses ): yield True, user_input yield False, generated_response if self.new_user_input: yield True, self.new_user_input def __repr__( self : Tuple ) -> List[str]: lowerCAmelCase__ = f'Conversation id: {self.uuid} \n' for is_user, text in self.iter_texts(): lowerCAmelCase__ = "user" if is_user else "bot" output += f'{name} >> {text} \n' return output @add_end_docstrings( UpperCamelCase__ , r"\n min_length_for_response (`int`, *optional*, defaults to 32):\n The minimum length (in number of tokens) for a response.\n minimum_tokens (`int`, *optional*, defaults to 10):\n The minimum length of tokens to leave for a response.\n " , ) class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" def __init__( self : str , *SCREAMING_SNAKE_CASE__ : int , **SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> List[Any]: super().__init__(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) if self.tokenizer.pad_token_id is None: lowerCAmelCase__ = self.tokenizer.eos_token def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , SCREAMING_SNAKE_CASE__ : List[Any]=None , SCREAMING_SNAKE_CASE__ : Tuple=None , **SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Union[str, Any]: lowerCAmelCase__ = {} lowerCAmelCase__ = {} lowerCAmelCase__ = {} if min_length_for_response is not None: lowerCAmelCase__ = min_length_for_response if minimum_tokens is not None: lowerCAmelCase__ = minimum_tokens if "max_length" in generate_kwargs: lowerCAmelCase__ = generate_kwargs["max_length"] # self.max_length = generate_kwargs.get("max_length", self.model.config.max_length) if clean_up_tokenization_spaces is not None: lowerCAmelCase__ = clean_up_tokenization_spaces if generate_kwargs: forward_params.update(SCREAMING_SNAKE_CASE__ ) return preprocess_params, forward_params, postprocess_params def __call__( self : Dict , SCREAMING_SNAKE_CASE__ : Union[Conversation, List[Conversation]] , SCREAMING_SNAKE_CASE__ : List[str]=0 , **SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Union[str, Any]: lowerCAmelCase__ = super().__call__(SCREAMING_SNAKE_CASE__ , num_workers=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and len(SCREAMING_SNAKE_CASE__ ) == 1: return outputs[0] return outputs def a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Conversation , SCREAMING_SNAKE_CASE__ : int=32 ) -> Dict[str, Any]: if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): raise ValueError("ConversationalPipeline, expects Conversation as inputs" ) if conversation.new_user_input is None: raise ValueError( f'Conversation with UUID {type(conversation.uuid )} does not contain new user input to process. ' "Add user inputs with the conversation's `add_user_input` method" ) if hasattr(self.tokenizer , "_build_conversation_input_ids" ): lowerCAmelCase__ = self.tokenizer._build_conversation_input_ids(SCREAMING_SNAKE_CASE__ ) else: # If the tokenizer cannot handle conversations, we default to only the old version lowerCAmelCase__ = self._legacy_parse_and_tokenize(SCREAMING_SNAKE_CASE__ ) if self.framework == "pt": lowerCAmelCase__ = torch.LongTensor([input_ids] ) elif self.framework == "tf": lowerCAmelCase__ = tf.constant([input_ids] ) return {"input_ids": input_ids, "conversation": conversation} def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Dict=10 , **SCREAMING_SNAKE_CASE__ : Dict ) -> Any: lowerCAmelCase__ = generate_kwargs.get("max_length" , self.model.config.max_length ) lowerCAmelCase__ = model_inputs["input_ids"].shape[1] if max_length - minimum_tokens < n: logger.warning(f'Conversation input is to long ({n}), trimming it to ({max_length} - {minimum_tokens})' ) lowerCAmelCase__ = max_length - minimum_tokens lowerCAmelCase__ = model_inputs["input_ids"][:, -trim:] if "attention_mask" in model_inputs: lowerCAmelCase__ = model_inputs["attention_mask"][:, -trim:] lowerCAmelCase__ = model_inputs.pop("conversation" ) lowerCAmelCase__ = max_length lowerCAmelCase__ = self.model.generate(**SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) if self.model.config.is_encoder_decoder: lowerCAmelCase__ = 1 else: lowerCAmelCase__ = n return {"output_ids": output_ids[:, start_position:], "conversation": conversation} def a ( self : Dict , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Any=True ) -> List[str]: lowerCAmelCase__ = model_outputs["output_ids"] lowerCAmelCase__ = self.tokenizer.decode( output_ids[0] , skip_special_tokens=SCREAMING_SNAKE_CASE__ , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE__ , ) lowerCAmelCase__ = model_outputs["conversation"] conversation.mark_processed() conversation.append_response(SCREAMING_SNAKE_CASE__ ) return conversation def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Conversation ) -> Dict: lowerCAmelCase__ = self.tokenizer.eos_token_id lowerCAmelCase__ = [] for is_user, text in conversation.iter_texts(): if eos_token_id is not None: input_ids.extend(self.tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) + [eos_token_id] ) else: input_ids.extend(self.tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) ) if len(SCREAMING_SNAKE_CASE__ ) > self.tokenizer.model_max_length: lowerCAmelCase__ = input_ids[-self.tokenizer.model_max_length :] return input_ids
221
import shutil import tempfile import unittest import numpy as np import pytest from transformers.testing_utils import require_vision from transformers.utils import is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, BlipaProcessor, BlipImageProcessor, GPTaTokenizer, PreTrainedTokenizerFast @require_vision class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def a ( self : Dict ) -> Optional[int]: lowerCAmelCase__ = tempfile.mkdtemp() lowerCAmelCase__ = BlipImageProcessor() lowerCAmelCase__ = GPTaTokenizer.from_pretrained("hf-internal-testing/tiny-random-GPT2Model" ) lowerCAmelCase__ = BlipaProcessor(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) def a ( self : int , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[Any]: return AutoProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ).tokenizer def a ( self : Tuple , **SCREAMING_SNAKE_CASE__ : Tuple ) -> Optional[Any]: return AutoProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ).image_processor def a ( self : str ) -> int: shutil.rmtree(self.tmpdirname ) def a ( self : List[Any] ) -> Any: lowerCAmelCase__ = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] lowerCAmelCase__ = [Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def a ( self : str ) -> Dict: lowerCAmelCase__ = BlipaProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) lowerCAmelCase__ = self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)" ) lowerCAmelCase__ = self.get_image_processor(do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) lowerCAmelCase__ = BlipaProcessor.from_pretrained( self.tmpdirname , bos_token="(BOS)" , eos_token="(EOS)" , do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , SCREAMING_SNAKE_CASE__ ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE__ ) def a ( self : int ) -> str: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_tokenizer() lowerCAmelCase__ = BlipaProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.prepare_image_inputs() lowerCAmelCase__ = image_processor(SCREAMING_SNAKE_CASE__ , return_tensors="np" ) lowerCAmelCase__ = processor(images=SCREAMING_SNAKE_CASE__ , return_tensors="np" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def a ( self : Tuple ) -> int: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_tokenizer() lowerCAmelCase__ = BlipaProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = "lower newer" lowerCAmelCase__ = processor(text=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer(SCREAMING_SNAKE_CASE__ , return_token_type_ids=SCREAMING_SNAKE_CASE__ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def a ( self : Dict ) -> str: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_tokenizer() lowerCAmelCase__ = BlipaProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = "lower newer" lowerCAmelCase__ = self.prepare_image_inputs() lowerCAmelCase__ = processor(text=SCREAMING_SNAKE_CASE__ , images=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(list(inputs.keys() ) , ["pixel_values", "input_ids", "attention_mask"] ) # test if it raises when no input is passed with pytest.raises(SCREAMING_SNAKE_CASE__ ): processor() def a ( self : str ) -> List[str]: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_tokenizer() lowerCAmelCase__ = BlipaProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] lowerCAmelCase__ = processor.batch_decode(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.batch_decode(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] ) -> Any: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_tokenizer() lowerCAmelCase__ = BlipaProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = "lower newer" lowerCAmelCase__ = self.prepare_image_inputs() lowerCAmelCase__ = processor(text=SCREAMING_SNAKE_CASE__ , images=SCREAMING_SNAKE_CASE__ ) # For now the processor supports only ['pixel_values', 'input_ids', 'attention_mask'] self.assertListEqual(list(inputs.keys() ) , ["pixel_values", "input_ids", "attention_mask"] )
221
1
'''simple docstring''' def __snake_case( _lowerCAmelCase = 1_000 ) -> int: snake_case__ : Union[str, Any] = 2**power snake_case__ : List[str] = 0 while n: snake_case__ , snake_case__ : int = r + n % 10, n // 10 return r if __name__ == "__main__": print(solution(int(str(input()).strip())))
35
'''simple docstring''' import json import os import unittest from transformers.models.gptsan_japanese.tokenization_gptsan_japanese import ( VOCAB_FILES_NAMES, GPTSanJapaneseTokenizer, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCAmelCase_ ( _a , unittest.TestCase ): """simple docstring""" lowercase = GPTSanJapaneseTokenizer lowercase = False lowercase = {"do_clean_text": False, "add_prefix_space": False} def lowerCamelCase ( self : str ): super().setUp() # fmt: off snake_case__ : Optional[Any] = ["""こん""", """こんに""", """にちは""", """ばんは""", """世界,㔺界""", """、""", """。""", """<BR>""", """<SP>""", """<TAB>""", """<URL>""", """<EMAIL>""", """<TEL>""", """<DATE>""", """<PRICE>""", """<BLOCK>""", """<KIGOU>""", """<U2000U2BFF>""", """<|emoji1|>""", """<unk>""", """<|bagoftoken|>""", """<|endoftext|>"""] # fmt: on snake_case__ : int = {"""emoji""": {"""\ud83d\ude00""": """<|emoji1|>"""}, """emoji_inv""": {"""<|emoji1|>""": """\ud83d\ude00"""}} # 😀 snake_case__ : List[Any] = {"""unk_token""": """<unk>"""} snake_case__ : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) snake_case__ : Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""emoji_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) with open(self.emoji_file , """w""" ) as emoji_writer: emoji_writer.write(json.dumps(snake_case_ ) ) def lowerCamelCase ( self : Any , **snake_case_ : Union[str, Any] ): kwargs.update(self.special_tokens_map ) return GPTSanJapaneseTokenizer.from_pretrained(self.tmpdirname , **snake_case_ ) def lowerCamelCase ( self : Any , snake_case_ : str ): snake_case__ : Union[str, Any] = """こんにちは、世界。 \nこんばんは、㔺界。😀""" snake_case__ : List[str] = """こんにちは、世界。 \nこんばんは、世界。😀""" return input_text, output_text def lowerCamelCase ( self : Any , snake_case_ : Dict ): snake_case__ , snake_case__ : int = self.get_input_output_texts(snake_case_ ) snake_case__ : int = tokenizer.encode(snake_case_ , add_special_tokens=snake_case_ ) snake_case__ : List[str] = tokenizer.decode(snake_case_ , clean_up_tokenization_spaces=snake_case_ ) return text, ids def lowerCamelCase ( self : Optional[Any] ): pass # TODO add if relevant def lowerCamelCase ( self : Union[str, Any] ): pass # TODO add if relevant def lowerCamelCase ( self : List[str] ): pass # TODO add if relevant def lowerCamelCase ( self : Dict ): snake_case__ : Optional[Any] = self.get_tokenizer() # Testing tokenization snake_case__ : int = """こんにちは、世界。 こんばんは、㔺界。""" snake_case__ : Optional[int] = ["""こん""", """にちは""", """、""", """世界""", """。""", """<SP>""", """こん""", """ばんは""", """、""", """㔺界""", """。"""] snake_case__ : Dict = tokenizer.tokenize(snake_case_ ) self.assertListEqual(snake_case_ , snake_case_ ) # Testing conversion to ids without special tokens snake_case__ : Union[str, Any] = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6] snake_case__ : List[Any] = tokenizer.convert_tokens_to_ids(snake_case_ ) self.assertListEqual(snake_case_ , snake_case_ ) # Testing conversion to ids with special tokens snake_case__ : Union[str, Any] = tokens + [tokenizer.unk_token] snake_case__ : Dict = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6, 19] snake_case__ : Any = tokenizer.convert_tokens_to_ids(snake_case_ ) self.assertListEqual(snake_case_ , snake_case_ ) def lowerCamelCase ( self : Optional[Any] ): snake_case__ : Union[str, Any] = self.get_tokenizer() # Testing tokenization snake_case__ : Union[str, Any] = """こんにちは、<|bagoftoken|>世界。こんばんは、<|bagoftoken|>㔺界。""" snake_case__ : Optional[int] = """こんにちは、、、、世界。こんばんは、、、、世界。""" snake_case__ : Any = tokenizer.encode(snake_case_ ) snake_case__ : int = tokenizer.decode(snake_case_ ) self.assertEqual(snake_case_ , snake_case_ ) @slow def lowerCamelCase ( self : Union[str, Any] ): snake_case__ : Optional[Any] = self.tokenizer_class.from_pretrained("""Tanrei/GPTSAN-japanese""" ) # Testing tokenization snake_case__ : Tuple = """こんにちは、世界。""" snake_case__ : Optional[Any] = """こんばんは、㔺界。😀""" snake_case__ : List[str] = """こんにちは、世界。こんばんは、世界。😀""" snake_case__ : Dict = tokenizer.encode(prefix_text + input_text ) snake_case__ : Dict = tokenizer.encode("""""" , prefix_text=prefix_text + input_text ) snake_case__ : int = tokenizer.encode(snake_case_ , prefix_text=snake_case_ ) snake_case__ : Optional[Any] = tokenizer.decode(snake_case_ ) snake_case__ : Union[str, Any] = tokenizer.decode(snake_case_ ) snake_case__ : str = tokenizer.decode(snake_case_ ) self.assertEqual(snake_case_ , snake_case_ ) self.assertEqual(snake_case_ , snake_case_ ) self.assertEqual(snake_case_ , snake_case_ ) @slow def lowerCamelCase ( self : Union[str, Any] ): snake_case__ : Optional[Any] = self.tokenizer_class.from_pretrained("""Tanrei/GPTSAN-japanese""" ) # Testing tokenization snake_case__ : Dict = """こんにちは、世界。""" snake_case__ : Optional[int] = """こんばんは、㔺界。😀""" snake_case__ : Any = len(tokenizer.encode(snake_case_ ) ) - 2 snake_case__ : Optional[int] = len(tokenizer.encode(snake_case_ ) ) - 2 snake_case__ : List[str] = [1] + [0] * (len_prefix + len_text + 1) snake_case__ : Optional[int] = [1] * (len_prefix + len_text + 1) + [0] snake_case__ : int = [1] + [1] * (len_prefix) + [0] * (len_text + 1) snake_case__ : Any = tokenizer(prefix_text + input_text ).token_type_ids snake_case__ : str = tokenizer("""""" , prefix_text=prefix_text + input_text ).token_type_ids snake_case__ : Optional[Any] = tokenizer(snake_case_ , prefix_text=snake_case_ ).token_type_ids self.assertListEqual(snake_case_ , snake_case_ ) self.assertListEqual(snake_case_ , snake_case_ ) self.assertListEqual(snake_case_ , snake_case_ ) @slow def lowerCamelCase ( self : Optional[int] ): snake_case__ : Optional[Any] = self.tokenizer_class.from_pretrained("""Tanrei/GPTSAN-japanese""" ) snake_case__ : Union[str, Any] = tokenizer.encode("""あンいワ""" ) snake_case__ : int = tokenizer.encode("""""" , prefix_text="""あンいワ""" ) snake_case__ : Dict = tokenizer.encode("""いワ""" , prefix_text="""あン""" ) self.assertEqual(tokenizer.decode(snake_case_ ) , tokenizer.decode(snake_case_ ) ) self.assertEqual(tokenizer.decode(snake_case_ ) , tokenizer.decode(snake_case_ ) ) self.assertNotEqual(snake_case_ , snake_case_ ) self.assertNotEqual(snake_case_ , snake_case_ ) self.assertEqual(x_token_a[1] , x_token_a[-1] ) # SEG token self.assertEqual(x_token_a[1] , x_token_a[3] ) # SEG token @slow def lowerCamelCase ( self : Any ): snake_case__ : Optional[int] = self.tokenizer_class.from_pretrained("""Tanrei/GPTSAN-japanese""" ) snake_case__ : int = [["""武田信玄""", """は、"""], ["""織田信長""", """の配下の、"""]] snake_case__ : Optional[Any] = tokenizer(snake_case_ , padding=snake_case_ ) snake_case__ : Tuple = tokenizer.batch_encode_plus(snake_case_ , padding=snake_case_ ) # fmt: off snake_case__ : Optional[Any] = [[35_993, 8_640, 25_948, 35_998, 30_647, 35_675, 35_999, 35_999], [35_993, 10_382, 9_868, 35_998, 30_646, 9_459, 30_646, 35_675]] snake_case__ : Optional[Any] = [[1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0]] snake_case__ : Optional[Any] = [[1, 1, 1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1]] # fmt: on self.assertListEqual(x_token.input_ids , snake_case_ ) self.assertListEqual(x_token.token_type_ids , snake_case_ ) self.assertListEqual(x_token.attention_mask , snake_case_ ) self.assertListEqual(x_token_a.input_ids , snake_case_ ) self.assertListEqual(x_token_a.token_type_ids , snake_case_ ) self.assertListEqual(x_token_a.attention_mask , snake_case_ ) def lowerCamelCase ( self : Any ): # Intentionally convert some words to accommodate character fluctuations unique to Japanese pass def lowerCamelCase ( self : List[str] ): # tokenizer has no padding token pass
35
1
"""simple docstring""" from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Tuple = ["image_processor", "tokenizer"] snake_case__ : int = "BridgeTowerImageProcessor" snake_case__ : str = ("RobertaTokenizer", "RobertaTokenizerFast") def __init__( self : int , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[Any] ) -> Tuple: super().__init__(UpperCAmelCase__ , UpperCAmelCase__ ) def __call__( self : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : Union[bool, str, PaddingStrategy] = False , UpperCAmelCase__ : Union[bool, str, TruncationStrategy] = None , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : int = 0 , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : bool = False , UpperCAmelCase__ : bool = False , UpperCAmelCase__ : bool = False , UpperCAmelCase__ : bool = False , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : Optional[Union[str, TensorType]] = None , **UpperCAmelCase__ : int , ) -> BatchEncoding: __SCREAMING_SNAKE_CASE = self.tokenizer( text=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ , padding=UpperCAmelCase__ , truncation=UpperCAmelCase__ , max_length=UpperCAmelCase__ , stride=UpperCAmelCase__ , pad_to_multiple_of=UpperCAmelCase__ , return_token_type_ids=UpperCAmelCase__ , return_attention_mask=UpperCAmelCase__ , return_overflowing_tokens=UpperCAmelCase__ , return_special_tokens_mask=UpperCAmelCase__ , return_offsets_mapping=UpperCAmelCase__ , return_length=UpperCAmelCase__ , verbose=UpperCAmelCase__ , return_tensors=UpperCAmelCase__ , **UpperCAmelCase__ , ) # add pixel_values + pixel_mask __SCREAMING_SNAKE_CASE = self.image_processor( UpperCAmelCase__ , return_tensors=UpperCAmelCase__ , do_normalize=UpperCAmelCase__ , do_center_crop=UpperCAmelCase__ , **UpperCAmelCase__ ) encoding.update(UpperCAmelCase__ ) return encoding def UpperCAmelCase_ ( self : str , *UpperCAmelCase__ : Dict , **UpperCAmelCase__ : Optional[Any] ) -> Optional[int]: return self.tokenizer.batch_decode(*UpperCAmelCase__ , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Any , *UpperCAmelCase__ : Optional[Any] , **UpperCAmelCase__ : List[str] ) -> Union[str, Any]: return self.tokenizer.decode(*UpperCAmelCase__ , **UpperCAmelCase__ ) @property def UpperCAmelCase_ ( self : Optional[int] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.tokenizer.model_input_names __SCREAMING_SNAKE_CASE = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
195
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' return " ".join( "".join(word[::-1] ) if len(lowerCAmelCase_ ) > 4 else word for word in sentence.split() ) if __name__ == "__main__": import doctest doctest.testmod() print(reverse_long_words('''Hey wollef sroirraw'''))
195
1
import copy from dataclasses import dataclass from pathlib import Path from typing import Dict, Optional, Union @dataclass class lowerCAmelCase__ : a__ : Optional[Union[str, Path]] = None a__ : bool = False a__ : bool = False a__ : bool = False a__ : Optional[Dict] = None a__ : Optional[str] = None a__ : bool = False a__ : bool = False a__ : bool = False a__ : bool = True a__ : Optional[int] = None a__ : int = 1 a__ : Optional[Union[str, bool]] = None a__ : bool = False a__ : Optional[Dict] = None a__ : Optional[str] = None def __A ( self : int ) -> "DownloadConfig": return self.__class__(**{k: copy.deepcopy(SCREAMING_SNAKE_CASE__ ) for k, v in self.__dict__.items()} )
270
import pprint import requests SCREAMING_SNAKE_CASE__ : str = "https://zenquotes.io/api" def __magic_name__ ( ) -> list: return requests.get(API_ENDPOINT_URL + '''/today''' ).json() def __magic_name__ ( ) -> list: return requests.get(API_ENDPOINT_URL + '''/random''' ).json() if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : int = random_quotes() pprint.pprint(response)
270
1
import argparse import os # New Code # import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils import find_executable_batch_size ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to ensure out-of-memory errors never # interrupt training, and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## lowerCamelCase_ = 1_6 lowerCamelCase_ = 3_2 def lowerCamelCase ( a_ , a_ = 16 ) -> List[Any]: lowerCAmelCase_ = AutoTokenizer.from_pretrained('bert-base-cased' ) lowerCAmelCase_ = load_dataset('glue' , 'mrpc' ) def tokenize_function(a_ ): # max_length=None => use the model max length (it's actually the default) lowerCAmelCase_ = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=a_ , max_length=a_ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): lowerCAmelCase_ = datasets.map( a_ , batched=a_ , remove_columns=['idx', 'sentence1', 'sentence2'] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library lowerCAmelCase_ = tokenized_datasets.rename_column('label' , 'labels' ) def collate_fn(a_ ): # On TPU it's best to pad everything to the same length or training will be very slow. lowerCAmelCase_ = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": lowerCAmelCase_ = 16 elif accelerator.mixed_precision != "no": lowerCAmelCase_ = 8 else: lowerCAmelCase_ = None return tokenizer.pad( a_ , padding='longest' , max_length=a_ , pad_to_multiple_of=a_ , return_tensors='pt' , ) # Instantiate dataloaders. lowerCAmelCase_ = DataLoader( tokenized_datasets['train'] , shuffle=a_ , collate_fn=a_ , batch_size=a_ ) lowerCAmelCase_ = DataLoader( tokenized_datasets['validation'] , shuffle=a_ , collate_fn=a_ , batch_size=a_ ) return train_dataloader, eval_dataloader # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""", None) == "1": from accelerate.test_utils.training import mocked_dataloaders lowerCamelCase_ = mocked_dataloaders # noqa: F811 def lowerCamelCase ( a_ , a_ ) -> List[Any]: # For testing only if os.environ.get('TESTING_MOCKED_DATALOADERS' , a_ ) == "1": lowerCAmelCase_ = 2 # Initialize accelerator lowerCAmelCase_ = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs lowerCAmelCase_ = config['lr'] lowerCAmelCase_ = int(config['num_epochs'] ) lowerCAmelCase_ = int(config['seed'] ) lowerCAmelCase_ = int(config['batch_size'] ) lowerCAmelCase_ = evaluate.load('glue' , 'mrpc' ) # New Code # # We now can define an inner training loop function. It should take a batch size as the only parameter, # and build the dataloaders in there. # It also gets our decorator @find_executable_batch_size(starting_batch_size=a_ ) def inner_training_loop(a_ ): # And now just move everything below under this function # We need to bring in the Accelerator object from earlier nonlocal accelerator # And reset all of its attributes that could hold onto any memory: accelerator.free_memory() # Then we can declare the model, optimizer, and everything else: set_seed(a_ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) lowerCAmelCase_ = AutoModelForSequenceClassification.from_pretrained('bert-base-cased' , return_dict=a_ ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). lowerCAmelCase_ = model.to(accelerator.device ) # Instantiate optimizer lowerCAmelCase_ = AdamW(params=model.parameters() , lr=a_ ) lowerCAmelCase_ , lowerCAmelCase_ = get_dataloaders(a_ , a_ ) # Instantiate scheduler lowerCAmelCase_ = get_linear_schedule_with_warmup( optimizer=a_ , num_warmup_steps=100 , num_training_steps=(len(a_ ) * num_epochs) , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = accelerator.prepare( a_ , a_ , a_ , a_ , a_ ) # Now we train the model for epoch in range(a_ ): model.train() for step, batch in enumerate(a_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) lowerCAmelCase_ = model(**a_ ) lowerCAmelCase_ = outputs.loss accelerator.backward(a_ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(a_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): lowerCAmelCase_ = model(**a_ ) lowerCAmelCase_ = outputs.logits.argmax(dim=-1 ) lowerCAmelCase_ , lowerCAmelCase_ = accelerator.gather_for_metrics((predictions, batch['labels']) ) metric.add_batch( predictions=a_ , references=a_ , ) lowerCAmelCase_ = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'''epoch {epoch}:''' , a_ ) # New Code # # And call it at the end with no arguments # Note: You could also refactor this outside of your training loop function inner_training_loop() def lowerCamelCase ( ) -> List[str]: lowerCAmelCase_ = argparse.ArgumentParser(description='Simple example of training script.' ) parser.add_argument( '--mixed_precision' , type=a_ , default=a_ , choices=['no', 'fp16', 'bf16', 'fp8'] , help='Whether to use mixed precision. Choose' 'between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.' 'and an Nvidia Ampere GPU.' , ) parser.add_argument('--cpu' , action='store_true' , help='If passed, will train on the CPU.' ) lowerCAmelCase_ = parser.parse_args() lowerCAmelCase_ = {'lr': 2e-5, 'num_epochs': 3, 'seed': 42, 'batch_size': 16} training_function(a_ , a_ ) if __name__ == "__main__": main()
14
from math import acos, sin from typing import List, Tuple, Union import numpy as np import torch from PIL import Image from ...models import AutoencoderKL, UNetaDConditionModel from ...schedulers import DDIMScheduler, DDPMScheduler from ...utils import randn_tensor from ..pipeline_utils import AudioPipelineOutput, BaseOutput, DiffusionPipeline, ImagePipelineOutput from .mel import Mel class a_ ( a_ ): '''simple docstring''' __a: str = ['''vqvae'''] def __init__( self , lowercase_ , lowercase_ , lowercase_ , lowercase_ , ) -> Tuple: '''simple docstring''' super().__init__() self.register_modules(unet=lowercase_ , scheduler=lowercase_ , mel=lowercase_ , vqvae=lowercase_ ) def _lowercase ( self ) -> int: '''simple docstring''' return 5_0 if isinstance(self.scheduler , lowercase_ ) else 1_0_0_0 @torch.no_grad() def __call__( self , lowercase_ = 1 , lowercase_ = None , lowercase_ = None , lowercase_ = 0 , lowercase_ = 0 , lowercase_ = None , lowercase_ = None , lowercase_ = 0 , lowercase_ = 0 , lowercase_ = None , lowercase_ = 0 , lowercase_ = None , lowercase_ = None , lowercase_=True , ) -> Union[ Union[AudioPipelineOutput, ImagePipelineOutput], Tuple[List[Image.Image], Tuple[int, List[np.ndarray]]], ]: '''simple docstring''' lowerCAmelCase_ = steps or self.get_default_steps() self.scheduler.set_timesteps(lowercase_ ) lowerCAmelCase_ = step_generator or generator # For backwards compatibility if type(self.unet.config.sample_size ) == int: lowerCAmelCase_ = (self.unet.config.sample_size, self.unet.config.sample_size) if noise is None: lowerCAmelCase_ = randn_tensor( ( batch_size, self.unet.config.in_channels, self.unet.config.sample_size[0], self.unet.config.sample_size[1], ) , generator=lowercase_ , device=self.device , ) lowerCAmelCase_ = noise lowerCAmelCase_ = None if audio_file is not None or raw_audio is not None: self.mel.load_audio(lowercase_ , lowercase_ ) lowerCAmelCase_ = self.mel.audio_slice_to_image(lowercase_ ) lowerCAmelCase_ = np.frombuffer(input_image.tobytes() , dtype='uint8' ).reshape( (input_image.height, input_image.width) ) lowerCAmelCase_ = (input_image / 2_5_5) * 2 - 1 lowerCAmelCase_ = torch.tensor(input_image[np.newaxis, :, :] , dtype=torch.float ).to(self.device ) if self.vqvae is not None: lowerCAmelCase_ = self.vqvae.encode(torch.unsqueeze(lowercase_ , 0 ) ).latent_dist.sample( generator=lowercase_ )[0] lowerCAmelCase_ = self.vqvae.config.scaling_factor * input_images if start_step > 0: lowerCAmelCase_ = self.scheduler.add_noise(lowercase_ , lowercase_ , self.scheduler.timesteps[start_step - 1] ) lowerCAmelCase_ = ( self.unet.config.sample_size[1] * self.mel.get_sample_rate() / self.mel.x_res / self.mel.hop_length ) lowerCAmelCase_ = int(mask_start_secs * pixels_per_second ) lowerCAmelCase_ = int(mask_end_secs * pixels_per_second ) lowerCAmelCase_ = self.scheduler.add_noise(lowercase_ , lowercase_ , torch.tensor(self.scheduler.timesteps[start_step:] ) ) for step, t in enumerate(self.progress_bar(self.scheduler.timesteps[start_step:] ) ): if isinstance(self.unet , lowercase_ ): lowerCAmelCase_ = self.unet(lowercase_ , lowercase_ , lowercase_ )['sample'] else: lowerCAmelCase_ = self.unet(lowercase_ , lowercase_ )['sample'] if isinstance(self.scheduler , lowercase_ ): lowerCAmelCase_ = self.scheduler.step( model_output=lowercase_ , timestep=lowercase_ , sample=lowercase_ , eta=lowercase_ , generator=lowercase_ , )['prev_sample'] else: lowerCAmelCase_ = self.scheduler.step( model_output=lowercase_ , timestep=lowercase_ , sample=lowercase_ , generator=lowercase_ , )['prev_sample'] if mask is not None: if mask_start > 0: lowerCAmelCase_ = mask[:, step, :, :mask_start] if mask_end > 0: lowerCAmelCase_ = mask[:, step, :, -mask_end:] if self.vqvae is not None: # 0.18215 was scaling factor used in training to ensure unit variance lowerCAmelCase_ = 1 / self.vqvae.config.scaling_factor * images lowerCAmelCase_ = self.vqvae.decode(lowercase_ )['sample'] lowerCAmelCase_ = (images / 2 + 0.5).clamp(0 , 1 ) lowerCAmelCase_ = images.cpu().permute(0 , 2 , 3 , 1 ).numpy() lowerCAmelCase_ = (images * 2_5_5).round().astype('uint8' ) lowerCAmelCase_ = list( (Image.fromarray(_[:, :, 0] ) for _ in images) if images.shape[3] == 1 else (Image.fromarray(lowercase_ , mode='RGB' ).convert('L' ) for _ in images) ) lowerCAmelCase_ = [self.mel.image_to_audio(lowercase_ ) for _ in images] if not return_dict: return images, (self.mel.get_sample_rate(), audios) return BaseOutput(**AudioPipelineOutput(np.array(lowercase_ )[:, np.newaxis, :] ) , **ImagePipelineOutput(lowercase_ ) ) @torch.no_grad() def _lowercase ( self , lowercase_ , lowercase_ = 5_0 ) -> np.ndarray: '''simple docstring''' assert isinstance(self.scheduler , lowercase_ ) self.scheduler.set_timesteps(lowercase_ ) lowerCAmelCase_ = np.array( [np.frombuffer(image.tobytes() , dtype='uint8' ).reshape((1, image.height, image.width) ) for image in images] ) lowerCAmelCase_ = (sample / 2_5_5) * 2 - 1 lowerCAmelCase_ = torch.Tensor(lowercase_ ).to(self.device ) for t in self.progress_bar(torch.flip(self.scheduler.timesteps , (0,) ) ): lowerCAmelCase_ = t - self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps lowerCAmelCase_ = self.scheduler.alphas_cumprod[t] lowerCAmelCase_ = ( self.scheduler.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.scheduler.final_alpha_cumprod ) lowerCAmelCase_ = 1 - alpha_prod_t lowerCAmelCase_ = self.unet(lowercase_ , lowercase_ )['sample'] lowerCAmelCase_ = (1 - alpha_prod_t_prev) ** 0.5 * model_output lowerCAmelCase_ = (sample - pred_sample_direction) * alpha_prod_t_prev ** (-0.5) lowerCAmelCase_ = sample * alpha_prod_t ** 0.5 + beta_prod_t ** 0.5 * model_output return sample @staticmethod def _lowercase ( lowercase_ , lowercase_ , lowercase_ ) -> torch.Tensor: '''simple docstring''' lowerCAmelCase_ = acos(torch.dot(torch.flatten(lowercase_ ) , torch.flatten(lowercase_ ) ) / torch.norm(lowercase_ ) / torch.norm(lowercase_ ) ) return sin((1 - alpha) * theta ) * xa / sin(lowercase_ ) + sin(alpha * theta ) * xa / sin(lowercase_ )
14
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) __lowerCAmelCase : Any ={ 'configuration_vision_encoder_decoder': ['VisionEncoderDecoderConfig', 'VisionEncoderDecoderOnnxConfig'] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase : Union[str, Any] =['VisionEncoderDecoderModel'] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase : List[Any] =['TFVisionEncoderDecoderModel'] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase : Tuple =['FlaxVisionEncoderDecoderModel'] if TYPE_CHECKING: from .configuration_vision_encoder_decoder import VisionEncoderDecoderConfig, VisionEncoderDecoderOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vision_encoder_decoder import VisionEncoderDecoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vision_encoder_decoder import TFVisionEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_vision_encoder_decoder import FlaxVisionEncoderDecoderModel else: import sys __lowerCAmelCase : Dict =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
9
__lowerCamelCase : List[Any] = 6_5521 def __SCREAMING_SNAKE_CASE ( __UpperCamelCase : str ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = 1 SCREAMING_SNAKE_CASE__ = 0 for plain_chr in plain_text: SCREAMING_SNAKE_CASE__ = (a + ord(__UpperCamelCase )) % MOD_ADLER SCREAMING_SNAKE_CASE__ = (b + a) % MOD_ADLER return (b << 16) | a
219
0
'''simple docstring''' import unittest import numpy as np from transformers import is_flax_available from transformers.testing_utils import require_flax from ..test_modeling_flax_common import ids_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.generation import ( FlaxForcedBOSTokenLogitsProcessor, FlaxForcedEOSTokenLogitsProcessor, FlaxLogitsProcessorList, FlaxMinLengthLogitsProcessor, FlaxTemperatureLogitsWarper, FlaxTopKLogitsWarper, FlaxTopPLogitsWarper, ) @require_flax class a__ ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self : List[str] , a : int , a : int ): """simple docstring""" __lowerCamelCase = jnp.ones((batch_size, length) ) / length return scores def SCREAMING_SNAKE_CASE__ ( self : List[str] ): """simple docstring""" __lowerCamelCase = None __lowerCamelCase = 20 __lowerCamelCase = self._get_uniform_logits(batch_size=2 , length=lowerCAmelCase__ ) # tweak scores to not be uniform anymore __lowerCamelCase = scores.at[1, 5].set((1 / length) + 0.1 ) # peak, 1st batch __lowerCamelCase = scores.at[1, 10].set((1 / length) - 0.4 ) # valley, 1st batch # compute softmax __lowerCamelCase = jax.nn.softmax(lowerCAmelCase__ , axis=-1 ) __lowerCamelCase = FlaxTemperatureLogitsWarper(temperature=0.5 ) __lowerCamelCase = FlaxTemperatureLogitsWarper(temperature=1.3 ) __lowerCamelCase = jax.nn.softmax(temp_dist_warper_sharper(lowerCAmelCase__ , scores.copy() , cur_len=lowerCAmelCase__ ) , axis=-1 ) __lowerCamelCase = jax.nn.softmax(temp_dist_warper_smoother(lowerCAmelCase__ , scores.copy() , cur_len=lowerCAmelCase__ ) , axis=-1 ) # uniform distribution stays uniform self.assertTrue(jnp.allclose(probs[0, :] , warped_prob_sharp[0, :] , atol=1e-3 ) ) self.assertTrue(jnp.allclose(probs[0, :] , warped_prob_smooth[0, :] , atol=1e-3 ) ) # sharp peaks get higher, valleys get lower self.assertLess(probs[1, :].max() , warped_prob_sharp[1, :].max() ) self.assertGreater(probs[1, :].min() , warped_prob_sharp[1, :].min() ) # smooth peaks get lower, valleys get higher self.assertGreater(probs[1, :].max() , warped_prob_smooth[1, :].max() ) self.assertLess(probs[1, :].min() , warped_prob_smooth[1, :].min() ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): """simple docstring""" __lowerCamelCase = None __lowerCamelCase = 10 __lowerCamelCase = 2 # create ramp distribution __lowerCamelCase = np.broadcast_to(np.arange(lowerCAmelCase__ )[None, :] , (batch_size, vocab_size) ).copy() __lowerCamelCase = ramp_logits[1:, : vocab_size // 2] + vocab_size __lowerCamelCase = FlaxTopKLogitsWarper(3 ) __lowerCamelCase = top_k_warp(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) # check that correct tokens are filtered self.assertListEqual(jnp.isinf(scores[0] ).tolist() , 7 * [True] + 3 * [False] ) self.assertListEqual(jnp.isinf(scores[1] ).tolist() , 2 * [True] + 3 * [False] + 5 * [True] ) # check special case __lowerCamelCase = 5 __lowerCamelCase = FlaxTopKLogitsWarper(top_k=1 , filter_value=0.0 , min_tokens_to_keep=3 ) __lowerCamelCase = np.broadcast_to(np.arange(lowerCAmelCase__ )[None, :] , (batch_size, length) ).copy() __lowerCamelCase = top_k_warp_safety_check(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) # min_tokens overwrites k: 3 tokens are kept => 2 tokens are nullified self.assertListEqual((scores == 0.0).sum(axis=-1 ).tolist() , [2, 2] ) def SCREAMING_SNAKE_CASE__ ( self : List[str] ): """simple docstring""" __lowerCamelCase = None __lowerCamelCase = 10 __lowerCamelCase = 2 # create distribution and take log (inverse to Softmax as taken in TopPLogitsWarper) __lowerCamelCase = np.log(np.array([[0.3, 0.1, 0.1, 0.5], [0.15, 0.3, 0.3, 0.25]] ) ) __lowerCamelCase = FlaxTopPLogitsWarper(0.8 ) __lowerCamelCase = np.exp(top_p_warp(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) ) # dist should be filtered to keep min num values so that sum is >= top_p # exp (-inf) => 0 __lowerCamelCase = np.array([[0.3, 0.0, 0.0, 0.5], [0.0, 0.3, 0.3, 0.25]] ) self.assertTrue(np.allclose(lowerCAmelCase__ , lowerCAmelCase__ , atol=1e-3 ) ) # check edge cases with negative and extreme logits __lowerCamelCase = np.broadcast_to(np.arange(lowerCAmelCase__ )[None, :] , (batch_size, vocab_size) ).copy() - ( vocab_size // 2 ) # make ramp_logits more extreme __lowerCamelCase = ramp_logits[1] * 1_00.0 # make sure at least 2 tokens are kept __lowerCamelCase = FlaxTopPLogitsWarper(0.9 , min_tokens_to_keep=2 , filter_value=0.0 ) __lowerCamelCase = top_p_warp(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) # first batch should keep three tokens, second batch would keep only 1, but due to `min_tokens_to_keep=2` keeps 2. self.assertListEqual((filtered_dist != 0.0).sum(axis=-1 ).tolist() , [3, 2] ) def SCREAMING_SNAKE_CASE__ ( self : Any ): """simple docstring""" __lowerCamelCase = 20 __lowerCamelCase = 4 __lowerCamelCase = 0 __lowerCamelCase = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=lowerCAmelCase__ ) # check that min length is applied at length 5 __lowerCamelCase = ids_tensor((batch_size, 20) , vocab_size=20 ) __lowerCamelCase = 5 __lowerCamelCase = self._get_uniform_logits(lowerCAmelCase__ , lowerCAmelCase__ ) __lowerCamelCase = min_dist_processor(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) self.assertListEqual(scores_before_min_length[:, eos_token_id].tolist() , 4 * [-float('''inf''' )] ) # check that min length is not applied anymore at length 15 __lowerCamelCase = self._get_uniform_logits(lowerCAmelCase__ , lowerCAmelCase__ ) __lowerCamelCase = 15 __lowerCamelCase = min_dist_processor(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) self.assertFalse(jnp.isinf(lowerCAmelCase__ ).any() ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] ): """simple docstring""" __lowerCamelCase = 20 __lowerCamelCase = 4 __lowerCamelCase = 0 __lowerCamelCase = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=lowerCAmelCase__ ) # check that all scores are -inf except the bos_token_id score __lowerCamelCase = ids_tensor((batch_size, 1) , vocab_size=20 ) __lowerCamelCase = 1 __lowerCamelCase = self._get_uniform_logits(lowerCAmelCase__ , lowerCAmelCase__ ) __lowerCamelCase = logits_processor(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) self.assertTrue(jnp.isneginf(scores[:, bos_token_id + 1 :] ).all() ) self.assertListEqual(scores[:, bos_token_id].tolist() , 4 * [0] ) # score for bos_token_id shold be zero # check that bos_token_id is not forced if current length is greater than 1 __lowerCamelCase = 3 __lowerCamelCase = self._get_uniform_logits(lowerCAmelCase__ , lowerCAmelCase__ ) __lowerCamelCase = logits_processor(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) self.assertFalse(jnp.isinf(lowerCAmelCase__ ).any() ) def SCREAMING_SNAKE_CASE__ ( self : int ): """simple docstring""" __lowerCamelCase = 20 __lowerCamelCase = 4 __lowerCamelCase = 0 __lowerCamelCase = 5 __lowerCamelCase = FlaxForcedEOSTokenLogitsProcessor(max_length=lowerCAmelCase__ , eos_token_id=lowerCAmelCase__ ) # check that all scores are -inf except the eos_token_id when max_length is reached __lowerCamelCase = ids_tensor((batch_size, 4) , vocab_size=20 ) __lowerCamelCase = 4 __lowerCamelCase = self._get_uniform_logits(lowerCAmelCase__ , lowerCAmelCase__ ) __lowerCamelCase = logits_processor(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) self.assertTrue(jnp.isneginf(scores[:, eos_token_id + 1 :] ).all() ) self.assertListEqual(scores[:, eos_token_id].tolist() , 4 * [0] ) # score for eos_token_id should be zero # check that eos_token_id is not forced if max_length is not reached __lowerCamelCase = 3 __lowerCamelCase = self._get_uniform_logits(lowerCAmelCase__ , lowerCAmelCase__ ) __lowerCamelCase = logits_processor(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) self.assertFalse(jnp.isinf(lowerCAmelCase__ ).any() ) def SCREAMING_SNAKE_CASE__ ( self : Dict ): """simple docstring""" __lowerCamelCase = 4 __lowerCamelCase = 10 __lowerCamelCase = 15 __lowerCamelCase = 2 __lowerCamelCase = 1 __lowerCamelCase = 15 # dummy input_ids and scores __lowerCamelCase = ids_tensor((batch_size, sequence_length) , lowerCAmelCase__ ) __lowerCamelCase = input_ids.copy() __lowerCamelCase = self._get_uniform_logits(lowerCAmelCase__ , lowerCAmelCase__ ) __lowerCamelCase = scores.copy() # instantiate all dist processors __lowerCamelCase = FlaxTemperatureLogitsWarper(temperature=0.5 ) __lowerCamelCase = FlaxTopKLogitsWarper(3 ) __lowerCamelCase = FlaxTopPLogitsWarper(0.8 ) # instantiate all logits processors __lowerCamelCase = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=lowerCAmelCase__ ) __lowerCamelCase = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=lowerCAmelCase__ ) __lowerCamelCase = FlaxForcedEOSTokenLogitsProcessor(max_length=lowerCAmelCase__ , eos_token_id=lowerCAmelCase__ ) __lowerCamelCase = 10 # no processor list __lowerCamelCase = temp_dist_warp(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) __lowerCamelCase = top_k_warp(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) __lowerCamelCase = top_p_warp(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) __lowerCamelCase = min_dist_proc(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) __lowerCamelCase = bos_dist_proc(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) __lowerCamelCase = eos_dist_proc(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) # with processor list __lowerCamelCase = FlaxLogitsProcessorList( [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc] ) __lowerCamelCase = processor(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) # scores should be equal self.assertTrue(jnp.allclose(lowerCAmelCase__ , lowerCAmelCase__ , atol=1e-3 ) ) # input_ids should never be changed self.assertListEqual(input_ids.tolist() , input_ids_comp.tolist() ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): """simple docstring""" __lowerCamelCase = 4 __lowerCamelCase = 10 __lowerCamelCase = 15 __lowerCamelCase = 2 __lowerCamelCase = 1 __lowerCamelCase = 15 # dummy input_ids and scores __lowerCamelCase = ids_tensor((batch_size, sequence_length) , lowerCAmelCase__ ) __lowerCamelCase = input_ids.copy() __lowerCamelCase = self._get_uniform_logits(lowerCAmelCase__ , lowerCAmelCase__ ) __lowerCamelCase = scores.copy() # instantiate all dist processors __lowerCamelCase = FlaxTemperatureLogitsWarper(temperature=0.5 ) __lowerCamelCase = FlaxTopKLogitsWarper(3 ) __lowerCamelCase = FlaxTopPLogitsWarper(0.8 ) # instantiate all logits processors __lowerCamelCase = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=lowerCAmelCase__ ) __lowerCamelCase = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=lowerCAmelCase__ ) __lowerCamelCase = FlaxForcedEOSTokenLogitsProcessor(max_length=lowerCAmelCase__ , eos_token_id=lowerCAmelCase__ ) __lowerCamelCase = 10 # no processor list def run_no_processor_list(a : Dict , a : int , a : Optional[int] ): __lowerCamelCase = temp_dist_warp(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) __lowerCamelCase = top_k_warp(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) __lowerCamelCase = top_p_warp(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) __lowerCamelCase = min_dist_proc(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) __lowerCamelCase = bos_dist_proc(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) __lowerCamelCase = eos_dist_proc(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) return scores # with processor list def run_processor_list(a : str , a : str , a : List[str] ): __lowerCamelCase = FlaxLogitsProcessorList( [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc] ) __lowerCamelCase = processor(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) return scores __lowerCamelCase = jax.jit(lowerCAmelCase__ ) __lowerCamelCase = jax.jit(lowerCAmelCase__ ) __lowerCamelCase = jitted_run_no_processor_list(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) __lowerCamelCase = jitted_run_processor_list(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # scores should be equal self.assertTrue(jnp.allclose(lowerCAmelCase__ , lowerCAmelCase__ , atol=1e-3 ) ) # input_ids should never be changed self.assertListEqual(input_ids.tolist() , input_ids_comp.tolist() )
367
'''simple docstring''' from __future__ import annotations from typing import Any def __lowerCAmelCase ( UpperCamelCase__ ) -> None: create_state_space_tree(UpperCamelCase__ , [] , 0 ) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> None: if index == len(UpperCamelCase__ ): print(UpperCamelCase__ ) return create_state_space_tree(UpperCamelCase__ , UpperCamelCase__ , index + 1 ) current_subsequence.append(sequence[index] ) create_state_space_tree(UpperCamelCase__ , UpperCamelCase__ , index + 1 ) current_subsequence.pop() if __name__ == "__main__": __UpperCAmelCase =[3, 1, 2, 4] generate_all_subsequences(seq) seq.clear() seq.extend(["A", "B", "C"]) generate_all_subsequences(seq)
237
0
import os import random import sys from . import cryptomath_module as cryptomath from . import rabin_miller UpperCamelCase = 3 def lowercase_ ( _lowerCamelCase : int): print("Generating primitive root of p") while True: lowercase__ : str = random.randrange(3 , _lowerCamelCase) if pow(_lowerCamelCase , 2 , _lowerCamelCase) == 1: continue if pow(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase) == 1: continue return g def lowercase_ ( _lowerCamelCase : int): print("Generating prime p...") lowercase__ : Optional[Any] = rabin_miller.generate_large_prime(_lowerCamelCase) # select large prime number. lowercase__ : int = primitive_root(_lowerCamelCase) # one primitive root on modulo p. lowercase__ : str = random.randrange(3 , _lowerCamelCase) # private_key -> have to be greater than 2 for safety. lowercase__ : List[Any] = cryptomath.find_mod_inverse(pow(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase) , _lowerCamelCase) lowercase__ : Optional[Any] = (key_size, e_a, e_a, p) lowercase__ : Any = (key_size, d) return public_key, private_key def lowercase_ ( _lowerCamelCase : str , _lowerCamelCase : int): if os.path.exists(f'''{name}_pubkey.txt''') or os.path.exists(f'''{name}_privkey.txt'''): print("\nWARNING:") print( f'''"{name}_pubkey.txt" or "{name}_privkey.txt" already exists. \n''' "Use a different name or delete these files and re-run this program.") sys.exit() lowercase__ , lowercase__ : Union[str, Any] = generate_key(_lowerCamelCase) print(f'''\nWriting public key to file {name}_pubkey.txt...''') with open(f'''{name}_pubkey.txt''' , "w") as fo: fo.write(f'''{public_key[0]},{public_key[1]},{public_key[2]},{public_key[3]}''') print(f'''Writing private key to file {name}_privkey.txt...''') with open(f'''{name}_privkey.txt''' , "w") as fo: fo.write(f'''{private_key[0]},{private_key[1]}''') def lowercase_ ( ): print("Making key files...") make_key_files("elgamal" , 2048) print("Key files generation successful") if __name__ == "__main__": main()
87
UpperCamelCase = [0, 2, 4, 6, 8] UpperCamelCase = [1, 3, 5, 7, 9] def lowercase_ ( _lowerCamelCase : int , _lowerCamelCase : int , _lowerCamelCase : list[int] , _lowerCamelCase : int): if remaining_length == 0: if digits[0] == 0 or digits[-1] == 0: return 0 for i in range(length // 2 - 1 , -1 , -1): remainder += digits[i] + digits[length - i - 1] if remainder % 2 == 0: return 0 remainder //= 10 return 1 if remaining_length == 1: if remainder % 2 == 0: return 0 lowercase__ : str = 0 for digit in range(10): lowercase__ : str = digit result += reversible_numbers( 0 , (remainder + 2 * digit) // 10 , _lowerCamelCase , _lowerCamelCase) return result lowercase__ : Dict = 0 for digita in range(10): lowercase__ : int = digita if (remainder + digita) % 2 == 0: lowercase__ : Optional[Any] = ODD_DIGITS else: lowercase__ : str = EVEN_DIGITS for digita in other_parity_digits: lowercase__ : List[str] = digita result += reversible_numbers( remaining_length - 2 , (remainder + digita + digita) // 10 , _lowerCamelCase , _lowerCamelCase , ) return result def lowercase_ ( _lowerCamelCase : int = 9): lowercase__ : Tuple = 0 for length in range(1 , max_power + 1): result += reversible_numbers(_lowerCamelCase , 0 , [0] * length , _lowerCamelCase) return result if __name__ == "__main__": print(f"{solution() = }")
87
1
import random def __UpperCamelCase ( _lowerCAmelCase ) -> bool: """simple docstring""" A : Dict = num - 1 A : List[Any] = 0 while s % 2 == 0: A : Tuple = s // 2 t += 1 for _ in range(5 ): A : Any = random.randrange(2 , num - 1 ) A : int = pow(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) if v != 1: A : Tuple = 0 while v != (num - 1): if i == t - 1: return False else: A : Optional[Any] = i + 1 A : Union[str, Any] = (v**2) % num return True def __UpperCamelCase ( _lowerCAmelCase ) -> bool: """simple docstring""" if num < 2: return False A : Dict = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, ] if num in low_primes: return True for prime in low_primes: if (num % prime) == 0: return False return rabin_miller(_lowerCAmelCase ) def __UpperCamelCase ( _lowerCAmelCase = 1024 ) -> int: """simple docstring""" while True: A : Optional[int] = random.randrange(2 ** (keysize - 1) , 2 ** (keysize) ) if is_prime_low_num(_lowerCAmelCase ): return num if __name__ == "__main__": SCREAMING_SNAKE_CASE_:Optional[int] = generate_large_prime() print(("""Prime number:""", num)) print(("""is_prime_low_num:""", is_prime_low_num(num)))
115
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import BertTokenizer, BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import FEATURE_EXTRACTOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor, ChineseCLIPProcessor @require_vision class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): '''simple docstring''' def _lowerCAmelCase ( self ): A : str = tempfile.mkdtemp() A : Any = [ """[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """的""", """价""", """格""", """是""", """15""", """便""", """alex""", """##andra""", """,""", """。""", """-""", """t""", """shirt""", ] A : Any = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file, """w""", encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) A : Any = { """do_resize""": True, """size""": {"""height""": 224, """width""": 224}, """do_center_crop""": True, """crop_size""": {"""height""": 18, """width""": 18}, """do_normalize""": True, """image_mean""": [0.4814_5466, 0.457_8275, 0.4082_1073], """image_std""": [0.2686_2954, 0.2613_0258, 0.2757_7711], """do_convert_rgb""": True, } A : int = os.path.join(self.tmpdirname, lowerCamelCase__ ) with open(self.image_processor_file, """w""", encoding="""utf-8""" ) as fp: json.dump(lowerCamelCase__, lowerCamelCase__ ) def _lowerCAmelCase ( self, **lowerCamelCase__ ): return BertTokenizer.from_pretrained(self.tmpdirname, **lowerCamelCase__ ) def _lowerCAmelCase ( self, **lowerCamelCase__ ): return BertTokenizerFast.from_pretrained(self.tmpdirname, **lowerCamelCase__ ) def _lowerCAmelCase ( self, **lowerCamelCase__ ): return ChineseCLIPImageProcessor.from_pretrained(self.tmpdirname, **lowerCamelCase__ ) def _lowerCAmelCase ( self ): shutil.rmtree(self.tmpdirname ) def _lowerCAmelCase ( self ): A : Optional[int] = [np.random.randint(255, size=(3, 30, 400), dtype=np.uinta )] A : List[Any] = [Image.fromarray(np.moveaxis(lowerCamelCase__, 0, -1 ) ) for x in image_inputs] return image_inputs def _lowerCAmelCase ( self ): A : List[Any] = self.get_tokenizer() A : Dict = self.get_rust_tokenizer() A : List[Any] = self.get_image_processor() A : int = ChineseCLIPProcessor(tokenizer=lowerCamelCase__, image_processor=lowerCamelCase__ ) processor_slow.save_pretrained(self.tmpdirname ) A : Optional[Any] = ChineseCLIPProcessor.from_pretrained(self.tmpdirname, use_fast=lowerCamelCase__ ) A : str = ChineseCLIPProcessor(tokenizer=lowerCamelCase__, image_processor=lowerCamelCase__ ) processor_fast.save_pretrained(self.tmpdirname ) A : Tuple = ChineseCLIPProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab(), tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab(), tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab(), tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer, lowerCamelCase__ ) self.assertIsInstance(processor_fast.tokenizer, lowerCamelCase__ ) self.assertEqual(processor_slow.image_processor.to_json_string(), image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string(), image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor, lowerCamelCase__ ) self.assertIsInstance(processor_fast.image_processor, lowerCamelCase__ ) def _lowerCAmelCase ( self ): A : str = ChineseCLIPProcessor(tokenizer=self.get_tokenizer(), image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) A : Optional[int] = self.get_tokenizer(cls_token="""(CLS)""", sep_token="""(SEP)""" ) A : Optional[int] = self.get_image_processor(do_normalize=lowerCamelCase__ ) A : Optional[int] = ChineseCLIPProcessor.from_pretrained( self.tmpdirname, cls_token="""(CLS)""", sep_token="""(SEP)""", do_normalize=lowerCamelCase__ ) self.assertEqual(processor.tokenizer.get_vocab(), tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer, lowerCamelCase__ ) self.assertEqual(processor.image_processor.to_json_string(), image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor, lowerCamelCase__ ) def _lowerCAmelCase ( self ): A : Tuple = self.get_image_processor() A : List[str] = self.get_tokenizer() A : List[str] = ChineseCLIPProcessor(tokenizer=lowerCamelCase__, image_processor=lowerCamelCase__ ) A : Any = self.prepare_image_inputs() A : Union[str, Any] = image_processor(lowerCamelCase__, return_tensors="""np""" ) A : str = processor(images=lowerCamelCase__, return_tensors="""np""" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum(), input_processor[key].sum(), delta=1e-2 ) def _lowerCAmelCase ( self ): A : List[str] = self.get_image_processor() A : Tuple = self.get_tokenizer() A : str = ChineseCLIPProcessor(tokenizer=lowerCamelCase__, image_processor=lowerCamelCase__ ) A : Any = """Alexandra,T-shirt的价格是15便士。""" A : Optional[Any] = processor(text=lowerCamelCase__ ) A : int = tokenizer(lowerCamelCase__ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key], encoded_processor[key] ) def _lowerCAmelCase ( self ): A : Dict = self.get_image_processor() A : List[str] = self.get_tokenizer() A : int = ChineseCLIPProcessor(tokenizer=lowerCamelCase__, image_processor=lowerCamelCase__ ) A : str = """Alexandra,T-shirt的价格是15便士。""" A : Dict = self.prepare_image_inputs() A : Optional[int] = processor(text=lowerCamelCase__, images=lowerCamelCase__ ) self.assertListEqual(list(inputs.keys() ), ["""input_ids""", """token_type_ids""", """attention_mask""", """pixel_values"""] ) # test if it raises when no input is passed with pytest.raises(lowerCamelCase__ ): processor() def _lowerCAmelCase ( self ): A : Union[str, Any] = self.get_image_processor() A : List[str] = self.get_tokenizer() A : List[str] = ChineseCLIPProcessor(tokenizer=lowerCamelCase__, image_processor=lowerCamelCase__ ) A : int = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] A : List[Any] = processor.batch_decode(lowerCamelCase__ ) A : str = tokenizer.batch_decode(lowerCamelCase__ ) self.assertListEqual(lowerCamelCase__, lowerCamelCase__ ) def _lowerCAmelCase ( self ): A : List[str] = self.get_image_processor() A : List[str] = self.get_tokenizer() A : Any = ChineseCLIPProcessor(tokenizer=lowerCamelCase__, image_processor=lowerCamelCase__ ) A : List[Any] = """Alexandra,T-shirt的价格是15便士。""" A : Optional[Any] = self.prepare_image_inputs() A : str = processor(text=lowerCamelCase__, images=lowerCamelCase__ ) self.assertListEqual(list(inputs.keys() ), processor.model_input_names )
115
1
'''simple docstring''' # DISCLAIMER: This file is strongly influenced by https://github.com/ermongroup/ddim from dataclasses import dataclass from typing import Optional, Tuple, Union import flax import jax import jax.numpy as jnp from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils_flax import ( CommonSchedulerState, FlaxKarrasDiffusionSchedulers, FlaxSchedulerMixin, FlaxSchedulerOutput, add_noise_common, get_velocity_common, ) @flax.struct.dataclass class lowerCAmelCase__ : lowerCAmelCase_ = 42 # setable values lowerCAmelCase_ = 42 lowerCAmelCase_ = 42 lowerCAmelCase_ = None @classmethod def _snake_case ( cls , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" return cls(common=__SCREAMING_SNAKE_CASE , init_noise_sigma=__SCREAMING_SNAKE_CASE , timesteps=__SCREAMING_SNAKE_CASE ) @dataclass class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = 42 class lowerCAmelCase__ ( lowerCamelCase_ , lowerCamelCase_ ): lowerCAmelCase_ = [e.name for e in FlaxKarrasDiffusionSchedulers] lowerCAmelCase_ = 42 @property def _snake_case ( self ): """simple docstring""" return True @register_to_config def __init__( self , __SCREAMING_SNAKE_CASE = 10_00 , __SCREAMING_SNAKE_CASE = 0.0_001 , __SCREAMING_SNAKE_CASE = 0.02 , __SCREAMING_SNAKE_CASE = "linear" , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = "fixed_small" , __SCREAMING_SNAKE_CASE = True , __SCREAMING_SNAKE_CASE = "epsilon" , __SCREAMING_SNAKE_CASE = jnp.floataa , ): """simple docstring""" lowercase_ : Dict = dtype def _snake_case ( self , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" if common is None: lowercase_ : Tuple = CommonSchedulerState.create(self ) # standard deviation of the initial noise distribution lowercase_ : Union[str, Any] = jnp.array(1.0 , dtype=self.dtype ) lowercase_ : List[Any] = jnp.arange(0 , self.config.num_train_timesteps ).round()[::-1] return DDPMSchedulerState.create( common=__SCREAMING_SNAKE_CASE , init_noise_sigma=__SCREAMING_SNAKE_CASE , timesteps=__SCREAMING_SNAKE_CASE , ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" return sample def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = () ): """simple docstring""" lowercase_ : Optional[Any] = self.config.num_train_timesteps // num_inference_steps # creates integer timesteps by multiplying by ratio # rounding to avoid issues when num_inference_step is power of 3 lowercase_ : int = (jnp.arange(0 , __SCREAMING_SNAKE_CASE ) * step_ratio).round()[::-1] return state.replace( num_inference_steps=__SCREAMING_SNAKE_CASE , timesteps=__SCREAMING_SNAKE_CASE , ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None ): """simple docstring""" lowercase_ : List[Any] = state.common.alphas_cumprod[t] lowercase_ : str = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) ) # For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf) # and sample from it to get previous sample # x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample lowercase_ : int = (1 - alpha_prod_t_prev) / (1 - alpha_prod_t) * state.common.betas[t] if variance_type is None: lowercase_ : str = self.config.variance_type # hacks - were probably added for training stability if variance_type == "fixed_small": lowercase_ : int = jnp.clip(__SCREAMING_SNAKE_CASE , a_min=1E-2_0 ) # for rl-diffuser https://arxiv.org/abs/2205.09991 elif variance_type == "fixed_small_log": lowercase_ : List[str] = jnp.log(jnp.clip(__SCREAMING_SNAKE_CASE , a_min=1E-2_0 ) ) elif variance_type == "fixed_large": lowercase_ : List[Any] = state.common.betas[t] elif variance_type == "fixed_large_log": # Glide max_log lowercase_ : List[Any] = jnp.log(state.common.betas[t] ) elif variance_type == "learned": return predicted_variance elif variance_type == "learned_range": lowercase_ : Optional[Any] = variance lowercase_ : Union[str, Any] = state.common.betas[t] lowercase_ : Union[str, Any] = (predicted_variance + 1) / 2 lowercase_ : Any = frac * max_log + (1 - frac) * min_log return variance def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = True , ): """simple docstring""" lowercase_ : Optional[int] = timestep if key is None: lowercase_ : int = jax.random.PRNGKey(0 ) if model_output.shape[1] == sample.shape[1] * 2 and self.config.variance_type in ["learned", "learned_range"]: lowercase_ , lowercase_ : Optional[Any] = jnp.split(__SCREAMING_SNAKE_CASE , sample.shape[1] , axis=1 ) else: lowercase_ : int = None # 1. compute alphas, betas lowercase_ : Any = state.common.alphas_cumprod[t] lowercase_ : Optional[int] = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) ) lowercase_ : int = 1 - alpha_prod_t lowercase_ : str = 1 - alpha_prod_t_prev # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if self.config.prediction_type == "epsilon": lowercase_ : Tuple = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif self.config.prediction_type == "sample": lowercase_ : Any = model_output elif self.config.prediction_type == "v_prediction": lowercase_ : List[Any] = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output else: raise ValueError( F'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample` ''' ''' for the FlaxDDPMScheduler.''' ) # 3. Clip "predicted x_0" if self.config.clip_sample: lowercase_ : Optional[Any] = jnp.clip(__SCREAMING_SNAKE_CASE , -1 , 1 ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf lowercase_ : List[Any] = (alpha_prod_t_prev ** 0.5 * state.common.betas[t]) / beta_prod_t lowercase_ : Optional[Any] = state.common.alphas[t] ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf lowercase_ : Optional[Any] = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise def random_variance(): lowercase_ : str = jax.random.split(__SCREAMING_SNAKE_CASE , num=1 ) lowercase_ : List[Any] = jax.random.normal(__SCREAMING_SNAKE_CASE , shape=model_output.shape , dtype=self.dtype ) return (self._get_variance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , predicted_variance=__SCREAMING_SNAKE_CASE ) ** 0.5) * noise lowercase_ : Optional[Any] = jnp.where(t > 0 , random_variance() , jnp.zeros(model_output.shape , dtype=self.dtype ) ) lowercase_ : Any = pred_prev_sample + variance if not return_dict: return (pred_prev_sample, state) return FlaxDDPMSchedulerOutput(prev_sample=__SCREAMING_SNAKE_CASE , state=__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , ): """simple docstring""" return add_noise_common(state.common , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , ): """simple docstring""" return get_velocity_common(state.common , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def __len__( self ): """simple docstring""" return self.config.num_train_timesteps
93
"""simple docstring""" import datasets __SCREAMING_SNAKE_CASE : Tuple = '\\n@InProceedings{conneau2018xnli,\n author = "Conneau, Alexis\n and Rinott, Ruty\n and Lample, Guillaume\n and Williams, Adina\n and Bowman, Samuel R.\n and Schwenk, Holger\n and Stoyanov, Veselin",\n title = "XNLI: Evaluating Cross-lingual Sentence Representations",\n booktitle = "Proceedings of the 2018 Conference on Empirical Methods\n in Natural Language Processing",\n year = "2018",\n publisher = "Association for Computational Linguistics",\n location = "Brussels, Belgium",\n}\n' __SCREAMING_SNAKE_CASE : Dict = '\\nXNLI is a subset of a few thousand examples from MNLI which has been translated\ninto a 14 different languages (some low-ish resource). As with MNLI, the goal is\nto predict textual entailment (does sentence A imply/contradict/neither sentence\nB) and is a classification task (given two sentences, predict one of three\nlabels).\n' __SCREAMING_SNAKE_CASE : List[str] = '\nComputes XNLI score which is just simple accuracy.\nArgs:\n predictions: Predicted labels.\n references: Ground truth labels.\nReturns:\n \'accuracy\': accuracy\nExamples:\n\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> xnli_metric = datasets.load_metric("xnli")\n >>> results = xnli_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0}\n' def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[Any]: return (preds == labels).mean() @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class __A (datasets.Metric): '''simple docstring''' def lowerCAmelCase ( self : str ) ->Any: """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""int64""" if self.config_name != """sts-b""" else """float32""" ), """references""": datasets.Value("""int64""" if self.config_name != """sts-b""" else """float32""" ), } ) , codebase_urls=[] , reference_urls=[] , format="""numpy""" , ) def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Any ) ->int: """simple docstring""" return {"accuracy": simple_accuracy(UpperCAmelCase_ , UpperCAmelCase_ )}
347
0
from typing import Optional, Tuple import jax import jax.numpy as jnp from flax import linen as nn from flax.core.frozen_dict import FrozenDict from transformers import CLIPConfig, FlaxPreTrainedModel from transformers.models.clip.modeling_flax_clip import FlaxCLIPVisionModule def UpperCamelCase ( _A, _A, _A=1e-12 ): """simple docstring""" __magic_name__ : Optional[int] = jnp.divide(emb_a.T, jnp.clip(jnp.linalg.norm(_A, axis=1 ), a_min=_A ) ).T __magic_name__ : List[Any] = jnp.divide(emb_a.T, jnp.clip(jnp.linalg.norm(_A, axis=1 ), a_min=_A ) ).T return jnp.matmul(_A, norm_emb_a.T ) class snake_case__ ( nn.Module ): lowercase__ : CLIPConfig lowercase__ : jnp.dtype = jnp.floataa def __magic_name__ ( self ) -> Tuple: __magic_name__ : Optional[Any] = FlaxCLIPVisionModule(self.config.vision_config ) __magic_name__ : List[Any] = nn.Dense(self.config.projection_dim , use_bias=lowerCAmelCase__ , dtype=self.dtype ) __magic_name__ : Optional[Any] = self.param("""concept_embeds""" , jax.nn.initializers.ones , (17, self.config.projection_dim) ) __magic_name__ : Optional[int] = self.param( """special_care_embeds""" , jax.nn.initializers.ones , (3, self.config.projection_dim) ) __magic_name__ : Optional[int] = self.param("""concept_embeds_weights""" , jax.nn.initializers.ones , (17,) ) __magic_name__ : List[Any] = self.param("""special_care_embeds_weights""" , jax.nn.initializers.ones , (3,) ) def __call__( self , lowerCAmelCase__ ) -> Optional[Any]: __magic_name__ : Union[str, Any] = self.vision_model(lowerCAmelCase__ )[1] __magic_name__ : List[str] = self.visual_projection(lowerCAmelCase__ ) __magic_name__ : int = jax_cosine_distance(lowerCAmelCase__ , self.special_care_embeds ) __magic_name__ : str = jax_cosine_distance(lowerCAmelCase__ , self.concept_embeds ) # increase this value to create a stronger `nfsw` filter # at the cost of increasing the possibility of filtering benign image inputs __magic_name__ : Optional[Any] = 0.0 __magic_name__ : Union[str, Any] = special_cos_dist - self.special_care_embeds_weights[None, :] + adjustment __magic_name__ : Dict = jnp.round(lowerCAmelCase__ , 3 ) __magic_name__ : Optional[Any] = jnp.any(special_scores > 0 , axis=1 , keepdims=lowerCAmelCase__ ) # Use a lower threshold if an image has any special care concept __magic_name__ : List[Any] = is_special_care * 0.0_1 __magic_name__ : Optional[int] = cos_dist - self.concept_embeds_weights[None, :] + special_adjustment __magic_name__ : Optional[Any] = jnp.round(lowerCAmelCase__ , 3 ) __magic_name__ : Union[str, Any] = jnp.any(concept_scores > 0 , axis=1 ) return has_nsfw_concepts class snake_case__ ( _lowerCAmelCase ): lowercase__ : Any = CLIPConfig lowercase__ : List[str] = '''clip_input''' lowercase__ : Tuple = FlaxStableDiffusionSafetyCheckerModule def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ = None , lowerCAmelCase__ = 0 , lowerCAmelCase__ = jnp.floataa , lowerCAmelCase__ = True , **lowerCAmelCase__ , ) -> List[str]: if input_shape is None: __magic_name__ : int = (1, 2_24, 2_24, 3) __magic_name__ : List[str] = self.module_class(config=lowerCAmelCase__ , dtype=lowerCAmelCase__ , **lowerCAmelCase__ ) super().__init__(lowerCAmelCase__ , lowerCAmelCase__ , input_shape=lowerCAmelCase__ , seed=lowerCAmelCase__ , dtype=lowerCAmelCase__ , _do_init=_do_init ) def __magic_name__ ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = None ) -> FrozenDict: # init input tensor __magic_name__ : Union[str, Any] = jax.random.normal(lowerCAmelCase__ , lowerCAmelCase__ ) __magic_name__ ,__magic_name__ : Optional[int] = jax.random.split(lowerCAmelCase__ ) __magic_name__ : Union[str, Any] = {"""params""": params_rng, """dropout""": dropout_rng} __magic_name__ : List[str] = self.module.init(lowerCAmelCase__ , lowerCAmelCase__ )["""params"""] return random_params def __call__( self , lowerCAmelCase__ , lowerCAmelCase__ = None , ) -> Any: __magic_name__ : Dict = jnp.transpose(lowerCAmelCase__ , (0, 2, 3, 1) ) return self.module.apply( {"""params""": params or self.params} , jnp.array(lowerCAmelCase__ , dtype=jnp.floataa ) , rngs={} , )
138
from manim import * class snake_case__ ( _lowerCAmelCase ): def __magic_name__ ( self ) -> Dict: __magic_name__ : int = Rectangle(height=0.5 , width=0.5 ) __magic_name__ : Optional[int] = Rectangle(height=0.2_5 , width=0.2_5 ) __magic_name__ : str = Rectangle(height=0.4_6 , width=0.4_6 ).set_stroke(width=0 ) __magic_name__ : List[Any] = [mem.copy() for i in range(6 )] __magic_name__ : int = [mem.copy() for i in range(6 )] __magic_name__ : Tuple = VGroup(*lowerCAmelCase__ ).arrange(lowerCAmelCase__ , buff=0 ) __magic_name__ : List[str] = VGroup(*lowerCAmelCase__ ).arrange(lowerCAmelCase__ , buff=0 ) __magic_name__ : str = VGroup(lowerCAmelCase__ , lowerCAmelCase__ ).arrange(lowerCAmelCase__ , buff=0 ) __magic_name__ : Union[str, Any] = Text("""CPU""" , font_size=24 ) __magic_name__ : Tuple = Group(lowerCAmelCase__ , lowerCAmelCase__ ).arrange(lowerCAmelCase__ , buff=0.5 , aligned_edge=lowerCAmelCase__ ) cpu.move_to([-2.5, -0.5, 0] ) self.add(lowerCAmelCase__ ) __magic_name__ : Any = [mem.copy() for i in range(4 )] __magic_name__ : List[Any] = VGroup(*lowerCAmelCase__ ).arrange(lowerCAmelCase__ , buff=0 ) __magic_name__ : Tuple = Text("""GPU""" , font_size=24 ) __magic_name__ : Tuple = Group(lowerCAmelCase__ , lowerCAmelCase__ ).arrange(lowerCAmelCase__ , buff=0.5 , aligned_edge=lowerCAmelCase__ ) gpu.move_to([-1, -1, 0] ) self.add(lowerCAmelCase__ ) __magic_name__ : Union[str, Any] = [mem.copy() for i in range(6 )] __magic_name__ : Union[str, Any] = VGroup(*lowerCAmelCase__ ).arrange(lowerCAmelCase__ , buff=0 ) __magic_name__ : str = Text("""Model""" , font_size=24 ) __magic_name__ : Optional[int] = Group(lowerCAmelCase__ , lowerCAmelCase__ ).arrange(lowerCAmelCase__ , buff=0.5 , aligned_edge=lowerCAmelCase__ ) model.move_to([3, -1.0, 0] ) self.add(lowerCAmelCase__ ) __magic_name__ : str = [] __magic_name__ : Tuple = [] __magic_name__ : Union[str, Any] = [] for i, rect in enumerate(lowerCAmelCase__ ): rect.set_stroke(lowerCAmelCase__ ) __magic_name__ : Optional[Any] = Rectangle(height=0.4_6 / 4 , width=0.4_6 / 3 ).set_stroke(width=0.0 ).set_fill(lowerCAmelCase__ , opacity=0.7 ) if i == 0: cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.0_2 , direction=lowerCAmelCase__ ) cpu_target.set_x(cpu_target.get_x() + 0.1 ) elif i == 3: cpu_target.next_to(model_cpu_arr[0] , direction=lowerCAmelCase__ , buff=0.0 ) else: cpu_target.next_to(model_cpu_arr[i - 1] , direction=lowerCAmelCase__ , buff=0.0 ) self.add(lowerCAmelCase__ ) model_cpu_arr.append(lowerCAmelCase__ ) self.add(*lowerCAmelCase__ , *lowerCAmelCase__ , *lowerCAmelCase__ ) __magic_name__ : Optional[Any] = [mem.copy() for i in range(6 )] __magic_name__ : Optional[Any] = VGroup(*lowerCAmelCase__ ).arrange(lowerCAmelCase__ , buff=0 ) __magic_name__ : Any = Text("""Loaded Checkpoint""" , font_size=24 ) __magic_name__ : Optional[int] = Group(lowerCAmelCase__ , lowerCAmelCase__ ).arrange(lowerCAmelCase__ , buff=0.5 , aligned_edge=lowerCAmelCase__ ) checkpoint.move_to([3, 0.5, 0] ) self.add(lowerCAmelCase__ ) __magic_name__ : Optional[int] = [] __magic_name__ : Tuple = [] for i, rect in enumerate(lowerCAmelCase__ ): __magic_name__ : Dict = fill.copy().set_fill(lowerCAmelCase__ , opacity=0.7 ) target.move_to(lowerCAmelCase__ ) ckpt_arr.append(lowerCAmelCase__ ) __magic_name__ : int = 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(lowerCAmelCase__ ) self.add(*lowerCAmelCase__ , *lowerCAmelCase__ ) __magic_name__ : Tuple = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) __magic_name__ : str = 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(lowerCAmelCase__ , lowerCAmelCase__ ) __magic_name__ : Any = MarkupText( F'<span fgcolor=\'{BLUE}\'>●</span> Checkpoint' , font_size=18 , ) blue_text.next_to(lowerCAmelCase__ , DOWN * 2.4 , aligned_edge=key_text.get_left() ) self.add(lowerCAmelCase__ ) __magic_name__ : Optional[Any] = 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] ) __magic_name__ : int = [meta_mem.copy() for i in range(6 )] __magic_name__ : Union[str, Any] = [meta_mem.copy() for i in range(6 )] __magic_name__ : Any = VGroup(*lowerCAmelCase__ ).arrange(lowerCAmelCase__ , buff=0 ) __magic_name__ : str = VGroup(*lowerCAmelCase__ ).arrange(lowerCAmelCase__ , buff=0 ) __magic_name__ : Tuple = VGroup(lowerCAmelCase__ , lowerCAmelCase__ ).arrange(lowerCAmelCase__ , buff=0 ) __magic_name__ : int = Text("""Disk""" , font_size=24 ) __magic_name__ : Union[str, Any] = Group(lowerCAmelCase__ , lowerCAmelCase__ ).arrange(lowerCAmelCase__ , buff=0.5 , aligned_edge=lowerCAmelCase__ ) disk.move_to([-4.0, -1.2_5, 0] ) self.play(Write(lowerCAmelCase__ , run_time=3 ) , Write(lowerCAmelCase__ , run_time=1 ) , Create(lowerCAmelCase__ , run_time=1 ) ) __magic_name__ : List[Any] = [] for i, rect in enumerate(lowerCAmelCase__ ): __magic_name__ : Dict = rect.copy() target.generate_target() target.target.move_to(disk_left_col_base[i] ).scale(0.5 ) animations.append(MoveToTarget(lowerCAmelCase__ , run_time=1.5 ) ) self.play(*lowerCAmelCase__ ) self.play(FadeOut(lowerCAmelCase__ ) ) __magic_name__ : str = 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(lowerCAmelCase__ , run_time=3 ) ) self.play( FadeOut(lowerCAmelCase__ , lowerCAmelCase__ , *lowerCAmelCase__ , *lowerCAmelCase__ ) , ) self.wait()
138
1
"""simple docstring""" import argparse import json import torch from diffusers import DDPMScheduler, LDMPipeline, UNetaDModel, VQModel def lowercase ( __snake_case : List[Any] , __snake_case : Tuple=1 ): if n_shave_prefix_segments >= 0: return ".".join(path.split('''.''' )[n_shave_prefix_segments:] ) else: return ".".join(path.split('''.''' )[:n_shave_prefix_segments] ) def lowercase ( __snake_case : str , __snake_case : str=0 ): lowercase_ : Dict = [] for old_item in old_list: lowercase_ : Optional[Any] = old_item.replace('''in_layers.0''' , '''norm1''' ) lowercase_ : List[Any] = new_item.replace('''in_layers.2''' , '''conv1''' ) lowercase_ : Any = new_item.replace('''out_layers.0''' , '''norm2''' ) lowercase_ : int = new_item.replace('''out_layers.3''' , '''conv2''' ) lowercase_ : Any = new_item.replace('''emb_layers.1''' , '''time_emb_proj''' ) lowercase_ : Tuple = new_item.replace('''skip_connection''' , '''conv_shortcut''' ) lowercase_ : Union[str, Any] = shave_segments(__snake_case , n_shave_prefix_segments=__snake_case ) mapping.append({'''old''': old_item, '''new''': new_item} ) return mapping def lowercase ( __snake_case : Union[str, Any] , __snake_case : Optional[int]=0 ): lowercase_ : List[Any] = [] for old_item in old_list: lowercase_ : Optional[int] = old_item lowercase_ : Tuple = new_item.replace('''norm.weight''' , '''group_norm.weight''' ) lowercase_ : Dict = new_item.replace('''norm.bias''' , '''group_norm.bias''' ) lowercase_ : Optional[Any] = new_item.replace('''proj_out.weight''' , '''proj_attn.weight''' ) lowercase_ : Dict = new_item.replace('''proj_out.bias''' , '''proj_attn.bias''' ) lowercase_ : Tuple = shave_segments(__snake_case , n_shave_prefix_segments=__snake_case ) mapping.append({'''old''': old_item, '''new''': new_item} ) return mapping def lowercase ( __snake_case : str , __snake_case : int , __snake_case : Optional[Any] , __snake_case : Optional[int]=None , __snake_case : Union[str, Any]=None , __snake_case : Dict=None ): assert isinstance(__snake_case , __snake_case ), "Paths should be a list of dicts containing 'old' and 'new' keys." # Splits the attention layers into three variables. if attention_paths_to_split is not None: for path, path_map in attention_paths_to_split.items(): lowercase_ : List[str] = old_checkpoint[path] lowercase_ : Union[str, Any] = old_tensor.shape[0] // 3 lowercase_ : List[str] = (-1, channels) if len(old_tensor.shape ) == 3 else (-1) lowercase_ : Optional[Any] = old_tensor.shape[0] // config['''num_head_channels'''] // 3 lowercase_ : Optional[Any] = old_tensor.reshape((num_heads, 3 * channels // num_heads) + old_tensor.shape[1:] ) lowercase_ , lowercase_ , lowercase_ : Dict = old_tensor.split(channels // num_heads , dim=1 ) lowercase_ : int = query.reshape(__snake_case ) lowercase_ : Optional[int] = key.reshape(__snake_case ) lowercase_ : Optional[int] = value.reshape(__snake_case ) for path in paths: lowercase_ : Optional[int] = path['''new'''] # These have already been assigned if attention_paths_to_split is not None and new_path in attention_paths_to_split: continue # Global renaming happens here lowercase_ : Optional[Any] = new_path.replace('''middle_block.0''' , '''mid_block.resnets.0''' ) lowercase_ : Optional[Any] = new_path.replace('''middle_block.1''' , '''mid_block.attentions.0''' ) lowercase_ : str = new_path.replace('''middle_block.2''' , '''mid_block.resnets.1''' ) if additional_replacements is not None: for replacement in additional_replacements: lowercase_ : List[str] = new_path.replace(replacement['''old'''] , replacement['''new'''] ) # proj_attn.weight has to be converted from conv 1D to linear if "proj_attn.weight" in new_path: lowercase_ : List[Any] = old_checkpoint[path['''old''']][:, :, 0] else: lowercase_ : str = old_checkpoint[path['''old''']] def lowercase ( __snake_case : int , __snake_case : List[Any] ): lowercase_ : Any = {} lowercase_ : str = checkpoint['''time_embed.0.weight'''] lowercase_ : Tuple = checkpoint['''time_embed.0.bias'''] lowercase_ : Tuple = checkpoint['''time_embed.2.weight'''] lowercase_ : Dict = checkpoint['''time_embed.2.bias'''] lowercase_ : Tuple = checkpoint['''input_blocks.0.0.weight'''] lowercase_ : Union[str, Any] = checkpoint['''input_blocks.0.0.bias'''] lowercase_ : Dict = checkpoint['''out.0.weight'''] lowercase_ : Optional[int] = checkpoint['''out.0.bias'''] lowercase_ : Union[str, Any] = checkpoint['''out.2.weight'''] lowercase_ : Tuple = checkpoint['''out.2.bias'''] # Retrieves the keys for the input blocks only lowercase_ : Union[str, Any] = len({'''.'''.join(layer.split('''.''' )[:2] ) for layer in checkpoint if '''input_blocks''' in layer} ) lowercase_ : Tuple = { layer_id: [key for key in checkpoint if F'''input_blocks.{layer_id}''' in key] for layer_id in range(__snake_case ) } # Retrieves the keys for the middle blocks only lowercase_ : str = len({'''.'''.join(layer.split('''.''' )[:2] ) for layer in checkpoint if '''middle_block''' in layer} ) lowercase_ : Optional[int] = { layer_id: [key for key in checkpoint if F'''middle_block.{layer_id}''' in key] for layer_id in range(__snake_case ) } # Retrieves the keys for the output blocks only lowercase_ : Union[str, Any] = len({'''.'''.join(layer.split('''.''' )[:2] ) for layer in checkpoint if '''output_blocks''' in layer} ) lowercase_ : Optional[int] = { layer_id: [key for key in checkpoint if F'''output_blocks.{layer_id}''' in key] for layer_id in range(__snake_case ) } for i in range(1 , __snake_case ): lowercase_ : List[str] = (i - 1) // (config['''num_res_blocks'''] + 1) lowercase_ : str = (i - 1) % (config['''num_res_blocks'''] + 1) lowercase_ : List[Any] = [key for key in input_blocks[i] if F'''input_blocks.{i}.0''' in key] lowercase_ : List[str] = [key for key in input_blocks[i] if F'''input_blocks.{i}.1''' in key] if F'''input_blocks.{i}.0.op.weight''' in checkpoint: lowercase_ : Any = checkpoint[ F'''input_blocks.{i}.0.op.weight''' ] lowercase_ : Union[str, Any] = checkpoint[ F'''input_blocks.{i}.0.op.bias''' ] continue lowercase_ : int = renew_resnet_paths(__snake_case ) lowercase_ : List[str] = {'''old''': F'''input_blocks.{i}.0''', '''new''': F'''down_blocks.{block_id}.resnets.{layer_in_block_id}'''} lowercase_ : List[Any] = {'''old''': '''resnets.2.op''', '''new''': '''downsamplers.0.op'''} assign_to_checkpoint( __snake_case , __snake_case , __snake_case , additional_replacements=[meta_path, resnet_op] , config=__snake_case ) if len(__snake_case ): lowercase_ : List[str] = renew_attention_paths(__snake_case ) lowercase_ : Optional[Any] = { '''old''': F'''input_blocks.{i}.1''', '''new''': F'''down_blocks.{block_id}.attentions.{layer_in_block_id}''', } lowercase_ : Optional[int] = { F'''input_blocks.{i}.1.qkv.bias''': { '''key''': F'''down_blocks.{block_id}.attentions.{layer_in_block_id}.key.bias''', '''query''': F'''down_blocks.{block_id}.attentions.{layer_in_block_id}.query.bias''', '''value''': F'''down_blocks.{block_id}.attentions.{layer_in_block_id}.value.bias''', }, F'''input_blocks.{i}.1.qkv.weight''': { '''key''': F'''down_blocks.{block_id}.attentions.{layer_in_block_id}.key.weight''', '''query''': F'''down_blocks.{block_id}.attentions.{layer_in_block_id}.query.weight''', '''value''': F'''down_blocks.{block_id}.attentions.{layer_in_block_id}.value.weight''', }, } assign_to_checkpoint( __snake_case , __snake_case , __snake_case , additional_replacements=[meta_path] , attention_paths_to_split=__snake_case , config=__snake_case , ) lowercase_ : List[Any] = middle_blocks[0] lowercase_ : List[str] = middle_blocks[1] lowercase_ : Union[str, Any] = middle_blocks[2] lowercase_ : Dict = renew_resnet_paths(__snake_case ) assign_to_checkpoint(__snake_case , __snake_case , __snake_case , config=__snake_case ) lowercase_ : Tuple = renew_resnet_paths(__snake_case ) assign_to_checkpoint(__snake_case , __snake_case , __snake_case , config=__snake_case ) lowercase_ : int = renew_attention_paths(__snake_case ) lowercase_ : Union[str, Any] = { '''middle_block.1.qkv.bias''': { '''key''': '''mid_block.attentions.0.key.bias''', '''query''': '''mid_block.attentions.0.query.bias''', '''value''': '''mid_block.attentions.0.value.bias''', }, '''middle_block.1.qkv.weight''': { '''key''': '''mid_block.attentions.0.key.weight''', '''query''': '''mid_block.attentions.0.query.weight''', '''value''': '''mid_block.attentions.0.value.weight''', }, } assign_to_checkpoint( __snake_case , __snake_case , __snake_case , attention_paths_to_split=__snake_case , config=__snake_case ) for i in range(__snake_case ): lowercase_ : List[str] = i // (config['''num_res_blocks'''] + 1) lowercase_ : Union[str, Any] = i % (config['''num_res_blocks'''] + 1) lowercase_ : int = [shave_segments(__snake_case , 2 ) for name in output_blocks[i]] lowercase_ : Dict = {} for layer in output_block_layers: lowercase_ , lowercase_ : Tuple = layer.split('''.''' )[0], shave_segments(__snake_case , 1 ) if layer_id in output_block_list: output_block_list[layer_id].append(__snake_case ) else: lowercase_ : List[Any] = [layer_name] if len(__snake_case ) > 1: lowercase_ : Any = [key for key in output_blocks[i] if F'''output_blocks.{i}.0''' in key] lowercase_ : Optional[Any] = [key for key in output_blocks[i] if F'''output_blocks.{i}.1''' in key] lowercase_ : int = renew_resnet_paths(__snake_case ) lowercase_ : Dict = renew_resnet_paths(__snake_case ) lowercase_ : Optional[Any] = {'''old''': F'''output_blocks.{i}.0''', '''new''': F'''up_blocks.{block_id}.resnets.{layer_in_block_id}'''} assign_to_checkpoint(__snake_case , __snake_case , __snake_case , additional_replacements=[meta_path] , config=__snake_case ) if ["conv.weight", "conv.bias"] in output_block_list.values(): lowercase_ : int = list(output_block_list.values() ).index(['''conv.weight''', '''conv.bias'''] ) lowercase_ : Any = checkpoint[ F'''output_blocks.{i}.{index}.conv.weight''' ] lowercase_ : Any = checkpoint[ F'''output_blocks.{i}.{index}.conv.bias''' ] # Clear attentions as they have been attributed above. if len(__snake_case ) == 2: lowercase_ : Dict = [] if len(__snake_case ): lowercase_ : int = renew_attention_paths(__snake_case ) lowercase_ : Union[str, Any] = { '''old''': F'''output_blocks.{i}.1''', '''new''': F'''up_blocks.{block_id}.attentions.{layer_in_block_id}''', } lowercase_ : str = { F'''output_blocks.{i}.1.qkv.bias''': { '''key''': F'''up_blocks.{block_id}.attentions.{layer_in_block_id}.key.bias''', '''query''': F'''up_blocks.{block_id}.attentions.{layer_in_block_id}.query.bias''', '''value''': F'''up_blocks.{block_id}.attentions.{layer_in_block_id}.value.bias''', }, F'''output_blocks.{i}.1.qkv.weight''': { '''key''': F'''up_blocks.{block_id}.attentions.{layer_in_block_id}.key.weight''', '''query''': F'''up_blocks.{block_id}.attentions.{layer_in_block_id}.query.weight''', '''value''': F'''up_blocks.{block_id}.attentions.{layer_in_block_id}.value.weight''', }, } assign_to_checkpoint( __snake_case , __snake_case , __snake_case , additional_replacements=[meta_path] , attention_paths_to_split=to_split if any('''qkv''' in key for key in attentions ) else None , config=__snake_case , ) else: lowercase_ : Dict = renew_resnet_paths(__snake_case , n_shave_prefix_segments=1 ) for path in resnet_0_paths: lowercase_ : int = '''.'''.join(['''output_blocks''', str(__snake_case ), path['''old''']] ) lowercase_ : Optional[int] = '''.'''.join(['''up_blocks''', str(__snake_case ), '''resnets''', str(__snake_case ), path['''new''']] ) lowercase_ : Tuple = checkpoint[old_path] return new_checkpoint if __name__ == "__main__": __A : Optional[int] = argparse.ArgumentParser() parser.add_argument( '''--checkpoint_path''', default=None, type=str, required=True, help='''Path to the checkpoint to convert.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help='''The config json file corresponding to the architecture.''', ) parser.add_argument('''--dump_path''', default=None, type=str, required=True, help='''Path to the output model.''') __A : Tuple = parser.parse_args() __A : Dict = torch.load(args.checkpoint_path) with open(args.config_file) as f: __A : Any = json.loads(f.read()) __A : str = convert_ldm_checkpoint(checkpoint, config) if "ldm" in config: del config["ldm"] __A : Optional[Any] = UNetaDModel(**config) model.load_state_dict(converted_checkpoint) try: __A : Any = DDPMScheduler.from_config('''/'''.join(args.checkpoint_path.split('''/''')[:-1])) __A : Optional[int] = VQModel.from_pretrained('''/'''.join(args.checkpoint_path.split('''/''')[:-1])) __A : Tuple = LDMPipeline(unet=model, scheduler=scheduler, vae=vqvae) pipe.save_pretrained(args.dump_path) except: # noqa: E722 model.save_pretrained(args.dump_path)
33
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) __A : List[Any] = { '''configuration_mega''': ['''MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MegaConfig''', '''MegaOnnxConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : List[str] = [ '''MEGA_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MegaForCausalLM''', '''MegaForMaskedLM''', '''MegaForMultipleChoice''', '''MegaForQuestionAnswering''', '''MegaForSequenceClassification''', '''MegaForTokenClassification''', '''MegaModel''', '''MegaPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_mega import MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP, MegaConfig, MegaOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mega import ( MEGA_PRETRAINED_MODEL_ARCHIVE_LIST, MegaForCausalLM, MegaForMaskedLM, MegaForMultipleChoice, MegaForQuestionAnswering, MegaForSequenceClassification, MegaForTokenClassification, MegaModel, MegaPreTrainedModel, ) else: import sys __A : Any = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
33
1
"""simple docstring""" from __future__ import annotations lowercase_ = 1_0 def lowercase ( lowerCAmelCase__ : list[int] ) -> list[int]: __a = 1 __a = max(lowerCAmelCase__ ) while placement <= max_digit: # declare and initialize empty buckets __a = [[] for _ in range(lowerCAmelCase__ )] # split list_of_ints between the buckets for i in list_of_ints: __a = int((i / placement) % RADIX ) buckets[tmp].append(lowerCAmelCase__ ) # put each buckets' contents into list_of_ints __a = 0 for b in range(lowerCAmelCase__ ): for i in buckets[b]: __a = i a += 1 # move to next placement *= RADIX return list_of_ints if __name__ == "__main__": import doctest doctest.testmod()
11
"""simple docstring""" from transformers import DistilBertTokenizer, DistilBertTokenizerFast from transformers.testing_utils import require_tokenizers, slow from ..bert.test_tokenization_bert import BertTokenizationTest @require_tokenizers class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Dict = DistilBertTokenizer __UpperCAmelCase : Any = DistilBertTokenizerFast __UpperCAmelCase : int = True @slow def __UpperCAmelCase ( self ): __a = DistilBertTokenizer.from_pretrained('''distilbert-base-uncased''' ) __a = tokenizer.encode('''sequence builders''' , add_special_tokens=_a ) __a = tokenizer.encode('''multi-sequence build''' , add_special_tokens=_a ) __a = tokenizer.build_inputs_with_special_tokens(_a ) __a = tokenizer.build_inputs_with_special_tokens(_a , _a ) assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [ tokenizer.sep_token_id ]
11
1
import re from pathlib import Path from unittest import TestCase import pytest @pytest.mark.integration class lowerCamelCase_ ( _SCREAMING_SNAKE_CASE ): '''simple docstring''' def lowerCAmelCase_ ( self : str , _lowerCAmelCase : str ): with open(_lowerCAmelCase , encoding='utf-8' ) as input_file: SCREAMING_SNAKE_CASE_ = re.compile(R'(?!.*\b(?:encoding|rb|w|wb|w+|wb+|ab|ab+)\b)(?<=\s)(open)\((.*)\)' ) SCREAMING_SNAKE_CASE_ = input_file.read() SCREAMING_SNAKE_CASE_ = regexp.search(_lowerCAmelCase ) return match def lowerCAmelCase_ ( self : List[str] , _lowerCAmelCase : str ): with open(_lowerCAmelCase , encoding='utf-8' ) as input_file: SCREAMING_SNAKE_CASE_ = re.compile(R'#[^\r\n]*print\(|\"[^\r\n]*print\(|\"\"\".*?print\(.*?\"\"\"|(print\()' , re.DOTALL ) SCREAMING_SNAKE_CASE_ = input_file.read() # use `re.finditer` to handle the case where the ignored groups would be matched first by `re.search` SCREAMING_SNAKE_CASE_ = regexp.finditer(_lowerCAmelCase ) SCREAMING_SNAKE_CASE_ = [match for match in matches if match is not None and match.group(1 ) is not None] return matches[0] if matches else None def lowerCAmelCase_ ( self : str ): SCREAMING_SNAKE_CASE_ = Path('./datasets' ) SCREAMING_SNAKE_CASE_ = list(dataset_paths.absolute().glob('**/*.py' ) ) for dataset in dataset_files: if self._no_encoding_on_file_open(str(_lowerCAmelCase ) ): raise AssertionError(F"open(...) must use utf-8 encoding in {dataset}" ) def lowerCAmelCase_ ( self : int ): SCREAMING_SNAKE_CASE_ = Path('./datasets' ) SCREAMING_SNAKE_CASE_ = list(dataset_paths.absolute().glob('**/*.py' ) ) for dataset in dataset_files: if self._no_print_statements(str(_lowerCAmelCase ) ): raise AssertionError(F"print statement found in {dataset}. Use datasets.logger/logging instead." )
225
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowerCamelCase__ : str = { 'configuration_mask2former': [ 'MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Mask2FormerConfig', ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ : int = ['Mask2FormerImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ : Dict = [ 'MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'Mask2FormerForUniversalSegmentation', 'Mask2FormerModel', 'Mask2FormerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_maskaformer import MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskaFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_maskaformer import MaskaFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskaformer import ( MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskaFormerForUniversalSegmentation, MaskaFormerModel, MaskaFormerPreTrainedModel, ) else: import sys lowerCamelCase__ : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure)
225
1
from random import randint from tempfile import TemporaryFile import numpy as np def __snake_case ( _lowerCAmelCase : Optional[int] , _lowerCAmelCase : str , _lowerCAmelCase : Optional[int] ) -> Dict: A_ : Optional[Any] = 0 if start < end: A_ : Tuple = randint(_lowerCAmelCase , _lowerCAmelCase ) A_ : str = a[end] A_ : Optional[Any] = a[pivot] A_ : List[str] = temp A_ : int = _in_place_partition(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) count += _in_place_quick_sort(_lowerCAmelCase , _lowerCAmelCase , p - 1 ) count += _in_place_quick_sort(_lowerCAmelCase , p + 1 , _lowerCAmelCase ) return count def __snake_case ( _lowerCAmelCase : Tuple , _lowerCAmelCase : List[str] , _lowerCAmelCase : Optional[Any] ) -> str: A_ : Union[str, Any] = 0 A_ : List[str] = randint(_lowerCAmelCase , _lowerCAmelCase ) A_ : str = a[end] A_ : str = a[pivot] A_ : Any = temp A_ : int = start - 1 for index in range(_lowerCAmelCase , _lowerCAmelCase ): count += 1 if a[index] < a[end]: # check if current val is less than pivot value A_ : Union[str, Any] = new_pivot_index + 1 A_ : Union[str, Any] = a[new_pivot_index] A_ : Union[str, Any] = a[index] A_ : Union[str, Any] = temp A_ : Tuple = a[new_pivot_index + 1] A_ : Optional[int] = a[end] A_ : Dict = temp return new_pivot_index + 1, count _lowerCAmelCase : List[str] = TemporaryFile() _lowerCAmelCase : int = 100 # 1000 elements are to be sorted _lowerCAmelCase : Optional[Any] = 0, 1 # mean and standard deviation _lowerCAmelCase : int = np.random.normal(mu, sigma, p) np.save(outfile, X) print('''The array is''') print(X) outfile.seek(0) # using the same array _lowerCAmelCase : Optional[Any] = np.load(outfile) _lowerCAmelCase : Optional[int] = len(M) - 1 _lowerCAmelCase : Union[str, Any] = _in_place_quick_sort(M, 0, r) print( '''No of Comparisons for 100 elements selected from a standard normal distribution''' '''is :''' ) print(z)
362
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowerCAmelCase : Union[str, Any] = { '''configuration_xmod''': [ '''XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XmodConfig''', '''XmodOnnxConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase : str = [ '''XMOD_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XmodForCausalLM''', '''XmodForMaskedLM''', '''XmodForMultipleChoice''', '''XmodForQuestionAnswering''', '''XmodForSequenceClassification''', '''XmodForTokenClassification''', '''XmodModel''', '''XmodPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_xmod import XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP, XmodConfig, XmodOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xmod import ( XMOD_PRETRAINED_MODEL_ARCHIVE_LIST, XmodForCausalLM, XmodForMaskedLM, XmodForMultipleChoice, XmodForQuestionAnswering, XmodForSequenceClassification, XmodForTokenClassification, XmodModel, XmodPreTrainedModel, ) else: import sys _lowerCAmelCase : List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
70
0
"""simple docstring""" import gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMInverseScheduler, DDIMScheduler, DPMSolverMultistepInverseScheduler, DPMSolverMultistepScheduler, StableDiffusionDiffEditPipeline, UNetaDConditionModel, ) from diffusers.utils import load_image, slow from diffusers.utils.testing_utils import enable_full_determinism, floats_tensor, require_torch_gpu, torch_device from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class snake_case ( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ): """simple docstring""" snake_case__ = StableDiffusionDiffEditPipeline snake_case__ = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {"height", "width", "image"} | {"image_latents"} snake_case__ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS - {"image"} | {"image_latents"} snake_case__ = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess snake_case__ = frozenset([] ) def __lowerCAmelCase ( self : int ): torch.manual_seed(0 ) UpperCAmelCase__ = UNetaDConditionModel( block_out_channels=(32, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=4 ,out_channels=4 ,down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') ,up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') ,cross_attention_dim=32 ,attention_head_dim=(2, 4) ,use_linear_projection=lowerCamelCase__ ,) UpperCAmelCase__ = DDIMScheduler( beta_start=0.0_0_0_8_5 ,beta_end=0.0_1_2 ,beta_schedule='scaled_linear' ,clip_sample=lowerCamelCase__ ,set_alpha_to_one=lowerCamelCase__ ,) UpperCAmelCase__ = DDIMInverseScheduler( beta_start=0.0_0_0_8_5 ,beta_end=0.0_1_2 ,beta_schedule='scaled_linear' ,clip_sample=lowerCamelCase__ ,set_alpha_to_zero=lowerCamelCase__ ,) torch.manual_seed(0 ) UpperCAmelCase__ = AutoencoderKL( block_out_channels=[32, 64] ,in_channels=3 ,out_channels=3 ,down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] ,up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] ,latent_channels=4 ,sample_size=128 ,) torch.manual_seed(0 ) UpperCAmelCase__ = 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=1_000 ,hidden_act='gelu' ,projection_dim=512 ,) UpperCAmelCase__ = CLIPTextModel(lowerCamelCase__ ) UpperCAmelCase__ = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) UpperCAmelCase__ = { 'unet': unet, 'scheduler': scheduler, 'inverse_scheduler': inverse_scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def __lowerCAmelCase ( self : Dict ,lowerCamelCase__ : Optional[Any] ,lowerCamelCase__ : Union[str, Any]=0 ): UpperCAmelCase__ = floats_tensor((1, 16, 16) ,rng=random.Random(lowerCamelCase__ ) ).to(lowerCamelCase__ ) UpperCAmelCase__ = floats_tensor((1, 2, 4, 16, 16) ,rng=random.Random(lowerCamelCase__ ) ).to(lowerCamelCase__ ) if str(lowerCamelCase__ ).startswith('mps' ): UpperCAmelCase__ = torch.manual_seed(lowerCamelCase__ ) else: UpperCAmelCase__ = torch.Generator(device=lowerCamelCase__ ).manual_seed(lowerCamelCase__ ) UpperCAmelCase__ = { 'prompt': 'a dog and a newt', 'mask_image': mask, 'image_latents': latents, 'generator': generator, 'num_inference_steps': 2, 'inpaint_strength': 1.0, 'guidance_scale': 6.0, 'output_type': 'numpy', } return inputs def __lowerCAmelCase ( self : Dict ,lowerCamelCase__ : Optional[Any] ,lowerCamelCase__ : str=0 ): UpperCAmelCase__ = floats_tensor((1, 3, 32, 32) ,rng=random.Random(lowerCamelCase__ ) ).to(lowerCamelCase__ ) UpperCAmelCase__ = image.cpu().permute(0 ,2 ,3 ,1 )[0] UpperCAmelCase__ = Image.fromarray(np.uinta(lowerCamelCase__ ) ).convert('RGB' ) if str(lowerCamelCase__ ).startswith('mps' ): UpperCAmelCase__ = torch.manual_seed(lowerCamelCase__ ) else: UpperCAmelCase__ = torch.Generator(device=lowerCamelCase__ ).manual_seed(lowerCamelCase__ ) UpperCAmelCase__ = { 'image': image, 'source_prompt': 'a cat and a frog', 'target_prompt': 'a dog and a newt', 'generator': generator, 'num_inference_steps': 2, 'num_maps_per_mask': 2, 'mask_encode_strength': 1.0, 'guidance_scale': 6.0, 'output_type': 'numpy', } return inputs def __lowerCAmelCase ( self : Tuple ,lowerCamelCase__ : str ,lowerCamelCase__ : Any=0 ): UpperCAmelCase__ = floats_tensor((1, 3, 32, 32) ,rng=random.Random(lowerCamelCase__ ) ).to(lowerCamelCase__ ) UpperCAmelCase__ = image.cpu().permute(0 ,2 ,3 ,1 )[0] UpperCAmelCase__ = Image.fromarray(np.uinta(lowerCamelCase__ ) ).convert('RGB' ) if str(lowerCamelCase__ ).startswith('mps' ): UpperCAmelCase__ = torch.manual_seed(lowerCamelCase__ ) else: UpperCAmelCase__ = torch.Generator(device=lowerCamelCase__ ).manual_seed(lowerCamelCase__ ) UpperCAmelCase__ = { 'image': image, 'prompt': 'a cat and a frog', 'generator': generator, 'num_inference_steps': 2, 'inpaint_strength': 1.0, 'guidance_scale': 6.0, 'decode_latents': True, 'output_type': 'numpy', } return inputs def __lowerCAmelCase ( self : int ): if not hasattr(self.pipeline_class ,'_optional_components' ): return UpperCAmelCase__ = self.get_dummy_components() UpperCAmelCase__ = self.pipeline_class(**lowerCamelCase__ ) pipe.to(lowerCamelCase__ ) pipe.set_progress_bar_config(disable=lowerCamelCase__ ) # set all optional components to None and update pipeline config accordingly for optional_component in pipe._optional_components: setattr(lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ) pipe.register_modules(**{optional_component: None for optional_component in pipe._optional_components} ) UpperCAmelCase__ = self.get_dummy_inputs(lowerCamelCase__ ) UpperCAmelCase__ = pipe(**lowerCamelCase__ )[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(lowerCamelCase__ ) UpperCAmelCase__ = self.pipeline_class.from_pretrained(lowerCamelCase__ ) pipe_loaded.to(lowerCamelCase__ ) pipe_loaded.set_progress_bar_config(disable=lowerCamelCase__ ) for optional_component in pipe._optional_components: self.assertTrue( getattr(lowerCamelCase__ ,lowerCamelCase__ ) is None ,f'''`{optional_component}` did not stay set to None after loading.''' ,) UpperCAmelCase__ = self.get_dummy_inputs(lowerCamelCase__ ) UpperCAmelCase__ = pipe_loaded(**lowerCamelCase__ )[0] UpperCAmelCase__ = np.abs(output - output_loaded ).max() self.assertLess(lowerCamelCase__ ,1e-4 ) def __lowerCAmelCase ( self : Union[str, Any] ): UpperCAmelCase__ = 'cpu' UpperCAmelCase__ = self.get_dummy_components() UpperCAmelCase__ = self.pipeline_class(**lowerCamelCase__ ) pipe.to(lowerCamelCase__ ) pipe.set_progress_bar_config(disable=lowerCamelCase__ ) UpperCAmelCase__ = self.get_dummy_mask_inputs(lowerCamelCase__ ) UpperCAmelCase__ = pipe.generate_mask(**lowerCamelCase__ ) UpperCAmelCase__ = mask[0, -3:, -3:] self.assertEqual(mask.shape ,(1, 16, 16) ) UpperCAmelCase__ = np.array([0] * 9 ) UpperCAmelCase__ = np.abs(mask_slice.flatten() - expected_slice ).max() self.assertLessEqual(lowerCamelCase__ ,1e-3 ) self.assertEqual(mask[0, -3, -4] ,0 ) def __lowerCAmelCase ( self : List[Any] ): UpperCAmelCase__ = 'cpu' UpperCAmelCase__ = self.get_dummy_components() UpperCAmelCase__ = self.pipeline_class(**lowerCamelCase__ ) pipe.to(lowerCamelCase__ ) pipe.set_progress_bar_config(disable=lowerCamelCase__ ) UpperCAmelCase__ = self.get_dummy_inversion_inputs(lowerCamelCase__ ) UpperCAmelCase__ = pipe.invert(**lowerCamelCase__ ).images UpperCAmelCase__ = image[0, -1, -3:, -3:] self.assertEqual(image.shape ,(2, 32, 32, 3) ) UpperCAmelCase__ = np.array( [0.5_1_5_0, 0.5_1_3_4, 0.5_0_4_3, 0.5_3_7_6, 0.4_6_9_4, 0.5_1_0_5_0, 0.5_0_1_5, 0.4_4_0_7, 0.4_7_9_9] ,) UpperCAmelCase__ = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(lowerCamelCase__ ,1e-3 ) def __lowerCAmelCase ( self : Any ): super().test_inference_batch_single_identical(expected_max_diff=5e-3 ) def __lowerCAmelCase ( self : List[str] ): UpperCAmelCase__ = 'cpu' UpperCAmelCase__ = self.get_dummy_components() UpperCAmelCase__ = {'beta_start': 0.0_0_0_8_5, 'beta_end': 0.0_1_2, 'beta_schedule': 'scaled_linear'} UpperCAmelCase__ = DPMSolverMultistepScheduler(**lowerCamelCase__ ) UpperCAmelCase__ = DPMSolverMultistepInverseScheduler(**lowerCamelCase__ ) UpperCAmelCase__ = self.pipeline_class(**lowerCamelCase__ ) pipe.to(lowerCamelCase__ ) pipe.set_progress_bar_config(disable=lowerCamelCase__ ) UpperCAmelCase__ = self.get_dummy_inversion_inputs(lowerCamelCase__ ) UpperCAmelCase__ = pipe.invert(**lowerCamelCase__ ).images UpperCAmelCase__ = image[0, -1, -3:, -3:] self.assertEqual(image.shape ,(2, 32, 32, 3) ) UpperCAmelCase__ = np.array( [0.5_1_5_0, 0.5_1_3_4, 0.5_0_4_3, 0.5_3_7_6, 0.4_6_9_4, 0.5_1_0_5_0, 0.5_0_1_5, 0.4_4_0_7, 0.4_7_9_9] ,) UpperCAmelCase__ = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(lowerCamelCase__ ,1e-3 ) @require_torch_gpu @slow class snake_case ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self : List[str] ): super().tearDown() gc.collect() torch.cuda.empty_cache() @classmethod def __lowerCAmelCase ( cls : int ): UpperCAmelCase__ = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/diffedit/fruit.png' ) UpperCAmelCase__ = raw_image.convert('RGB' ).resize((768, 768) ) UpperCAmelCase__ = raw_image def __lowerCAmelCase ( self : int ): UpperCAmelCase__ = torch.manual_seed(0 ) UpperCAmelCase__ = StableDiffusionDiffEditPipeline.from_pretrained( 'stabilityai/stable-diffusion-2-1' ,safety_checker=lowerCamelCase__ ,torch_dtype=torch.floataa ) UpperCAmelCase__ = DDIMScheduler.from_config(pipe.scheduler.config ) UpperCAmelCase__ = DDIMInverseScheduler.from_config(pipe.scheduler.config ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=lowerCamelCase__ ) UpperCAmelCase__ = 'a bowl of fruit' UpperCAmelCase__ = 'a bowl of pears' UpperCAmelCase__ = pipe.generate_mask( image=self.raw_image ,source_prompt=lowerCamelCase__ ,target_prompt=lowerCamelCase__ ,generator=lowerCamelCase__ ,) UpperCAmelCase__ = pipe.invert( prompt=lowerCamelCase__ ,image=self.raw_image ,inpaint_strength=0.7 ,generator=lowerCamelCase__ ).latents UpperCAmelCase__ = pipe( prompt=lowerCamelCase__ ,mask_image=lowerCamelCase__ ,image_latents=lowerCamelCase__ ,generator=lowerCamelCase__ ,negative_prompt=lowerCamelCase__ ,inpaint_strength=0.7 ,output_type='numpy' ,).images[0] UpperCAmelCase__ = ( np.array( load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/diffedit/pears.png' ).resize((768, 768) ) ) / 255 ) assert np.abs((expected_image - image).max() ) < 5e-1 def __lowerCAmelCase ( self : Optional[Any] ): UpperCAmelCase__ = torch.manual_seed(0 ) UpperCAmelCase__ = StableDiffusionDiffEditPipeline.from_pretrained( 'stabilityai/stable-diffusion-2-1' ,safety_checker=lowerCamelCase__ ,torch_dtype=torch.floataa ) UpperCAmelCase__ = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) UpperCAmelCase__ = DPMSolverMultistepInverseScheduler.from_config(pipe.scheduler.config ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=lowerCamelCase__ ) UpperCAmelCase__ = 'a bowl of fruit' UpperCAmelCase__ = 'a bowl of pears' UpperCAmelCase__ = pipe.generate_mask( image=self.raw_image ,source_prompt=lowerCamelCase__ ,target_prompt=lowerCamelCase__ ,generator=lowerCamelCase__ ,) UpperCAmelCase__ = pipe.invert( prompt=lowerCamelCase__ ,image=self.raw_image ,inpaint_strength=0.7 ,generator=lowerCamelCase__ ,num_inference_steps=25 ,).latents UpperCAmelCase__ = pipe( prompt=lowerCamelCase__ ,mask_image=lowerCamelCase__ ,image_latents=lowerCamelCase__ ,generator=lowerCamelCase__ ,negative_prompt=lowerCamelCase__ ,inpaint_strength=0.7 ,num_inference_steps=25 ,output_type='numpy' ,).images[0] UpperCAmelCase__ = ( np.array( load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/diffedit/pears.png' ).resize((768, 768) ) ) / 255 ) assert np.abs((expected_image - image).max() ) < 5e-1
98
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 DeformableDetrImageProcessor 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=400 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _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 , _SCREAMING_SNAKE_CASE=1 / 255 , _SCREAMING_SNAKE_CASE=True , ) -> Dict: """simple docstring""" _UpperCAmelCase = size if size is not None else {'shortest_edge': 18, 'longest_edge': 1333} _UpperCAmelCase = parent _UpperCAmelCase = batch_size _UpperCAmelCase = num_channels _UpperCAmelCase = min_resolution _UpperCAmelCase = max_resolution _UpperCAmelCase = do_resize _UpperCAmelCase = size _UpperCAmelCase = do_normalize _UpperCAmelCase = image_mean _UpperCAmelCase = image_std _UpperCAmelCase = do_rescale _UpperCAmelCase = rescale_factor _UpperCAmelCase = do_pad def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) -> Any: """simple docstring""" if not batched: _UpperCAmelCase = image_inputs[0] if isinstance(_SCREAMING_SNAKE_CASE , Image.Image ): _UpperCAmelCase , _UpperCAmelCase = image.size else: _UpperCAmelCase , _UpperCAmelCase = image.shape[1], image.shape[2] if w < h: _UpperCAmelCase = int(self.size['shortest_edge'] * h / w ) _UpperCAmelCase = self.size['shortest_edge'] elif w > h: _UpperCAmelCase = self.size['shortest_edge'] _UpperCAmelCase = int(self.size['shortest_edge'] * w / h ) else: _UpperCAmelCase = self.size['shortest_edge'] _UpperCAmelCase = self.size['shortest_edge'] else: _UpperCAmelCase = [] for image in image_inputs: _UpperCAmelCase , _UpperCAmelCase = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) _UpperCAmelCase = max(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : item[0] )[0] _UpperCAmelCase = max(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class __a ( UpperCAmelCase , unittest.TestCase ): _a : str = DeformableDetrImageProcessor if is_vision_available() else None def UpperCAmelCase__ ( self ) -> str: """simple docstring""" _UpperCAmelCase = DeformableDetrImageProcessingTester(self ) @property def UpperCAmelCase__ ( self ) -> str: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase__ ( self ) -> List[str]: """simple docstring""" _UpperCAmelCase = 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_resize' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_rescale' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_pad' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'size' ) ) def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" _UpperCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'shortest_edge': 18, 'longest_edge': 1333} ) self.assertEqual(image_processor.do_pad , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = 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 UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" pass def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _UpperCAmelCase = 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 _UpperCAmelCase = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values _UpperCAmelCase , _UpperCAmelCase = 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 _UpperCAmelCase , _UpperCAmelCase = self.image_processor_tester.get_expected_values(_SCREAMING_SNAKE_CASE , batched=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = 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 UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _UpperCAmelCase = 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 _UpperCAmelCase = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values _UpperCAmelCase , _UpperCAmelCase = 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 _UpperCAmelCase = image_processing(_SCREAMING_SNAKE_CASE , return_tensors='pt' ).pixel_values _UpperCAmelCase , _UpperCAmelCase = 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 UpperCAmelCase__ ( self ) -> Any: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _UpperCAmelCase = 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 _UpperCAmelCase = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values _UpperCAmelCase , _UpperCAmelCase = 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 _UpperCAmelCase = image_processing(_SCREAMING_SNAKE_CASE , return_tensors='pt' ).pixel_values _UpperCAmelCase , _UpperCAmelCase = 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 UpperCAmelCase__ ( self ) -> List[str]: """simple docstring""" _UpperCAmelCase = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' , 'r' ) as f: _UpperCAmelCase = json.loads(f.read() ) _UpperCAmelCase = {'image_id': 39769, 'annotations': target} # encode them _UpperCAmelCase = DeformableDetrImageProcessor() _UpperCAmelCase = image_processing(images=_SCREAMING_SNAKE_CASE , annotations=_SCREAMING_SNAKE_CASE , return_tensors='pt' ) # verify pixel values _UpperCAmelCase = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding['pixel_values'].shape , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = 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 _UpperCAmelCase = torch.tensor([5887.9600, 11250.2061, 489353.8438, 837122.7500, 147967.5156, 165732.3438] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , _SCREAMING_SNAKE_CASE ) ) # verify boxes _UpperCAmelCase = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = 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 _UpperCAmelCase = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , _SCREAMING_SNAKE_CASE ) ) # verify is_crowd _UpperCAmelCase = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , _SCREAMING_SNAKE_CASE ) ) # verify class_labels _UpperCAmelCase = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , _SCREAMING_SNAKE_CASE ) ) # verify orig_size _UpperCAmelCase = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , _SCREAMING_SNAKE_CASE ) ) # verify size _UpperCAmelCase = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , _SCREAMING_SNAKE_CASE ) ) @slow def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" _UpperCAmelCase = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' , 'r' ) as f: _UpperCAmelCase = json.loads(f.read() ) _UpperCAmelCase = {'file_name': '000000039769.png', 'image_id': 39769, 'segments_info': target} _UpperCAmelCase = pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic' ) # encode them _UpperCAmelCase = DeformableDetrImageProcessor(format='coco_panoptic' ) _UpperCAmelCase = image_processing(images=_SCREAMING_SNAKE_CASE , annotations=_SCREAMING_SNAKE_CASE , masks_path=_SCREAMING_SNAKE_CASE , return_tensors='pt' ) # verify pixel values _UpperCAmelCase = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding['pixel_values'].shape , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = 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 _UpperCAmelCase = torch.tensor([147979.6875, 165527.0469, 484638.5938, 11292.9375, 5879.6562, 7634.1147] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , _SCREAMING_SNAKE_CASE ) ) # verify boxes _UpperCAmelCase = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = 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 _UpperCAmelCase = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , _SCREAMING_SNAKE_CASE ) ) # verify is_crowd _UpperCAmelCase = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , _SCREAMING_SNAKE_CASE ) ) # verify class_labels _UpperCAmelCase = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , _SCREAMING_SNAKE_CASE ) ) # verify masks _UpperCAmelCase = 822873 self.assertEqual(encoding['labels'][0]['masks'].sum().item() , _SCREAMING_SNAKE_CASE ) # verify orig_size _UpperCAmelCase = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , _SCREAMING_SNAKE_CASE ) ) # verify size _UpperCAmelCase = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , _SCREAMING_SNAKE_CASE ) )
329
0
from __future__ import annotations import unittest from transformers import AutoTokenizer, PegasusConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFPegasusForConditionalGeneration, TFPegasusModel @require_tf class a : """simple docstring""" lowerCamelCase :Optional[int] = PegasusConfig lowerCamelCase :Union[str, Any] = {} lowerCamelCase :str = '''gelu''' def __init__( self , lowerCAmelCase_ , lowerCAmelCase_=13 , lowerCAmelCase_=7 , lowerCAmelCase_=True , lowerCAmelCase_=False , lowerCAmelCase_=99 , lowerCAmelCase_=32 , lowerCAmelCase_=2 , lowerCAmelCase_=4 , lowerCAmelCase_=37 , lowerCAmelCase_=0.1 , lowerCAmelCase_=0.1 , lowerCAmelCase_=40 , lowerCAmelCase_=2 , lowerCAmelCase_=1 , lowerCAmelCase_=0 , ) -> Union[str, Any]: _A = parent _A = batch_size _A = seq_length _A = is_training _A = use_labels _A = vocab_size _A = hidden_size _A = num_hidden_layers _A = num_attention_heads _A = intermediate_size _A = hidden_dropout_prob _A = attention_probs_dropout_prob _A = max_position_embeddings _A = eos_token_id _A = pad_token_id _A = bos_token_id def UpperCAmelCase ( self ) -> Union[str, Any]: _A = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) _A = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) _A = tf.concat([input_ids, eos_tensor] , axis=1 ) _A = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _A = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) _A = prepare_pegasus_inputs_dict(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) return config, inputs_dict def UpperCAmelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ ) -> List[Any]: _A = TFPegasusModel(config=__UpperCAmelCase ).get_decoder() _A = inputs_dict["""input_ids"""] _A = input_ids[:1, :] _A = inputs_dict["""attention_mask"""][:1, :] _A = inputs_dict["""head_mask"""] _A = 1 # first forward pass _A = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , head_mask=__UpperCAmelCase , use_cache=__UpperCAmelCase ) _A , _A = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids _A = ids_tensor((self.batch_size, 3) , config.vocab_size ) _A = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and _A = tf.concat([input_ids, next_tokens] , axis=-1 ) _A = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) _A = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase )[0] _A = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , past_key_values=__UpperCAmelCase )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice _A = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) _A = output_from_no_past[:, -3:, random_slice_idx] _A = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(__UpperCAmelCase , __UpperCAmelCase , rtol=1E-3 ) def snake_case ( snake_case__ :Any , snake_case__ :Optional[Any] , snake_case__ :int , snake_case__ :Tuple=None , snake_case__ :Optional[int]=None , snake_case__ :List[Any]=None , snake_case__ :int=None , snake_case__ :Any=None , ) -> Union[str, Any]: if attention_mask is None: _A = tf.cast(tf.math.not_equal(snake_case__ , config.pad_token_id) , tf.inta) if decoder_attention_mask is None: _A = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id) , tf.inta), ] , axis=-1 , ) if head_mask is None: _A = tf.ones((config.encoder_layers, config.encoder_attention_heads)) if decoder_head_mask is None: _A = tf.ones((config.decoder_layers, config.decoder_attention_heads)) if cross_attn_head_mask is None: _A = tf.ones((config.decoder_layers, config.decoder_attention_heads)) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class a ( __lowerCAmelCase , __lowerCAmelCase , unittest.TestCase ): """simple docstring""" lowerCamelCase :str = (TFPegasusForConditionalGeneration, TFPegasusModel) if is_tf_available() else () lowerCamelCase :List[Any] = (TFPegasusForConditionalGeneration,) if is_tf_available() else () lowerCamelCase :List[Any] = ( { '''conversational''': TFPegasusForConditionalGeneration, '''feature-extraction''': TFPegasusModel, '''summarization''': TFPegasusForConditionalGeneration, '''text2text-generation''': TFPegasusForConditionalGeneration, '''translation''': TFPegasusForConditionalGeneration, } if is_tf_available() else {} ) lowerCamelCase :Dict = True lowerCamelCase :int = False lowerCamelCase :List[str] = False def UpperCAmelCase ( self ) -> Union[str, Any]: _A = TFPegasusModelTester(self ) _A = ConfigTester(self , config_class=__UpperCAmelCase ) def UpperCAmelCase ( self ) -> List[Any]: self.config_tester.run_common_tests() def UpperCAmelCase ( self ) -> str: _A = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*__UpperCAmelCase ) @require_sentencepiece @require_tokenizers @require_tf class a ( unittest.TestCase ): """simple docstring""" lowerCamelCase :Dict = [ ''' PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.''', ''' The London trio are up for best UK act and best album, as well as getting two nominations in the best song category."We got told like this morning \'Oh I think you\'re nominated\'", said Dappy."And I was like \'Oh yeah, which one?\' And now we\'ve got nominated for four awards. I mean, wow!"Bandmate Fazer added: "We thought it\'s best of us to come down and mingle with everyone and say hello to the cameras. And now we find we\'ve got four nominations."The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn\'t be too disappointed if they didn\'t win this time around."At the end of the day we\'re grateful to be where we are in our careers."If it don\'t happen then it don\'t happen - live to fight another day and keep on making albums and hits for the fans."Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers\' All These Things That I\'ve Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year\'s Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border."We just done Edinburgh the other day," said Dappy."We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!" ''', ] lowerCamelCase :Union[str, Any] = [ '''California\'s largest electricity provider has cut power to hundreds of thousands of customers in an effort to''' ''' reduce the risk of wildfires.''', '''N-Dubz have revealed they\'re "grateful" to have been nominated for four Mobo Awards.''', ] # differs slightly from pytorch, likely due to numerical differences in linear layers lowerCamelCase :List[Any] = '''google/pegasus-xsum''' @cached_property def UpperCAmelCase ( self ) -> str: return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def UpperCAmelCase ( self ) -> Dict: _A = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def UpperCAmelCase ( self , **lowerCAmelCase_ ) -> Dict: _A = self.translate_src_text(**__UpperCAmelCase ) assert self.expected_text == generated_words def UpperCAmelCase ( self , **lowerCAmelCase_ ) -> Optional[int]: _A = self.tokenizer(self.src_text , **__UpperCAmelCase , padding=__UpperCAmelCase , return_tensors="""tf""" ) _A = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=__UpperCAmelCase , ) _A = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=__UpperCAmelCase ) return generated_words @slow def UpperCAmelCase ( self ) -> int: self._assert_generated_batch_equal_expected()
354
import cva import numpy as np class a : """simple docstring""" def __init__( self , lowerCAmelCase_ , lowerCAmelCase_ ) -> Any: if k in (0.04, 0.06): _A = k _A = window_size else: raise ValueError("""invalid k value""" ) def __str__( self ) -> str: return str(self.k ) def UpperCAmelCase ( self , lowerCAmelCase_ ) -> tuple[cva.Mat, list[list[int]]]: _A = cva.imread(lowerCAmelCase_ , 0 ) _A , _A = img.shape _A = [] _A = img.copy() _A = cva.cvtColor(lowerCAmelCase_ , cva.COLOR_GRAY2RGB ) _A , _A = np.gradient(lowerCAmelCase_ ) _A = dx**2 _A = dy**2 _A = dx * dy _A = 0.04 _A = self.window_size // 2 for y in range(lowerCAmelCase_ , h - offset ): for x in range(lowerCAmelCase_ , w - offset ): _A = ixx[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() _A = iyy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() _A = ixy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() _A = (wxx * wyy) - (wxy**2) _A = wxx + wyy _A = det - k * (trace**2) # Can change the value if r > 0.5: corner_list.append([x, y, r] ) color_img.itemset((y, x, 0) , 0 ) color_img.itemset((y, x, 1) , 0 ) color_img.itemset((y, x, 2) , 2_55 ) return color_img, corner_list if __name__ == "__main__": _SCREAMING_SNAKE_CASE = HarrisCorner(0.04, 3) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = edge_detect.detect('path_to_image') cva.imwrite('detect.png', color_img)
81
0
"""simple docstring""" import random def SCREAMING_SNAKE_CASE__ ( __UpperCAmelCase ) -> bool: lowercase__: Dict = num - 1 lowercase__: Tuple = 0 while s % 2 == 0: lowercase__: int = s // 2 t += 1 for _ in range(5 ): lowercase__: Tuple = random.randrange(2 , num - 1 ) lowercase__: Union[str, Any] = pow(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) if v != 1: lowercase__: List[str] = 0 while v != (num - 1): if i == t - 1: return False else: lowercase__: str = i + 1 lowercase__: Dict = (v**2) % num return True def SCREAMING_SNAKE_CASE__ ( __UpperCAmelCase ) -> bool: if num < 2: return False lowercase__: int = [ 2, 3, 5, 7, 1_1, 1_3, 1_7, 1_9, 2_3, 2_9, 3_1, 3_7, 4_1, 4_3, 4_7, 5_3, 5_9, 6_1, 6_7, 7_1, 7_3, 7_9, 8_3, 8_9, 9_7, 1_0_1, 1_0_3, 1_0_7, 1_0_9, 1_1_3, 1_2_7, 1_3_1, 1_3_7, 1_3_9, 1_4_9, 1_5_1, 1_5_7, 1_6_3, 1_6_7, 1_7_3, 1_7_9, 1_8_1, 1_9_1, 1_9_3, 1_9_7, 1_9_9, 2_1_1, 2_2_3, 2_2_7, 2_2_9, 2_3_3, 2_3_9, 2_4_1, 2_5_1, 2_5_7, 2_6_3, 2_6_9, 2_7_1, 2_7_7, 2_8_1, 2_8_3, 2_9_3, 3_0_7, 3_1_1, 3_1_3, 3_1_7, 3_3_1, 3_3_7, 3_4_7, 3_4_9, 3_5_3, 3_5_9, 3_6_7, 3_7_3, 3_7_9, 3_8_3, 3_8_9, 3_9_7, 4_0_1, 4_0_9, 4_1_9, 4_2_1, 4_3_1, 4_3_3, 4_3_9, 4_4_3, 4_4_9, 4_5_7, 4_6_1, 4_6_3, 4_6_7, 4_7_9, 4_8_7, 4_9_1, 4_9_9, 5_0_3, 5_0_9, 5_2_1, 5_2_3, 5_4_1, 5_4_7, 5_5_7, 5_6_3, 5_6_9, 5_7_1, 5_7_7, 5_8_7, 5_9_3, 5_9_9, 6_0_1, 6_0_7, 6_1_3, 6_1_7, 6_1_9, 6_3_1, 6_4_1, 6_4_3, 6_4_7, 6_5_3, 6_5_9, 6_6_1, 6_7_3, 6_7_7, 6_8_3, 6_9_1, 7_0_1, 7_0_9, 7_1_9, 7_2_7, 7_3_3, 7_3_9, 7_4_3, 7_5_1, 7_5_7, 7_6_1, 7_6_9, 7_7_3, 7_8_7, 7_9_7, 8_0_9, 8_1_1, 8_2_1, 8_2_3, 8_2_7, 8_2_9, 8_3_9, 8_5_3, 8_5_7, 8_5_9, 8_6_3, 8_7_7, 8_8_1, 8_8_3, 8_8_7, 9_0_7, 9_1_1, 9_1_9, 9_2_9, 9_3_7, 9_4_1, 9_4_7, 9_5_3, 9_6_7, 9_7_1, 9_7_7, 9_8_3, 9_9_1, 9_9_7, ] if num in low_primes: return True for prime in low_primes: if (num % prime) == 0: return False return rabin_miller(__UpperCAmelCase ) def SCREAMING_SNAKE_CASE__ ( __UpperCAmelCase = 1_0_2_4 ) -> int: while True: lowercase__: Optional[int] = random.randrange(2 ** (keysize - 1) , 2 ** (keysize) ) if is_prime_low_num(__UpperCAmelCase ): return num if __name__ == "__main__": __A = generate_large_prime() print(("Prime number:", num)) print(("is_prime_low_num:", is_prime_low_num(num)))
177
"""simple docstring""" def SCREAMING_SNAKE_CASE__ ( __UpperCAmelCase ) -> int: if not grid or not grid[0]: raise TypeError('''The grid does not contain the appropriate information''' ) for cell_n in range(1 , len(grid[0] ) ): grid[0][cell_n] += grid[0][cell_n - 1] lowercase__: Tuple = grid[0] for row_n in range(1 , len(__UpperCAmelCase ) ): lowercase__: Tuple = grid[row_n] lowercase__: Dict = fill_row(__UpperCAmelCase , __UpperCAmelCase ) lowercase__: Union[str, Any] = grid[row_n] return grid[-1][-1] def SCREAMING_SNAKE_CASE__ ( __UpperCAmelCase , __UpperCAmelCase ) -> list: current_row[0] += row_above[0] for cell_n in range(1 , len(__UpperCAmelCase ) ): current_row[cell_n] += min(current_row[cell_n - 1] , row_above[cell_n] ) return current_row if __name__ == "__main__": import doctest doctest.testmod()
177
1
import unittest import torch from torch import nn from diffusers.models.activations import get_activation class lowerCAmelCase ( unittest.TestCase ): def A_ ( self : List[str] ) -> Union[str, Any]: lowerCamelCase__ : int = get_activation('swish' ) self.assertIsInstance(UpperCAmelCase , 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 A_ ( self : Any ) -> Optional[int]: lowerCamelCase__ : Optional[Any] = get_activation('silu' ) self.assertIsInstance(UpperCAmelCase , 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 A_ ( self : Dict ) -> str: lowerCamelCase__ : int = get_activation('mish' ) self.assertIsInstance(UpperCAmelCase , 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 A_ ( self : List[Any] ) -> Tuple: lowerCamelCase__ : Dict = get_activation('gelu' ) self.assertIsInstance(UpperCAmelCase , 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 )
370
import argparse import pytorch_lightning as pl import torch from torch import nn from transformers import LongformerForQuestionAnswering, LongformerModel class lowerCAmelCase ( pl.LightningModule ): def __init__( self : List[str] , UpperCAmelCase : Optional[Any] ) -> int: super().__init__() lowerCamelCase__ : List[str] = model lowerCamelCase__ : Dict = 2 lowerCamelCase__ : Dict = nn.Linear(self.model.config.hidden_size , self.num_labels ) def A_ ( self : Optional[Any] ) -> Optional[Any]: pass def SCREAMING_SNAKE_CASE ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) -> Any: # load longformer model from model identifier lowerCamelCase__ : List[str] = LongformerModel.from_pretrained(_UpperCAmelCase ) lowerCamelCase__ : Dict = LightningModel(_UpperCAmelCase ) lowerCamelCase__ : List[Any] = torch.load(_UpperCAmelCase , map_location=torch.device('cpu' ) ) lightning_model.load_state_dict(ckpt['state_dict'] ) # init longformer question answering model lowerCamelCase__ : Dict = LongformerForQuestionAnswering.from_pretrained(_UpperCAmelCase ) # transfer weights longformer_for_qa.longformer.load_state_dict(lightning_model.model.state_dict() ) longformer_for_qa.qa_outputs.load_state_dict(lightning_model.qa_outputs.state_dict() ) longformer_for_qa.eval() # save model longformer_for_qa.save_pretrained(_UpperCAmelCase ) print(F"""Conversion successful. Model saved under {pytorch_dump_folder_path}""" ) if __name__ == "__main__": _UpperCAmelCase : Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--longformer_model""", default=None, type=str, required=True, help="""model identifier of longformer. Should be either `longformer-base-4096` or `longformer-large-4096`.""", ) parser.add_argument( """--longformer_question_answering_ckpt_path""", default=None, type=str, required=True, help="""Path the official PyTorch Lightning Checkpoint.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) _UpperCAmelCase : Any = parser.parse_args() convert_longformer_qa_checkpoint_to_pytorch( args.longformer_model, args.longformer_question_answering_ckpt_path, args.pytorch_dump_folder_path )
45
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) __snake_case : Dict = {'configuration_deit': ['DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'DeiTConfig', 'DeiTOnnxConfig']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case : List[str] = ['DeiTFeatureExtractor'] __snake_case : Any = ['DeiTImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case : List[Any] = [ 'DEIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'DeiTForImageClassification', 'DeiTForImageClassificationWithTeacher', 'DeiTForMaskedImageModeling', 'DeiTModel', 'DeiTPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case : Dict = [ 'TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFDeiTForImageClassification', 'TFDeiTForImageClassificationWithTeacher', 'TFDeiTForMaskedImageModeling', 'TFDeiTModel', 'TFDeiTPreTrainedModel', ] if TYPE_CHECKING: from .configuration_deit import DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, DeiTConfig, DeiTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_deit import DeiTFeatureExtractor from .image_processing_deit import DeiTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_deit import ( DEIT_PRETRAINED_MODEL_ARCHIVE_LIST, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, DeiTModel, DeiTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_deit import ( TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, TFDeiTModel, TFDeiTPreTrainedModel, ) else: import sys __snake_case : List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
269
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _a = logging.get_logger(__name__) _a = { "camembert-base": "https://huggingface.co/camembert-base/resolve/main/config.json", "umberto-commoncrawl-cased-v1": ( "https://huggingface.co/Musixmatch/umberto-commoncrawl-cased-v1/resolve/main/config.json" ), "umberto-wikipedia-uncased-v1": ( "https://huggingface.co/Musixmatch/umberto-wikipedia-uncased-v1/resolve/main/config.json" ), } class __A ( lowerCAmelCase ): '''simple docstring''' lowerCAmelCase_ = """camembert""" def __init__( self , __lowerCAmelCase=3_0_5_2_2 , __lowerCAmelCase=7_6_8 , __lowerCAmelCase=1_2 , __lowerCAmelCase=1_2 , __lowerCAmelCase=3_0_7_2 , __lowerCAmelCase="gelu" , __lowerCAmelCase=0.1 , __lowerCAmelCase=0.1 , __lowerCAmelCase=5_1_2 , __lowerCAmelCase=2 , __lowerCAmelCase=0.02 , __lowerCAmelCase=1E-12 , __lowerCAmelCase=1 , __lowerCAmelCase=0 , __lowerCAmelCase=2 , __lowerCAmelCase="absolute" , __lowerCAmelCase=True , __lowerCAmelCase=None , **__lowerCAmelCase , ): '''simple docstring''' super().__init__(pad_token_id=__lowerCAmelCase , bos_token_id=__lowerCAmelCase , eos_token_id=__lowerCAmelCase , **__lowerCAmelCase ) lowerCamelCase__ = vocab_size lowerCamelCase__ = hidden_size lowerCamelCase__ = num_hidden_layers lowerCamelCase__ = num_attention_heads lowerCamelCase__ = hidden_act lowerCamelCase__ = intermediate_size lowerCamelCase__ = hidden_dropout_prob lowerCamelCase__ = attention_probs_dropout_prob lowerCamelCase__ = max_position_embeddings lowerCamelCase__ = type_vocab_size lowerCamelCase__ = initializer_range lowerCamelCase__ = layer_norm_eps lowerCamelCase__ = position_embedding_type lowerCamelCase__ = use_cache lowerCamelCase__ = classifier_dropout class __A ( lowerCAmelCase ): '''simple docstring''' @property def __lowerCamelCase ( self ): '''simple docstring''' if self.task == "multiple-choice": lowerCamelCase__ = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: lowerCamelCase__ = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ] )
209
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 __SCREAMING_SNAKE_CASE ( __a ): snake_case_ = ['pixel_values'] def __init__( self : List[str] , snake_case : bool = True , snake_case : Dict[str, int] = None , snake_case : PILImageResampling = PILImageResampling.BICUBIC , snake_case : bool = True , snake_case : Dict[str, int] = None , snake_case : bool = True , snake_case : Union[int, float] = 1 / 255 , snake_case : bool = True , snake_case : Optional[Union[float, List[float]]] = None , snake_case : Optional[Union[float, List[float]]] = None , snake_case : bool = True , **snake_case : List[Any] , ): '''simple docstring''' super().__init__(**UpperCamelCase__ ) A__ : Optional[Any] = size if size is not None else {"""shortest_edge""": 224} A__ : str = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ ) A__ : Optional[Any] = crop_size if crop_size is not None else {"""height""": 224, """width""": 224} A__ : Tuple = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ , param_name="""crop_size""" ) A__ : Dict = do_resize A__ : List[str] = size A__ : Optional[Any] = resample A__ : Optional[int] = do_center_crop A__ : str = crop_size A__ : Tuple = do_rescale A__ : List[str] = rescale_factor A__ : Tuple = do_normalize A__ : str = image_mean if image_mean is not None else OPENAI_CLIP_MEAN A__ : Union[str, Any] = image_std if image_std is not None else OPENAI_CLIP_STD A__ : int = do_convert_rgb def _UpperCamelCase ( self : List[str] , snake_case : np.ndarray , snake_case : Dict[str, int] , snake_case : PILImageResampling = PILImageResampling.BICUBIC , snake_case : Optional[Union[str, ChannelDimension]] = None , **snake_case : Dict , ): '''simple docstring''' A__ : int = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ ) if "shortest_edge" not in size: raise ValueError(F'The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}' ) A__ : Tuple = get_resize_output_image_size(UpperCamelCase__ , size=size["""shortest_edge"""] , default_to_square=UpperCamelCase__ ) return resize(UpperCamelCase__ , size=UpperCamelCase__ , resample=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def _UpperCamelCase ( self : Optional[Any] , snake_case : np.ndarray , snake_case : Dict[str, int] , snake_case : Optional[Union[str, ChannelDimension]] = None , **snake_case : Tuple , ): '''simple docstring''' A__ : List[str] = get_size_dict(UpperCamelCase__ ) 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(UpperCamelCase__ , size=(size["""height"""], size["""width"""]) , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def _UpperCamelCase ( self : Optional[int] , snake_case : np.ndarray , snake_case : Union[int, float] , snake_case : Optional[Union[str, ChannelDimension]] = None , **snake_case : Any , ): '''simple docstring''' return rescale(UpperCamelCase__ , scale=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def _UpperCamelCase ( self : Any , snake_case : np.ndarray , snake_case : Union[float, List[float]] , snake_case : Union[float, List[float]] , snake_case : Optional[Union[str, ChannelDimension]] = None , **snake_case : Optional[int] , ): '''simple docstring''' return normalize(UpperCamelCase__ , mean=UpperCamelCase__ , std=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def _UpperCamelCase ( self : List[str] , snake_case : ImageInput , snake_case : bool = None , snake_case : Dict[str, int] = None , snake_case : PILImageResampling = None , snake_case : bool = None , snake_case : int = None , snake_case : bool = None , snake_case : float = None , snake_case : bool = None , snake_case : Optional[Union[float, List[float]]] = None , snake_case : Optional[Union[float, List[float]]] = None , snake_case : bool = None , snake_case : Optional[Union[str, TensorType]] = None , snake_case : Optional[ChannelDimension] = ChannelDimension.FIRST , **snake_case : Tuple , ): '''simple docstring''' A__ : List[Any] = do_resize if do_resize is not None else self.do_resize A__ : Optional[int] = size if size is not None else self.size A__ : List[Any] = get_size_dict(UpperCamelCase__ , param_name="""size""" , default_to_square=UpperCamelCase__ ) A__ : Union[str, Any] = resample if resample is not None else self.resample A__ : Optional[int] = do_center_crop if do_center_crop is not None else self.do_center_crop A__ : List[Any] = crop_size if crop_size is not None else self.crop_size A__ : List[str] = get_size_dict(UpperCamelCase__ , param_name="""crop_size""" , default_to_square=UpperCamelCase__ ) A__ : Any = do_rescale if do_rescale is not None else self.do_rescale A__ : Any = rescale_factor if rescale_factor is not None else self.rescale_factor A__ : Any = do_normalize if do_normalize is not None else self.do_normalize A__ : Union[str, Any] = image_mean if image_mean is not None else self.image_mean A__ : Optional[Any] = image_std if image_std is not None else self.image_std A__ : Tuple = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb A__ : str = make_list_of_images(UpperCamelCase__ ) if not valid_images(UpperCamelCase__ ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None: 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: A__ : str = [convert_to_rgb(UpperCamelCase__ ) for image in images] # All transformations expect numpy arrays. A__ : Optional[Any] = [to_numpy_array(UpperCamelCase__ ) for image in images] if do_resize: A__ : Union[str, Any] = [self.resize(image=UpperCamelCase__ , size=UpperCamelCase__ , resample=UpperCamelCase__ ) for image in images] if do_center_crop: A__ : Optional[Any] = [self.center_crop(image=UpperCamelCase__ , size=UpperCamelCase__ ) for image in images] if do_rescale: A__ : List[str] = [self.rescale(image=UpperCamelCase__ , scale=UpperCamelCase__ ) for image in images] if do_normalize: A__ : str = [self.normalize(image=UpperCamelCase__ , mean=UpperCamelCase__ , std=UpperCamelCase__ ) for image in images] A__ : List[Any] = [to_channel_dimension_format(UpperCamelCase__ , UpperCamelCase__ ) for image in images] A__ : int = {"""pixel_values""": images} return BatchFeature(data=UpperCamelCase__ , tensor_type=UpperCamelCase__ )
369
"""simple docstring""" import numpy as np class __SCREAMING_SNAKE_CASE : def __init__( self : List[str] ): '''simple docstring''' A__ : Optional[int] = (0, 0) A__ : Dict = None A__ : int = 0 A__ : str = 0 A__ : Optional[Any] = 0 def __eq__( self : str , snake_case : Optional[int] ): '''simple docstring''' return self.position == cell.position def _UpperCamelCase ( self : List[str] ): '''simple docstring''' print(self.position ) class __SCREAMING_SNAKE_CASE : def __init__( self : int , snake_case : Any=(5, 5) ): '''simple docstring''' A__ : Optional[int] = np.zeros(snake_case ) A__ : List[Any] = world_size[0] A__ : Dict = world_size[1] def _UpperCamelCase ( self : Any ): '''simple docstring''' print(self.w ) def _UpperCamelCase ( self : Optional[int] , snake_case : List[Any] ): '''simple docstring''' A__ : int = [ (-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1), ] A__ : int = cell.position[0] A__ : str = cell.position[1] A__ : Any = [] for n in neughbour_cord: A__ : List[Any] = current_x + n[0] A__ : Tuple = current_y + n[1] if 0 <= x < self.world_x_limit and 0 <= y < self.world_y_limit: A__ : List[Any] = Cell() A__ : str = (x, y) A__ : Optional[Any] = cell neighbours.append(snake_case ) return neighbours def _lowerCAmelCase ( UpperCAmelCase__ : List[str], UpperCAmelCase__ : Optional[Any], UpperCAmelCase__ : Dict ) ->Dict: A__ : Union[str, Any] = [] A__ : Optional[int] = [] _open.append(UpperCAmelCase__ ) while _open: A__ : List[Any] = np.argmin([n.f for n in _open] ) A__ : Union[str, Any] = _open[min_f] _closed.append(_open.pop(UpperCAmelCase__ ) ) if current == goal: break for n in world.get_neigbours(UpperCAmelCase__ ): for c in _closed: if c == n: continue A__ : Dict = current.g + 1 A__ , A__ : int = n.position A__ , A__ : Optional[int] = goal.position A__ : Union[str, Any] = (ya - ya) ** 2 + (xa - xa) ** 2 A__ : Optional[int] = n.h + n.g for c in _open: if c == n and c.f < n.f: continue _open.append(UpperCAmelCase__ ) A__ : List[str] = [] while current.parent is not None: path.append(current.position ) A__ : Union[str, Any] = current.parent path.append(current.position ) return path[::-1] if __name__ == "__main__": A_ = Gridworld() # Start position and goal A_ = Cell() A_ = (0, 0) A_ = Cell() A_ = (4, 4) print(F'path from {start.position} to {goal.position}') A_ = astar(world, start, goal) # Just for visual reasons. for i in s: A_ = 1 print(world.w)
296
0
"""simple docstring""" import argparse import re import requests import torch # git clone https://github.com/salesforce/BLIP.git from models.blip import blip_decoder from models.blip_itm import blip_itm from models.blip_vqa import blip_vqa from PIL import Image from torchvision import transforms from torchvision.transforms.functional import InterpolationMode from transformers import ( BertTokenizer, BlipConfig, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, ) def lowercase ( _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Optional[int] ): '''simple docstring''' _UpperCAmelCase = '''https://storage.googleapis.com/sfr-vision-language-research/BLIP/demo.jpg''' _UpperCAmelCase = Image.open(requests.get(_SCREAMING_SNAKE_CASE , stream=_SCREAMING_SNAKE_CASE ).raw ).convert('''RGB''' ) _UpperCAmelCase = transforms.Compose( [ transforms.Resize((image_size, image_size) , interpolation=InterpolationMode.BICUBIC ), transforms.ToTensor(), transforms.Normalize((0.48145466, 0.4578275, 0.40821073) , (0.26862954, 0.26130258, 0.27577711) ), ] ) _UpperCAmelCase = transform(_SCREAMING_SNAKE_CASE ).unsqueeze(0 ).to(_SCREAMING_SNAKE_CASE ) return image def lowercase ( _SCREAMING_SNAKE_CASE : Optional[int] ): '''simple docstring''' if "visual_encoder" in key: _UpperCAmelCase = re.sub('''visual_encoder*''' , '''vision_model.encoder''' , _SCREAMING_SNAKE_CASE ) if "blocks" in key: _UpperCAmelCase = re.sub(r'''blocks''' , '''layers''' , _SCREAMING_SNAKE_CASE ) if "attn" in key: _UpperCAmelCase = re.sub(r'''attn''' , '''self_attn''' , _SCREAMING_SNAKE_CASE ) if "norm1" in key: _UpperCAmelCase = re.sub(r'''norm1''' , '''layer_norm1''' , _SCREAMING_SNAKE_CASE ) if "norm2" in key: _UpperCAmelCase = re.sub(r'''norm2''' , '''layer_norm2''' , _SCREAMING_SNAKE_CASE ) if "encoder.norm" in key: _UpperCAmelCase = re.sub(r'''encoder.norm''' , '''post_layernorm''' , _SCREAMING_SNAKE_CASE ) if "encoder.patch_embed.proj" in key: _UpperCAmelCase = re.sub(r'''encoder.patch_embed.proj''' , '''embeddings.patch_embedding''' , _SCREAMING_SNAKE_CASE ) if "encoder.pos_embed" in key: _UpperCAmelCase = re.sub(r'''encoder.pos_embed''' , '''embeddings.position_embedding''' , _SCREAMING_SNAKE_CASE ) if "encoder.cls_token" in key: _UpperCAmelCase = re.sub(r'''encoder.cls_token''' , '''embeddings.class_embedding''' , _SCREAMING_SNAKE_CASE ) if "self_attn" in key: _UpperCAmelCase = re.sub(r'''self_attn.proj''' , '''self_attn.projection''' , _SCREAMING_SNAKE_CASE ) return key @torch.no_grad() def lowercase ( _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : Any=None ): '''simple docstring''' if config_path is not None: _UpperCAmelCase = BlipConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) else: _UpperCAmelCase = BlipConfig(projection_dim=512 , text_config={} , vision_config={} ) _UpperCAmelCase = BlipForConditionalGeneration(_SCREAMING_SNAKE_CASE ).eval() _UpperCAmelCase = '''https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_capfilt_large.pth''' _UpperCAmelCase = blip_decoder(pretrained=_SCREAMING_SNAKE_CASE , image_size=384 , vit='''base''' ) _UpperCAmelCase = pt_model.eval() _UpperCAmelCase = pt_model.state_dict() for key in modified_state_dict.copy(): _UpperCAmelCase = modified_state_dict.pop(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = rename_key(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = value hf_model.load_state_dict(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = 384 _UpperCAmelCase = load_demo_image(image_size=_SCREAMING_SNAKE_CASE , device='''cpu''' ) _UpperCAmelCase = BertTokenizer.from_pretrained('''bert-base-uncased''' ) _UpperCAmelCase = tokenizer(['''a picture of'''] ).input_ids _UpperCAmelCase = hf_model.generate(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) assert out[0].tolist() == [3_0522, 1037, 3861, 1997, 1037, 2450, 3564, 2006, 1996, 3509, 2007, 2014, 3899, 102] _UpperCAmelCase = hf_model.generate(_SCREAMING_SNAKE_CASE ) assert out[0].tolist() == [3_0522, 1037, 2450, 3564, 2006, 1996, 3509, 2007, 2014, 3899, 102] if pytorch_dump_folder_path is not None: hf_model.save_pretrained(_SCREAMING_SNAKE_CASE ) # model_url = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_vqa.pth' _UpperCAmelCase = ( '''https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_vqa_capfilt_large.pth''' ) _UpperCAmelCase = blip_vqa(pretrained=_SCREAMING_SNAKE_CASE , image_size=_SCREAMING_SNAKE_CASE , vit='''base''' ) vqa_model.eval() _UpperCAmelCase = vqa_model.state_dict() for key in modified_state_dict.copy(): _UpperCAmelCase = modified_state_dict.pop(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = rename_key(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = value _UpperCAmelCase = BlipForQuestionAnswering(_SCREAMING_SNAKE_CASE ) hf_vqa_model.load_state_dict(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = ['''How many dogs are in this image?'''] _UpperCAmelCase = tokenizer(_SCREAMING_SNAKE_CASE , return_tensors='''pt''' ).input_ids _UpperCAmelCase = hf_vqa_model.generate(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) print(tokenizer.decode(answer[0] ) ) assert tokenizer.decode(answer[0] ) == "[UNK] 1 [SEP]" if pytorch_dump_folder_path is not None: hf_vqa_model.save_pretrained(pytorch_dump_folder_path + '''_vqa''' ) _UpperCAmelCase = '''https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_retrieval_coco.pth''' _UpperCAmelCase = blip_itm(pretrained=_SCREAMING_SNAKE_CASE , image_size=_SCREAMING_SNAKE_CASE , vit='''base''' ) itm_model.eval() _UpperCAmelCase = itm_model.state_dict() for key in modified_state_dict.copy(): _UpperCAmelCase = modified_state_dict.pop(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = rename_key(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = value _UpperCAmelCase = BlipForImageTextRetrieval(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = ['''A picture of a woman with a dog sitting in a beach'''] _UpperCAmelCase = tokenizer( _SCREAMING_SNAKE_CASE , return_tensors='''pt''' , padding='''max_length''' , truncation=_SCREAMING_SNAKE_CASE , max_length=35 , ).input_ids hf_itm_model.load_state_dict(_SCREAMING_SNAKE_CASE ) hf_itm_model.eval() _UpperCAmelCase = hf_itm_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , use_itm_head=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = hf_itm_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , use_itm_head=_SCREAMING_SNAKE_CASE ) assert out[0].item() == 0.2110687494277954 assert torch.nn.functional.softmax(out_itm[0] , dim=1 )[:, 1].item() == 0.45698845386505127 if pytorch_dump_folder_path is not None: hf_itm_model.save_pretrained(pytorch_dump_folder_path + '''_itm''' ) if __name__ == "__main__": __A : List[str] = argparse.ArgumentParser() parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert") __A : List[str] = parser.parse_args() convert_blip_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
260
"""simple docstring""" def lowercase ( ): '''simple docstring''' _UpperCAmelCase = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] _UpperCAmelCase = 6 _UpperCAmelCase = 1 _UpperCAmelCase = 1901 _UpperCAmelCase = 0 while year < 2001: day += 7 if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0): if day > days_per_month[month - 1] and month != 2: month += 1 _UpperCAmelCase = day - days_per_month[month - 2] elif day > 29 and month == 2: month += 1 _UpperCAmelCase = day - 29 else: if day > days_per_month[month - 1]: month += 1 _UpperCAmelCase = day - days_per_month[month - 2] if month > 12: year += 1 _UpperCAmelCase = 1 if year < 2001 and day == 1: sundays += 1 return sundays if __name__ == "__main__": print(solution())
260
1
import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ConvNextConfig, UperNetConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import UperNetForSemanticSegmentation from transformers.models.upernet.modeling_upernet import UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class A: '''simple docstring''' def __init__( self : str , A_ : List[Any] , A_ : List[Any]=13 , A_ : Optional[Any]=32 , A_ : Union[str, Any]=3 , A_ : List[str]=4 , A_ : Dict=[10, 20, 30, 40] , A_ : List[str]=[2, 2, 3, 2] , A_ : Dict=True , A_ : Optional[Any]=True , A_ : Optional[int]=37 , A_ : List[Any]="gelu" , A_ : str=10 , A_ : Optional[Any]=0.02 , A_ : int=["stage2", "stage3", "stage4"] , A_ : Union[str, Any]=3 , A_ : List[str]=None , ) -> Optional[int]: """simple docstring""" lowerCamelCase_ = parent lowerCamelCase_ = batch_size lowerCamelCase_ = image_size lowerCamelCase_ = num_channels lowerCamelCase_ = num_stages lowerCamelCase_ = hidden_sizes lowerCamelCase_ = depths lowerCamelCase_ = is_training lowerCamelCase_ = use_labels lowerCamelCase_ = intermediate_size lowerCamelCase_ = hidden_act lowerCamelCase_ = type_sequence_label_size lowerCamelCase_ = initializer_range lowerCamelCase_ = out_features lowerCamelCase_ = num_labels lowerCamelCase_ = scope lowerCamelCase_ = num_stages def a__ ( self : Union[str, Any] ) -> str: """simple docstring""" lowerCamelCase_ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCamelCase_ = None if self.use_labels: lowerCamelCase_ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCamelCase_ = self.get_config() return config, pixel_values, labels def a__ ( self : Optional[Any] ) -> Any: """simple docstring""" return ConvNextConfig( num_channels=self.num_channels , num_stages=self.num_stages , hidden_sizes=self.hidden_sizes , depths=self.depths , is_training=self.is_training , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , out_features=self.out_features , ) def a__ ( self : str ) -> Union[str, Any]: """simple docstring""" return UperNetConfig( backbone_config=self.get_backbone_config() , hidden_size=512 , pool_scales=[1, 2, 3, 6] , use_auxiliary_head=A_ , auxiliary_loss_weight=0.4 , auxiliary_in_channels=40 , auxiliary_channels=256 , auxiliary_num_convs=1 , auxiliary_concat_input=A_ , loss_ignore_index=255 , num_labels=self.num_labels , ) def a__ ( self : str , A_ : Any , A_ : str , A_ : List[str] ) -> Optional[Any]: """simple docstring""" lowerCamelCase_ = UperNetForSemanticSegmentation(config=A_ ) model.to(A_ ) model.eval() lowerCamelCase_ = model(A_ ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size, self.image_size) ) def a__ ( self : Union[str, Any] ) -> List[Any]: """simple docstring""" lowerCamelCase_ = self.prepare_config_and_inputs() ( ( lowerCamelCase_ ) , ( lowerCamelCase_ ) , ( lowerCamelCase_ ) , ) = config_and_inputs lowerCamelCase_ = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class A( UpperCamelCase , UpperCamelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase = (UperNetForSemanticSegmentation,) if is_torch_available() else () UpperCamelCase = {'''image-segmentation''': UperNetForSemanticSegmentation} if is_torch_available() else {} UpperCamelCase = False UpperCamelCase = False UpperCamelCase = False UpperCamelCase = False UpperCamelCase = False UpperCamelCase = False def a__ ( self : Optional[int] ) -> Optional[Any]: """simple docstring""" lowerCamelCase_ = UperNetModelTester(self ) lowerCamelCase_ = ConfigTester(self , config_class=A_ , has_text_modality=A_ , hidden_size=37 ) def a__ ( self : Optional[Any] ) -> Optional[int]: """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 a__ ( self : List[str] ) -> List[Any]: """simple docstring""" return def a__ ( self : Tuple ) -> Union[str, Any]: """simple docstring""" lowerCamelCase_ , lowerCamelCase_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase_ = model_class(A_ ) lowerCamelCase_ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCamelCase_ = [*signature.parameters.keys()] lowerCamelCase_ = ['pixel_values'] self.assertListEqual(arg_names[:1] , A_ ) def a__ ( self : Union[str, Any] ) -> Dict: """simple docstring""" lowerCamelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*A_ ) @unittest.skip(reason='UperNet does not use inputs_embeds' ) def a__ ( self : List[Any] ) -> str: """simple docstring""" pass @unittest.skip(reason='UperNet does not support input and output embeddings' ) def a__ ( self : Optional[int] ) -> int: """simple docstring""" pass @unittest.skip(reason='UperNet does not have a base model' ) def a__ ( self : str ) -> str: """simple docstring""" pass @unittest.skip(reason='UperNet does not have a base model' ) def a__ ( self : Optional[Any] ) -> int: """simple docstring""" pass @require_torch_multi_gpu @unittest.skip(reason='UperNet has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`' ) def a__ ( self : Tuple ) -> Optional[Any]: """simple docstring""" pass @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def a__ ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" pass def a__ ( self : List[Any] ) -> Optional[Any]: """simple docstring""" def check_hidden_states_output(A_ : str , A_ : List[Any] , A_ : Optional[Any] ): lowerCamelCase_ = model_class(A_ ) model.to(A_ ) model.eval() with torch.no_grad(): lowerCamelCase_ = model(**self._prepare_for_class(A_ , A_ ) ) lowerCamelCase_ = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states lowerCamelCase_ = self.model_tester.num_stages self.assertEqual(len(A_ ) , expected_num_stages + 1 ) # ConvNext's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) lowerCamelCase_ , lowerCamelCase_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase_ = True check_hidden_states_output(A_ , A_ , A_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCamelCase_ = True check_hidden_states_output(A_ , A_ , A_ ) def a__ ( self : Dict ) -> Any: """simple docstring""" lowerCamelCase_ , lowerCamelCase_ = self.model_tester.prepare_config_and_inputs_for_common() lowerCamelCase_ = _config_zero_init(A_ ) lowerCamelCase_ = _config_zero_init(configs_no_init.backbone_config ) for model_class in self.all_model_classes: lowerCamelCase_ = model_class(config=A_ ) for name, param in model.named_parameters(): if param.requires_grad: self.assertIn( ((param.data.mean() * 1E9).round() / 1E9).item() , [0.0, 1.0] , msg=f"""Parameter {name} of model {model_class} seems not properly initialized""" , ) @unittest.skip(reason='UperNet does not have tied weights' ) def a__ ( self : List[Any] ) -> int: """simple docstring""" pass @slow def a__ ( self : int ) -> List[Any]: """simple docstring""" for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCamelCase_ = UperNetForSemanticSegmentation.from_pretrained(A_ ) self.assertIsNotNone(A_ ) def _SCREAMING_SNAKE_CASE ( ): '''simple docstring''' lowerCamelCase_ = hf_hub_download( repo_id='hf-internal-testing/fixtures_ade20k' , repo_type='dataset' , filename='ADE_val_00000001.jpg' ) lowerCamelCase_ = Image.open(lowercase ).convert('RGB' ) return image @require_torch @require_vision @slow class A( unittest.TestCase ): '''simple docstring''' def a__ ( self : str ) -> List[str]: """simple docstring""" lowerCamelCase_ = AutoImageProcessor.from_pretrained('openmmlab/upernet-swin-tiny' ) lowerCamelCase_ = UperNetForSemanticSegmentation.from_pretrained('openmmlab/upernet-swin-tiny' ).to(A_ ) lowerCamelCase_ = prepare_img() lowerCamelCase_ = processor(images=A_ , return_tensors='pt' ).to(A_ ) with torch.no_grad(): lowerCamelCase_ = model(**A_ ) lowerCamelCase_ = torch.Size((1, model.config.num_labels, 512, 512) ) self.assertEqual(outputs.logits.shape , A_ ) lowerCamelCase_ = torch.tensor( [[-7.5958, -7.5958, -7.4302], [-7.5958, -7.5958, -7.4302], [-7.4797, -7.4797, -7.3068]] ).to(A_ ) self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3] , A_ , atol=1E-4 ) ) def a__ ( self : List[str] ) -> Optional[int]: """simple docstring""" lowerCamelCase_ = AutoImageProcessor.from_pretrained('openmmlab/upernet-convnext-tiny' ) lowerCamelCase_ = UperNetForSemanticSegmentation.from_pretrained('openmmlab/upernet-convnext-tiny' ).to(A_ ) lowerCamelCase_ = prepare_img() lowerCamelCase_ = processor(images=A_ , return_tensors='pt' ).to(A_ ) with torch.no_grad(): lowerCamelCase_ = model(**A_ ) lowerCamelCase_ = torch.Size((1, model.config.num_labels, 512, 512) ) self.assertEqual(outputs.logits.shape , A_ ) lowerCamelCase_ = torch.tensor( [[-8.8110, -8.8110, -8.6521], [-8.8110, -8.8110, -8.6521], [-8.7746, -8.7746, -8.6130]] ).to(A_ ) self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3] , A_ , atol=1E-4 ) )
208
import os import time import numpy as np import onnxruntime as ort lowerCamelCase : int = "1" lowerCamelCase : int = "0" lowerCamelCase : Union[str, Any] = "1" lowerCamelCase : List[Any] = ort.SessionOptions() lowerCamelCase : Optional[Any] = ort.GraphOptimizationLevel.ORT_DISABLE_ALL print("Create inference session...") lowerCamelCase : Union[str, Any] = ["TensorrtExecutionProvider", "CUDAExecutionProvider"] lowerCamelCase : Tuple = ort.InferenceSession("model.onnx", sess_options=sess_opt, providers=execution_provider) lowerCamelCase : List[Any] = ort.RunOptions() lowerCamelCase : List[str] = 128 lowerCamelCase : List[Any] = 1 lowerCamelCase : Union[str, Any] = np.ones((batch, sequence), dtype=np.intaa) lowerCamelCase : Dict = np.ones((batch, sequence), dtype=np.intaa) lowerCamelCase : Optional[Any] = np.ones((batch, sequence), dtype=np.intaa) print("Warm up phase...") sess.run( None, { sess.get_inputs()[0].name: input_ids, sess.get_inputs()[1].name: attention_mask, sess.get_inputs()[2].name: token_type_ids, }, run_options=run_opt, ) print("Start inference...") lowerCamelCase : int = time.time() lowerCamelCase : Dict = 2_000 lowerCamelCase : Any = {} for iter in range(max_iters): lowerCamelCase : Union[str, Any] = sess.run( None, { sess.get_inputs()[0].name: input_ids, sess.get_inputs()[1].name: attention_mask, sess.get_inputs()[2].name: token_type_ids, }, run_options=run_opt, ) print("Average Inference Time = {:.3f} ms".format((time.time() - start_time) * 1_000 / max_iters))
208
1
'''simple docstring''' import importlib.metadata import warnings from copy import deepcopy from packaging import version from ..utils import logging from .import_utils import is_accelerate_available, is_bitsandbytes_available if is_bitsandbytes_available(): import bitsandbytes as bnb import torch import torch.nn as nn from ..pytorch_utils import ConvaD if is_accelerate_available(): from accelerate import init_empty_weights from accelerate.utils import find_tied_parameters lowerCamelCase : int = logging.get_logger(__name__) def _SCREAMING_SNAKE_CASE (A , A , A , A=None , A=None ) -> int: """simple docstring""" if "." in tensor_name: lowercase__ = tensor_name.split('''.''' ) for split in splits[:-1]: lowercase__ = getattr(A , A ) if new_module is None: raise ValueError(f"{module} has no attribute {split}." ) lowercase__ = new_module lowercase__ = splits[-1] if tensor_name not in module._parameters and tensor_name not in module._buffers: raise ValueError(f"{module} does not have a parameter or a buffer named {tensor_name}." ) lowercase__ = tensor_name in module._buffers lowercase__ = getattr(A , A ) if old_value.device == torch.device('''meta''' ) and device not in ["meta", torch.device('''meta''' )] and value is None: raise ValueError(f"{tensor_name} is on the meta device, we need a `value` to put in on {device}." ) lowercase__ = False lowercase__ = False if is_buffer or not is_bitsandbytes_available(): lowercase__ = False lowercase__ = False else: lowercase__ = hasattr(bnb.nn , '''Params4bit''' ) and isinstance(module._parameters[tensor_name] , bnb.nn.Paramsabit ) lowercase__ = isinstance(module._parameters[tensor_name] , bnb.nn.IntaParams ) if is_abit or is_abit: lowercase__ = module._parameters[tensor_name] if param.device.type != "cuda": if value is None: lowercase__ = old_value.to(A ) elif isinstance(A , torch.Tensor ): lowercase__ = value.to('''cpu''' ) if value.dtype == torch.inta: lowercase__ = version.parse(importlib.metadata.version('''bitsandbytes''' ) ) > version.parse( '''0.37.2''' ) if not is_abit_serializable: raise ValueError( '''Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. ''' '''Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`.''' ) else: lowercase__ = torch.tensor(A , device='''cpu''' ) # Support models using `Conv1D` in place of `nn.Linear` (e.g. gpt2) by transposing the weight matrix prior to quantization. # Since weights are saved in the correct "orientation", we skip transposing when loading. if issubclass(module.source_cls , A ) and fpaa_statistics is None: lowercase__ = new_value.T lowercase__ = old_value.__dict__ if is_abit: lowercase__ = bnb.nn.IntaParams(A , requires_grad=A , **A ).to(A ) elif is_abit: lowercase__ = bnb.nn.Paramsabit(A , requires_grad=A , **A ).to(A ) lowercase__ = new_value if fpaa_statistics is not None: setattr(module.weight , '''SCB''' , fpaa_statistics.to(A ) ) else: if value is None: lowercase__ = old_value.to(A ) elif isinstance(A , torch.Tensor ): lowercase__ = value.to(A ) else: lowercase__ = torch.tensor(A , device=A ) if is_buffer: lowercase__ = new_value else: lowercase__ = nn.Parameter(A , requires_grad=old_value.requires_grad ) lowercase__ = new_value def _SCREAMING_SNAKE_CASE (A , A=None , A=None , A=None , A=False ) -> Union[str, Any]: """simple docstring""" for name, module in model.named_children(): if current_key_name is None: lowercase__ = [] current_key_name.append(A ) if (isinstance(A , nn.Linear ) or isinstance(A , A )) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` if not any(key in '''.'''.join(A ) for key in modules_to_not_convert ): with init_empty_weights(): if isinstance(A , A ): lowercase__ ,lowercase__ = module.weight.shape else: lowercase__ = module.in_features lowercase__ = module.out_features if quantization_config.quantization_method() == "llm_int8": lowercase__ = bnb.nn.LinearabitLt( A , A , module.bias is not None , has_fpaa_weights=quantization_config.llm_inta_has_fpaa_weight , threshold=quantization_config.llm_inta_threshold , ) lowercase__ = True else: if ( quantization_config.llm_inta_skip_modules is not None and name in quantization_config.llm_inta_skip_modules ): pass else: lowercase__ = bnb.nn.Linearabit( A , A , module.bias is not None , quantization_config.bnb_abit_compute_dtype , compress_statistics=quantization_config.bnb_abit_use_double_quant , quant_type=quantization_config.bnb_abit_quant_type , ) lowercase__ = True # Store the module class in case we need to transpose the weight later lowercase__ = type(A ) # Force requires grad to False to avoid unexpected errors model._modules[name].requires_grad_(A ) if len(list(module.children() ) ) > 0: lowercase__ ,lowercase__ = _replace_with_bnb_linear( A , A , A , A , has_been_replaced=A , ) # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def _SCREAMING_SNAKE_CASE (A , A=None , A=None , A=None ) -> Optional[int]: """simple docstring""" lowercase__ = ['''lm_head'''] if modules_to_not_convert is None else modules_to_not_convert lowercase__ ,lowercase__ = _replace_with_bnb_linear( A , A , A , A ) if not has_been_replaced: logger.warning( '''You are loading your model in 8bit or 4bit but no linear modules were found in your model.''' ''' Please double check your model architecture, or submit an issue on github if you think this is''' ''' a bug.''' ) return model def _SCREAMING_SNAKE_CASE (*A , **A ) -> List[str]: """simple docstring""" warnings.warn( '''`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead''' , A , ) return replace_with_bnb_linear(*A , **A ) def _SCREAMING_SNAKE_CASE (*A , **A ) -> Tuple: """simple docstring""" warnings.warn( '''`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead''' , A , ) return set_module_quantized_tensor_to_device(*A , **A ) def _SCREAMING_SNAKE_CASE (A ) -> int: """simple docstring""" lowercase__ = deepcopy(A ) # this has 0 cost since it is done inside `init_empty_weights` context manager` tied_model.tie_weights() lowercase__ = find_tied_parameters(A ) # For compatibility with Accelerate < 0.18 if isinstance(A , A ): lowercase__ = sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() ) else: lowercase__ = sum(A , [] ) lowercase__ = len(A ) > 0 # Check if it is a base model lowercase__ = not hasattr(A , model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head lowercase__ = list(model.named_children() ) lowercase__ = [list_modules[-1][0]] # add last module together with tied weights lowercase__ = set(A ) - set(A ) lowercase__ = list(set(A ) ) + list(A ) # remove ".weight" from the keys lowercase__ = ['''.weight''', '''.bias'''] lowercase__ = [] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: lowercase__ = name.replace(A , '''''' ) filtered_module_names.append(A ) return filtered_module_names
2
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_torch_available, ) lowerCAmelCase_ = { 'configuration_speecht5': [ 'SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP', 'SpeechT5Config', 'SpeechT5HifiGanConfig', ], 'feature_extraction_speecht5': ['SpeechT5FeatureExtractor'], 'processing_speecht5': ['SpeechT5Processor'], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = ['SpeechT5Tokenizer'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ 'SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST', 'SpeechT5ForSpeechToText', 'SpeechT5ForSpeechToSpeech', 'SpeechT5ForTextToSpeech', 'SpeechT5Model', 'SpeechT5PreTrainedModel', 'SpeechT5HifiGan', ] if TYPE_CHECKING: from .configuration_speechta import ( SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP, SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP, SpeechTaConfig, SpeechTaHifiGanConfig, ) from .feature_extraction_speechta import SpeechTaFeatureExtractor from .processing_speechta import SpeechTaProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speechta import SpeechTaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speechta import ( SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechTaForSpeechToSpeech, SpeechTaForSpeechToText, SpeechTaForTextToSpeech, SpeechTaHifiGan, SpeechTaModel, SpeechTaPreTrainedModel, ) else: import sys lowerCAmelCase_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
16
0
"""simple docstring""" # coding=utf-8 # Copyright 2020 The HuggingFace Inc. team. # # 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. # this script dumps information about the environment import os import sys import transformers a__ : Optional[int] = '''3''' print('''Python version:''', sys.version) print('''transformers version:''', transformers.__version__) try: import torch print('''Torch version:''', torch.__version__) print('''Cuda available:''', torch.cuda.is_available()) print('''Cuda version:''', torch.version.cuda) print('''CuDNN version:''', torch.backends.cudnn.version()) print('''Number of GPUs available:''', torch.cuda.device_count()) print('''NCCL version:''', torch.cuda.nccl.version()) except ImportError: print('''Torch version:''', None) try: import deepspeed print('''DeepSpeed version:''', deepspeed.__version__) except ImportError: print('''DeepSpeed version:''', None) try: import tensorflow as tf print('''TensorFlow version:''', tf.__version__) print('''TF GPUs available:''', bool(tf.config.list_physical_devices('''GPU'''))) print('''Number of TF GPUs available:''', len(tf.config.list_physical_devices('''GPU'''))) except ImportError: print('''TensorFlow version:''', None)
195
"""simple docstring""" import inspect import unittest import numpy as np from transformers import ViTConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor if is_flax_available(): import jax from transformers.models.vit.modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Tuple=1_3 , UpperCAmelCase__ : Optional[int]=3_0 , UpperCAmelCase__ : Any=2 , UpperCAmelCase__ : List[str]=3 , UpperCAmelCase__ : Optional[Any]=True , UpperCAmelCase__ : Optional[int]=True , UpperCAmelCase__ : int=3_2 , UpperCAmelCase__ : Any=5 , UpperCAmelCase__ : Union[str, Any]=4 , UpperCAmelCase__ : List[str]=3_7 , UpperCAmelCase__ : Tuple="gelu" , UpperCAmelCase__ : List[str]=0.1 , UpperCAmelCase__ : str=0.1 , UpperCAmelCase__ : Any=1_0 , UpperCAmelCase__ : str=0.02 , ) -> Tuple: __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = patch_size __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = type_sequence_label_size __SCREAMING_SNAKE_CASE = initializer_range # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) __SCREAMING_SNAKE_CASE = (image_size // patch_size) ** 2 __SCREAMING_SNAKE_CASE = num_patches + 1 def UpperCAmelCase_ ( self : Union[str, Any] ) -> Tuple: __SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __SCREAMING_SNAKE_CASE = ViTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=UpperCAmelCase__ , initializer_range=self.initializer_range , ) return config, pixel_values def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : str , UpperCAmelCase__ : List[str] ) -> Any: __SCREAMING_SNAKE_CASE = FlaxViTModel(config=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token) __SCREAMING_SNAKE_CASE = (self.image_size, self.image_size) __SCREAMING_SNAKE_CASE = (self.patch_size, self.patch_size) __SCREAMING_SNAKE_CASE = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, num_patches + 1, self.hidden_size) ) def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Tuple ) -> Tuple: __SCREAMING_SNAKE_CASE = self.type_sequence_label_size __SCREAMING_SNAKE_CASE = FlaxViTForImageClassification(config=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = FlaxViTForImageClassification(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[Any]: __SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() ( ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ) = config_and_inputs __SCREAMING_SNAKE_CASE = {"pixel_values": pixel_values} return config, inputs_dict @require_flax class UpperCamelCase_ ( UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : List[str] = (FlaxViTModel, FlaxViTForImageClassification) if is_flax_available() else () def UpperCAmelCase_ ( self : int ) -> None: __SCREAMING_SNAKE_CASE = FlaxViTModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=UpperCAmelCase__ , has_text_modality=UpperCAmelCase__ , hidden_size=3_7 ) def UpperCAmelCase_ ( self : int ) -> Union[str, Any]: self.config_tester.run_common_tests() def UpperCAmelCase_ ( self : Tuple ) -> List[str]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Dict ) -> Dict: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple ) -> Any: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE = model_class(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = inspect.signature(model.__call__ ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __SCREAMING_SNAKE_CASE = [*signature.parameters.keys()] __SCREAMING_SNAKE_CASE = ["pixel_values"] self.assertListEqual(arg_names[:1] , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Any ) -> List[Any]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __SCREAMING_SNAKE_CASE = self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model_class(UpperCAmelCase__ ) @jax.jit def model_jitted(UpperCAmelCase__ : Optional[int] , **UpperCAmelCase__ : Any ): return model(pixel_values=UpperCAmelCase__ , **UpperCAmelCase__ ) with self.subTest("JIT Enabled" ): __SCREAMING_SNAKE_CASE = model_jitted(**UpperCAmelCase__ ).to_tuple() with self.subTest("JIT Disabled" ): with jax.disable_jit(): __SCREAMING_SNAKE_CASE = model_jitted(**UpperCAmelCase__ ).to_tuple() self.assertEqual(len(UpperCAmelCase__ ) , len(UpperCAmelCase__ ) ) for jitted_output, output in zip(UpperCAmelCase__ , UpperCAmelCase__ ): self.assertEqual(jitted_output.shape , output.shape ) @slow def UpperCAmelCase_ ( self : int ) -> Union[str, Any]: for model_class_name in self.all_model_classes: __SCREAMING_SNAKE_CASE = model_class_name.from_pretrained("google/vit-base-patch16-224" ) __SCREAMING_SNAKE_CASE = model(np.ones((1, 3, 2_2_4, 2_2_4) ) ) self.assertIsNotNone(UpperCAmelCase__ )
195
1
from sklearn.metrics import fa_score, matthews_corrcoef import datasets from .record_evaluation import evaluate as evaluate_record a__ = """\ @article{wang2019superglue, title={SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems}, author={Wang, Alex and Pruksachatkun, Yada and Nangia, Nikita and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R}, journal={arXiv preprint arXiv:1905.00537}, year={2019} } """ a__ = """\ SuperGLUE (https://super.gluebenchmark.com/) is a new benchmark styled after GLUE with a new set of more difficult language understanding tasks, improved resources, and a new public leaderboard. """ a__ = """ Compute SuperGLUE evaluation metric associated to each SuperGLUE dataset. Args: predictions: list of predictions to score. Depending on the SuperGlUE subset: - for 'record': list of question-answer dictionaries with the following keys: - 'idx': index of the question as specified by the dataset - 'prediction_text': the predicted answer text - for 'multirc': list of question-answer dictionaries with the following keys: - 'idx': index of the question-answer pair as specified by the dataset - 'prediction': the predicted answer label - otherwise: list of predicted labels references: list of reference labels. Depending on the SuperGLUE subset: - for 'record': list of question-answers dictionaries with the following keys: - 'idx': index of the question as specified by the dataset - 'answers': list of possible answers - otherwise: list of reference labels Returns: depending on the SuperGLUE subset: - for 'record': - 'exact_match': Exact match between answer and gold answer - 'f1': F1 score - for 'multirc': - 'exact_match': Exact match between answer and gold answer - 'f1_m': Per-question macro-F1 score - 'f1_a': Average F1 score over all answers - for 'axb': 'matthews_correlation': Matthew Correlation - for 'cb': - 'accuracy': Accuracy - 'f1': F1 score - for all others: - 'accuracy': Accuracy Examples: >>> super_glue_metric = datasets.load_metric('super_glue', 'copa') # any of [\"copa\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"boolq\", \"axg\"] >>> predictions = [0, 1] >>> references = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'accuracy': 1.0} >>> super_glue_metric = datasets.load_metric('super_glue', 'cb') >>> predictions = [0, 1] >>> references = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'accuracy': 1.0, 'f1': 1.0} >>> super_glue_metric = datasets.load_metric('super_glue', 'record') >>> predictions = [{'idx': {'passage': 0, 'query': 0}, 'prediction_text': 'answer'}] >>> references = [{'idx': {'passage': 0, 'query': 0}, 'answers': ['answer', 'another_answer']}] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'exact_match': 1.0, 'f1': 1.0} >>> super_glue_metric = datasets.load_metric('super_glue', 'multirc') >>> predictions = [{'idx': {'answer': 0, 'paragraph': 0, 'question': 0}, 'prediction': 0}, {'idx': {'answer': 1, 'paragraph': 2, 'question': 3}, 'prediction': 1}] >>> references = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'exact_match': 1.0, 'f1_m': 1.0, 'f1_a': 1.0} >>> super_glue_metric = datasets.load_metric('super_glue', 'axb') >>> references = [0, 1] >>> predictions = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'matthews_correlation': 1.0} """ def lowercase ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Any ) -> str: return float((preds == labels).mean() ) def lowercase ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int="binary" ) -> Optional[Any]: _snake_case : Tuple = simple_accuracy(snake_case__ , snake_case__ ) _snake_case : str = float(fa_score(y_true=snake_case__ , y_pred=snake_case__ , average=snake_case__ ) ) return { "accuracy": acc, "f1": fa, } def lowercase ( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Dict ) -> int: _snake_case : Any = {} for id_pred, label in zip(snake_case__ , snake_case__ ): _snake_case : str = F'''{id_pred['idx']['paragraph']}-{id_pred['idx']['question']}''' _snake_case : int = id_pred["""prediction"""] if question_id in question_map: question_map[question_id].append((pred, label) ) else: _snake_case : List[Any] = [(pred, label)] _snake_case , _snake_case : Any = [], [] for question, preds_labels in question_map.items(): _snake_case , _snake_case : List[str] = zip(*snake_case__ ) _snake_case : Optional[int] = fa_score(y_true=snake_case__ , y_pred=snake_case__ , average="""macro""" ) fas.append(snake_case__ ) _snake_case : List[str] = int(sum(pred == label for pred, label in preds_labels ) == len(snake_case__ ) ) ems.append(snake_case__ ) _snake_case : List[Any] = float(sum(snake_case__ ) / len(snake_case__ ) ) _snake_case : Dict = sum(snake_case__ ) / len(snake_case__ ) _snake_case : List[Any] = float(fa_score(y_true=snake_case__ , y_pred=[id_pred["""prediction"""] for id_pred in ids_preds] ) ) return {"exact_match": em, "f1_m": fa_m, "f1_a": fa_a} @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION ,_KWARGS_DESCRIPTION ) class snake_case ( datasets.Metric ): '''simple docstring''' def UpperCamelCase_ ( self : List[Any]) -> Dict: """simple docstring""" if self.config_name not in [ "boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg", ]: raise KeyError( """You should supply a configuration name selected in """ """[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]""") return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types()) , codebase_urls=[] , reference_urls=[] , format="""numpy""" if not self.config_name == """record""" and not self.config_name == """multirc""" else None , ) def UpperCamelCase_ ( self : List[str]) -> int: """simple docstring""" if self.config_name == "record": return { "predictions": { "idx": { "passage": datasets.Value("""int64"""), "query": datasets.Value("""int64"""), }, "prediction_text": datasets.Value("""string"""), }, "references": { "idx": { "passage": datasets.Value("""int64"""), "query": datasets.Value("""int64"""), }, "answers": datasets.Sequence(datasets.Value("""string""")), }, } elif self.config_name == "multirc": return { "predictions": { "idx": { "answer": datasets.Value("""int64"""), "paragraph": datasets.Value("""int64"""), "question": datasets.Value("""int64"""), }, "prediction": datasets.Value("""int64"""), }, "references": datasets.Value("""int64"""), } else: return { "predictions": datasets.Value("""int64"""), "references": datasets.Value("""int64"""), } def UpperCamelCase_ ( self : Tuple , lowerCAmelCase : Union[str, Any] , lowerCAmelCase : Any) -> int: """simple docstring""" if self.config_name == "axb": return {"matthews_correlation": matthews_corrcoef(_a , _a)} elif self.config_name == "cb": return acc_and_fa(_a , _a , fa_avg="""macro""") elif self.config_name == "record": _snake_case : Dict = [ { """qas""": [ {"""id""": ref["""idx"""]["""query"""], """answers""": [{"""text""": ans} for ans in ref["""answers"""]]} for ref in references ] } ] _snake_case : int = {pred["""idx"""]["""query"""]: pred["""prediction_text"""] for pred in predictions} return evaluate_record(_a , _a)[0] elif self.config_name == "multirc": return evaluate_multirc(_a , _a) elif self.config_name in ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]: return {"accuracy": simple_accuracy(_a , _a)} else: raise KeyError( """You should supply a configuration name selected in """ """[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]""")
317
"""simple docstring""" from math import ceil from typing import List, Optional, Union import numpy as np from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import BatchFeature, SequenceFeatureExtractor from ...utils import TensorType, logging lowerCAmelCase : List[str] = logging.get_logger(__name__) class __magic_name__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = ["audio_values", "audio_mask"] def __init__( self , _a=2_048 , _a=1 , _a=[16, 16] , _a=128 , _a=44_100 , _a=86 , _a=2_048 , _a=0.0 , **_a , ): """simple docstring""" super().__init__( feature_size=_a , sampling_rate=_a , padding_value=_a , **_a , ) lowerCamelCase = spectrogram_length lowerCamelCase = num_channels lowerCamelCase = patch_size lowerCamelCase = feature_size // self.patch_size[1] lowerCamelCase = n_fft lowerCamelCase = sampling_rate // hop_length_to_sampling_rate lowerCamelCase = sampling_rate lowerCamelCase = padding_value lowerCamelCase = mel_filter_bank( num_frequency_bins=1 + n_fft // 2 , num_mel_filters=_a , min_frequency=0.0 , max_frequency=22_050.0 , sampling_rate=_a , norm="""slaney""" , mel_scale="""slaney""" , ).T def _lowerCAmelCase ( self , _a ): """simple docstring""" lowerCamelCase = spectrogram( _a , window_function(self.n_fft , """hann""" ) , frame_length=self.n_fft , hop_length=self.hop_length , power=2.0 , mel_filters=self.mel_filters.T , log_mel="""dB""" , db_range=80.0 , ) lowerCamelCase = log_spec[:, :-1] lowerCamelCase = log_spec - 20.0 lowerCamelCase = np.clip(log_spec / 40.0 , -2.0 , 0.0 ) + 1.0 return log_spec def __call__( self , _a , _a = None , _a = True , _a = None , _a = False , _a = False , **_a , ): """simple docstring""" if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( """This feature extractor is set to support sampling rate""" f' of {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled' f' with {self.sampling_rate} and not {sampling_rate}.' ) else: logger.warning( """It is strongly recommended to pass the `sampling_rate` argument to this function. """ """Failing to do so can result in silent errors that might be hard to debug.""" ) lowerCamelCase = isinstance(_a , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f'Only mono-channel audio is supported for input to {self}' ) lowerCamelCase = is_batched_numpy or ( isinstance(_a , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: lowerCamelCase = [np.asarray([speech] , dtype=np.floataa ).T for speech in raw_speech] elif not is_batched and not isinstance(_a , np.ndarray ): lowerCamelCase = np.asarray(_a , dtype=np.floataa ) elif isinstance(_a , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): lowerCamelCase = raw_speech.astype(np.floataa ) # always return batch if not is_batched: lowerCamelCase = [np.asarray([raw_speech] ).T] # Convert audio signals to log mel spectrograms, truncate by time axis lowerCamelCase = [ self._np_extract_fbank_features(waveform.squeeze() ).T[: self.spectrogram_length] for waveform in raw_speech ] if isinstance(audio_features[0] , _a ): lowerCamelCase = [np.asarray(_a , dtype=np.floataa ) for feature in audio_features] # Create audio attention mask lowerCamelCase = max( [ceil(feature.shape[0] / self.patch_size[0] ) * self.freq_len for feature in audio_features] ) # The maximum number of audio patches in a batch if return_attention_mask: lowerCamelCase = [ (ceil(feature.shape[0] / self.patch_size[0] ) * self.freq_len) * [1] + (max_patch_len - ceil(feature.shape[0] / self.patch_size[0] ) * self.freq_len) * [0] for feature in audio_features ] lowerCamelCase = np.array(_a ).astype(np.floataa ) # convert into correct format for padding lowerCamelCase = max_patch_len // self.freq_len * self.patch_size[0] # The maximum audio size in a batch lowerCamelCase = np.ones([len(_a ), 1, max_time_len, self.feature_size] ).astype(np.floataa ) lowerCamelCase = padded_audio_features * self.padding_value for i in range(len(_a ) ): lowerCamelCase = audio_features[i] lowerCamelCase = feature # return as BatchFeature if return_attention_mask: lowerCamelCase = {"""audio_values""": padded_audio_features, """audio_mask""": audio_mask} else: lowerCamelCase = {"""audio_values""": padded_audio_features} lowerCamelCase = BatchFeature(data=_a , tensor_type=_a ) return encoded_inputs
291
0
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer from ...utils import logging __lowerCamelCase : Tuple = logging.get_logger(__name__) __lowerCamelCase : Union[str, Any] = '''▁''' __lowerCamelCase : str = {'''vocab_file''': '''sentencepiece.bpe.model'''} __lowerCamelCase : Optional[Any] = { '''vocab_file''': { '''facebook/nllb-200-distilled-600M''': ( '''https://huggingface.co/facebook/nllb-200-distilled-600M/blob/main/sentencepiece.bpe.model''' ), } } __lowerCamelCase : Any = { '''facebook/nllb-200-distilled-600M''': 1024, } # fmt: off __lowerCamelCase : 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 __snake_case ( lowerCamelCase_ ): lowerCAmelCase_ = VOCAB_FILES_NAMES lowerCAmelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase_ = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase_ = ["input_ids", "attention_mask"] lowerCAmelCase_ = [] lowerCAmelCase_ = [] def __init__( self : List[str] , _lowercase : Union[str, Any] , _lowercase : Union[str, Any]="<s>" , _lowercase : Any="</s>" , _lowercase : Optional[int]="</s>" , _lowercase : Dict="<s>" , _lowercase : Tuple="<unk>" , _lowercase : Tuple="<pad>" , _lowercase : Optional[Any]="<mask>" , _lowercase : Any=None , _lowercase : Optional[int]=None , _lowercase : Union[str, Any]=None , _lowercase : Optional[Dict[str, Any]] = None , _lowercase : List[str]=None , _lowercase : int=False , **_lowercase : Optional[int] , ): """simple docstring""" SCREAMING_SNAKE_CASE__ = AddedToken(_lowercase , lstrip=_lowercase , rstrip=_lowercase ) if isinstance(_lowercase , _lowercase ) else mask_token SCREAMING_SNAKE_CASE__ = {} if sp_model_kwargs is None else sp_model_kwargs SCREAMING_SNAKE_CASE__ = legacy_behaviour super().__init__( bos_token=_lowercase , eos_token=_lowercase , unk_token=_lowercase , sep_token=_lowercase , cls_token=_lowercase , pad_token=_lowercase , mask_token=_lowercase , tokenizer_file=_lowercase , src_lang=_lowercase , tgt_lang=_lowercase , additional_special_tokens=_lowercase , sp_model_kwargs=self.sp_model_kwargs , legacy_behaviour=_lowercase , **_lowercase , ) SCREAMING_SNAKE_CASE__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(_lowercase ) ) SCREAMING_SNAKE_CASE__ = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | ---- | ---- | ---- | ---- | ---- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | 'an' | '▁n' | '▁m' | '▁t' | '▁k' | '▁a' # spm | '<unk>' | '<s>' | '</s>' | 'an' | '▁n' | '▁m' | '▁t' | '▁k' | '▁a' | '▁s' # Mimic fairseq token-to-id alignment for the first 4 token SCREAMING_SNAKE_CASE__ = {"""<s>""": 0, """<pad>""": 1, """</s>""": 2, """<unk>""": 3} # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab SCREAMING_SNAKE_CASE__ = 1 SCREAMING_SNAKE_CASE__ = len(self.sp_model ) SCREAMING_SNAKE_CASE__ = { code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(_lowercase ) } SCREAMING_SNAKE_CASE__ = {v: k for k, v in self.lang_code_to_id.items()} SCREAMING_SNAKE_CASE__ = len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset self.fairseq_tokens_to_ids.update(self.lang_code_to_id ) SCREAMING_SNAKE_CASE__ = {v: k for k, v in self.fairseq_tokens_to_ids.items()} SCREAMING_SNAKE_CASE__ = list(self.lang_code_to_id.keys() ) if additional_special_tokens is not None: # Only add those special tokens if they are not already there. self._additional_special_tokens.extend( [t for t in additional_special_tokens if t not in self._additional_special_tokens] ) SCREAMING_SNAKE_CASE__ = src_lang if src_lang is not None else """eng_Latn""" SCREAMING_SNAKE_CASE__ = self.lang_code_to_id[self._src_lang] SCREAMING_SNAKE_CASE__ = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) def __getstate__( self : Any ): """simple docstring""" SCREAMING_SNAKE_CASE__ = self.__dict__.copy() SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = self.sp_model.serialized_model_proto() return state def __setstate__( self : int , _lowercase : Union[str, Any] ): """simple docstring""" SCREAMING_SNAKE_CASE__ = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): SCREAMING_SNAKE_CASE__ = {} SCREAMING_SNAKE_CASE__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) @property def __a ( self : Optional[int] ): """simple docstring""" return len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset + 1 # Plus 1 for the mask token @property def __a ( self : Dict ): """simple docstring""" return self._src_lang @src_lang.setter def __a ( self : int , _lowercase : str ): """simple docstring""" SCREAMING_SNAKE_CASE__ = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def __a ( self : Union[str, Any] , _lowercase : List[int] , _lowercase : Optional[List[int]] = None , _lowercase : bool = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_lowercase , token_ids_a=_lowercase , already_has_special_tokens=_lowercase ) SCREAMING_SNAKE_CASE__ = [1] * len(self.prefix_tokens ) SCREAMING_SNAKE_CASE__ = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(_lowercase )) + suffix_ones return prefix_ones + ([0] * len(_lowercase )) + ([0] * len(_lowercase )) + suffix_ones def __a ( self : List[str] , _lowercase : List[int] , _lowercase : Optional[List[int]] = None ): """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 __a ( self : List[str] , _lowercase : List[int] , _lowercase : Optional[List[int]] = None ): """simple docstring""" SCREAMING_SNAKE_CASE__ = [self.sep_token_id] SCREAMING_SNAKE_CASE__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def __a ( self : Dict , _lowercase : List[Any] , _lowercase : str , _lowercase : Optional[str] , _lowercase : Optional[str] , **_lowercase : int ): """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""" ) SCREAMING_SNAKE_CASE__ = src_lang SCREAMING_SNAKE_CASE__ = self(_lowercase , add_special_tokens=_lowercase , return_tensors=_lowercase , **_lowercase ) SCREAMING_SNAKE_CASE__ = self.convert_tokens_to_ids(_lowercase ) SCREAMING_SNAKE_CASE__ = tgt_lang_id return inputs def __a ( self : str ): """simple docstring""" SCREAMING_SNAKE_CASE__ = {self.convert_ids_to_tokens(_lowercase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __a ( self : Any , _lowercase : str ): """simple docstring""" return self.sp_model.encode(_lowercase , out_type=_lowercase ) def __a ( self : Tuple , _lowercase : Any ): """simple docstring""" if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] SCREAMING_SNAKE_CASE__ = self.sp_model.PieceToId(_lowercase ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def __a ( self : str , _lowercase : int ): """simple docstring""" if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def __a ( self : List[str] , _lowercase : Tuple ): """simple docstring""" SCREAMING_SNAKE_CASE__ = """""".join(_lowercase ).replace(_lowercase , """ """ ).strip() return out_string def __a ( self : List[Any] , _lowercase : str , _lowercase : Optional[str] = None ): """simple docstring""" if not os.path.isdir(_lowercase ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return SCREAMING_SNAKE_CASE__ = os.path.join( _lowercase , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowercase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _lowercase ) elif not os.path.isfile(self.vocab_file ): with open(_lowercase , """wb""" ) as fi: SCREAMING_SNAKE_CASE__ = self.sp_model.serialized_model_proto() fi.write(_lowercase ) return (out_vocab_file,) def __a ( self : Any , _lowercase : List[str] , _lowercase : str = "eng_Latn" , _lowercase : Optional[List[str]] = None , _lowercase : str = "fra_Latn" , **_lowercase : Any , ): """simple docstring""" SCREAMING_SNAKE_CASE__ = src_lang SCREAMING_SNAKE_CASE__ = tgt_lang return super().prepare_seqaseq_batch(_lowercase , _lowercase , **_lowercase ) def __a ( self : Any ): """simple docstring""" return self.set_src_lang_special_tokens(self.src_lang ) def __a ( self : Dict ): """simple docstring""" return self.set_tgt_lang_special_tokens(self.tgt_lang ) def __a ( self : Optional[Any] , _lowercase : List[str] ): """simple docstring""" SCREAMING_SNAKE_CASE__ = self.lang_code_to_id[src_lang] if self.legacy_behaviour: SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ = [self.eos_token_id, self.cur_lang_code] else: SCREAMING_SNAKE_CASE__ = [self.cur_lang_code] SCREAMING_SNAKE_CASE__ = [self.eos_token_id] def __a ( self : int , _lowercase : str ): """simple docstring""" SCREAMING_SNAKE_CASE__ = self.lang_code_to_id[lang] if self.legacy_behaviour: SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ = [self.eos_token_id, self.cur_lang_code] else: SCREAMING_SNAKE_CASE__ = [self.cur_lang_code] SCREAMING_SNAKE_CASE__ = [self.eos_token_id]
204
from __future__ import annotations __lowerCamelCase : Tuple = list[list[int]] # assigning initial values to the grid __lowerCamelCase : Matrix = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] # a grid with no solution __lowerCamelCase : Matrix = [ [5, 0, 6, 5, 0, 8, 4, 0, 3], [5, 2, 0, 0, 0, 0, 0, 0, 2], [1, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] def __SCREAMING_SNAKE_CASE ( __UpperCamelCase : Matrix , __UpperCamelCase : int , __UpperCamelCase : int , __UpperCamelCase : int ) -> bool: """simple docstring""" for i in range(9 ): if grid[row][i] == n or grid[i][column] == n: return False for i in range(3 ): for j in range(3 ): if grid[(row - row % 3) + i][(column - column % 3) + j] == n: return False return True def __SCREAMING_SNAKE_CASE ( __UpperCamelCase : Matrix ) -> tuple[int, int] | None: """simple docstring""" for i in range(9 ): for j in range(9 ): if grid[i][j] == 0: return i, j return None def __SCREAMING_SNAKE_CASE ( __UpperCamelCase : Matrix ) -> Matrix | None: """simple docstring""" if location := find_empty_location(__UpperCamelCase ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = location else: # If the location is ``None``, then the grid is solved. return grid for digit in range(1 , 10 ): if is_safe(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ): SCREAMING_SNAKE_CASE__ = digit if sudoku(__UpperCamelCase ) is not None: return grid SCREAMING_SNAKE_CASE__ = 0 return None def __SCREAMING_SNAKE_CASE ( __UpperCamelCase : Matrix ) -> None: """simple docstring""" for row in grid: for cell in row: print(__UpperCamelCase , end=""" """ ) print() if __name__ == "__main__": # make a copy of grid so that you can compare with the unmodified grid for example_grid in (initial_grid, no_solution): print('''\nExample grid:\n''' + '''=''' * 20) print_solution(example_grid) print('''\nExample grid solution:''') __lowerCamelCase : str = sudoku(example_grid) if solution is not None: print_solution(solution) else: print('''Cannot find a solution.''')
204
1
import unittest import numpy as np from transformers import MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING, TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING from transformers.pipelines import AudioClassificationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_torchaudio, slow, ) from .test_pipelines_common import ANY @is_pipeline_test class a (unittest.TestCase ): """simple docstring""" __UpperCAmelCase : List[Any] = MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING __UpperCAmelCase : Tuple = TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING def __snake_case ( self : str , lowerCamelCase : str , lowerCamelCase : Any , lowerCamelCase : Optional[Any] ) -> Optional[Any]: __snake_case : str = AudioClassificationPipeline(model=lowerCamelCase , feature_extractor=lowerCamelCase ) # test with a raw waveform __snake_case : Union[str, Any] = np.zeros((34000,) ) __snake_case : Any = np.zeros((14000,) ) return audio_classifier, [audioa, audio] def __snake_case ( self : Union[str, Any] , lowerCamelCase : Any , lowerCamelCase : List[Any] ) -> Optional[int]: __snake_case , __snake_case : str = examples __snake_case : str = audio_classifier(lowerCamelCase ) # by default a model is initialized with num_labels=2 self.assertEqual( lowerCamelCase , [ {"score": ANY(lowerCamelCase ), "label": ANY(lowerCamelCase )}, {"score": ANY(lowerCamelCase ), "label": ANY(lowerCamelCase )}, ] , ) __snake_case : Optional[int] = audio_classifier(lowerCamelCase , top_k=1 ) self.assertEqual( lowerCamelCase , [ {"score": ANY(lowerCamelCase ), "label": ANY(lowerCamelCase )}, ] , ) self.run_torchaudio(lowerCamelCase ) @require_torchaudio def __snake_case ( self : str , lowerCamelCase : Optional[int] ) -> Any: import datasets # test with a local file __snake_case : List[Any] = datasets.load_dataset("hf-internal-testing/librispeech_asr_dummy" , "clean" , split="validation" ) __snake_case : Union[str, Any] = dataset[0]["audio"]["array"] __snake_case : List[Any] = audio_classifier(lowerCamelCase ) self.assertEqual( lowerCamelCase , [ {"score": ANY(lowerCamelCase ), "label": ANY(lowerCamelCase )}, {"score": ANY(lowerCamelCase ), "label": ANY(lowerCamelCase )}, ] , ) @require_torch def __snake_case ( self : str ) -> int: __snake_case : Tuple = "anton-l/wav2vec2-random-tiny-classifier" __snake_case : Union[str, Any] = pipeline("audio-classification" , model=lowerCamelCase ) __snake_case : Dict = np.ones((8000,) ) __snake_case : Any = audio_classifier(lowerCamelCase , top_k=4 ) __snake_case : Optional[Any] = [ {"score": 0.08_42, "label": "no"}, {"score": 0.08_38, "label": "up"}, {"score": 0.08_37, "label": "go"}, {"score": 0.08_34, "label": "right"}, ] __snake_case : Union[str, Any] = [ {"score": 0.08_45, "label": "stop"}, {"score": 0.08_44, "label": "on"}, {"score": 0.08_41, "label": "right"}, {"score": 0.08_34, "label": "left"}, ] self.assertIn(nested_simplify(lowerCamelCase , decimals=4 ) , [EXPECTED_OUTPUT, EXPECTED_OUTPUT_PT_2] ) __snake_case : Optional[int] = {"array": np.ones((8000,) ), "sampling_rate": audio_classifier.feature_extractor.sampling_rate} __snake_case : str = audio_classifier(lowerCamelCase , top_k=4 ) self.assertIn(nested_simplify(lowerCamelCase , decimals=4 ) , [EXPECTED_OUTPUT, EXPECTED_OUTPUT_PT_2] ) @require_torch @slow def __snake_case ( self : List[str] ) -> Optional[int]: import datasets __snake_case : Union[str, Any] = "superb/wav2vec2-base-superb-ks" __snake_case : List[str] = pipeline("audio-classification" , model=lowerCamelCase ) __snake_case : List[str] = datasets.load_dataset("anton-l/superb_dummy" , "ks" , split="test" ) __snake_case : Optional[Any] = np.array(dataset[3]["speech"] , dtype=np.floataa ) __snake_case : int = audio_classifier(lowerCamelCase , top_k=4 ) self.assertEqual( nested_simplify(lowerCamelCase , decimals=3 ) , [ {"score": 0.9_81, "label": "go"}, {"score": 0.0_07, "label": "up"}, {"score": 0.0_06, "label": "_unknown_"}, {"score": 0.0_01, "label": "down"}, ] , ) @require_tf @unittest.skip("Audio classification is not implemented for TF" ) def __snake_case ( self : int ) -> Union[str, Any]: pass
123
import argparse import json import os from collections import OrderedDict import torch from transformers import LukeConfig, LukeForMaskedLM, MLukeTokenizer, XLMRobertaTokenizer from transformers.tokenization_utils_base import AddedToken @torch.no_grad() def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): # Load configuration defined in the metadata file with open(__lowerCamelCase ) as metadata_file: __snake_case : Tuple = json.load(__lowerCamelCase ) __snake_case : int = LukeConfig(use_entity_aware_attention=__lowerCamelCase , **metadata["model_config"] ) # Load in the weights from the checkpoint_path __snake_case : Any = torch.load(__lowerCamelCase , map_location="cpu" )["module"] # Load the entity vocab file __snake_case : Any = load_original_entity_vocab(__lowerCamelCase ) # add an entry for [MASK2] __snake_case : int = max(entity_vocab.values() ) + 1 config.entity_vocab_size += 1 __snake_case : List[str] = XLMRobertaTokenizer.from_pretrained(metadata["model_config"]["bert_model_name"] ) # Add special tokens to the token vocabulary for downstream tasks __snake_case : List[Any] = AddedToken("<ent>" , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) __snake_case : str = AddedToken("<ent2>" , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) tokenizer.add_special_tokens({"additional_special_tokens": [entity_token_a, entity_token_a]} ) config.vocab_size += 2 print(F'Saving tokenizer to {pytorch_dump_folder_path}' ) tokenizer.save_pretrained(__lowerCamelCase ) with open(os.path.join(__lowerCamelCase , "tokenizer_config.json" ) , "r" ) as f: __snake_case : int = json.load(__lowerCamelCase ) __snake_case : str = "MLukeTokenizer" with open(os.path.join(__lowerCamelCase , "tokenizer_config.json" ) , "w" ) as f: json.dump(__lowerCamelCase , __lowerCamelCase ) with open(os.path.join(__lowerCamelCase , MLukeTokenizer.vocab_files_names["entity_vocab_file"] ) , "w" ) as f: json.dump(__lowerCamelCase , __lowerCamelCase ) __snake_case : Any = MLukeTokenizer.from_pretrained(__lowerCamelCase ) # Initialize the embeddings of the special tokens __snake_case : Optional[int] = tokenizer.convert_tokens_to_ids(["@"] )[0] __snake_case : Tuple = tokenizer.convert_tokens_to_ids(["#"] )[0] __snake_case : Union[str, Any] = state_dict["embeddings.word_embeddings.weight"] __snake_case : Tuple = word_emb[ent_init_index].unsqueeze(0 ) __snake_case : Tuple = word_emb[enta_init_index].unsqueeze(0 ) __snake_case : List[Any] = torch.cat([word_emb, ent_emb, enta_emb] ) # add special tokens for 'entity_predictions.bias' for bias_name in ["lm_head.decoder.bias", "lm_head.bias"]: __snake_case : Optional[int] = state_dict[bias_name] __snake_case : Any = decoder_bias[ent_init_index].unsqueeze(0 ) __snake_case : Union[str, Any] = decoder_bias[enta_init_index].unsqueeze(0 ) __snake_case : List[str] = torch.cat([decoder_bias, ent_decoder_bias, enta_decoder_bias] ) # Initialize the query layers of the entity-aware self-attention mechanism for layer_index in range(config.num_hidden_layers ): for matrix_name in ["query.weight", "query.bias"]: __snake_case : Optional[int] = F'encoder.layer.{layer_index}.attention.self.' __snake_case : int = state_dict[prefix + matrix_name] __snake_case : Optional[Any] = state_dict[prefix + matrix_name] __snake_case : Optional[int] = state_dict[prefix + matrix_name] # Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks __snake_case : Union[str, Any] = state_dict["entity_embeddings.entity_embeddings.weight"] __snake_case : Union[str, Any] = entity_emb[entity_vocab["[MASK]"]].unsqueeze(0 ) __snake_case : Union[str, Any] = torch.cat([entity_emb, entity_mask_emb] ) # add [MASK2] for 'entity_predictions.bias' __snake_case : List[Any] = state_dict["entity_predictions.bias"] __snake_case : str = entity_prediction_bias[entity_vocab["[MASK]"]].unsqueeze(0 ) __snake_case : Optional[int] = torch.cat([entity_prediction_bias, entity_mask_bias] ) __snake_case : Any = LukeForMaskedLM(config=__lowerCamelCase ).eval() state_dict.pop("entity_predictions.decoder.weight" ) state_dict.pop("lm_head.decoder.weight" ) state_dict.pop("lm_head.decoder.bias" ) __snake_case : Optional[int] = OrderedDict() for key, value in state_dict.items(): if not (key.startswith("lm_head" ) or key.startswith("entity_predictions" )): __snake_case : Dict = state_dict[key] else: __snake_case : int = state_dict[key] __snake_case , __snake_case : Union[str, Any] = model.load_state_dict(__lowerCamelCase , strict=__lowerCamelCase ) if set(__lowerCamelCase ) != {"luke.embeddings.position_ids"}: raise ValueError(F'Unexpected unexpected_keys: {unexpected_keys}' ) if set(__lowerCamelCase ) != { "lm_head.decoder.weight", "lm_head.decoder.bias", "entity_predictions.decoder.weight", }: raise ValueError(F'Unexpected missing_keys: {missing_keys}' ) model.tie_weights() assert (model.luke.embeddings.word_embeddings.weight == model.lm_head.decoder.weight).all() assert (model.luke.entity_embeddings.entity_embeddings.weight == model.entity_predictions.decoder.weight).all() # Check outputs __snake_case : Union[str, Any] = MLukeTokenizer.from_pretrained(__lowerCamelCase , task="entity_classification" ) __snake_case : Optional[Any] = "ISO 639-3 uses the code fas for the dialects spoken across Iran and アフガニスタン (Afghanistan)." __snake_case : Tuple = (0, 9) __snake_case : Dict = tokenizer(__lowerCamelCase , entity_spans=[span] , return_tensors="pt" ) __snake_case : Optional[Any] = model(**__lowerCamelCase ) # Verify word hidden states if model_size == "large": raise NotImplementedError else: # base __snake_case : str = torch.Size((1, 3_3, 7_6_8) ) __snake_case : List[str] = torch.tensor([[0.0_8_9_2, 0.0_5_9_6, -0.2_8_1_9], [0.0_1_3_4, 0.1_1_9_9, 0.0_5_7_3], [-0.0_1_6_9, 0.0_9_2_7, 0.0_6_4_4]] ) if not (outputs.last_hidden_state.shape == expected_shape): raise ValueError( F'Outputs.last_hidden_state.shape is {outputs.last_hidden_state.shape}, Expected shape is {expected_shape}' ) if not torch.allclose(outputs.last_hidden_state[0, :3, :3] , __lowerCamelCase , atol=1e-4 ): raise ValueError # Verify entity hidden states if model_size == "large": raise NotImplementedError else: # base __snake_case : Union[str, Any] = torch.Size((1, 1, 7_6_8) ) __snake_case : Optional[int] = torch.tensor([[-0.1_4_8_2, 0.0_6_0_9, 0.0_3_2_2]] ) if not (outputs.entity_last_hidden_state.shape == expected_shape): raise ValueError( F'Outputs.entity_last_hidden_state.shape is {outputs.entity_last_hidden_state.shape}, Expected shape is' F' {expected_shape}' ) if not torch.allclose(outputs.entity_last_hidden_state[0, :3, :3] , __lowerCamelCase , atol=1e-4 ): raise ValueError # Verify masked word/entity prediction __snake_case : Union[str, Any] = MLukeTokenizer.from_pretrained(__lowerCamelCase ) __snake_case : List[Any] = "Tokyo is the capital of <mask>." __snake_case : List[Any] = (2_4, 3_0) __snake_case : Tuple = tokenizer(__lowerCamelCase , entity_spans=[span] , return_tensors="pt" ) __snake_case : Optional[Any] = model(**__lowerCamelCase ) __snake_case : Tuple = encoding["input_ids"][0].tolist() __snake_case : Tuple = input_ids.index(tokenizer.convert_tokens_to_ids("<mask>" ) ) __snake_case : Optional[int] = outputs.logits[0][mask_position_id].argmax(dim=-1 ) assert "Japan" == tokenizer.decode(__lowerCamelCase ) __snake_case : Dict = outputs.entity_logits[0][0].argmax().item() __snake_case : Dict = [ entity for entity, entity_id in tokenizer.entity_vocab.items() if entity_id == predicted_entity_id ] assert [e for e in multilingual_predicted_entities if e.startswith("en:" )][0] == "en:Japan" # Finally, save our PyTorch model and tokenizer print("Saving PyTorch model to {}".format(__lowerCamelCase ) ) model.save_pretrained(__lowerCamelCase ) def lowerCAmelCase_ ( __lowerCamelCase ): __snake_case : Union[str, Any] = ["[MASK]", "[PAD]", "[UNK]"] __snake_case : Tuple = [json.loads(__lowerCamelCase ) for line in open(__lowerCamelCase )] __snake_case : Dict = {} for entry in data: __snake_case : Optional[Any] = entry["id"] for entity_name, language in entry["entities"]: if entity_name in SPECIAL_TOKENS: __snake_case : Union[str, Any] = entity_id break __snake_case : Tuple = F'{language}:{entity_name}' __snake_case : int = entity_id return new_mapping if __name__ == "__main__": _snake_case : Any = argparse.ArgumentParser() # Required parameters parser.add_argument("--checkpoint_path", type=str, help="Path to a pytorch_model.bin file.") parser.add_argument( "--metadata_path", default=None, type=str, help="Path to a metadata.json file, defining the configuration." ) parser.add_argument( "--entity_vocab_path", default=None, type=str, help="Path to an entity_vocab.tsv file, containing the entity vocabulary.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to where to dump the output PyTorch model." ) parser.add_argument( "--model_size", default="base", type=str, choices=["base", "large"], help="Size of the model to be converted." ) _snake_case : int = parser.parse_args() convert_luke_checkpoint( args.checkpoint_path, args.metadata_path, args.entity_vocab_path, args.pytorch_dump_folder_path, args.model_size, )
123
1
"""simple docstring""" import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert from transformers.utils import logging logging.set_verbosity_info() def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ) -> Tuple: """simple docstring""" _UpperCamelCase : Any = BertConfig.from_json_file(lowercase_ ) print(F'''Building PyTorch model from configuration: {config}''' ) _UpperCamelCase : Any = BertForPreTraining(lowercase_ ) # Load weights from tf checkpoint load_tf_weights_in_bert(lowercase_ ,lowercase_ ,lowercase_ ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) torch.save(model.state_dict() ,lowercase_ ) if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( "--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path." ) parser.add_argument( "--bert_config_file", default=None, type=str, required=True, help=( "The config json file corresponding to the pre-trained BERT model. \n" "This specifies the model architecture." ), ) parser.add_argument( "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) lowerCamelCase__ = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
310
"""simple docstring""" import copy from ...configuration_utils import PretrainedConfig from ...utils import add_start_docstrings lowerCamelCase__ = R"\n [`RagConfig`] stores the configuration of a *RagModel*. Configuration objects inherit from [`PretrainedConfig`] and\n can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information.\n\n Args:\n title_sep (`str`, *optional*, defaults to `\" / \"`):\n Separator inserted between the title and the text of the retrieved document when calling [`RagRetriever`].\n doc_sep (`str`, *optional*, defaults to `\" // \"`):\n Separator inserted between the text of the retrieved document and the original input when calling\n [`RagRetriever`].\n n_docs (`int`, *optional*, defaults to 5):\n Number of documents to retrieve.\n max_combined_length (`int`, *optional*, defaults to 300):\n Max length of contextualized input returned by [`~RagRetriever.__call__`].\n retrieval_vector_size (`int`, *optional*, defaults to 768):\n Dimensionality of the document embeddings indexed by [`RagRetriever`].\n retrieval_batch_size (`int`, *optional*, defaults to 8):\n Retrieval batch size, defined as the number of queries issues concurrently to the faiss index encapsulated\n [`RagRetriever`].\n dataset (`str`, *optional*, defaults to `\"wiki_dpr\"`):\n A dataset identifier of the indexed dataset in HuggingFace Datasets (list all available datasets and ids\n using `datasets.list_datasets()`).\n dataset_split (`str`, *optional*, defaults to `\"train\"`)\n Which split of the `dataset` to load.\n index_name (`str`, *optional*, defaults to `\"compressed\"`)\n The index name of the index associated with the `dataset`. One can choose between `\"legacy\"`, `\"exact\"` and\n `\"compressed\"`.\n index_path (`str`, *optional*)\n The path to the serialized faiss index on disk.\n passages_path (`str`, *optional*):\n A path to text passages compatible with the faiss index. Required if using\n [`~models.rag.retrieval_rag.LegacyIndex`]\n use_dummy_dataset (`bool`, *optional*, defaults to `False`)\n Whether to load a \"dummy\" variant of the dataset specified by `dataset`.\n label_smoothing (`float`, *optional*, defaults to 0.0):\n Only relevant if `return_loss` is set to `True`. Controls the `epsilon` parameter value for label smoothing\n in the loss calculation. If set to 0, no label smoothing is performed.\n do_marginalize (`bool`, *optional*, defaults to `False`):\n If `True`, the logits are marginalized over all documents by making use of\n `torch.nn.functional.log_softmax`.\n reduce_loss (`bool`, *optional*, defaults to `False`):\n Whether or not to reduce the NLL loss using the `torch.Tensor.sum` operation.\n do_deduplication (`bool`, *optional*, defaults to `True`):\n Whether or not to deduplicate the generations from different context documents for a given input. Has to be\n set to `False` if used while training with distributed backend.\n exclude_bos_score (`bool`, *optional*, defaults to `False`):\n Whether or not to disregard the BOS token when computing the loss.\n output_retrieved(`bool`, *optional*, defaults to `False`):\n If set to `True`, `retrieved_doc_embeds`, `retrieved_doc_ids`, `context_input_ids` and\n `context_attention_mask` are returned. See returned tensors for more detail.\n use_cache (`bool`, *optional*, defaults to `True`):\n Whether or not the model should return the last key/values attentions (not used by all models).\n forced_eos_token_id (`int`, *optional*):\n The id of the token to force as the last generated token when `max_length` is reached. Usually set to\n `eos_token_id`.\n" @add_start_docstrings(_UpperCamelCase ) class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :int = "rag" SCREAMING_SNAKE_CASE__ :List[str] = True def __init__( self : List[Any] , __a : Optional[Any]=None , __a : str=True , __a : Tuple=None , __a : Dict=None , __a : Optional[int]=None , __a : Optional[int]=None , __a : List[Any]=None , __a : Dict=" / " , __a : int=" // " , __a : Optional[Any]=5 , __a : Dict=300 , __a : Optional[int]=768 , __a : Tuple=8 , __a : Union[str, Any]="wiki_dpr" , __a : Dict="train" , __a : List[Any]="compressed" , __a : str=None , __a : Tuple=None , __a : int=False , __a : str=False , __a : Optional[int]=0.0 , __a : Dict=True , __a : Tuple=False , __a : Dict=False , __a : str=False , __a : str=True , __a : Optional[Any]=None , **__a : Tuple , ) -> Any: super().__init__( bos_token_id=__a , pad_token_id=__a , eos_token_id=__a , decoder_start_token_id=__a , forced_eos_token_id=__a , is_encoder_decoder=__a , prefix=__a , vocab_size=__a , **__a , ) assert ( "question_encoder" in kwargs and "generator" in kwargs ), "Config has to be initialized with question_encoder and generator config" _UpperCamelCase : Optional[int] = kwargs.pop("question_encoder" ) _UpperCamelCase : str = question_encoder_config.pop("model_type" ) _UpperCamelCase : Tuple = kwargs.pop("generator" ) _UpperCamelCase : str = decoder_config.pop("model_type" ) from ..auto.configuration_auto import AutoConfig _UpperCamelCase : Union[str, Any] = AutoConfig.for_model(__a , **__a ) _UpperCamelCase : str = AutoConfig.for_model(__a , **__a ) _UpperCamelCase : Optional[int] = reduce_loss _UpperCamelCase : str = label_smoothing _UpperCamelCase : int = exclude_bos_score _UpperCamelCase : List[str] = do_marginalize _UpperCamelCase : Optional[int] = title_sep _UpperCamelCase : Optional[int] = doc_sep _UpperCamelCase : Union[str, Any] = n_docs _UpperCamelCase : Tuple = max_combined_length _UpperCamelCase : Union[str, Any] = dataset _UpperCamelCase : Any = dataset_split _UpperCamelCase : List[str] = index_name _UpperCamelCase : int = retrieval_vector_size _UpperCamelCase : str = retrieval_batch_size _UpperCamelCase : Dict = passages_path _UpperCamelCase : str = index_path _UpperCamelCase : Tuple = use_dummy_dataset _UpperCamelCase : Union[str, Any] = output_retrieved _UpperCamelCase : Optional[Any] = do_deduplication _UpperCamelCase : str = use_cache if self.forced_eos_token_id is None: _UpperCamelCase : List[str] = getattr(self.generator , "forced_eos_token_id" , __a ) @classmethod def __SCREAMING_SNAKE_CASE ( cls : Union[str, Any] , __a : PretrainedConfig , __a : PretrainedConfig , **__a : Optional[int] ) -> PretrainedConfig: return cls(question_encoder=question_encoder_config.to_dict() , generator=generator_config.to_dict() , **__a ) def __SCREAMING_SNAKE_CASE ( self : Dict ) -> int: _UpperCamelCase : Dict = copy.deepcopy(self.__dict__ ) _UpperCamelCase : List[Any] = self.question_encoder.to_dict() _UpperCamelCase : Tuple = self.generator.to_dict() _UpperCamelCase : Any = self.__class__.model_type return output
310
1
'''simple docstring''' import os def UpperCAmelCase_ (__a : List[str] ): """simple docstring""" _a : Dict = len(grid[0] ) _a : Dict = len(__a ) _a : Dict = 0 _a : Optional[int] = 0 _a : Any = 0 # Check vertically, horizontally, diagonally at the same time (only works # for nxn grid) for i in range(__a ): for j in range(n_rows - 3 ): _a : int = grid[j][i] * grid[j + 1][i] * grid[j + 2][i] * grid[j + 3][i] _a : Any = grid[i][j] * grid[i][j + 1] * grid[i][j + 2] * grid[i][j + 3] # Left-to-right diagonal (\) product if i < n_columns - 3: _a : Union[str, Any] = ( grid[i][j] * grid[i + 1][j + 1] * grid[i + 2][j + 2] * grid[i + 3][j + 3] ) # Right-to-left diagonal(/) product if i > 2: _a : Tuple = ( grid[i][j] * grid[i - 1][j + 1] * grid[i - 2][j + 2] * grid[i - 3][j + 3] ) _a : Union[str, Any] = max( __a , __a , __a , __a ) if max_product > largest: _a : Any = max_product return largest def UpperCAmelCase_ (): """simple docstring""" _a : Any = [] with open(os.path.dirname(__a ) + '/grid.txt' ) as file: for line in file: grid.append(line.strip('\n' ).split(' ' ) ) _a : Any = [[int(__a ) for i in grid[j]] for j in range(len(__a ) )] return largest_product(__a ) if __name__ == "__main__": print(solution())
271
'''simple docstring''' import os from huggingface_hub.constants import HUGGINGFACE_HUB_CACHE, hf_cache_home __lowerCAmelCase = HUGGINGFACE_HUB_CACHE __lowerCAmelCase = """config.json""" __lowerCAmelCase = """diffusion_pytorch_model.bin""" __lowerCAmelCase = """diffusion_flax_model.msgpack""" __lowerCAmelCase = """model.onnx""" __lowerCAmelCase = """diffusion_pytorch_model.safetensors""" __lowerCAmelCase = """weights.pb""" __lowerCAmelCase = """https://huggingface.co""" __lowerCAmelCase = default_cache_path __lowerCAmelCase = """diffusers_modules""" __lowerCAmelCase = os.getenv("""HF_MODULES_CACHE""", os.path.join(hf_cache_home, """modules""")) __lowerCAmelCase = ["""fp16""", """non-ema"""] __lowerCAmelCase = """.self_attn"""
271
1
from __future__ import annotations import math def _A ( __magic_name__ ): 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(__magic_name__ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def _A ( __magic_name__ ): lowercase__ = str(__magic_name__ ) lowercase__ = [n] for i in range(1 , len(__magic_name__ ) ): list_nums.append(int(str_num[i:] ) ) list_nums.append(int(str_num[:-i] ) ) return list_nums def _A ( __magic_name__ ): if len(str(__magic_name__ ) ) > 3: if not is_prime(int(str(__magic_name__ )[-3:] ) ) or not is_prime(int(str(__magic_name__ )[:3] ) ): return False return True def _A ( __magic_name__ = 11 ): lowercase__ = [] lowercase__ = 13 while len(__magic_name__ ) != count: if validate(__magic_name__ ): lowercase__ = list_truncated_nums(__magic_name__ ) if all(is_prime(__magic_name__ ) for i in list_nums ): list_truncated_primes.append(__magic_name__ ) num += 2 return list_truncated_primes def _A ( ): return sum(compute_truncated_primes(11 ) ) if __name__ == "__main__": print(F"""{sum(compute_truncated_primes(11)) = }""")
201
def _A ( __magic_name__ ): try: lowercase__ = float(__magic_name__ ) except ValueError: raise ValueError("Please enter a valid number" ) lowercase__ = decimal - int(__magic_name__ ) if fractional_part == 0: return int(__magic_name__ ), 1 else: lowercase__ = len(str(__magic_name__ ).split("." )[1] ) lowercase__ = int(decimal * (10**number_of_frac_digits) ) lowercase__ = 10**number_of_frac_digits lowercase__ , lowercase__ = denominator, numerator while True: lowercase__ = dividend % divisor if remainder == 0: break lowercase__ , lowercase__ = divisor, remainder lowercase__ , lowercase__ = numerator / divisor, denominator / divisor return int(__magic_name__ ), int(__magic_name__ ) if __name__ == "__main__": print(F"""{decimal_to_fraction(2) = }""") print(F"""{decimal_to_fraction(89.0) = }""") print(F"""{decimal_to_fraction("67") = }""") print(F"""{decimal_to_fraction("45.0") = }""") print(F"""{decimal_to_fraction(1.5) = }""") print(F"""{decimal_to_fraction("6.25") = }""") print(F"""{decimal_to_fraction("78td") = }""")
201
1
from __future__ import annotations from typing import Any class A : def __init__(self : Dict , __UpperCAmelCase : int , __UpperCAmelCase : int , __UpperCAmelCase : float = 0 ) -> None: """simple docstring""" UpperCAmelCase__ , UpperCAmelCase__ = row, column UpperCAmelCase__ = [[default_value for c in range(__UpperCAmelCase )] for r in range(__UpperCAmelCase )] def __str__(self : Tuple ) -> str: """simple docstring""" UpperCAmelCase__ = f"""Matrix consist of {self.row} rows and {self.column} columns\n""" # Make string identifier UpperCAmelCase__ = 0 for row_vector in self.array: for obj in row_vector: UpperCAmelCase__ = max(__UpperCAmelCase , len(str(__UpperCAmelCase ) ) ) UpperCAmelCase__ = f"""%{max_element_length}s""" # Make string and return def single_line(__UpperCAmelCase : list[float] ) -> str: nonlocal string_format_identifier UpperCAmelCase__ = "[" line += ", ".join(string_format_identifier % (obj,) for obj in row_vector ) line += "]" return line s += "\n".join(single_line(__UpperCAmelCase ) for row_vector in self.array ) return s def __repr__(self : Dict ) -> str: """simple docstring""" return str(self ) def lowercase_ (self : Optional[Any] , __UpperCAmelCase : tuple[int, int] ) -> bool: """simple docstring""" if not (isinstance(__UpperCAmelCase , (list, tuple) ) and len(__UpperCAmelCase ) == 2): return False elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column): return False else: return True def __getitem__(self : Union[str, Any] , __UpperCAmelCase : tuple[int, int] ) -> Any: """simple docstring""" assert self.validate_indicies(__UpperCAmelCase ) return self.array[loc[0]][loc[1]] def __setitem__(self : List[Any] , __UpperCAmelCase : tuple[int, int] , __UpperCAmelCase : float ) -> None: """simple docstring""" assert self.validate_indicies(__UpperCAmelCase ) UpperCAmelCase__ = value def __add__(self : Dict , __UpperCAmelCase : Matrix ) -> Matrix: """simple docstring""" assert isinstance(__UpperCAmelCase , __UpperCAmelCase ) assert self.row == another.row and self.column == another.column # Add UpperCAmelCase__ = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): UpperCAmelCase__ = self[r, c] + another[r, c] return result def __neg__(self : Optional[int] ) -> Matrix: """simple docstring""" UpperCAmelCase__ = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): UpperCAmelCase__ = -self[r, c] return result def __sub__(self : Optional[int] , __UpperCAmelCase : Matrix ) -> Matrix: """simple docstring""" return self + (-another) def __mul__(self : Optional[Any] , __UpperCAmelCase : int | float | Matrix ) -> Matrix: """simple docstring""" if isinstance(__UpperCAmelCase , (int, float) ): # Scalar multiplication UpperCAmelCase__ = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): UpperCAmelCase__ = self[r, c] * another return result elif isinstance(__UpperCAmelCase , __UpperCAmelCase ): # Matrix multiplication assert self.column == another.row UpperCAmelCase__ = Matrix(self.row , another.column ) for r in range(self.row ): for c in range(another.column ): for i in range(self.column ): result[r, c] += self[r, i] * another[i, c] return result else: UpperCAmelCase__ = f"""Unsupported type given for another ({type(__UpperCAmelCase )})""" raise TypeError(__UpperCAmelCase ) def lowercase_ (self : str ) -> Matrix: """simple docstring""" UpperCAmelCase__ = Matrix(self.column , self.row ) for r in range(self.row ): for c in range(self.column ): UpperCAmelCase__ = self[r, c] return result def lowercase_ (self : str , __UpperCAmelCase : Matrix , __UpperCAmelCase : Matrix ) -> Any: """simple docstring""" assert isinstance(__UpperCAmelCase , __UpperCAmelCase ) and isinstance(__UpperCAmelCase , __UpperCAmelCase ) assert self.row == self.column == u.row == v.row # u, v should be column vector assert u.column == v.column == 1 # u, v should be column vector # Calculate UpperCAmelCase__ = v.transpose() UpperCAmelCase__ = (v_t * self * u)[0, 0] + 1 if numerator_factor == 0: return None # It's not invertable return self - ((self * u) * (v_t * self) * (1.0 / numerator_factor)) # Testing if __name__ == "__main__": def lowerCAmelCase_ ( ) -> None: '''simple docstring''' UpperCAmelCase__ = Matrix(3, 3, 0 ) for i in range(3 ): UpperCAmelCase__ = 1 print(f"""a^(-1) is {ainv}""" ) # u, v UpperCAmelCase__ = Matrix(3, 1, 0 ) UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ = 1, 2, -3 UpperCAmelCase__ = Matrix(3, 1, 0 ) UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ = 4, -2, 5 print(f"""u is {u}""" ) print(f"""v is {v}""" ) print(f"""uv^T is {u * v.transpose()}""" ) # Sherman Morrison print(f"""(a + uv^T)^(-1) is {ainv.sherman_morrison(_A, _A )}""" ) def lowerCAmelCase_ ( ) -> None: '''simple docstring''' import doctest doctest.testmod() testa()
65
from math import isclose, sqrt def a_ ( _A , _A , _A ) -> tuple[float, float, float]: """simple docstring""" snake_case__ = point_y / 4 / point_x snake_case__ = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) snake_case__ = (1 - normal_gradient * normal_gradient) / ( 1 + normal_gradient * normal_gradient ) snake_case__ = (sa - ca * incoming_gradient) / (ca + sa * incoming_gradient) # to find the next point, solve the simultaeneous equations: # y^2 + 4x^2 = 100 # y - b = m * (x - a) # ==> A x^2 + B x + C = 0 snake_case__ = outgoing_gradient**2 + 4 snake_case__ = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) snake_case__ = (point_y - outgoing_gradient * point_x) ** 2 - 100 snake_case__ = ( -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) snake_case__ = ( -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) # two solutions, one of which is our input point snake_case__ = x_minus if isclose(_A , _A ) else x_plus snake_case__ = point_y + outgoing_gradient * (next_x - point_x) return next_x, next_y, outgoing_gradient def a_ ( _A = 1.4 , _A = -9.6 ) -> int: """simple docstring""" snake_case__ = 0 snake_case__ = first_x_coord snake_case__ = first_y_coord snake_case__ = (10.1 - point_y) / (0.0 - point_x) while not (-0.01 <= point_x <= 0.01 and point_y > 0): snake_case__ , snake_case__ , snake_case__ = next_point(_A , _A , _A ) num_reflections += 1 return num_reflections if __name__ == "__main__": print(f'''{solution() = }''')
307
0
from pathlib import Path from typing import List from transformers import is_torch_available, is_vision_available from transformers.testing_utils import get_tests_dir, is_tool_test from transformers.tools.agent_types import AGENT_TYPE_MAPPING, AgentAudio, AgentImage, AgentText if is_torch_available(): import torch if is_vision_available(): from PIL import Image lowerCamelCase_ = ['''text''', '''image''', '''audio'''] def __magic_name__ ( __a : List[str] ): '''simple docstring''' UpperCamelCase__ = [] for input_type in input_types: if input_type == "text": inputs.append("""Text input""" ) elif input_type == "image": inputs.append( Image.open(Path(get_tests_dir("""fixtures/tests_samples/COCO""" ) ) / """000000039769.png""" ).resize((512, 512) ) ) elif input_type == "audio": inputs.append(torch.ones(3_000 ) ) elif isinstance(__a , __a ): inputs.append(create_inputs(__a ) ) else: raise ValueError(f"Invalid type requested: {input_type}" ) return inputs def __magic_name__ ( __a : List ): '''simple docstring''' UpperCamelCase__ = [] for output in outputs: if isinstance(__a , (str, AgentText) ): output_types.append("""text""" ) elif isinstance(__a , (Image.Image, AgentImage) ): output_types.append("""image""" ) elif isinstance(__a , (torch.Tensor, AgentAudio) ): output_types.append("""audio""" ) else: raise ValueError(f"Invalid output: {output}" ) return output_types @is_tool_test class __A: """simple docstring""" def UpperCAmelCase_ (self ): self.assertTrue(hasattr(self.tool , """inputs""" ) ) self.assertTrue(hasattr(self.tool , """outputs""" ) ) UpperCamelCase__ = self.tool.inputs for _input in inputs: if isinstance(_input , SCREAMING_SNAKE_CASE_ ): for __input in _input: self.assertTrue(__input in authorized_types ) else: self.assertTrue(_input in authorized_types ) UpperCamelCase__ = self.tool.outputs for _output in outputs: self.assertTrue(_output in authorized_types ) def UpperCAmelCase_ (self ): UpperCamelCase__ = create_inputs(self.tool.inputs ) UpperCamelCase__ = self.tool(*SCREAMING_SNAKE_CASE_ ) # There is a single output if len(self.tool.outputs ) == 1: UpperCamelCase__ = [outputs] self.assertListEqual(output_types(SCREAMING_SNAKE_CASE_ ) , self.tool.outputs ) def UpperCAmelCase_ (self ): self.assertTrue(hasattr(self.tool , """description""" ) ) self.assertTrue(hasattr(self.tool , """default_checkpoint""" ) ) self.assertTrue(self.tool.description.startswith("""This is a tool that""" ) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = create_inputs(self.tool.inputs ) UpperCamelCase__ = self.tool(*SCREAMING_SNAKE_CASE_ ) if not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = [outputs] self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , len(self.tool.outputs ) ) for output, output_type in zip(SCREAMING_SNAKE_CASE_ , self.tool.outputs ): UpperCamelCase__ = AGENT_TYPE_MAPPING[output_type] self.assertTrue(isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = create_inputs(self.tool.inputs ) UpperCamelCase__ = [] for _input, input_type in zip(SCREAMING_SNAKE_CASE_ , self.tool.inputs ): if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): _inputs.append([AGENT_TYPE_MAPPING[_input_type](_input ) for _input_type in input_type] ) else: _inputs.append(AGENT_TYPE_MAPPING[input_type](_input ) ) # Should not raise an error UpperCamelCase__ = self.tool(*SCREAMING_SNAKE_CASE_ ) if not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = [outputs] self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , len(self.tool.outputs ) )
178
import numpy as np from sklearn.datasets import fetch_california_housing from sklearn.metrics import mean_absolute_error, mean_squared_error from sklearn.model_selection import train_test_split from xgboost import XGBRegressor def __magic_name__ ( __a : dict ): '''simple docstring''' return (data["data"], data["target"]) def __magic_name__ ( __a : np.ndarray , __a : np.ndarray , __a : np.ndarray ): '''simple docstring''' UpperCamelCase__ = XGBRegressor(verbosity=0 , random_state=42 ) xgb.fit(__a , __a ) # Predict target for test data UpperCamelCase__ = xgb.predict(__a ) UpperCamelCase__ = predictions.reshape(len(__a ) , 1 ) return predictions def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = fetch_california_housing() UpperCamelCase__ , UpperCamelCase__ = data_handling(__a ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = train_test_split( __a , __a , test_size=0.25 , random_state=1 ) UpperCamelCase__ = xgboost(__a , __a , __a ) # Error printing print(f"Mean Absolute Error : {mean_absolute_error(__a , __a )}" ) print(f"Mean Square Error : {mean_squared_error(__a , __a )}" ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
178
1
'''simple docstring''' import shutil import tempfile import unittest from unittest.mock import patch from transformers import ( DefaultFlowCallback, IntervalStrategy, PrinterCallback, ProgressCallback, Trainer, TrainerCallback, TrainingArguments, is_torch_available, ) from transformers.testing_utils import require_torch if is_torch_available(): from transformers.trainer import DEFAULT_CALLBACKS from .test_trainer import RegressionDataset, RegressionModelConfig, RegressionPreTrainedModel class a_ ( snake_case_ ): '''simple docstring''' def __init__( self ) -> List[str]: _SCREAMING_SNAKE_CASE = [] def snake_case_( self , A , A , A , **A ) -> Tuple: self.events.append("""on_init_end""" ) def snake_case_( self , A , A , A , **A ) -> Optional[int]: self.events.append("""on_train_begin""" ) def snake_case_( self , A , A , A , **A ) -> Any: self.events.append("""on_train_end""" ) def snake_case_( self , A , A , A , **A ) -> Tuple: self.events.append("""on_epoch_begin""" ) def snake_case_( self , A , A , A , **A ) -> Tuple: self.events.append("""on_epoch_end""" ) def snake_case_( self , A , A , A , **A ) -> str: self.events.append("""on_step_begin""" ) def snake_case_( self , A , A , A , **A ) -> Dict: self.events.append("""on_step_end""" ) def snake_case_( self , A , A , A , **A ) -> List[Any]: self.events.append("""on_evaluate""" ) def snake_case_( self , A , A , A , **A ) -> Optional[Any]: self.events.append("""on_predict""" ) def snake_case_( self , A , A , A , **A ) -> Optional[Any]: self.events.append("""on_save""" ) def snake_case_( self , A , A , A , **A ) -> int: self.events.append("""on_log""" ) def snake_case_( self , A , A , A , **A ) -> Union[str, Any]: self.events.append("""on_prediction_step""" ) @require_torch class a_ ( unittest.TestCase ): '''simple docstring''' def snake_case_( self ) -> Any: _SCREAMING_SNAKE_CASE = tempfile.mkdtemp() def snake_case_( self ) -> List[str]: shutil.rmtree(self.output_dir ) def snake_case_( self , A=0 , A=0 , A=64 , A=64 , A=None , A=False , **A ) -> Dict: # disable_tqdm in TrainingArguments has a flaky default since it depends on the level of logging. We make sure # its set to False since the tests later on depend on its value. _SCREAMING_SNAKE_CASE = RegressionDataset(length=A ) _SCREAMING_SNAKE_CASE = RegressionDataset(length=A ) _SCREAMING_SNAKE_CASE = RegressionModelConfig(a=A , b=A ) _SCREAMING_SNAKE_CASE = RegressionPreTrainedModel(A ) _SCREAMING_SNAKE_CASE = TrainingArguments(self.output_dir , disable_tqdm=A , report_to=[] , **A ) return Trainer( A , A , train_dataset=A , eval_dataset=A , callbacks=A , ) def snake_case_( self , A , A ) -> Tuple: self.assertEqual(len(A ) , len(A ) ) # Order doesn't matter _SCREAMING_SNAKE_CASE = sorted(A , key=lambda A : cb.__name__ if isinstance(A , A ) else cb.__class__.__name__ ) _SCREAMING_SNAKE_CASE = sorted(A , key=lambda A : cb.__name__ if isinstance(A , A ) else cb.__class__.__name__ ) for cba, cba in zip(A , A ): if isinstance(A , A ) and isinstance(A , A ): self.assertEqual(A , A ) elif isinstance(A , A ) and not isinstance(A , A ): self.assertEqual(A , cba.__class__ ) elif not isinstance(A , A ) and isinstance(A , A ): self.assertEqual(cba.__class__ , A ) else: self.assertEqual(A , A ) def snake_case_( self , A ) -> Optional[Any]: _SCREAMING_SNAKE_CASE = ["""on_init_end""", """on_train_begin"""] _SCREAMING_SNAKE_CASE = 0 _SCREAMING_SNAKE_CASE = len(trainer.get_eval_dataloader() ) _SCREAMING_SNAKE_CASE = ["""on_prediction_step"""] * len(trainer.get_eval_dataloader() ) + ["""on_log""", """on_evaluate"""] for _ in range(trainer.state.num_train_epochs ): expected_events.append("""on_epoch_begin""" ) for _ in range(A ): step += 1 expected_events += ["on_step_begin", "on_step_end"] if step % trainer.args.logging_steps == 0: expected_events.append("""on_log""" ) if trainer.args.evaluation_strategy == IntervalStrategy.STEPS and step % trainer.args.eval_steps == 0: expected_events += evaluation_events.copy() if step % trainer.args.save_steps == 0: expected_events.append("""on_save""" ) expected_events.append("""on_epoch_end""" ) if trainer.args.evaluation_strategy == IntervalStrategy.EPOCH: expected_events += evaluation_events.copy() expected_events += ["on_log", "on_train_end"] return expected_events def snake_case_( self ) -> Tuple: _SCREAMING_SNAKE_CASE = self.get_trainer() _SCREAMING_SNAKE_CASE = DEFAULT_CALLBACKS.copy() + [ProgressCallback] self.check_callbacks_equality(trainer.callback_handler.callbacks , A ) # Callbacks passed at init are added to the default callbacks _SCREAMING_SNAKE_CASE = self.get_trainer(callbacks=[MyTestTrainerCallback] ) expected_callbacks.append(A ) self.check_callbacks_equality(trainer.callback_handler.callbacks , A ) # TrainingArguments.disable_tqdm controls if use ProgressCallback or PrinterCallback _SCREAMING_SNAKE_CASE = self.get_trainer(disable_tqdm=A ) _SCREAMING_SNAKE_CASE = DEFAULT_CALLBACKS.copy() + [PrinterCallback] self.check_callbacks_equality(trainer.callback_handler.callbacks , A ) def snake_case_( self ) -> Optional[int]: _SCREAMING_SNAKE_CASE = DEFAULT_CALLBACKS.copy() + [ProgressCallback] _SCREAMING_SNAKE_CASE = self.get_trainer() # We can add, pop, or remove by class name trainer.remove_callback(A ) expected_callbacks.remove(A ) self.check_callbacks_equality(trainer.callback_handler.callbacks , A ) _SCREAMING_SNAKE_CASE = self.get_trainer() _SCREAMING_SNAKE_CASE = trainer.pop_callback(A ) self.assertEqual(cb.__class__ , A ) self.check_callbacks_equality(trainer.callback_handler.callbacks , A ) trainer.add_callback(A ) expected_callbacks.insert(0 , A ) self.check_callbacks_equality(trainer.callback_handler.callbacks , A ) # We can also add, pop, or remove by instance _SCREAMING_SNAKE_CASE = self.get_trainer() _SCREAMING_SNAKE_CASE = trainer.callback_handler.callbacks[0] trainer.remove_callback(A ) expected_callbacks.remove(A ) self.check_callbacks_equality(trainer.callback_handler.callbacks , A ) _SCREAMING_SNAKE_CASE = self.get_trainer() _SCREAMING_SNAKE_CASE = trainer.callback_handler.callbacks[0] _SCREAMING_SNAKE_CASE = trainer.pop_callback(A ) self.assertEqual(A , A ) self.check_callbacks_equality(trainer.callback_handler.callbacks , A ) trainer.add_callback(A ) expected_callbacks.insert(0 , A ) self.check_callbacks_equality(trainer.callback_handler.callbacks , A ) def snake_case_( self ) -> Tuple: import warnings # XXX: for now ignore scatter_gather warnings in this test since it's not relevant to what's being tested warnings.simplefilter(action="""ignore""" , category=A ) _SCREAMING_SNAKE_CASE = self.get_trainer(callbacks=[MyTestTrainerCallback] ) trainer.train() _SCREAMING_SNAKE_CASE = trainer.callback_handler.callbacks[-2].events self.assertEqual(A , self.get_expected_events(A ) ) # Independent log/save/eval _SCREAMING_SNAKE_CASE = self.get_trainer(callbacks=[MyTestTrainerCallback] , logging_steps=5 ) trainer.train() _SCREAMING_SNAKE_CASE = trainer.callback_handler.callbacks[-2].events self.assertEqual(A , self.get_expected_events(A ) ) _SCREAMING_SNAKE_CASE = self.get_trainer(callbacks=[MyTestTrainerCallback] , save_steps=5 ) trainer.train() _SCREAMING_SNAKE_CASE = trainer.callback_handler.callbacks[-2].events self.assertEqual(A , self.get_expected_events(A ) ) _SCREAMING_SNAKE_CASE = self.get_trainer(callbacks=[MyTestTrainerCallback] , eval_steps=5 , evaluation_strategy="""steps""" ) trainer.train() _SCREAMING_SNAKE_CASE = trainer.callback_handler.callbacks[-2].events self.assertEqual(A , self.get_expected_events(A ) ) _SCREAMING_SNAKE_CASE = self.get_trainer(callbacks=[MyTestTrainerCallback] , evaluation_strategy="""epoch""" ) trainer.train() _SCREAMING_SNAKE_CASE = trainer.callback_handler.callbacks[-2].events self.assertEqual(A , self.get_expected_events(A ) ) # A bit of everything _SCREAMING_SNAKE_CASE = self.get_trainer( callbacks=[MyTestTrainerCallback] , logging_steps=3 , save_steps=10 , eval_steps=5 , evaluation_strategy="""steps""" , ) trainer.train() _SCREAMING_SNAKE_CASE = trainer.callback_handler.callbacks[-2].events self.assertEqual(A , self.get_expected_events(A ) ) # warning should be emitted for duplicated callbacks with patch("""transformers.trainer_callback.logger.warning""" ) as warn_mock: _SCREAMING_SNAKE_CASE = self.get_trainer( callbacks=[MyTestTrainerCallback, MyTestTrainerCallback] , ) assert str(A ) in warn_mock.call_args[0][0]
58
'''simple docstring''' import argparse import logging import pickle from collections import Counter logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""", datefmt="""%m/%d/%Y %H:%M:%S""", level=logging.INFO ) lowercase_ = logging.getLogger(__name__) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser( description="""Token Counts for smoothing the masking probabilities in MLM (cf XLM/word2vec)""" ) parser.add_argument( """--data_file""", type=str, default="""data/dump.bert-base-uncased.pickle""", help="""The binarized dataset.""" ) parser.add_argument( """--token_counts_dump""", type=str, default="""data/token_counts.bert-base-uncased.pickle""", help="""The dump file.""" ) parser.add_argument("""--vocab_size""", default=30_522, type=int) lowercase_ = parser.parse_args() logger.info(f"""Loading data from {args.data_file}""") with open(args.data_file, """rb""") as fp: lowercase_ = pickle.load(fp) logger.info("""Counting occurrences for MLM.""") lowercase_ = Counter() for tk_ids in data: counter.update(tk_ids) lowercase_ = [0] * args.vocab_size for k, v in counter.items(): lowercase_ = v logger.info(f"""Dump to {args.token_counts_dump}""") with open(args.token_counts_dump, """wb""") as handle: pickle.dump(counts, handle, protocol=pickle.HIGHEST_PROTOCOL)
58
1
'''simple docstring''' def UpperCAmelCase_ ( __lowercase : float , __lowercase : float ) -> float: '''simple docstring''' if mass < 0: raise ValueError("The mass of a body cannot be negative" ) return 0.5 * mass * abs(__lowercase ) * abs(__lowercase ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
156
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __SCREAMING_SNAKE_CASE :Dict = { '''configuration_upernet''': ['''UperNetConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE :Optional[int] = [ '''UperNetForSemanticSegmentation''', '''UperNetPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_upernet import UperNetConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_upernet import UperNetForSemanticSegmentation, UperNetPreTrainedModel else: import sys __SCREAMING_SNAKE_CASE :List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
156
1
def UpperCamelCase_( lowerCamelCase_ ) -> bool: _lowercase : str = (1 + 24 * n) ** 0.5 return ((1 + root) / 6) % 1 == 0 def UpperCamelCase_( lowerCamelCase_ = 5000 ) -> int: _lowercase : Optional[Any] = [(i * (3 * i - 1)) // 2 for i in range(1 , lowerCamelCase_ )] for i, pentagonal_i in enumerate(lowerCamelCase_ ): for j in range(lowerCamelCase_ , len(lowerCamelCase_ ) ): _lowercase : List[Any] = pentagonal_nums[j] _lowercase : Optional[int] = pentagonal_i + pentagonal_j _lowercase : str = pentagonal_j - pentagonal_i if is_pentagonal(lowerCamelCase_ ) and is_pentagonal(lowerCamelCase_ ): return b return -1 if __name__ == "__main__": print(F"{solution() = }")
21
'''simple docstring''' def lowerCamelCase ( UpperCAmelCase__ : list ) -> list: if any(not isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) or x < 0 for x in sequence ): raise TypeError("""Sequence must be list of non-negative integers""" ) for _ in range(len(UpperCAmelCase__ ) ): for i, (rod_upper, rod_lower) in enumerate(zip(UpperCAmelCase__ , sequence[1:] ) ): if rod_upper > rod_lower: sequence[i] -= rod_upper - rod_lower sequence[i + 1] += rod_upper - rod_lower return sequence if __name__ == "__main__": assert bead_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5] assert bead_sort([7, 9, 4, 3, 5]) == [3, 4, 5, 7, 9]
239
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__)
290
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) UpperCAmelCase__ = { "configuration_clip": [ "CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP", "CLIPConfig", "CLIPOnnxConfig", "CLIPTextConfig", "CLIPVisionConfig", ], "processing_clip": ["CLIPProcessor"], "tokenization_clip": ["CLIPTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = ["CLIPTokenizerFast"] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = ["CLIPFeatureExtractor"] UpperCAmelCase__ = ["CLIPImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "CLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "CLIPModel", "CLIPPreTrainedModel", "CLIPTextModel", "CLIPTextModelWithProjection", "CLIPVisionModel", "CLIPVisionModelWithProjection", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "TFCLIPModel", "TFCLIPPreTrainedModel", "TFCLIPTextModel", "TFCLIPVisionModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "FlaxCLIPModel", "FlaxCLIPPreTrainedModel", "FlaxCLIPTextModel", "FlaxCLIPTextPreTrainedModel", "FlaxCLIPVisionModel", "FlaxCLIPVisionPreTrainedModel", ] if TYPE_CHECKING: from .configuration_clip import ( CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, CLIPConfig, CLIPOnnxConfig, CLIPTextConfig, CLIPVisionConfig, ) from .processing_clip import CLIPProcessor from .tokenization_clip import CLIPTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_clip_fast import CLIPTokenizerFast try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_clip import CLIPFeatureExtractor from .image_processing_clip import CLIPImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_clip import ( CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, CLIPModel, CLIPPreTrainedModel, CLIPTextModel, CLIPTextModelWithProjection, CLIPVisionModel, CLIPVisionModelWithProjection, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_clip import ( TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFCLIPModel, TFCLIPPreTrainedModel, TFCLIPTextModel, TFCLIPVisionModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_clip import ( FlaxCLIPModel, FlaxCLIPPreTrainedModel, FlaxCLIPTextModel, FlaxCLIPTextPreTrainedModel, FlaxCLIPVisionModel, FlaxCLIPVisionPreTrainedModel, ) else: import sys UpperCAmelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
290
1
from ...configuration_utils import PretrainedConfig from ...utils import logging __snake_case : List[Any] =logging.get_logger(__name__) __snake_case : Union[str, Any] ={ 'google/realm-cc-news-pretrained-embedder': ( 'https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/config.json' ), 'google/realm-cc-news-pretrained-encoder': ( 'https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/config.json' ), 'google/realm-cc-news-pretrained-scorer': ( 'https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/config.json' ), 'google/realm-cc-news-pretrained-openqa': ( 'https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/config.json' ), 'google/realm-orqa-nq-openqa': 'https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/config.json', 'google/realm-orqa-nq-reader': 'https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/config.json', 'google/realm-orqa-wq-openqa': 'https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/config.json', 'google/realm-orqa-wq-reader': 'https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/config.json', # See all REALM models at https://huggingface.co/models?filter=realm } class lowerCamelCase__ ( lowerCamelCase__): '''simple docstring''' snake_case_ ="""realm""" def __init__(self ,__lowerCamelCase=3_05_22 ,__lowerCamelCase=7_68 ,__lowerCamelCase=1_28 ,__lowerCamelCase=12 ,__lowerCamelCase=12 ,__lowerCamelCase=8 ,__lowerCamelCase=30_72 ,__lowerCamelCase="gelu_new" ,__lowerCamelCase=0.1 ,__lowerCamelCase=0.1 ,__lowerCamelCase=5_12 ,__lowerCamelCase=2 ,__lowerCamelCase=0.02 ,__lowerCamelCase=1e-12 ,__lowerCamelCase=2_56 ,__lowerCamelCase=10 ,__lowerCamelCase=1e-3 ,__lowerCamelCase=5 ,__lowerCamelCase=3_20 ,__lowerCamelCase=13_35_37_18 ,__lowerCamelCase=50_00 ,__lowerCamelCase=1 ,__lowerCamelCase=0 ,__lowerCamelCase=2 ,**__lowerCamelCase ,) -> Union[str, Any]: """simple docstring""" super().__init__(pad_token_id=__lowerCamelCase ,bos_token_id=__lowerCamelCase ,eos_token_id=__lowerCamelCase ,**__lowerCamelCase ) # Common config lowerCAmelCase__ : Any = vocab_size lowerCAmelCase__ : Union[str, Any] = max_position_embeddings lowerCAmelCase__ : str = hidden_size lowerCAmelCase__ : Union[str, Any] = retriever_proj_size lowerCAmelCase__ : Union[str, Any] = num_hidden_layers lowerCAmelCase__ : Tuple = num_attention_heads lowerCAmelCase__ : Tuple = num_candidates lowerCAmelCase__ : Union[str, Any] = intermediate_size lowerCAmelCase__ : List[str] = hidden_act lowerCAmelCase__ : int = hidden_dropout_prob lowerCAmelCase__ : List[str] = attention_probs_dropout_prob lowerCAmelCase__ : Optional[int] = initializer_range lowerCAmelCase__ : Tuple = type_vocab_size lowerCAmelCase__ : Optional[Any] = layer_norm_eps # Reader config lowerCAmelCase__ : Any = span_hidden_size lowerCAmelCase__ : Tuple = max_span_width lowerCAmelCase__ : Tuple = reader_layer_norm_eps lowerCAmelCase__ : Optional[int] = reader_beam_size lowerCAmelCase__ : Tuple = reader_seq_len # Retrieval config lowerCAmelCase__ : List[str] = num_block_records lowerCAmelCase__ : List[Any] = searcher_beam_size
129
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 __snake_case : Optional[Any] =logging.get_logger(__name__) __snake_case : Union[str, Any] ={'vocab_file': 'spm_char.model'} __snake_case : List[str] ={ 'vocab_file': { 'microsoft/speecht5_asr': 'https://huggingface.co/microsoft/speecht5_asr/resolve/main/spm_char.model', 'microsoft/speecht5_tts': 'https://huggingface.co/microsoft/speecht5_tts/resolve/main/spm_char.model', 'microsoft/speecht5_vc': 'https://huggingface.co/microsoft/speecht5_vc/resolve/main/spm_char.model', } } __snake_case : Union[str, Any] ={ 'microsoft/speecht5_asr': 1_0_2_4, 'microsoft/speecht5_tts': 1_0_2_4, 'microsoft/speecht5_vc': 1_0_2_4, } class lowerCamelCase__ ( lowerCamelCase__): '''simple docstring''' snake_case_ =VOCAB_FILES_NAMES snake_case_ =PRETRAINED_VOCAB_FILES_MAP snake_case_ =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case_ =["""input_ids""", """attention_mask"""] def __init__(self ,__lowerCamelCase ,__lowerCamelCase="<s>" ,__lowerCamelCase="</s>" ,__lowerCamelCase="<unk>" ,__lowerCamelCase="<pad>" ,__lowerCamelCase = None ,**__lowerCamelCase ,) -> None: """simple docstring""" lowerCAmelCase__ : Dict = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__lowerCamelCase ,eos_token=__lowerCamelCase ,unk_token=__lowerCamelCase ,pad_token=__lowerCamelCase ,sp_model_kwargs=self.sp_model_kwargs ,**__lowerCamelCase ,) lowerCAmelCase__ : List[str] = vocab_file lowerCAmelCase__ : Dict = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(__lowerCamelCase ) @property def lowerCAmelCase__ (self ) -> Optional[int]: """simple docstring""" return self.sp_model.get_piece_size() def lowerCAmelCase__ (self ) -> List[Any]: """simple docstring""" lowerCAmelCase__ : int = {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 ) -> Dict: """simple docstring""" lowerCAmelCase__ : Union[str, Any] = self.__dict__.copy() lowerCAmelCase__ : Any = None return state def __setstate__(self ,__lowerCamelCase ) -> Union[str, Any]: """simple docstring""" lowerCAmelCase__ : Optional[int] = d # for backward compatibility if not hasattr(self ,'''sp_model_kwargs''' ): lowerCAmelCase__ : Optional[int] = {} lowerCAmelCase__ : str = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def lowerCAmelCase__ (self ,__lowerCamelCase ) -> List[str]: """simple docstring""" return self.sp_model.encode(__lowerCamelCase ,out_type=__lowerCamelCase ) def lowerCAmelCase__ (self ,__lowerCamelCase ) -> Optional[Any]: """simple docstring""" return self.sp_model.piece_to_id(__lowerCamelCase ) def lowerCAmelCase__ (self ,__lowerCamelCase ) -> Any: """simple docstring""" lowerCAmelCase__ : str = self.sp_model.IdToPiece(__lowerCamelCase ) return token def lowerCAmelCase__ (self ,__lowerCamelCase ) -> Dict: """simple docstring""" lowerCAmelCase__ : Optional[Any] = [] lowerCAmelCase__ : Union[str, Any] = '''''' 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 lowerCAmelCase__ : str = [] else: current_sub_tokens.append(__lowerCamelCase ) out_string += self.sp_model.decode(__lowerCamelCase ) return out_string.strip() def lowerCAmelCase__ (self ,__lowerCamelCase ,__lowerCamelCase=None ) -> List[int]: """simple docstring""" if token_ids_a is None: return token_ids_a + [self.eos_token_id] # We don't expect to process pairs, but leave the pair logic for API consistency return token_ids_a + token_ids_a + [self.eos_token_id] def lowerCAmelCase__ (self ,__lowerCamelCase ,__lowerCamelCase = None ,__lowerCamelCase = False ) -> List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__lowerCamelCase ,token_ids_a=__lowerCamelCase ,already_has_special_tokens=__lowerCamelCase ) lowerCAmelCase__ : Dict = [1] if token_ids_a is None: return ([0] * len(__lowerCamelCase )) + suffix_ones return ([0] * len(__lowerCamelCase )) + ([0] * len(__lowerCamelCase )) + suffix_ones def lowerCAmelCase__ (self ,__lowerCamelCase ,__lowerCamelCase = None ) -> Tuple[str]: """simple docstring""" if not os.path.isdir(__lowerCamelCase ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return lowerCAmelCase__ : Union[str, Any] = 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: lowerCAmelCase__ : Tuple = self.sp_model.serialized_model_proto() fi.write(__lowerCamelCase ) return (out_vocab_file,)
129
1
def __UpperCamelCase ( lowercase__ : int = 10**9 ) -> int: '''simple docstring''' lowerCAmelCase_ : Any = 1 lowerCAmelCase_ : Dict = 2 lowerCAmelCase_ : str = 0 lowerCAmelCase_ : Optional[Any] = 0 lowerCAmelCase_ : Any = 0 while perimeter <= max_perimeter: perimeters_sum += perimeter prev_value += 2 * value value += prev_value lowerCAmelCase_ : str = 2 * value + 2 if i % 2 == 0 else 2 * value - 2 i += 1 return perimeters_sum if __name__ == "__main__": print(f"""{solution() = }""")
364
import argparse import numpy as np import torch from transformers import SpeechTaHifiGan, SpeechTaHifiGanConfig, logging logging.set_verbosity_info() __UpperCAmelCase = logging.get_logger('transformers.models.speecht5') def __UpperCamelCase ( lowercase__ : Optional[Any] , lowercase__ : Optional[Any] , lowercase__ : str ) -> List[str]: '''simple docstring''' hf_model.apply_weight_norm() lowerCAmelCase_ : Dict = checkpoint["""input_conv.weight_g"""] lowerCAmelCase_ : Any = checkpoint["""input_conv.weight_v"""] lowerCAmelCase_ : Any = checkpoint["""input_conv.bias"""] for i in range(len(config.upsample_rates ) ): lowerCAmelCase_ : Tuple = checkpoint[f'upsamples.{i}.1.weight_g'] lowerCAmelCase_ : Any = checkpoint[f'upsamples.{i}.1.weight_v'] lowerCAmelCase_ : int = checkpoint[f'upsamples.{i}.1.bias'] for i in range(len(config.upsample_rates ) * len(config.resblock_kernel_sizes ) ): for j in range(len(config.resblock_dilation_sizes ) ): lowerCAmelCase_ : Dict = checkpoint[f'blocks.{i}.convs1.{j}.1.weight_g'] lowerCAmelCase_ : Dict = checkpoint[f'blocks.{i}.convs1.{j}.1.weight_v'] lowerCAmelCase_ : Tuple = checkpoint[f'blocks.{i}.convs1.{j}.1.bias'] lowerCAmelCase_ : str = checkpoint[f'blocks.{i}.convs2.{j}.1.weight_g'] lowerCAmelCase_ : Optional[Any] = checkpoint[f'blocks.{i}.convs2.{j}.1.weight_v'] lowerCAmelCase_ : str = checkpoint[f'blocks.{i}.convs2.{j}.1.bias'] lowerCAmelCase_ : str = checkpoint["""output_conv.1.weight_g"""] lowerCAmelCase_ : Dict = checkpoint["""output_conv.1.weight_v"""] lowerCAmelCase_ : Optional[int] = checkpoint["""output_conv.1.bias"""] hf_model.remove_weight_norm() @torch.no_grad() def __UpperCamelCase ( lowercase__ : str , lowercase__ : Tuple , lowercase__ : Dict , lowercase__ : List[Any]=None , lowercase__ : Union[str, Any]=None , ) -> List[Any]: '''simple docstring''' if config_path is not None: lowerCAmelCase_ : Optional[Any] = SpeechTaHifiGanConfig.from_pretrained(lowercase__ ) else: lowerCAmelCase_ : Any = SpeechTaHifiGanConfig() lowerCAmelCase_ : str = SpeechTaHifiGan(lowercase__ ) lowerCAmelCase_ : Tuple = torch.load(lowercase__ ) load_weights(orig_checkpoint["""model"""]["""generator"""] , lowercase__ , lowercase__ ) lowerCAmelCase_ : Optional[int] = np.load(lowercase__ ) lowerCAmelCase_ : Any = stats[0].reshape(-1 ) lowerCAmelCase_ : List[str] = stats[1].reshape(-1 ) lowerCAmelCase_ : Optional[int] = torch.from_numpy(lowercase__ ).float() lowerCAmelCase_ : Any = torch.from_numpy(lowercase__ ).float() model.save_pretrained(lowercase__ ) if repo_id: print("""Pushing to the hub...""" ) model.push_to_hub(lowercase__ ) if __name__ == "__main__": __UpperCAmelCase = argparse.ArgumentParser() parser.add_argument('--checkpoint_path', required=True, default=None, type=str, help='Path to original checkpoint') parser.add_argument('--stats_path', required=True, default=None, type=str, help='Path to stats.npy file') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') parser.add_argument( '--pytorch_dump_folder_path', required=True, default=None, type=str, help='Path to the output PyTorch model.' ) parser.add_argument( '--push_to_hub', default=None, type=str, help='Where to upload the converted model on the 🤗 hub.' ) __UpperCAmelCase = parser.parse_args() convert_hifigan_checkpoint( args.checkpoint_path, args.stats_path, args.pytorch_dump_folder_path, args.config_path, args.push_to_hub, )
28
0
import inspect import warnings from typing import Any, Dict, Optional, Union from packaging import version def __A ( *__lowerCamelCase , __lowerCamelCase = None , __lowerCamelCase=True , __lowerCamelCase=2 ) -> Optional[Any]: from .. import __version__ a = take_from a = () if not isinstance(args[0] , __lowerCamelCase ): a = (args,) for attribute, version_name, message in args: if version.parse(version.parse(__lowerCamelCase ).base_version ) >= version.parse(__lowerCamelCase ): raise ValueError( f'The deprecation tuple {(attribute, version_name, message)} should be removed since diffusers\'' f' version {__version__} is >= {version_name}' ) a = None if isinstance(__lowerCamelCase , __lowerCamelCase ) and attribute in deprecated_kwargs: values += (deprecated_kwargs.pop(__lowerCamelCase ),) a = f'The `{attribute}` argument is deprecated and will be removed in version {version_name}.' elif hasattr(__lowerCamelCase , __lowerCamelCase ): values += (getattr(__lowerCamelCase , __lowerCamelCase ),) a = f'The `{attribute}` attribute is deprecated and will be removed in version {version_name}.' elif deprecated_kwargs is None: a = f'`{attribute}` is deprecated and will be removed in version {version_name}.' if warning is not None: a = warning + """ """ if standard_warn else """""" warnings.warn(warning + message , __lowerCamelCase , stacklevel=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) and len(__lowerCamelCase ) > 0: a = inspect.getouterframes(inspect.currentframe() )[1] a = call_frame.filename a = call_frame.lineno a = call_frame.function a , a = next(iter(deprecated_kwargs.items() ) ) raise TypeError(f'{function} in {filename} line {line_number-1} got an unexpected keyword argument `{key}`' ) if len(__lowerCamelCase ) == 0: return elif len(__lowerCamelCase ) == 1: return values[0] return values
228
__UpperCamelCase : Optional[int] = { "Pillow": "Pillow", "accelerate": "accelerate>=0.11.0", "compel": "compel==0.1.8", "black": "black~=23.1", "datasets": "datasets", "filelock": "filelock", "flax": "flax>=0.4.1", "hf-doc-builder": "hf-doc-builder>=0.3.0", "huggingface-hub": "huggingface-hub>=0.13.2", "requests-mock": "requests-mock==1.10.0", "importlib_metadata": "importlib_metadata", "invisible-watermark": "invisible-watermark", "isort": "isort>=5.5.4", "jax": "jax>=0.2.8,!=0.3.2", "jaxlib": "jaxlib>=0.1.65", "Jinja2": "Jinja2", "k-diffusion": "k-diffusion>=0.0.12", "torchsde": "torchsde", "note_seq": "note_seq", "librosa": "librosa", "numpy": "numpy", "omegaconf": "omegaconf", "parameterized": "parameterized", "protobuf": "protobuf>=3.20.3,<4", "pytest": "pytest", "pytest-timeout": "pytest-timeout", "pytest-xdist": "pytest-xdist", "ruff": "ruff>=0.0.241", "safetensors": "safetensors", "sentencepiece": "sentencepiece>=0.1.91,!=0.1.92", "scipy": "scipy", "onnx": "onnx", "regex": "regex!=2019.12.17", "requests": "requests", "tensorboard": "tensorboard", "torch": "torch>=1.4", "torchvision": "torchvision", "transformers": "transformers>=4.25.1", "urllib3": "urllib3<=2.0.0", }
228
1
"""simple docstring""" import argparse import requests import torch from PIL import Image from transformers import SwinConfig, SwinForMaskedImageModeling, ViTImageProcessor def lowerCamelCase_ (UpperCamelCase__ : Dict ): _UpperCAmelCase : str = SwinConfig(image_size=192 ) if "base" in model_name: _UpperCAmelCase : Optional[int] = 6 _UpperCAmelCase : Tuple = 128 _UpperCAmelCase : Dict = (2, 2, 18, 2) _UpperCAmelCase : Tuple = (4, 8, 16, 32) elif "large" in model_name: _UpperCAmelCase : Dict = 12 _UpperCAmelCase : int = 192 _UpperCAmelCase : Any = (2, 2, 18, 2) _UpperCAmelCase : str = (6, 12, 24, 48) else: raise ValueError('''Model not supported, only supports base and large variants''' ) _UpperCAmelCase : Dict = window_size _UpperCAmelCase : str = embed_dim _UpperCAmelCase : Optional[Any] = depths _UpperCAmelCase : List[Any] = num_heads return config def lowerCamelCase_ (UpperCamelCase__ : Tuple ): if "encoder.mask_token" in name: _UpperCAmelCase : str = name.replace('''encoder.mask_token''' , '''embeddings.mask_token''' ) if "encoder.patch_embed.proj" in name: _UpperCAmelCase : str = name.replace('''encoder.patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' ) if "encoder.patch_embed.norm" in name: _UpperCAmelCase : Union[str, Any] = name.replace('''encoder.patch_embed.norm''' , '''embeddings.norm''' ) if "attn.proj" in name: _UpperCAmelCase : str = name.replace('''attn.proj''' , '''attention.output.dense''' ) if "attn" in name: _UpperCAmelCase : List[str] = name.replace('''attn''' , '''attention.self''' ) if "norm1" in name: _UpperCAmelCase : Any = name.replace('''norm1''' , '''layernorm_before''' ) if "norm2" in name: _UpperCAmelCase : str = name.replace('''norm2''' , '''layernorm_after''' ) if "mlp.fc1" in name: _UpperCAmelCase : List[Any] = name.replace('''mlp.fc1''' , '''intermediate.dense''' ) if "mlp.fc2" in name: _UpperCAmelCase : int = name.replace('''mlp.fc2''' , '''output.dense''' ) if name == "encoder.norm.weight": _UpperCAmelCase : int = '''layernorm.weight''' if name == "encoder.norm.bias": _UpperCAmelCase : Optional[int] = '''layernorm.bias''' if "decoder" in name: pass else: _UpperCAmelCase : Any = '''swin.''' + name return name def lowerCamelCase_ (UpperCamelCase__ : str , UpperCamelCase__ : Tuple ): for key in orig_state_dict.copy().keys(): _UpperCAmelCase : Optional[int] = orig_state_dict.pop(UpperCamelCase__ ) if "attn_mask" in key: pass elif "qkv" in key: _UpperCAmelCase : List[Any] = key.split('''.''' ) _UpperCAmelCase : Tuple = int(key_split[2] ) _UpperCAmelCase : Tuple = int(key_split[4] ) _UpperCAmelCase : str = model.swin.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: _UpperCAmelCase : List[str] = val[:dim, :] _UpperCAmelCase : List[str] = val[ dim : dim * 2, : ] _UpperCAmelCase : int = val[-dim:, :] else: _UpperCAmelCase : str = val[ :dim ] _UpperCAmelCase : Optional[int] = val[ dim : dim * 2 ] _UpperCAmelCase : Optional[int] = val[ -dim: ] else: _UpperCAmelCase : List[str] = val return orig_state_dict def lowerCamelCase_ (UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Any , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Optional[int] ): _UpperCAmelCase : Any = torch.load(UpperCamelCase__ , map_location='''cpu''' )['''model'''] _UpperCAmelCase : Union[str, Any] = get_swin_config(UpperCamelCase__ ) _UpperCAmelCase : Tuple = SwinForMaskedImageModeling(UpperCamelCase__ ) model.eval() _UpperCAmelCase : Tuple = convert_state_dict(UpperCamelCase__ , UpperCamelCase__ ) model.load_state_dict(UpperCamelCase__ ) _UpperCAmelCase : str = '''http://images.cocodataset.org/val2017/000000039769.jpg''' _UpperCAmelCase : Optional[int] = ViTImageProcessor(size={'''height''': 192, '''width''': 192} ) _UpperCAmelCase : Tuple = Image.open(requests.get(UpperCamelCase__ , stream=UpperCamelCase__ ).raw ) _UpperCAmelCase : Optional[int] = image_processor(images=UpperCamelCase__ , return_tensors='''pt''' ) with torch.no_grad(): _UpperCAmelCase : str = model(**UpperCamelCase__ ).logits print(outputs.keys() ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: print(F'Saving model {model_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(UpperCamelCase__ ) print(F'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(UpperCamelCase__ ) if push_to_hub: print(F'Pushing model and image processor for {model_name} to hub' ) model.push_to_hub(F'microsoft/{model_name}' ) image_processor.push_to_hub(F'microsoft/{model_name}' ) if __name__ == "__main__": _lowerCAmelCase :Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='swin-base-simmim-window6-192', type=str, choices=['swin-base-simmim-window6-192', 'swin-large-simmim-window12-192'], help='Name of the Swin SimMIM model you\'d like to convert.', ) parser.add_argument( '--checkpoint_path', default='/Users/nielsrogge/Documents/SwinSimMIM/simmim_pretrain__swin_base__img192_window6__100ep.pth', type=str, help='Path to the original PyTorch checkpoint (.pth file).', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.' ) _lowerCAmelCase :Optional[Any] = parser.parse_args() convert_swin_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub)
360
"""simple docstring""" from __future__ import annotations from itertools import permutations from random import randint from timeit import repeat def lowerCamelCase_ (): _UpperCAmelCase : Optional[int] = [randint(-1000 , 1000 ) for i in range(10 )] _UpperCAmelCase : int = randint(-5000 , 5000 ) return (arr, r) _lowerCAmelCase :Optional[Any] = make_dataset() def lowerCamelCase_ (UpperCamelCase__ : list[int] , UpperCamelCase__ : int ): for triplet in permutations(UpperCamelCase__ , 3 ): if sum(UpperCamelCase__ ) == target: return tuple(sorted(UpperCamelCase__ ) ) return (0, 0, 0) def lowerCamelCase_ (UpperCamelCase__ : list[int] , UpperCamelCase__ : int ): arr.sort() _UpperCAmelCase : Optional[int] = len(UpperCamelCase__ ) for i in range(n - 1 ): _UpperCAmelCase , _UpperCAmelCase : Any = i + 1, n - 1 while left < right: if arr[i] + arr[left] + arr[right] == target: return (arr[i], arr[left], arr[right]) elif arr[i] + arr[left] + arr[right] < target: left += 1 elif arr[i] + arr[left] + arr[right] > target: right -= 1 return (0, 0, 0) def lowerCamelCase_ (): _UpperCAmelCase : Union[str, Any] = ''' from __main__ import dataset, triplet_sum1, triplet_sum2 ''' _UpperCAmelCase : Any = ''' triplet_sum1(*dataset) ''' _UpperCAmelCase : List[Any] = ''' triplet_sum2(*dataset) ''' _UpperCAmelCase : List[Any] = repeat(setup=UpperCamelCase__ , stmt=UpperCamelCase__ , repeat=5 , number=1_0000 ) _UpperCAmelCase : List[Any] = repeat(setup=UpperCamelCase__ , stmt=UpperCamelCase__ , repeat=5 , number=1_0000 ) return (min(UpperCamelCase__ ), min(UpperCamelCase__ )) if __name__ == "__main__": from doctest import testmod testmod() _lowerCAmelCase :List[str] = solution_times() print(f"The time for naive implementation is {times[0]}.") print(f"The time for optimized implementation is {times[1]}.")
68
0
"""simple docstring""" import argparse import collections import os import re import tempfile import pandas as pd from datasets import Dataset from huggingface_hub import hf_hub_download, upload_folder from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/update_metadata.py lowerCamelCase_ : int = 'src/transformers' # This is to make sure the transformers module imported is the one in the repo. lowerCamelCase_ : int = direct_transformers_import(TRANSFORMERS_PATH) # Regexes that match TF/Flax/PT model names. lowerCamelCase_ : Optional[Any] = re.compile(r'TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') lowerCamelCase_ : str = re.compile(r'Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') # Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes. lowerCamelCase_ : Tuple = re.compile(r'(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') # Fill this with tuples (pipeline_tag, model_mapping, auto_model) lowerCamelCase_ : int = [ ('pretraining', 'MODEL_FOR_PRETRAINING_MAPPING_NAMES', 'AutoModelForPreTraining'), ('feature-extraction', 'MODEL_MAPPING_NAMES', 'AutoModel'), ('audio-classification', 'MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForAudioClassification'), ('text-generation', 'MODEL_FOR_CAUSAL_LM_MAPPING_NAMES', 'AutoModelForCausalLM'), ('automatic-speech-recognition', 'MODEL_FOR_CTC_MAPPING_NAMES', 'AutoModelForCTC'), ('image-classification', 'MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForImageClassification'), ('image-segmentation', 'MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES', 'AutoModelForImageSegmentation'), ('fill-mask', 'MODEL_FOR_MASKED_LM_MAPPING_NAMES', 'AutoModelForMaskedLM'), ('object-detection', 'MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES', 'AutoModelForObjectDetection'), ( 'zero-shot-object-detection', 'MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES', 'AutoModelForZeroShotObjectDetection', ), ('question-answering', 'MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES', 'AutoModelForQuestionAnswering'), ('text2text-generation', 'MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES', 'AutoModelForSeq2SeqLM'), ('text-classification', 'MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForSequenceClassification'), ('automatic-speech-recognition', 'MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES', 'AutoModelForSpeechSeq2Seq'), ( 'table-question-answering', 'MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES', 'AutoModelForTableQuestionAnswering', ), ('token-classification', 'MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForTokenClassification'), ('multiple-choice', 'MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES', 'AutoModelForMultipleChoice'), ( 'next-sentence-prediction', 'MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES', 'AutoModelForNextSentencePrediction', ), ( 'audio-frame-classification', 'MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForAudioFrameClassification', ), ('audio-xvector', 'MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES', 'AutoModelForAudioXVector'), ( 'document-question-answering', 'MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES', 'AutoModelForDocumentQuestionAnswering', ), ( 'visual-question-answering', 'MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING_NAMES', 'AutoModelForVisualQuestionAnswering', ), ('image-to-text', 'MODEL_FOR_FOR_VISION_2_SEQ_MAPPING_NAMES', 'AutoModelForVision2Seq'), ( 'zero-shot-image-classification', 'MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForZeroShotImageClassification', ), ('depth-estimation', 'MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES', 'AutoModelForDepthEstimation'), ('video-classification', 'MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForVideoClassification'), ('mask-generation', 'MODEL_FOR_MASK_GENERATION_MAPPING_NAMES', 'AutoModelForMaskGeneration'), ] def UpperCAmelCase__ ( _UpperCAmelCase ): """simple docstring""" A_ : List[Any] = re.finditer('.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)' , a_ ) return [m.group(0 ) for m in matches] def UpperCAmelCase__ ( ): """simple docstring""" A_ : Optional[Any] = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES A_ : List[Any] = { config.replace('Config' , '' ): model_type for model_type, config in config_maping_names.items() } # Dictionaries flagging if each model prefix has a backend in PT/TF/Flax. A_ : Dict = collections.defaultdict(a_ ) A_ : int = collections.defaultdict(a_ ) A_ : List[str] = collections.defaultdict(a_ ) # Let's lookup through all transformers object (once) and find if models are supported by a given backend. for attr_name in dir(a_ ): A_ : Any = None if _re_tf_models.match(a_ ) is not None: A_ : Any = tf_models A_ : Tuple = _re_tf_models.match(a_ ).groups()[0] elif _re_flax_models.match(a_ ) is not None: A_ : Any = flax_models A_ : Optional[int] = _re_flax_models.match(a_ ).groups()[0] elif _re_pt_models.match(a_ ) is not None: A_ : Any = pt_models A_ : int = _re_pt_models.match(a_ ).groups()[0] if lookup_dict is not None: while len(a_ ) > 0: if attr_name in model_prefix_to_model_type: A_ : str = True break # Try again after removing the last word in the name A_ : List[Any] = ''.join(camel_case_split(a_ )[:-1] ) A_ : str = set(list(pt_models.keys() ) + list(tf_models.keys() ) + list(flax_models.keys() ) ) A_ : Tuple = list(a_ ) all_models.sort() A_ : Optional[int] = {'model_type': all_models} A_ : int = [pt_models[t] for t in all_models] A_ : Optional[Any] = [tf_models[t] for t in all_models] A_ : List[Any] = [flax_models[t] for t in all_models] # Now let's use the auto-mapping names to make sure A_ : str = {} for t in all_models: if t in transformers_module.models.auto.processing_auto.PROCESSOR_MAPPING_NAMES: A_ : Dict = 'AutoProcessor' elif t in transformers_module.models.auto.tokenization_auto.TOKENIZER_MAPPING_NAMES: A_ : Tuple = 'AutoTokenizer' elif t in transformers_module.models.auto.feature_extraction_auto.FEATURE_EXTRACTOR_MAPPING_NAMES: A_ : Any = 'AutoFeatureExtractor' else: # Default to AutoTokenizer if a model has nothing, for backward compatibility. A_ : Optional[Any] = 'AutoTokenizer' A_ : str = [processors[t] for t in all_models] return pd.DataFrame(a_ ) def UpperCAmelCase__ ( _UpperCAmelCase ): """simple docstring""" A_ : Optional[Any] = [ transformers_module.models.auto.modeling_auto, transformers_module.models.auto.modeling_tf_auto, transformers_module.models.auto.modeling_flax_auto, ] for pipeline_tag, model_mapping, auto_class in PIPELINE_TAGS_AND_AUTO_MODELS: A_ : int = [model_mapping, f"""TF_{model_mapping}""", f"""FLAX_{model_mapping}"""] A_ : Optional[int] = [auto_class, f"""TF_{auto_class}""", f"""Flax_{auto_class}"""] # Loop through all three frameworks for module, cls, mapping in zip(a_ , a_ , a_ ): # The type of pipeline may not exist in this framework if not hasattr(a_ , a_ ): continue # First extract all model_names A_ : Tuple = [] for name in getattr(a_ , a_ ).values(): if isinstance(a_ , a_ ): model_names.append(a_ ) else: model_names.extend(list(a_ ) ) # Add pipeline tag and auto model class for those models table.update({model_name: (pipeline_tag, cls) for model_name in model_names} ) return table def UpperCAmelCase__ ( _UpperCAmelCase , _UpperCAmelCase ): """simple docstring""" A_ : str = get_frameworks_table() A_ : List[str] = Dataset.from_pandas(a_ ) A_ : List[str] = hf_hub_download( 'huggingface/transformers-metadata' , 'pipeline_tags.json' , repo_type='dataset' , token=a_ ) A_ : Optional[Any] = Dataset.from_json(a_ ) A_ : Optional[int] = { tags_dataset[i]['model_class']: (tags_dataset[i]['pipeline_tag'], tags_dataset[i]['auto_class']) for i in range(len(a_ ) ) } A_ : Optional[Any] = update_pipeline_and_auto_class_table(a_ ) # Sort the model classes to avoid some nondeterministic updates to create false update commits. A_ : Optional[int] = sorted(table.keys() ) A_ : Any = pd.DataFrame( { 'model_class': model_classes, 'pipeline_tag': [table[m][0] for m in model_classes], 'auto_class': [table[m][1] for m in model_classes], } ) A_ : int = Dataset.from_pandas(a_ ) with tempfile.TemporaryDirectory() as tmp_dir: frameworks_dataset.to_json(os.path.join(a_ , 'frameworks.json' ) ) tags_dataset.to_json(os.path.join(a_ , 'pipeline_tags.json' ) ) if commit_sha is not None: A_ : List[Any] = ( f"""Update with commit {commit_sha}\n\nSee: """ f"""https://github.com/huggingface/transformers/commit/{commit_sha}""" ) else: A_ : Any = 'Update' upload_folder( repo_id='huggingface/transformers-metadata' , folder_path=a_ , repo_type='dataset' , token=a_ , commit_message=a_ , ) def UpperCAmelCase__ ( ): """simple docstring""" A_ : Optional[Any] = {tag: cls for tag, _, cls in PIPELINE_TAGS_AND_AUTO_MODELS} A_ : str = transformers_module.pipelines.SUPPORTED_TASKS A_ : Tuple = [] for key in pipeline_tasks: if key not in in_table: A_ : List[str] = pipeline_tasks[key]['pt'] if isinstance(a_ , (list, tuple) ): A_ : Union[str, Any] = model[0] A_ : Optional[Any] = model.__name__ if model not in in_table.values(): missing.append(a_ ) if len(a_ ) > 0: A_ : List[Any] = ', '.join(a_ ) raise ValueError( 'The following pipeline tags are not present in the `PIPELINE_TAGS_AND_AUTO_MODELS` constant inside ' f"""`utils/update_metadata.py`: {msg}. Please add them!""" ) if __name__ == "__main__": lowerCamelCase_ : Optional[int] = argparse.ArgumentParser() parser.add_argument('--token', type=str, help='The token to use to push to the transformers-metadata dataset.') parser.add_argument('--commit_sha', type=str, help='The sha of the commit going with this update.') parser.add_argument('--check-only', action='store_true', help='Activate to just check all pipelines are present.') lowerCamelCase_ : int = parser.parse_args() if args.check_only: check_pipeline_tags() else: update_metadata(args.token, args.commit_sha)
286
from typing import Dict, Optional import numpy as np import datasets SCREAMING_SNAKE_CASE :List[Any] = '\nIoU is the area of overlap between the predicted segmentation and the ground truth divided by the area of union\nbetween the predicted segmentation and the ground truth. For binary (two classes) or multi-class segmentation,\nthe mean IoU of the image is calculated by taking the IoU of each class and averaging them.\n' SCREAMING_SNAKE_CASE :List[str] = '\nArgs:\n predictions (`List[ndarray]`):\n List of predicted segmentation maps, each of shape (height, width). Each segmentation map can be of a different size.\n references (`List[ndarray]`):\n List of ground truth segmentation maps, each of shape (height, width). Each segmentation map can be of a different size.\n num_labels (`int`):\n Number of classes (categories).\n ignore_index (`int`):\n Index that will be ignored during evaluation.\n nan_to_num (`int`, *optional*):\n If specified, NaN values will be replaced by the number defined by the user.\n label_map (`dict`, *optional*):\n If specified, dictionary mapping old label indices to new label indices.\n reduce_labels (`bool`, *optional*, defaults to `False`):\n Whether or not to reduce all label values of segmentation maps by 1. Usually used for datasets where 0 is used for background,\n and background itself is not included in all classes of a dataset (e.g. ADE20k). The background label will be replaced by 255.\n\nReturns:\n `Dict[str, float | ndarray]` comprising various elements:\n - *mean_iou* (`float`):\n Mean Intersection-over-Union (IoU averaged over all categories).\n - *mean_accuracy* (`float`):\n Mean accuracy (averaged over all categories).\n - *overall_accuracy* (`float`):\n Overall accuracy on all images.\n - *per_category_accuracy* (`ndarray` of shape `(num_labels,)`):\n Per category accuracy.\n - *per_category_iou* (`ndarray` of shape `(num_labels,)`):\n Per category IoU.\n\nExamples:\n\n >>> import numpy as np\n\n >>> mean_iou = datasets.load_metric("mean_iou")\n\n >>> # suppose one has 3 different segmentation maps predicted\n >>> predicted_1 = np.array([[1, 2], [3, 4], [5, 255]])\n >>> actual_1 = np.array([[0, 3], [5, 4], [6, 255]])\n\n >>> predicted_2 = np.array([[2, 7], [9, 2], [3, 6]])\n >>> actual_2 = np.array([[1, 7], [9, 2], [3, 6]])\n\n >>> predicted_3 = np.array([[2, 2, 3], [8, 2, 4], [3, 255, 2]])\n >>> actual_3 = np.array([[1, 2, 2], [8, 2, 1], [3, 255, 1]])\n\n >>> predicted = [predicted_1, predicted_2, predicted_3]\n >>> ground_truth = [actual_1, actual_2, actual_3]\n\n >>> results = mean_iou.compute(predictions=predicted, references=ground_truth, num_labels=10, ignore_index=255, reduce_labels=False)\n >>> print(results) # doctest: +NORMALIZE_WHITESPACE\n {\'mean_iou\': 0.47750000000000004, \'mean_accuracy\': 0.5916666666666666, \'overall_accuracy\': 0.5263157894736842, \'per_category_iou\': array([0. , 0. , 0.375, 0.4 , 0.5 , 0. , 0.5 , 1. , 1. , 1. ]), \'per_category_accuracy\': array([0. , 0. , 0.75 , 0.66666667, 1. , 0. , 0.5 , 1. , 1. , 1. ])}\n' SCREAMING_SNAKE_CASE :str = '\\n@software{MMSegmentation_Contributors_OpenMMLab_Semantic_Segmentation_2020,\nauthor = {{MMSegmentation Contributors}},\nlicense = {Apache-2.0},\nmonth = {7},\ntitle = {{OpenMMLab Semantic Segmentation Toolbox and Benchmark}},\nurl = {https://github.com/open-mmlab/mmsegmentation},\nyear = {2020}\n}' def UpperCAmelCase ( a_ , a_ , a_ , a_ , a_ = None , a_ = False , ) -> Tuple: """simple docstring""" if label_map is not None: for old_id, new_id in label_map.items(): __A = new_id # turn into Numpy arrays __A = np.array(a_ ) __A = np.array(a_ ) if reduce_labels: __A = 2_5_5 __A = label - 1 __A = 2_5_5 __A = label != ignore_index __A = np.not_equal(a_ , a_ ) __A = pred_label[mask] __A = np.array(a_ )[mask] __A = pred_label[pred_label == label] __A = np.histogram(a_ , bins=a_ , range=(0, num_labels - 1) )[0] __A = np.histogram(a_ , bins=a_ , range=(0, num_labels - 1) )[0] __A = np.histogram(a_ , bins=a_ , range=(0, num_labels - 1) )[0] __A = area_pred_label + area_label - area_intersect return area_intersect, area_union, area_pred_label, area_label def UpperCAmelCase ( a_ , a_ , a_ , a_ , a_ = None , a_ = False , ) -> Union[str, Any]: """simple docstring""" __A = np.zeros((num_labels,) , dtype=np.floataa ) __A = np.zeros((num_labels,) , dtype=np.floataa ) __A = np.zeros((num_labels,) , dtype=np.floataa ) __A = np.zeros((num_labels,) , dtype=np.floataa ) for result, gt_seg_map in zip(a_ , a_ ): __A , __A , __A , __A = intersect_and_union( a_ , a_ , a_ , a_ , a_ , a_ ) total_area_intersect += area_intersect total_area_union += area_union total_area_pred_label += area_pred_label total_area_label += area_label return total_area_intersect, total_area_union, total_area_pred_label, total_area_label def UpperCAmelCase ( a_ , a_ , a_ , a_ , a_ = None , a_ = None , a_ = False , ) -> str: """simple docstring""" __A , __A , __A , __A = total_intersect_and_union( a_ , a_ , a_ , a_ , a_ , a_ ) # compute metrics __A = {} __A = total_area_intersect.sum() / total_area_label.sum() __A = total_area_intersect / total_area_union __A = total_area_intersect / total_area_label __A = np.nanmean(a_ ) __A = np.nanmean(a_ ) __A = all_acc __A = iou __A = acc if nan_to_num is not None: __A = {metric: np.nan_to_num(a_ , nan=a_ ) for metric, metric_value in metrics.items()} return metrics @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCAmelCase ( datasets.Metric ): '''simple docstring''' def UpperCamelCase_ ( self : List[Any] ): return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( # 1st Seq - height dim, 2nd - width dim { "predictions": datasets.Sequence(datasets.Sequence(datasets.Value("uint16" ) ) ), "references": datasets.Sequence(datasets.Sequence(datasets.Value("uint16" ) ) ), } ) ,reference_urls=[ "https://github.com/open-mmlab/mmsegmentation/blob/71c201b1813267d78764f306a297ca717827c4bf/mmseg/core/evaluation/metrics.py" ] ,) def UpperCamelCase_ ( self : int ,A : Optional[Any] ,A : Optional[Any] ,A : int ,A : bool ,A : Optional[int] = None ,A : Optional[Dict[int, int]] = None ,A : bool = False ,): __A = mean_iou( results=A ,gt_seg_maps=A ,num_labels=A ,ignore_index=A ,nan_to_num=A ,label_map=A ,reduce_labels=A ,) return iou_result
15
0
# Lint as: python3 import os import re import urllib.parse from pathlib import Path from typing import Callable, List, Optional, Union from zipfile import ZipFile from ..utils.file_utils import cached_path, hf_github_url from ..utils.logging import get_logger from ..utils.version import Version _SCREAMING_SNAKE_CASE : int = get_logger(__name__) class A__ : """simple docstring""" __magic_name__ = 'dummy_data' __magic_name__ = 'datasets' __magic_name__ = False def __init__( self , __snake_case , __snake_case , __snake_case , __snake_case = None , __snake_case = False , __snake_case = True , __snake_case = None , ): snake_case = 0 snake_case = dataset_name snake_case = cache_dir snake_case = use_local_dummy_data snake_case = config # download_callbacks take a single url as input snake_case = download_callbacks or [] # if False, it doesn't load existing files and it returns the paths of the dummy files relative # to the dummy_data zip file root snake_case = load_existing_dummy_data # TODO(PVP, QL) might need to make this more general snake_case = str(__snake_case ) # to be downloaded snake_case = None snake_case = None @property def a_ ( self ): if self._dummy_file is None: snake_case = self.download_dummy_data() return self._dummy_file @property def a_ ( self ): if self.config is not None: # structure is dummy / config_name / version_name return os.path.join('''dummy''' , self.config.name , self.version_name ) # structure is dummy / version_name return os.path.join('''dummy''' , self.version_name ) @property def a_ ( self ): return os.path.join(self.dummy_data_folder , '''dummy_data.zip''' ) def a_ ( self ): snake_case = ( self.local_path_to_dummy_data if self.use_local_dummy_data is True else self.github_path_to_dummy_data ) snake_case = cached_path( __snake_case , cache_dir=self.cache_dir , extract_compressed_file=__snake_case , force_extract=__snake_case ) return os.path.join(__snake_case , self.dummy_file_name ) @property def a_ ( self ): return os.path.join(self.datasets_scripts_dir , self.dataset_name , self.dummy_zip_file ) @property def a_ ( self ): if self._bucket_url is None: snake_case = hf_github_url(self.dataset_name , self.dummy_zip_file.replace(os.sep , '''/''' ) ) return self._bucket_url @property def a_ ( self ): # return full path if its a dir if os.path.isdir(self.dummy_file ): return self.dummy_file # else cut off path to file -> example `xsum`. return "/".join(self.dummy_file.replace(os.sep , '''/''' ).split('''/''' )[:-1] ) def a_ ( self , __snake_case , *__snake_case ): if self.load_existing_dummy_data: # dummy data is downloaded and tested snake_case = self.dummy_file else: # dummy data cannot be downloaded and only the path to dummy file is returned snake_case = self.dummy_file_name # special case when data_url is a dict if isinstance(__snake_case , __snake_case ): return self.create_dummy_data_dict(__snake_case , __snake_case ) elif isinstance(__snake_case , (list, tuple) ): return self.create_dummy_data_list(__snake_case , __snake_case ) else: return self.create_dummy_data_single(__snake_case , __snake_case ) def a_ ( self , __snake_case , *__snake_case ): return self.download_and_extract(__snake_case ) def a_ ( self , __snake_case , __snake_case ): return self.download_and_extract(__snake_case ) def a_ ( self , __snake_case , *__snake_case , **__snake_case ): return path def a_ ( self ): return {} def a_ ( self , __snake_case , __snake_case ): snake_case = {} for key, single_urls in data_url.items(): for download_callback in self.download_callbacks: if isinstance(__snake_case , __snake_case ): for single_url in single_urls: download_callback(__snake_case ) else: snake_case = single_urls download_callback(__snake_case ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus if isinstance(__snake_case , __snake_case ): snake_case = [os.path.join(__snake_case , urllib.parse.quote_plus(Path(__snake_case ).name ) ) for x in single_urls] else: snake_case = single_urls snake_case = os.path.join(__snake_case , urllib.parse.quote_plus(Path(__snake_case ).name ) ) snake_case = value # make sure that values are unique if all(isinstance(__snake_case , __snake_case ) for i in dummy_data_dict.values() ) and len(set(dummy_data_dict.values() ) ) < len( dummy_data_dict.values() ): # append key to value to make its name unique snake_case = {key: value + key for key, value in dummy_data_dict.items()} return dummy_data_dict def a_ ( self , __snake_case , __snake_case ): snake_case = [] # trick: if there are many shards named like `data.txt-000001-of-00300`, only use the first one snake_case = all(bool(re.findall('''[0-9]{3,}-of-[0-9]{3,}''' , __snake_case ) ) for url in data_url ) snake_case = all( url.startswith('''https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/pubmed''' ) for url in data_url ) if data_url and (is_tf_records or is_pubmed_records): snake_case = [data_url[0]] * len(__snake_case ) for single_url in data_url: for download_callback in self.download_callbacks: download_callback(__snake_case ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus snake_case = os.path.join(__snake_case , urllib.parse.quote_plus(single_url.split('''/''' )[-1] ) ) dummy_data_list.append(__snake_case ) return dummy_data_list def a_ ( self , __snake_case , __snake_case ): for download_callback in self.download_callbacks: download_callback(__snake_case ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus snake_case = os.path.join(__snake_case , urllib.parse.quote_plus(data_url.split('''/''' )[-1] ) ) if os.path.exists(__snake_case ) or not self.load_existing_dummy_data: return value else: # Backward compatibility, maybe deprecate at one point. # For many datasets with single url calls to dl_manager.download_and_extract, # the dummy_data.zip file is actually the zipped downloaded file # while now we expected the dummy_data.zip file to be a directory containing # the downloaded file. return path_to_dummy_data def a_ ( self ): pass def a_ ( self ): pass def a_ ( self , __snake_case ): def _iter_archive_members(__snake_case ): # this preserves the order of the members inside the ZIP archive snake_case = Path(self.dummy_file ).parent snake_case = path.relative_to(__snake_case ) with ZipFile(self.local_path_to_dummy_data ) as zip_file: snake_case = zip_file.namelist() for member in members: if member.startswith(relative_path.as_posix() ): yield dummy_parent_path.joinpath(__snake_case ) snake_case = Path(__snake_case ) snake_case = _iter_archive_members(__snake_case ) if self.use_local_dummy_data else path.rglob('''*''' ) for file_path in file_paths: if file_path.is_file() and not file_path.name.startswith(('''.''', '''__''') ): yield file_path.relative_to(__snake_case ).as_posix(), file_path.open('''rb''' ) def a_ ( self , __snake_case ): if not isinstance(__snake_case , __snake_case ): snake_case = [paths] for path in paths: if os.path.isfile(__snake_case ): if os.path.basename(__snake_case ).startswith(('''.''', '''__''') ): return yield path else: for dirpath, dirnames, filenames in os.walk(__snake_case ): if os.path.basename(__snake_case ).startswith(('''.''', '''__''') ): continue dirnames.sort() for filename in sorted(__snake_case ): if filename.startswith(('''.''', '''__''') ): continue yield os.path.join(__snake_case , __snake_case )
213
from __future__ import annotations import time _SCREAMING_SNAKE_CASE : List[Any] = list[tuple[int, int]] _SCREAMING_SNAKE_CASE : Any = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] _SCREAMING_SNAKE_CASE : Any = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right class A__ : """simple docstring""" def __init__( self , __snake_case , __snake_case , __snake_case , __snake_case , __snake_case ): snake_case = pos_x snake_case = pos_y snake_case = (pos_y, pos_x) snake_case = goal_x snake_case = goal_y snake_case = parent class A__ : """simple docstring""" def __init__( self , __snake_case , __snake_case ): snake_case = Node(start[1] , start[0] , goal[1] , goal[0] , __snake_case ) snake_case = Node(goal[1] , goal[0] , goal[1] , goal[0] , __snake_case ) snake_case = [self.start] snake_case = False def a_ ( self ): while self.node_queue: snake_case = self.node_queue.pop(0 ) if current_node.pos == self.target.pos: snake_case = True return self.retrace_path(__snake_case ) snake_case = self.get_successors(__snake_case ) for node in successors: self.node_queue.append(__snake_case ) if not self.reached: return [self.start.pos] return None def a_ ( self , __snake_case ): snake_case = [] for action in delta: snake_case = parent.pos_x + action[1] snake_case = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(__snake_case ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node(__snake_case , __snake_case , self.target.pos_y , self.target.pos_x , __snake_case ) ) return successors def a_ ( self , __snake_case ): snake_case = node snake_case = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) snake_case = current_node.parent path.reverse() return path class A__ : """simple docstring""" def __init__( self , __snake_case , __snake_case ): snake_case = BreadthFirstSearch(__snake_case , __snake_case ) snake_case = BreadthFirstSearch(__snake_case , __snake_case ) snake_case = False def a_ ( self ): while self.fwd_bfs.node_queue or self.bwd_bfs.node_queue: snake_case = self.fwd_bfs.node_queue.pop(0 ) snake_case = self.bwd_bfs.node_queue.pop(0 ) if current_bwd_node.pos == current_fwd_node.pos: snake_case = True return self.retrace_bidirectional_path( __snake_case , __snake_case ) snake_case = current_bwd_node snake_case = current_fwd_node snake_case = { self.fwd_bfs: self.fwd_bfs.get_successors(__snake_case ), self.bwd_bfs: self.bwd_bfs.get_successors(__snake_case ), } for bfs in [self.fwd_bfs, self.bwd_bfs]: for node in successors[bfs]: bfs.node_queue.append(__snake_case ) if not self.reached: return [self.fwd_bfs.start.pos] return None def a_ ( self , __snake_case , __snake_case ): snake_case = self.fwd_bfs.retrace_path(__snake_case ) snake_case = self.bwd_bfs.retrace_path(__snake_case ) bwd_path.pop() bwd_path.reverse() snake_case = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] import doctest doctest.testmod() _SCREAMING_SNAKE_CASE : Optional[Any] = (0, 0) _SCREAMING_SNAKE_CASE : List[Any] = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) _SCREAMING_SNAKE_CASE : List[Any] = time.time() _SCREAMING_SNAKE_CASE : List[Any] = BreadthFirstSearch(init, goal) _SCREAMING_SNAKE_CASE : List[str] = bfs.search() _SCREAMING_SNAKE_CASE : int = time.time() - start_bfs_time print("Unidirectional BFS computation time : ", bfs_time) _SCREAMING_SNAKE_CASE : Any = time.time() _SCREAMING_SNAKE_CASE : Union[str, Any] = BidirectionalBreadthFirstSearch(init, goal) _SCREAMING_SNAKE_CASE : Union[str, Any] = bd_bfs.search() _SCREAMING_SNAKE_CASE : Tuple = time.time() - start_bd_bfs_time print("Bidirectional BFS computation time : ", bd_bfs_time)
213
1
from typing import Callable, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase__ = logging.get_logger(__name__) UpperCamelCase__ = { "microsoft/xprophetnet-large-wiki100-cased": ( "https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/config.json" ), } class a__ ( _UpperCAmelCase ): _a : Dict = """xlm-prophetnet""" _a : Union[str, Any] = ["""past_key_values"""] _a : List[Any] = { """num_attention_heads""": """num_encoder_attention_heads""", } def __init__( self , _A = 0.1 , _A = "gelu" , _A = 3_0_5_2_2 , _A = 1_0_2_4 , _A = 4_0_9_6 , _A = 1_2 , _A = 1_6 , _A = 4_0_9_6 , _A = 1_2 , _A = 1_6 , _A = 0.1 , _A = 0.1 , _A = 5_1_2 , _A = 0.02 , _A = True , _A = True , _A = 0 , _A = 2 , _A = 3_2 , _A = 1_2_8 , _A = False , _A = 0.0 , _A = True , _A = 0 , _A = 1 , _A = 2 , **_A , ): """simple docstring""" __lowerCAmelCase = vocab_size __lowerCAmelCase = hidden_size __lowerCAmelCase = encoder_ffn_dim __lowerCAmelCase = num_encoder_layers __lowerCAmelCase = num_encoder_attention_heads __lowerCAmelCase = decoder_ffn_dim __lowerCAmelCase = num_decoder_layers __lowerCAmelCase = num_decoder_attention_heads __lowerCAmelCase = max_position_embeddings __lowerCAmelCase = init_std # Normal(0, this parameter) __lowerCAmelCase = activation_function # parameters for xlmprophetnet __lowerCAmelCase = ngram __lowerCAmelCase = num_buckets __lowerCAmelCase = relative_max_distance __lowerCAmelCase = disable_ngram_loss __lowerCAmelCase = eps # 3 Types of Dropout __lowerCAmelCase = attention_dropout __lowerCAmelCase = activation_dropout __lowerCAmelCase = dropout __lowerCAmelCase = use_cache super().__init__( pad_token_id=lowercase_ , bos_token_id=lowercase_ , eos_token_id=lowercase_ , is_encoder_decoder=lowercase_ , add_cross_attention=lowercase_ , decoder_start_token_id=lowercase_ , **lowercase_ , ) @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return self.num_encoder_layers + self.num_decoder_layers @num_hidden_layers.setter def __SCREAMING_SNAKE_CASE( self , _A ): """simple docstring""" raise NotImplementedError( "This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and" " `num_decoder_layers`." )
92
'''simple docstring''' import argparse import json import os import sys import tempfile import unittest from argparse import Namespace from dataclasses import dataclass, field from enum import Enum from pathlib import Path from typing import List, Literal, Optional import yaml from transformers import HfArgumentParser, TrainingArguments from transformers.hf_argparser import make_choice_type_function, string_to_bool # Since Python 3.10, we can use the builtin `|` operator for Union types # See PEP 604: https://peps.python.org/pep-0604 _lowercase : int = sys.version_info >= (3, 10) def lowerCamelCase ( UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : Union[str, Any]=None ) -> Tuple: return field(default_factory=lambda: default , metadata=UpperCAmelCase__ ) @dataclass class __magic_name__ : UpperCamelCase__ = 42 UpperCamelCase__ = 42 UpperCamelCase__ = 42 UpperCamelCase__ = 42 @dataclass class __magic_name__ : UpperCamelCase__ = 42 UpperCamelCase__ = field(default='''toto''', metadata={'''help''': '''help message'''}) @dataclass class __magic_name__ : UpperCamelCase__ = False UpperCamelCase__ = True UpperCamelCase__ = None class __magic_name__ ( _UpperCAmelCase): UpperCamelCase__ = '''titi''' UpperCamelCase__ = '''toto''' class __magic_name__ ( _UpperCAmelCase): UpperCamelCase__ = '''titi''' UpperCamelCase__ = '''toto''' UpperCamelCase__ = 42 @dataclass class __magic_name__ : UpperCamelCase__ = "toto" def SCREAMING_SNAKE_CASE_ ( self : int ): lowercase_ : Optional[int] = BasicEnum(self.foo ) @dataclass class __magic_name__ : UpperCamelCase__ = "toto" def SCREAMING_SNAKE_CASE_ ( self : int ): lowercase_ : Optional[int] = MixedTypeEnum(self.foo ) @dataclass class __magic_name__ : UpperCamelCase__ = None UpperCamelCase__ = field(default=_UpperCAmelCase, metadata={'''help''': '''help message'''}) UpperCamelCase__ = None UpperCamelCase__ = list_field(default=[]) UpperCamelCase__ = list_field(default=[]) @dataclass class __magic_name__ : UpperCamelCase__ = list_field(default=[]) UpperCamelCase__ = list_field(default=[1, 2, 3]) UpperCamelCase__ = list_field(default=['''Hallo''', '''Bonjour''', '''Hello''']) UpperCamelCase__ = list_field(default=[0.1, 0.2, 0.3]) @dataclass class __magic_name__ : UpperCamelCase__ = field() UpperCamelCase__ = field() UpperCamelCase__ = field() def SCREAMING_SNAKE_CASE_ ( self : List[str] ): lowercase_ : List[Any] = BasicEnum(self.required_enum ) @dataclass class __magic_name__ : UpperCamelCase__ = 42 UpperCamelCase__ = field() UpperCamelCase__ = None UpperCamelCase__ = field(default='''toto''', metadata={'''help''': '''help message'''}) UpperCamelCase__ = list_field(default=['''Hallo''', '''Bonjour''', '''Hello''']) if is_python_no_less_than_3_10: @dataclass class __magic_name__ : UpperCamelCase__ = False UpperCamelCase__ = True UpperCamelCase__ = None @dataclass class __magic_name__ : UpperCamelCase__ = None UpperCamelCase__ = field(default=_UpperCAmelCase, metadata={'''help''': '''help message'''}) UpperCamelCase__ = None UpperCamelCase__ = list_field(default=[]) UpperCamelCase__ = list_field(default=[]) class __magic_name__ ( unittest.TestCase): def SCREAMING_SNAKE_CASE_ ( self : Dict , lowercase_ : argparse.ArgumentParser , lowercase_ : argparse.ArgumentParser ): self.assertEqual(len(a._actions ) , len(b._actions ) ) for x, y in zip(a._actions , b._actions ): lowercase_ : List[str] = {k: v for k, v in vars(lowercase_ ).items() if k != """container"""} lowercase_ : Any = {k: v for k, v in vars(lowercase_ ).items() if k != """container"""} # Choices with mixed type have custom function as "type" # So we need to compare results directly for equality if xx.get("""choices""" , lowercase_ ) and yy.get("""choices""" , lowercase_ ): for expected_choice in yy["choices"] + xx["choices"]: self.assertEqual(xx["""type"""](lowercase_ ) , yy["""type"""](lowercase_ ) ) del xx["type"], yy["type"] self.assertEqual(lowercase_ , lowercase_ ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ): lowercase_ : List[str] = HfArgumentParser(lowercase_ ) lowercase_ : str = argparse.ArgumentParser() expected.add_argument("""--foo""" , type=lowercase_ , required=lowercase_ ) expected.add_argument("""--bar""" , type=lowercase_ , required=lowercase_ ) expected.add_argument("""--baz""" , type=lowercase_ , required=lowercase_ ) expected.add_argument("""--flag""" , type=lowercase_ , default=lowercase_ , const=lowercase_ , nargs="""?""" ) self.argparsersEqual(lowercase_ , lowercase_ ) lowercase_ : List[str] = ["""--foo""", """1""", """--baz""", """quux""", """--bar""", """0.5"""] ((lowercase_) , ) : Optional[Any] = parser.parse_args_into_dataclasses(lowercase_ , look_for_args_file=lowercase_ ) self.assertFalse(example.flag ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ): lowercase_ : Any = HfArgumentParser(lowercase_ ) lowercase_ : str = argparse.ArgumentParser() expected.add_argument("""--foo""" , default=42 , type=lowercase_ ) expected.add_argument("""--baz""" , default="""toto""" , type=lowercase_ , help="""help message""" ) self.argparsersEqual(lowercase_ , lowercase_ ) def SCREAMING_SNAKE_CASE_ ( self : int ): lowercase_ : Optional[int] = argparse.ArgumentParser() expected.add_argument("""--foo""" , type=lowercase_ , default=lowercase_ , const=lowercase_ , nargs="""?""" ) expected.add_argument("""--baz""" , type=lowercase_ , default=lowercase_ , const=lowercase_ , nargs="""?""" ) # A boolean no_* argument always has to come after its "default: True" regular counter-part # and its default must be set to False expected.add_argument("""--no_baz""" , action="""store_false""" , default=lowercase_ , dest="""baz""" ) expected.add_argument("""--opt""" , type=lowercase_ , default=lowercase_ ) lowercase_ : List[Any] = [WithDefaultBoolExample] if is_python_no_less_than_3_10: dataclass_types.append(lowercase_ ) for dataclass_type in dataclass_types: lowercase_ : List[str] = HfArgumentParser(lowercase_ ) self.argparsersEqual(lowercase_ , lowercase_ ) lowercase_ : str = parser.parse_args([] ) self.assertEqual(lowercase_ , Namespace(foo=lowercase_ , baz=lowercase_ , opt=lowercase_ ) ) lowercase_ : Optional[Any] = parser.parse_args(["""--foo""", """--no_baz"""] ) self.assertEqual(lowercase_ , Namespace(foo=lowercase_ , baz=lowercase_ , opt=lowercase_ ) ) lowercase_ : Optional[Any] = parser.parse_args(["""--foo""", """--baz"""] ) self.assertEqual(lowercase_ , Namespace(foo=lowercase_ , baz=lowercase_ , opt=lowercase_ ) ) lowercase_ : Dict = parser.parse_args(["""--foo""", """True""", """--baz""", """True""", """--opt""", """True"""] ) self.assertEqual(lowercase_ , Namespace(foo=lowercase_ , baz=lowercase_ , opt=lowercase_ ) ) lowercase_ : int = parser.parse_args(["""--foo""", """False""", """--baz""", """False""", """--opt""", """False"""] ) self.assertEqual(lowercase_ , Namespace(foo=lowercase_ , baz=lowercase_ , opt=lowercase_ ) ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ): lowercase_ : str = HfArgumentParser(lowercase_ ) lowercase_ : Tuple = argparse.ArgumentParser() expected.add_argument( """--foo""" , default="""toto""" , choices=["""titi""", """toto""", 42] , type=make_choice_type_function(["""titi""", """toto""", 42] ) , ) self.argparsersEqual(lowercase_ , lowercase_ ) lowercase_ : Optional[int] = parser.parse_args([] ) self.assertEqual(args.foo , """toto""" ) lowercase_ : Union[str, Any] = parser.parse_args_into_dataclasses([] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.toto ) lowercase_ : int = parser.parse_args(["""--foo""", """titi"""] ) self.assertEqual(args.foo , """titi""" ) lowercase_ : int = parser.parse_args_into_dataclasses(["""--foo""", """titi"""] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.titi ) lowercase_ : List[str] = parser.parse_args(["""--foo""", """42"""] ) self.assertEqual(args.foo , 42 ) lowercase_ : List[str] = parser.parse_args_into_dataclasses(["""--foo""", """42"""] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.fourtytwo ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ): @dataclass class __magic_name__ : UpperCamelCase__ = "toto" lowercase_ : Optional[int] = HfArgumentParser(lowercase_ ) lowercase_ : List[str] = argparse.ArgumentParser() expected.add_argument( """--foo""" , default="""toto""" , choices=("""titi""", """toto""", 42) , type=make_choice_type_function(["""titi""", """toto""", 42] ) , ) self.argparsersEqual(lowercase_ , lowercase_ ) lowercase_ : List[str] = parser.parse_args([] ) self.assertEqual(args.foo , """toto""" ) lowercase_ : Optional[int] = parser.parse_args(["""--foo""", """titi"""] ) self.assertEqual(args.foo , """titi""" ) lowercase_ : List[Any] = parser.parse_args(["""--foo""", """42"""] ) self.assertEqual(args.foo , 42 ) def SCREAMING_SNAKE_CASE_ ( self : Dict ): lowercase_ : int = HfArgumentParser(lowercase_ ) lowercase_ : Dict = argparse.ArgumentParser() expected.add_argument("""--foo_int""" , nargs="""+""" , default=[] , type=lowercase_ ) expected.add_argument("""--bar_int""" , nargs="""+""" , default=[1, 2, 3] , type=lowercase_ ) expected.add_argument("""--foo_str""" , nargs="""+""" , default=["""Hallo""", """Bonjour""", """Hello"""] , type=lowercase_ ) expected.add_argument("""--foo_float""" , nargs="""+""" , default=[0.1, 0.2, 0.3] , type=lowercase_ ) self.argparsersEqual(lowercase_ , lowercase_ ) lowercase_ : int = parser.parse_args([] ) self.assertEqual( lowercase_ , Namespace(foo_int=[] , bar_int=[1, 2, 3] , foo_str=["""Hallo""", """Bonjour""", """Hello"""] , foo_float=[0.1, 0.2, 0.3] ) , ) lowercase_ : Optional[int] = parser.parse_args("""--foo_int 1 --bar_int 2 3 --foo_str a b c --foo_float 0.1 0.7""".split() ) self.assertEqual(lowercase_ , Namespace(foo_int=[1] , bar_int=[2, 3] , foo_str=["""a""", """b""", """c"""] , foo_float=[0.1, 0.7] ) ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ): lowercase_ : Tuple = argparse.ArgumentParser() expected.add_argument("""--foo""" , default=lowercase_ , type=lowercase_ ) expected.add_argument("""--bar""" , default=lowercase_ , type=lowercase_ , help="""help message""" ) expected.add_argument("""--baz""" , default=lowercase_ , type=lowercase_ ) expected.add_argument("""--ces""" , nargs="""+""" , default=[] , type=lowercase_ ) expected.add_argument("""--des""" , nargs="""+""" , default=[] , type=lowercase_ ) lowercase_ : Optional[int] = [OptionalExample] if is_python_no_less_than_3_10: dataclass_types.append(lowercase_ ) for dataclass_type in dataclass_types: lowercase_ : Tuple = HfArgumentParser(lowercase_ ) self.argparsersEqual(lowercase_ , lowercase_ ) lowercase_ : Union[str, Any] = parser.parse_args([] ) self.assertEqual(lowercase_ , Namespace(foo=lowercase_ , bar=lowercase_ , baz=lowercase_ , ces=[] , des=[] ) ) lowercase_ : List[Any] = parser.parse_args("""--foo 12 --bar 3.14 --baz 42 --ces a b c --des 1 2 3""".split() ) self.assertEqual(lowercase_ , Namespace(foo=12 , bar=3.14 , baz="""42""" , ces=["""a""", """b""", """c"""] , des=[1, 2, 3] ) ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ): lowercase_ : Dict = HfArgumentParser(lowercase_ ) lowercase_ : int = argparse.ArgumentParser() expected.add_argument("""--required_list""" , nargs="""+""" , type=lowercase_ , required=lowercase_ ) expected.add_argument("""--required_str""" , type=lowercase_ , required=lowercase_ ) expected.add_argument( """--required_enum""" , type=make_choice_type_function(["""titi""", """toto"""] ) , choices=["""titi""", """toto"""] , required=lowercase_ , ) self.argparsersEqual(lowercase_ , lowercase_ ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ): lowercase_ : Dict = HfArgumentParser(lowercase_ ) lowercase_ : List[str] = argparse.ArgumentParser() expected.add_argument("""--foo""" , type=lowercase_ , required=lowercase_ ) expected.add_argument( """--required_enum""" , type=make_choice_type_function(["""titi""", """toto"""] ) , choices=["""titi""", """toto"""] , required=lowercase_ , ) expected.add_argument("""--opt""" , type=lowercase_ , default=lowercase_ ) expected.add_argument("""--baz""" , default="""toto""" , type=lowercase_ , help="""help message""" ) expected.add_argument("""--foo_str""" , nargs="""+""" , default=["""Hallo""", """Bonjour""", """Hello"""] , type=lowercase_ ) self.argparsersEqual(lowercase_ , lowercase_ ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ): lowercase_ : str = HfArgumentParser(lowercase_ ) lowercase_ : Optional[int] = { """foo""": 12, """bar""": 3.14, """baz""": """42""", """flag""": True, } lowercase_ : Optional[Any] = parser.parse_dict(lowercase_ )[0] lowercase_ : Dict = BasicExample(**lowercase_ ) self.assertEqual(lowercase_ , lowercase_ ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ): lowercase_ : Dict = HfArgumentParser(lowercase_ ) lowercase_ : Optional[int] = { """foo""": 12, """bar""": 3.14, """baz""": """42""", """flag""": True, """extra""": 42, } self.assertRaises(lowercase_ , parser.parse_dict , lowercase_ , allow_extra_keys=lowercase_ ) def SCREAMING_SNAKE_CASE_ ( self : Any ): lowercase_ : List[Any] = HfArgumentParser(lowercase_ ) lowercase_ : int = { """foo""": 12, """bar""": 3.14, """baz""": """42""", """flag""": True, } with tempfile.TemporaryDirectory() as tmp_dir: lowercase_ : Optional[int] = os.path.join(lowercase_ , """temp_json""" ) os.mkdir(lowercase_ ) with open(temp_local_path + """.json""" , """w+""" ) as f: json.dump(lowercase_ , lowercase_ ) lowercase_ : str = parser.parse_yaml_file(Path(temp_local_path + """.json""" ) )[0] lowercase_ : Tuple = BasicExample(**lowercase_ ) self.assertEqual(lowercase_ , lowercase_ ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ): lowercase_ : str = HfArgumentParser(lowercase_ ) lowercase_ : List[Any] = { """foo""": 12, """bar""": 3.14, """baz""": """42""", """flag""": True, } with tempfile.TemporaryDirectory() as tmp_dir: lowercase_ : Tuple = os.path.join(lowercase_ , """temp_yaml""" ) os.mkdir(lowercase_ ) with open(temp_local_path + """.yaml""" , """w+""" ) as f: yaml.dump(lowercase_ , lowercase_ ) lowercase_ : List[str] = parser.parse_yaml_file(Path(temp_local_path + """.yaml""" ) )[0] lowercase_ : Any = BasicExample(**lowercase_ ) self.assertEqual(lowercase_ , lowercase_ ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ): lowercase_ : str = HfArgumentParser(lowercase_ ) self.assertIsNotNone(lowercase_ )
239
0
def lowerCamelCase__ ( a__ : list , a__ : list , a__ : int , a__ : int , a__ : int ) -> int: if index == number_of_items: return 0 UpperCamelCase_ = 0 UpperCamelCase_ = 0 UpperCamelCase_ = knapsack(a__ , a__ , a__ , a__ , index + 1 ) if weights[index] <= max_weight: UpperCamelCase_ = values[index] + knapsack( a__ , a__ , a__ , max_weight - weights[index] , index + 1 ) return max(a__ , a__ ) if __name__ == "__main__": import doctest doctest.testmod()
261
import argparse import json import math import os import time import traceback import zipfile from collections import Counter import requests def lowerCamelCase__ ( a__ : Dict , a__ : Dict=None ) -> Union[str, Any]: UpperCamelCase_ = None if token is not None: UpperCamelCase_ = {"""Accept""": """application/vnd.github+json""", """Authorization""": f'''Bearer {token}'''} UpperCamelCase_ = f'''https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100''' UpperCamelCase_ = requests.get(a__ , headers=a__ ).json() UpperCamelCase_ = {} try: job_links.update({job["""name"""]: job["""html_url"""] for job in result["""jobs"""]} ) UpperCamelCase_ = math.ceil((result["""total_count"""] - 100) / 100 ) for i in range(a__ ): UpperCamelCase_ = requests.get(url + f'''&page={i + 2}''' , headers=a__ ).json() job_links.update({job["""name"""]: job["""html_url"""] for job in result["""jobs"""]} ) return job_links except Exception: print(f'''Unknown error, could not fetch links:\n{traceback.format_exc()}''' ) return {} def lowerCamelCase__ ( a__ : Union[str, Any] , a__ : Any=None ) -> Optional[int]: UpperCamelCase_ = None if token is not None: UpperCamelCase_ = {"""Accept""": """application/vnd.github+json""", """Authorization""": f'''Bearer {token}'''} UpperCamelCase_ = f'''https://api.github.com/repos/huggingface/transformers/actions/runs/{worflow_run_id}/artifacts?per_page=100''' UpperCamelCase_ = requests.get(a__ , headers=a__ ).json() UpperCamelCase_ = {} try: artifacts.update({artifact["""name"""]: artifact["""archive_download_url"""] for artifact in result["""artifacts"""]} ) UpperCamelCase_ = math.ceil((result["""total_count"""] - 100) / 100 ) for i in range(a__ ): UpperCamelCase_ = requests.get(url + f'''&page={i + 2}''' , headers=a__ ).json() artifacts.update({artifact["""name"""]: artifact["""archive_download_url"""] for artifact in result["""artifacts"""]} ) return artifacts except Exception: print(f'''Unknown error, could not fetch links:\n{traceback.format_exc()}''' ) return {} def lowerCamelCase__ ( a__ : Dict , a__ : Tuple , a__ : Union[str, Any] , a__ : List[Any] ) -> List[Any]: UpperCamelCase_ = None if token is not None: UpperCamelCase_ = {"""Accept""": """application/vnd.github+json""", """Authorization""": f'''Bearer {token}'''} UpperCamelCase_ = requests.get(a__ , headers=a__ , allow_redirects=a__ ) UpperCamelCase_ = result.headers["""Location"""] UpperCamelCase_ = requests.get(a__ , allow_redirects=a__ ) UpperCamelCase_ = os.path.join(a__ , f'''{artifact_name}.zip''' ) with open(a__ , """wb""" ) as fp: fp.write(response.content ) def lowerCamelCase__ ( a__ : Dict , a__ : Tuple=None ) -> Optional[int]: UpperCamelCase_ = [] UpperCamelCase_ = [] UpperCamelCase_ = None with zipfile.ZipFile(a__ ) as z: for filename in z.namelist(): if not os.path.isdir(a__ ): # read the file if filename in ["failures_line.txt", "summary_short.txt", "job_name.txt"]: with z.open(a__ ) as f: for line in f: UpperCamelCase_ = line.decode("""UTF-8""" ).strip() if filename == "failures_line.txt": try: # `error_line` is the place where `error` occurs UpperCamelCase_ = line[: line.index(""": """ )] UpperCamelCase_ = line[line.index(""": """ ) + len(""": """ ) :] errors.append([error_line, error] ) except Exception: # skip un-related lines pass elif filename == "summary_short.txt" and line.startswith("""FAILED """ ): # `test` is the test method that failed UpperCamelCase_ = line[len("""FAILED """ ) :] failed_tests.append(a__ ) elif filename == "job_name.txt": UpperCamelCase_ = line if len(a__ ) != len(a__ ): raise ValueError( f'''`errors` and `failed_tests` should have the same number of elements. Got {len(a__ )} for `errors` ''' f'''and {len(a__ )} for `failed_tests` instead. The test reports in {artifact_zip_path} have some''' """ problem.""" ) UpperCamelCase_ = None if job_name and job_links: UpperCamelCase_ = job_links.get(a__ , a__ ) # A list with elements of the form (line of error, error, failed test) UpperCamelCase_ = [x + [y] + [job_link] for x, y in zip(a__ , a__ )] return result def lowerCamelCase__ ( a__ : Any , a__ : Union[str, Any]=None ) -> Dict: UpperCamelCase_ = [] UpperCamelCase_ = [os.path.join(a__ , a__ ) for p in os.listdir(a__ ) if p.endswith(""".zip""" )] for p in paths: errors.extend(get_errors_from_single_artifact(a__ , job_links=a__ ) ) return errors def lowerCamelCase__ ( a__ : Union[str, Any] , a__ : Tuple=None ) -> List[Any]: UpperCamelCase_ = Counter() counter.update([x[1] for x in logs] ) UpperCamelCase_ = counter.most_common() UpperCamelCase_ = {} for error, count in counts: if error_filter is None or error not in error_filter: UpperCamelCase_ = {"""count""": count, """failed_tests""": [(x[2], x[0]) for x in logs if x[1] == error]} UpperCamelCase_ = dict(sorted(r.items() , key=lambda a__ : item[1]["count"] , reverse=a__ ) ) return r def lowerCamelCase__ ( a__ : Optional[int] ) -> Optional[Any]: UpperCamelCase_ = test.split("""::""" )[0] if test.startswith("""tests/models/""" ): UpperCamelCase_ = test.split("""/""" )[2] else: UpperCamelCase_ = None return test def lowerCamelCase__ ( a__ : List[str] , a__ : Optional[int]=None ) -> Dict: UpperCamelCase_ = [(x[0], x[1], get_model(x[2] )) for x in logs] UpperCamelCase_ = [x for x in logs if x[2] is not None] UpperCamelCase_ = {x[2] for x in logs} UpperCamelCase_ = {} for test in tests: UpperCamelCase_ = Counter() # count by errors in `test` counter.update([x[1] for x in logs if x[2] == test] ) UpperCamelCase_ = counter.most_common() UpperCamelCase_ = {error: count for error, count in counts if (error_filter is None or error not in error_filter)} UpperCamelCase_ = sum(error_counts.values() ) if n_errors > 0: UpperCamelCase_ = {"""count""": n_errors, """errors""": error_counts} UpperCamelCase_ = dict(sorted(r.items() , key=lambda a__ : item[1]["count"] , reverse=a__ ) ) return r def lowerCamelCase__ ( a__ : Any ) -> List[Any]: UpperCamelCase_ = """| no. | error | status |""" UpperCamelCase_ = """|-:|:-|:-|""" UpperCamelCase_ = [header, sep] for error in reduced_by_error: UpperCamelCase_ = reduced_by_error[error]["""count"""] UpperCamelCase_ = f'''| {count} | {error[:100]} | |''' lines.append(a__ ) return "\n".join(a__ ) def lowerCamelCase__ ( a__ : Optional[int] ) -> str: UpperCamelCase_ = """| model | no. of errors | major error | count |""" UpperCamelCase_ = """|-:|-:|-:|-:|""" UpperCamelCase_ = [header, sep] for model in reduced_by_model: UpperCamelCase_ = reduced_by_model[model]["""count"""] UpperCamelCase_ , UpperCamelCase_ = list(reduced_by_model[model]["""errors"""].items() )[0] UpperCamelCase_ = f'''| {model} | {count} | {error[:60]} | {_count} |''' lines.append(a__ ) return "\n".join(a__ ) if __name__ == "__main__": _A = argparse.ArgumentParser() # Required parameters parser.add_argument('''--workflow_run_id''', type=str, required=True, help='''A GitHub Actions workflow run id.''') parser.add_argument( '''--output_dir''', type=str, required=True, help='''Where to store the downloaded artifacts and other result files.''', ) parser.add_argument('''--token''', default=None, type=str, help='''A token that has actions:read permission.''') _A = parser.parse_args() os.makedirs(args.output_dir, exist_ok=True) _A = get_job_links(args.workflow_run_id, token=args.token) _A = {} # To deal with `workflow_call` event, where a job name is the combination of the job names in the caller and callee. # For example, `PyTorch 1.11 / Model tests (models/albert, single-gpu)`. if _job_links: for k, v in _job_links.items(): # This is how GitHub actions combine job names. if " / " in k: _A = k.find(''' / ''') _A = k[index + len(''' / ''') :] _A = v with open(os.path.join(args.output_dir, '''job_links.json'''), '''w''', encoding='''UTF-8''') as fp: json.dump(job_links, fp, ensure_ascii=False, indent=4) _A = get_artifacts_links(args.workflow_run_id, token=args.token) with open(os.path.join(args.output_dir, '''artifacts.json'''), '''w''', encoding='''UTF-8''') as fp: json.dump(artifacts, fp, ensure_ascii=False, indent=4) for idx, (name, url) in enumerate(artifacts.items()): download_artifact(name, url, args.output_dir, args.token) # Be gentle to GitHub time.sleep(1) _A = get_all_errors(args.output_dir, job_links=job_links) # `e[1]` is the error _A = Counter() counter.update([e[1] for e in errors]) # print the top 30 most common test errors _A = counter.most_common(30) for item in most_common: print(item) with open(os.path.join(args.output_dir, '''errors.json'''), '''w''', encoding='''UTF-8''') as fp: json.dump(errors, fp, ensure_ascii=False, indent=4) _A = reduce_by_error(errors) _A = reduce_by_model(errors) _A = make_github_table(reduced_by_error) _A = make_github_table_per_model(reduced_by_model) with open(os.path.join(args.output_dir, '''reduced_by_error.txt'''), '''w''', encoding='''UTF-8''') as fp: fp.write(sa) with open(os.path.join(args.output_dir, '''reduced_by_model.txt'''), '''w''', encoding='''UTF-8''') as fp: fp.write(sa)
261
1
'''simple docstring''' def __UpperCAmelCase ( A : Tuple , A : Any ) -> int: UpperCAmelCase_ : Union[str, Any] = 0 UpperCAmelCase_ : Optional[int] = len(A ) - 1 while left <= right: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None UpperCAmelCase_ : List[Any] = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(A ): return None UpperCAmelCase_ : Optional[Any] = sorted_collection[point] if current_item == item: return point else: if point < left: UpperCAmelCase_ : List[str] = left UpperCAmelCase_ : Any = point elif point > right: UpperCAmelCase_ : Dict = right UpperCAmelCase_ : Optional[Any] = point else: if item < current_item: UpperCAmelCase_ : Union[str, Any] = point - 1 else: UpperCAmelCase_ : Any = point + 1 return None def __UpperCAmelCase ( A : List[Any] , A : Tuple , A : Union[str, Any] , A : str ) -> Union[str, Any]: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None UpperCAmelCase_ : Optional[int] = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(A ): return None if sorted_collection[point] == item: return point elif point < left: return interpolation_search_by_recursion(A , A , A , A ) elif point > right: return interpolation_search_by_recursion(A , A , A , A ) else: if sorted_collection[point] > item: return interpolation_search_by_recursion( A , A , A , point - 1 ) else: return interpolation_search_by_recursion( A , A , point + 1 , A ) def __UpperCAmelCase ( A : Optional[int] ) -> Dict: if collection != sorted(A ): raise ValueError('''Collection must be ascending sorted''' ) return True if __name__ == "__main__": import sys _UpperCamelCase : Union[str, Any] = 0 if debug == 1: _UpperCamelCase : str = [10, 30, 40, 45, 50, 66, 77, 93] try: __assert_sorted(collection) except ValueError: sys.exit('Sequence must be ascending sorted to apply interpolation search') _UpperCamelCase : Optional[int] = 67 _UpperCamelCase : int = interpolation_search(collection, target) if result is not None: print(f'''{target} found at positions: {result}''') else: print('Not found')
304
'''simple docstring''' import tempfile import unittest import numpy as np from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import BertConfig, is_flax_available from transformers.testing_utils import TOKEN, USER, is_staging_test, require_flax if is_flax_available(): import os from flax.core.frozen_dict import unfreeze from flax.traverse_util import flatten_dict from transformers import FlaxBertModel _UpperCamelCase : Optional[int] = '0.12' # assumed parallelism: 8 @require_flax @is_staging_test class snake_case__ ( unittest.TestCase): @classmethod def A ( cls : Optional[int] ) -> Tuple: UpperCAmelCase_ : List[str] = TOKEN HfFolder.save_token(_A ) @classmethod def A ( cls : int ) -> Tuple: try: delete_repo(token=cls._token , repo_id='''test-model-flax''' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''valid_org/test-model-flax-org''' ) except HTTPError: pass def A ( self : Dict ) -> Optional[int]: UpperCAmelCase_ : List[Any] = BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 ) UpperCAmelCase_ : List[str] = FlaxBertModel(_A ) model.push_to_hub('''test-model-flax''' , use_auth_token=self._token ) UpperCAmelCase_ : Any = FlaxBertModel.from_pretrained(F"{USER}/test-model-flax" ) UpperCAmelCase_ : int = flatten_dict(unfreeze(model.params ) ) UpperCAmelCase_ : Optional[int] = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): UpperCAmelCase_ : List[str] = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(_A , 1e-3 , msg=F"{key} not identical" ) # Reset repo delete_repo(token=self._token , repo_id='''test-model-flax''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(_A , repo_id='''test-model-flax''' , push_to_hub=_A , use_auth_token=self._token ) UpperCAmelCase_ : Union[str, Any] = FlaxBertModel.from_pretrained(F"{USER}/test-model-flax" ) UpperCAmelCase_ : Optional[Any] = flatten_dict(unfreeze(model.params ) ) UpperCAmelCase_ : Optional[int] = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): UpperCAmelCase_ : int = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(_A , 1e-3 , msg=F"{key} not identical" ) def A ( self : str ) -> Tuple: UpperCAmelCase_ : List[str] = BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 ) UpperCAmelCase_ : Optional[Any] = FlaxBertModel(_A ) model.push_to_hub('''valid_org/test-model-flax-org''' , use_auth_token=self._token ) UpperCAmelCase_ : List[str] = FlaxBertModel.from_pretrained('''valid_org/test-model-flax-org''' ) UpperCAmelCase_ : Dict = flatten_dict(unfreeze(model.params ) ) UpperCAmelCase_ : Optional[Any] = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): UpperCAmelCase_ : Any = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(_A , 1e-3 , msg=F"{key} not identical" ) # Reset repo delete_repo(token=self._token , repo_id='''valid_org/test-model-flax-org''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained( _A , repo_id='''valid_org/test-model-flax-org''' , push_to_hub=_A , use_auth_token=self._token ) UpperCAmelCase_ : int = FlaxBertModel.from_pretrained('''valid_org/test-model-flax-org''' ) UpperCAmelCase_ : Dict = flatten_dict(unfreeze(model.params ) ) UpperCAmelCase_ : Tuple = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): UpperCAmelCase_ : Union[str, Any] = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(_A , 1e-3 , msg=F"{key} not identical" ) def __UpperCAmelCase ( A : Union[str, Any] , A : Optional[int] ) -> List[Any]: UpperCAmelCase_ : Optional[int] = True UpperCAmelCase_ : Optional[int] = flatten_dict(modela.params ) UpperCAmelCase_ : str = flatten_dict(modela.params ) for key in flat_params_a.keys(): if np.sum(np.abs(flat_params_a[key] - flat_params_a[key] ) ) > 1e-4: UpperCAmelCase_ : int = False return models_are_equal @require_flax class snake_case__ ( unittest.TestCase): def A ( self : Any ) -> Any: UpperCAmelCase_ : Any = BertConfig.from_pretrained('''hf-internal-testing/tiny-bert-flax-only''' ) UpperCAmelCase_ : Any = FlaxBertModel(_A ) UpperCAmelCase_ : Tuple = '''bert''' with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(os.path.join(_A , _A ) ) with self.assertRaises(_A ): UpperCAmelCase_ : Optional[int] = FlaxBertModel.from_pretrained(_A ) UpperCAmelCase_ : List[Any] = FlaxBertModel.from_pretrained(_A , subfolder=_A ) self.assertTrue(check_models_equal(_A , _A ) ) def A ( self : int ) -> Tuple: UpperCAmelCase_ : Dict = BertConfig.from_pretrained('''hf-internal-testing/tiny-bert-flax-only''' ) UpperCAmelCase_ : Tuple = FlaxBertModel(_A ) UpperCAmelCase_ : str = '''bert''' with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(os.path.join(_A , _A ) , max_shard_size='''10KB''' ) with self.assertRaises(_A ): UpperCAmelCase_ : str = FlaxBertModel.from_pretrained(_A ) UpperCAmelCase_ : Dict = FlaxBertModel.from_pretrained(_A , subfolder=_A ) self.assertTrue(check_models_equal(_A , _A ) ) def A ( self : int ) -> Optional[int]: UpperCAmelCase_ : int = '''bert''' UpperCAmelCase_ : Tuple = '''hf-internal-testing/tiny-random-bert-subfolder''' with self.assertRaises(_A ): UpperCAmelCase_ : Tuple = FlaxBertModel.from_pretrained(_A ) UpperCAmelCase_ : int = FlaxBertModel.from_pretrained(_A , subfolder=_A ) self.assertIsNotNone(_A ) def A ( self : Any ) -> str: UpperCAmelCase_ : Optional[Any] = '''bert''' UpperCAmelCase_ : Tuple = '''hf-internal-testing/tiny-random-bert-sharded-subfolder''' with self.assertRaises(_A ): UpperCAmelCase_ : List[Any] = FlaxBertModel.from_pretrained(_A ) UpperCAmelCase_ : List[Any] = FlaxBertModel.from_pretrained(_A , subfolder=_A ) self.assertIsNotNone(_A )
304
1
import argparse import ast import logging import os import sys import pandas as pd import torch from tqdm import tqdm from transformers import BartForConditionalGeneration, RagRetriever, RagSequenceForGeneration, RagTokenForGeneration from transformers import logging as transformers_logging sys.path.append(os.path.join(os.getcwd())) # noqa: E402 # isort:skip from utils_rag import exact_match_score, fa_score # noqa: E402 # isort:skip lowercase = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) transformers_logging.set_verbosity_info() def lowerCamelCase_ ( UpperCamelCase__ : List[Any] ): '''simple docstring''' if "token" in model_name_or_path: return "rag_token" if "sequence" in model_name_or_path: return "rag_sequence" if "bart" in model_name_or_path: return "bart" return None def lowerCamelCase_ ( UpperCamelCase__ : str, UpperCamelCase__ : str, UpperCamelCase__ : Optional[int] ): '''simple docstring''' return max(metric_fn(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) for gt in ground_truths ) def lowerCamelCase_ ( UpperCamelCase__ : Tuple, UpperCamelCase__ : List[str], UpperCamelCase__ : int ): '''simple docstring''' UpperCamelCase__ = [line.strip() for line in open(SCREAMING_SNAKE_CASE__, '''r''' ).readlines()] UpperCamelCase__ = [] if args.gold_data_mode == "qa": UpperCamelCase__ = pd.read_csv(SCREAMING_SNAKE_CASE__, sep='''\t''', header=SCREAMING_SNAKE_CASE__ ) for answer_list in data[1]: UpperCamelCase__ = ast.literal_eval(SCREAMING_SNAKE_CASE__ ) answers.append(SCREAMING_SNAKE_CASE__ ) else: UpperCamelCase__ = [line.strip() for line in open(SCREAMING_SNAKE_CASE__, '''r''' ).readlines()] UpperCamelCase__ = [[reference] for reference in references] UpperCamelCase__ = 0 for prediction, ground_truths in zip(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ): total += 1 em += metric_max_over_ground_truths(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) fa += metric_max_over_ground_truths(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) UpperCamelCase__ = 100.0 * em / total UpperCamelCase__ = 100.0 * fa / total logger.info(F"""F1: {fa:.2f}""" ) logger.info(F"""EM: {em:.2f}""" ) def lowerCamelCase_ ( UpperCamelCase__ : int, UpperCamelCase__ : Optional[int], UpperCamelCase__ : Any ): '''simple docstring''' UpperCamelCase__ = args.k UpperCamelCase__ = [line.strip() for line in open(SCREAMING_SNAKE_CASE__, '''r''' ).readlines()] UpperCamelCase__ = [line.strip() for line in open(SCREAMING_SNAKE_CASE__, '''r''' ).readlines()] UpperCamelCase__ = 0 for hypo, reference in zip(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ): UpperCamelCase__ = set(hypo.split('''\t''' )[:k] ) UpperCamelCase__ = set(reference.split('''\t''' ) ) total += 1 em += len(hypo_provenance & ref_provenance ) / k UpperCamelCase__ = 100.0 * em / total logger.info(F"""Precision@{k}: {em: .2f}""" ) def lowerCamelCase_ ( UpperCamelCase__ : Union[str, Any], UpperCamelCase__ : List[Any], UpperCamelCase__ : Optional[Any] ): '''simple docstring''' def strip_title(UpperCamelCase__ : Optional[int] ): if title.startswith('''"''' ): UpperCamelCase__ = title[1:] if title.endswith('''"''' ): UpperCamelCase__ = title[:-1] return title UpperCamelCase__ = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus( SCREAMING_SNAKE_CASE__, return_tensors='''pt''', padding=SCREAMING_SNAKE_CASE__, truncation=SCREAMING_SNAKE_CASE__, )['''input_ids'''].to(args.device ) UpperCamelCase__ = rag_model.rag.question_encoder(SCREAMING_SNAKE_CASE__ ) UpperCamelCase__ = question_enc_outputs[0] UpperCamelCase__ = rag_model.retriever( SCREAMING_SNAKE_CASE__, question_enc_pool_output.cpu().detach().to(torch.floataa ).numpy(), prefix=rag_model.rag.generator.config.prefix, n_docs=rag_model.config.n_docs, return_tensors='''pt''', ) UpperCamelCase__ = rag_model.retriever.index.get_doc_dicts(result.doc_ids ) UpperCamelCase__ = [] for docs in all_docs: UpperCamelCase__ = [strip_title(SCREAMING_SNAKE_CASE__ ) for title in docs['''title''']] provenance_strings.append('''\t'''.join(SCREAMING_SNAKE_CASE__ ) ) return provenance_strings def lowerCamelCase_ ( UpperCamelCase__ : str, UpperCamelCase__ : List[str], UpperCamelCase__ : Tuple ): '''simple docstring''' with torch.no_grad(): UpperCamelCase__ = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus( SCREAMING_SNAKE_CASE__, return_tensors='''pt''', padding=SCREAMING_SNAKE_CASE__, truncation=SCREAMING_SNAKE_CASE__ ) UpperCamelCase__ = inputs_dict.input_ids.to(args.device ) UpperCamelCase__ = inputs_dict.attention_mask.to(args.device ) UpperCamelCase__ = rag_model.generate( # rag_model overwrites generate SCREAMING_SNAKE_CASE__, attention_mask=SCREAMING_SNAKE_CASE__, num_beams=args.num_beams, min_length=args.min_length, max_length=args.max_length, early_stopping=SCREAMING_SNAKE_CASE__, num_return_sequences=1, bad_words_ids=[[0, 0]], ) UpperCamelCase__ = rag_model.retriever.generator_tokenizer.batch_decode(SCREAMING_SNAKE_CASE__, skip_special_tokens=SCREAMING_SNAKE_CASE__ ) if args.print_predictions: for q, a in zip(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ): logger.info('''Q: {} - A: {}'''.format(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) ) return answers def lowerCamelCase_ ( ): '''simple docstring''' UpperCamelCase__ = argparse.ArgumentParser() parser.add_argument( '''--model_type''', choices=['''rag_sequence''', '''rag_token''', '''bart'''], type=SCREAMING_SNAKE_CASE__, help=( '''RAG model type: rag_sequence, rag_token or bart, if none specified, the type is inferred from the''' ''' model_name_or_path''' ), ) parser.add_argument( '''--index_name''', default=SCREAMING_SNAKE_CASE__, choices=['''exact''', '''compressed''', '''legacy'''], type=SCREAMING_SNAKE_CASE__, help='''RAG model retriever type''', ) parser.add_argument( '''--index_path''', default=SCREAMING_SNAKE_CASE__, type=SCREAMING_SNAKE_CASE__, help='''Path to the retrieval index''', ) parser.add_argument('''--n_docs''', default=5, type=SCREAMING_SNAKE_CASE__, help='''Number of retrieved docs''' ) parser.add_argument( '''--model_name_or_path''', default=SCREAMING_SNAKE_CASE__, type=SCREAMING_SNAKE_CASE__, required=SCREAMING_SNAKE_CASE__, help='''Path to pretrained checkpoints or model identifier from huggingface.co/models''', ) parser.add_argument( '''--eval_mode''', choices=['''e2e''', '''retrieval'''], default='''e2e''', type=SCREAMING_SNAKE_CASE__, help=( '''Evaluation mode, e2e calculates exact match and F1 of the downstream task, retrieval calculates''' ''' precision@k.''' ), ) parser.add_argument('''--k''', default=1, type=SCREAMING_SNAKE_CASE__, help='''k for the precision@k calculation''' ) parser.add_argument( '''--evaluation_set''', default=SCREAMING_SNAKE_CASE__, type=SCREAMING_SNAKE_CASE__, required=SCREAMING_SNAKE_CASE__, help='''Path to a file containing evaluation samples''', ) parser.add_argument( '''--gold_data_path''', default=SCREAMING_SNAKE_CASE__, type=SCREAMING_SNAKE_CASE__, required=SCREAMING_SNAKE_CASE__, help='''Path to a tab-separated file with gold samples''', ) parser.add_argument( '''--gold_data_mode''', default='''qa''', type=SCREAMING_SNAKE_CASE__, choices=['''qa''', '''ans'''], help=( '''Format of the gold data file''' '''qa - a single line in the following format: question [tab] answer_list''' '''ans - a single line of the gold file contains the expected answer string''' ), ) parser.add_argument( '''--predictions_path''', type=SCREAMING_SNAKE_CASE__, default='''predictions.txt''', help='''Name of the predictions file, to be stored in the checkpoints directory''', ) parser.add_argument( '''--eval_all_checkpoints''', action='''store_true''', help='''Evaluate all checkpoints starting with the same prefix as model_name ending and ending with step number''', ) parser.add_argument( '''--eval_batch_size''', default=8, type=SCREAMING_SNAKE_CASE__, help='''Batch size per GPU/CPU for evaluation.''', ) parser.add_argument( '''--recalculate''', help='''Recalculate predictions even if the prediction file exists''', action='''store_true''', ) parser.add_argument( '''--num_beams''', default=4, type=SCREAMING_SNAKE_CASE__, help='''Number of beams to be used when generating answers''', ) parser.add_argument('''--min_length''', default=1, type=SCREAMING_SNAKE_CASE__, help='''Min length of the generated answers''' ) parser.add_argument('''--max_length''', default=50, type=SCREAMING_SNAKE_CASE__, help='''Max length of the generated answers''' ) parser.add_argument( '''--print_predictions''', action='''store_true''', help='''If True, prints predictions while evaluating.''', ) parser.add_argument( '''--print_docs''', action='''store_true''', help='''If True, prints docs retried while generating.''', ) UpperCamelCase__ = parser.parse_args() UpperCamelCase__ = torch.device('''cuda''' if torch.cuda.is_available() else '''cpu''' ) return args def lowerCamelCase_ ( UpperCamelCase__ : str ): '''simple docstring''' UpperCamelCase__ = {} if args.model_type is None: UpperCamelCase__ = infer_model_type(args.model_name_or_path ) assert args.model_type is not None if args.model_type.startswith('''rag''' ): UpperCamelCase__ = RagTokenForGeneration if args.model_type == '''rag_token''' else RagSequenceForGeneration UpperCamelCase__ = args.n_docs if args.index_name is not None: UpperCamelCase__ = args.index_name if args.index_path is not None: UpperCamelCase__ = args.index_path else: UpperCamelCase__ = BartForConditionalGeneration UpperCamelCase__ = ( [f.path for f in os.scandir(args.model_name_or_path ) if f.is_dir()] if args.eval_all_checkpoints else [args.model_name_or_path] ) logger.info('''Evaluate the following checkpoints: %s''', SCREAMING_SNAKE_CASE__ ) UpperCamelCase__ = get_scores if args.eval_mode == '''e2e''' else get_precision_at_k UpperCamelCase__ = evaluate_batch_eae if args.eval_mode == '''e2e''' else evaluate_batch_retrieval for checkpoint in checkpoints: if os.path.exists(args.predictions_path ) and (not args.recalculate): logger.info('''Calculating metrics based on an existing predictions file: {}'''.format(args.predictions_path ) ) score_fn(SCREAMING_SNAKE_CASE__, args.predictions_path, args.gold_data_path ) continue logger.info('''***** Running evaluation for {} *****'''.format(SCREAMING_SNAKE_CASE__ ) ) logger.info(''' Batch size = %d''', args.eval_batch_size ) logger.info(''' Predictions will be stored under {}'''.format(args.predictions_path ) ) if args.model_type.startswith('''rag''' ): UpperCamelCase__ = RagRetriever.from_pretrained(SCREAMING_SNAKE_CASE__, **SCREAMING_SNAKE_CASE__ ) UpperCamelCase__ = model_class.from_pretrained(SCREAMING_SNAKE_CASE__, retriever=SCREAMING_SNAKE_CASE__, **SCREAMING_SNAKE_CASE__ ) model.retriever.init_retrieval() else: UpperCamelCase__ = model_class.from_pretrained(SCREAMING_SNAKE_CASE__, **SCREAMING_SNAKE_CASE__ ) model.to(args.device ) with open(args.evaluation_set, '''r''' ) as eval_file, open(args.predictions_path, '''w''' ) as preds_file: UpperCamelCase__ = [] for line in tqdm(SCREAMING_SNAKE_CASE__ ): questions.append(line.strip() ) if len(SCREAMING_SNAKE_CASE__ ) == args.eval_batch_size: UpperCamelCase__ = evaluate_batch_fn(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) preds_file.write('''\n'''.join(SCREAMING_SNAKE_CASE__ ) + '''\n''' ) preds_file.flush() UpperCamelCase__ = [] if len(SCREAMING_SNAKE_CASE__ ) > 0: UpperCamelCase__ = evaluate_batch_fn(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) preds_file.write('''\n'''.join(SCREAMING_SNAKE_CASE__ ) ) preds_file.flush() score_fn(SCREAMING_SNAKE_CASE__, args.predictions_path, args.gold_data_path ) if __name__ == "__main__": lowercase = get_args() main(args)
366
import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.activations import gelu_new, gelu_python, get_activation @require_torch class __lowercase ( unittest.TestCase ): '''simple docstring''' def A_ ( self : List[Any] ): UpperCamelCase__ = torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100] ) UpperCamelCase__ = get_activation('''gelu''' ) self.assertTrue(torch.allclose(gelu_python(_a ) , torch_builtin(_a ) ) ) self.assertFalse(torch.allclose(gelu_python(_a ) , gelu_new(_a ) ) ) def A_ ( self : Tuple ): UpperCamelCase__ = torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100] ) UpperCamelCase__ = get_activation('''gelu''' ) UpperCamelCase__ = get_activation('''gelu_10''' ) UpperCamelCase__ = torch_builtin(_a ) UpperCamelCase__ = geluaa(_a ) UpperCamelCase__ = torch.where(y_gelu_aa < 10.0 , 1 , 0 ) self.assertTrue(torch.max(_a ).item() == 10.0 ) self.assertTrue(torch.allclose(y_gelu * clipped_mask , y_gelu_aa * clipped_mask ) ) def A_ ( self : str ): get_activation('''gelu''' ) get_activation('''gelu_10''' ) get_activation('''gelu_fast''' ) get_activation('''gelu_new''' ) get_activation('''gelu_python''' ) get_activation('''gelu_pytorch_tanh''' ) get_activation('''linear''' ) get_activation('''mish''' ) get_activation('''quick_gelu''' ) get_activation('''relu''' ) get_activation('''sigmoid''' ) get_activation('''silu''' ) get_activation('''swish''' ) get_activation('''tanh''' ) with self.assertRaises(_a ): get_activation('''bogus''' ) with self.assertRaises(_a ): get_activation(_a ) def A_ ( self : List[Any] ): UpperCamelCase__ = get_activation('''gelu''' ) UpperCamelCase__ = 1 UpperCamelCase__ = get_activation('''gelu''' ) self.assertEqual(acta.a , 1 ) with self.assertRaises(_a ): UpperCamelCase__ = acta.a
35
0
lowerCAmelCase = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] lowerCAmelCase = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] lowerCAmelCase = { 0: '''Sunday''', 1: '''Monday''', 2: '''Tuesday''', 3: '''Wednesday''', 4: '''Thursday''', 5: '''Friday''', 6: '''Saturday''', } def _lowerCamelCase( lowercase__ , lowercase__ , lowercase__ ) -> str: '''simple docstring''' assert len(str(lowercase__ ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 1_2, "month should be between 1 to 12" assert 1 <= day <= 3_1, "day should be between 1 to 31" # Doomsday algorithm: __lowercase= year // 1_0_0 __lowercase= (5 * (century % 4) + 2) % 7 __lowercase= year % 1_0_0 __lowercase= centurian % 1_2 __lowercase= ( (centurian // 1_2) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 __lowercase= ( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 4_0_0) == 0) else DOOMSDAY_LEAP[month - 1] ) __lowercase= (dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
295
def _lowerCamelCase( lowercase__ , lowercase__ = " " ) -> list: '''simple docstring''' __lowercase= [] __lowercase= 0 for index, char in enumerate(lowercase__ ): if char == separator: split_words.append(string[last_index:index] ) __lowercase= index + 1 elif index + 1 == len(lowercase__ ): split_words.append(string[last_index : index + 1] ) return split_words if __name__ == "__main__": from doctest import testmod testmod()
295
1
def SCREAMING_SNAKE_CASE ( snake_case_ : list , snake_case_ : list ): _validate_point(snake_case_ ) _validate_point(snake_case_ ) if len(snake_case_ ) != len(snake_case_ ): raise ValueError("Both points must be in the same n-dimensional space" ) return float(sum(abs(a - b ) for a, b in zip(snake_case_ , snake_case_ ) ) ) def SCREAMING_SNAKE_CASE ( snake_case_ : list[float] ): if point: if isinstance(snake_case_ , snake_case_ ): for item in point: if not isinstance(snake_case_ , (int, float) ): snake_case__ : Optional[int] = ( "Expected a list of numbers as input, found " F'''{type(snake_case_ ).__name__}''' ) raise TypeError(snake_case_ ) else: snake_case__ : str = F'''Expected a list of numbers as input, found {type(snake_case_ ).__name__}''' raise TypeError(snake_case_ ) else: raise ValueError("Missing an input" ) def SCREAMING_SNAKE_CASE ( snake_case_ : list , snake_case_ : list ): _validate_point(snake_case_ ) _validate_point(snake_case_ ) if len(snake_case_ ) != len(snake_case_ ): raise ValueError("Both points must be in the same n-dimensional space" ) return float(sum(abs(x - y ) for x, y in zip(snake_case_ , snake_case_ ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
363
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __lowerCamelCase : Union[str, Any] = { """configuration_time_series_transformer""": [ """TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """TimeSeriesTransformerConfig""", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase : Tuple = [ """TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """TimeSeriesTransformerForPrediction""", """TimeSeriesTransformerModel""", """TimeSeriesTransformerPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_time_series_transformer import ( TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TimeSeriesTransformerConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_time_series_transformer import ( TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TimeSeriesTransformerForPrediction, TimeSeriesTransformerModel, TimeSeriesTransformerPreTrainedModel, ) else: import sys __lowerCamelCase : Tuple = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
286
0
'''simple docstring''' from datetime import datetime as dt import os from github import Github __lowerCAmelCase = [ '''good first issue''', '''good second issue''', '''good difficult issue''', '''feature request''', '''new model''', '''wip''', ] def __lowerCamelCase ( ) -> Tuple: _a : List[Any] = Github(os.environ['GITHUB_TOKEN'] ) _a : List[Any] = g.get_repo('huggingface/transformers' ) _a : Tuple = repo.get_issues(state='open' ) for issue in open_issues: _a : str = sorted([comment for comment in issue.get_comments()] , key=lambda lowerCAmelCase_ : i.created_at , reverse=lowerCAmelCase_ ) _a : List[str] = comments[0] if len(lowerCAmelCase_ ) > 0 else None if ( last_comment is not None and last_comment.user.login == "github-actions[bot]" and (dt.utcnow() - issue.updated_at).days > 7 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # print(f"Would close issue {issue.number} since it has been 7 days of inactivity since bot mention.") issue.edit(state='closed' ) elif ( (dt.utcnow() - issue.updated_at).days > 23 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # print(f"Would add stale comment to {issue.number}") issue.create_comment( 'This issue has been automatically marked as stale because it has not had ' 'recent activity. If you think this still needs to be addressed ' 'please comment on this thread.\n\nPlease note that issues that do not follow the ' '[contributing guidelines](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md) ' 'are likely to be ignored.' ) if __name__ == "__main__": main()
89
"""simple docstring""" class SCREAMING_SNAKE_CASE__ : """simple docstring""" def __init__( self , snake_case__ = "" , snake_case__ = False ): """simple docstring""" lowerCAmelCase : dict[str, RadixNode] = {} # A node will be a leaf if the tree contains its word lowerCAmelCase : str = is_leaf lowerCAmelCase : str = prefix def lowercase__ ( self , snake_case__ ): """simple docstring""" lowerCAmelCase : Dict = 0 for q, w in zip(self.prefix , snake_case__ ): if q != w: break x += 1 return self.prefix[:x], self.prefix[x:], word[x:] def lowercase__ ( self , snake_case__ ): """simple docstring""" for word in words: self.insert(snake_case__ ) def lowercase__ ( self , snake_case__ ): """simple docstring""" if self.prefix == word: lowerCAmelCase : Union[str, Any] = True # Case 2: The node has no edges that have a prefix to the word # Solution: We create an edge from the current node to a new one # containing the word elif word[0] not in self.nodes: lowerCAmelCase : Optional[Any] = RadixNode(prefix=snake_case__ , is_leaf=snake_case__ ) else: lowerCAmelCase : Tuple = self.nodes[word[0]] lowerCAmelCase , lowerCAmelCase , lowerCAmelCase : Optional[Any] = incoming_node.match( snake_case__ ) # Case 3: The node prefix is equal to the matching # Solution: We insert remaining word on the next node if remaining_prefix == "": self.nodes[matching_string[0]].insert(snake_case__ ) # Case 4: The word is greater equal to the matching # Solution: Create a node in between both nodes, change # prefixes and add the new node for the remaining word else: lowerCAmelCase : Optional[Any] = remaining_prefix lowerCAmelCase : int = self.nodes[matching_string[0]] lowerCAmelCase : List[Any] = RadixNode(snake_case__ , snake_case__ ) lowerCAmelCase : Optional[int] = aux_node if remaining_word == "": lowerCAmelCase : Optional[int] = True else: self.nodes[matching_string[0]].insert(snake_case__ ) def lowercase__ ( self , snake_case__ ): """simple docstring""" lowerCAmelCase : str = self.nodes.get(word[0] , snake_case__ ) if not incoming_node: return False else: lowerCAmelCase , lowerCAmelCase , lowerCAmelCase : int = incoming_node.match( snake_case__ ) # If there is remaining prefix, the word can't be on the tree if remaining_prefix != "": return False # This applies when the word and the prefix are equal elif remaining_word == "": return incoming_node.is_leaf # We have word remaining so we check the next node else: return incoming_node.find(snake_case__ ) def lowercase__ ( self , snake_case__ ): """simple docstring""" lowerCAmelCase : int = self.nodes.get(word[0] , snake_case__ ) if not incoming_node: return False else: lowerCAmelCase , lowerCAmelCase , lowerCAmelCase : Union[str, Any] = incoming_node.match( snake_case__ ) # If there is remaining prefix, the word can't be on the tree if remaining_prefix != "": return False # We have word remaining so we check the next node elif remaining_word != "": return incoming_node.delete(snake_case__ ) else: # If it is not a leaf, we don't have to delete if not incoming_node.is_leaf: return False else: # We delete the nodes if no edges go from it if len(incoming_node.nodes ) == 0: del self.nodes[word[0]] # We merge the current node with its only child if len(self.nodes ) == 1 and not self.is_leaf: lowerCAmelCase : List[str] = list(self.nodes.values() )[0] lowerCAmelCase : List[str] = merging_node.is_leaf self.prefix += merging_node.prefix lowerCAmelCase : Optional[int] = merging_node.nodes # If there is more than 1 edge, we just mark it as non-leaf elif len(incoming_node.nodes ) > 1: lowerCAmelCase : Optional[int] = False # If there is 1 edge, we merge it with its child else: lowerCAmelCase : Optional[Any] = list(incoming_node.nodes.values() )[0] lowerCAmelCase : int = merging_node.is_leaf incoming_node.prefix += merging_node.prefix lowerCAmelCase : Tuple = merging_node.nodes return True def lowercase__ ( self , snake_case__ = 0 ): """simple docstring""" if self.prefix != "": print("-" * height , self.prefix , " (leaf)" if self.is_leaf else "" ) for value in self.nodes.values(): value.print_tree(height + 1 ) def a__ ( ): '''simple docstring''' lowerCAmelCase : Union[str, Any] = "banana bananas bandana band apple all beast".split() lowerCAmelCase : List[str] = RadixNode() root.insert_many(SCREAMING_SNAKE_CASE ) assert all(root.find(SCREAMING_SNAKE_CASE ) for word in words ) assert not root.find("bandanas" ) assert not root.find("apps" ) root.delete("all" ) assert not root.find("all" ) root.delete("banana" ) assert not root.find("banana" ) assert root.find("bananas" ) return True def a__ ( ): '''simple docstring''' assert test_trie() def a__ ( ): '''simple docstring''' lowerCAmelCase : Dict = RadixNode() lowerCAmelCase : Optional[Any] = "banana bananas bandanas bandana band apple all beast".split() root.insert_many(SCREAMING_SNAKE_CASE ) print("Words:" , SCREAMING_SNAKE_CASE ) print("Tree:" ) root.print_tree() if __name__ == "__main__": main()
108
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = ["""NllbTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = ["""NllbTokenizerFast"""] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_nllb import NllbTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_nllb_fast import NllbTokenizerFast else: import sys UpperCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
352
"""simple docstring""" import qiskit def lowercase ( a__ : int = 2 ) -> qiskit.result.counts.Counts: _UpperCamelCase = qubits # Using Aer's simulator _UpperCamelCase = qiskit.Aer.get_backend('''aer_simulator''' ) # Creating a Quantum Circuit acting on the q register _UpperCamelCase = qiskit.QuantumCircuit(a__ , a__ ) # Adding a H gate on qubit 0 (now q0 in superposition) circuit.h(0 ) for i in range(1 , a__ ): # Adding CX (CNOT) gate circuit.cx(i - 1 , a__ ) # Mapping the quantum measurement to the classical bits circuit.measure(list(range(a__ ) ) , list(range(a__ ) ) ) # Now measuring any one qubit would affect other qubits to collapse # their super position and have same state as the measured one. # Executing the circuit on the simulator _UpperCamelCase = qiskit.execute(a__ , a__ , shots=1000 ) return job.result().get_counts(a__ ) if __name__ == "__main__": print(F'''Total count for various states are: {quantum_entanglement(3)}''')
54
0
"""simple docstring""" import os import pytest from transformers.dynamic_module_utils import get_imports __snake_case = """ import os """ __snake_case = """ def foo(): import os return False """ __snake_case = """ def foo(): def bar(): if True: import os return False return bar() """ __snake_case = """ import os try: import bar except ImportError: raise ValueError() """ __snake_case = """ import os def foo(): try: import bar except ImportError: raise ValueError() """ __snake_case = """ import os try: import bar except (ImportError, AttributeError): raise ValueError() """ __snake_case = """ import os try: import bar except ImportError as e: raise ValueError() """ __snake_case = """ import os try: import bar except: raise ValueError() """ __snake_case = """ import os try: import bar import baz except ImportError: raise ValueError() """ __snake_case = """ import os try: import bar import baz except ImportError: x = 1 raise ValueError() """ __snake_case = [ TOP_LEVEL_IMPORT, IMPORT_IN_FUNCTION, DEEPLY_NESTED_IMPORT, TOP_LEVEL_TRY_IMPORT, GENERIC_EXCEPT_IMPORT, MULTILINE_TRY_IMPORT, MULTILINE_BOTH_IMPORT, MULTIPLE_EXCEPTS_IMPORT, EXCEPT_AS_IMPORT, TRY_IMPORT_IN_FUNCTION, ] @pytest.mark.parametrize("case" , lowercase ) def __lowerCAmelCase ( lowercase : List[Any] , lowercase : Union[str, Any] ) -> List[Any]: """simple docstring""" snake_case : str = os.path.join(lowercase , "test_file.py" ) with open(lowercase , "w" ) as _tmp_file: _tmp_file.write(lowercase ) snake_case : str = get_imports(lowercase ) assert parsed_imports == ["os"]
203
"""simple docstring""" def __lowerCAmelCase ( ) -> Union[str, Any]: """simple docstring""" snake_case : Dict = [] snake_case : List[Any] = 1 while len(lowercase ) < 1e6: constant.append(str(lowercase ) ) i += 1 snake_case : Tuple = "".join(lowercase ) return ( int(constant[0] ) * int(constant[9] ) * int(constant[99] ) * int(constant[999] ) * int(constant[9999] ) * int(constant[9_9999] ) * int(constant[99_9999] ) ) if __name__ == "__main__": print(solution())
203
1
"""simple docstring""" import importlib import json import os import sys import tempfile import unittest from pathlib import Path import transformers import transformers.models.auto from transformers.models.auto.configuration_auto import CONFIG_MAPPING, AutoConfig from transformers.models.bert.configuration_bert import BertConfig from transformers.models.roberta.configuration_roberta import RobertaConfig from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir sys.path.append(str(Path(__file__).parent.parent.parent.parent / """utils""")) from test_module.custom_configuration import CustomConfig # noqa E402 _a = get_tests_dir("""fixtures/dummy-config.json""") class _UpperCAmelCase( unittest.TestCase ): def UpperCAmelCase ( self) -> str: '''simple docstring''' _UpperCamelCase = 0 def UpperCAmelCase ( self) -> List[str]: '''simple docstring''' self.assertIsNotNone(transformers.models.auto.__spec__) self.assertIsNotNone(importlib.util.find_spec('''transformers.models.auto''')) def UpperCAmelCase ( self) -> str: '''simple docstring''' _UpperCamelCase = AutoConfig.from_pretrained('''bert-base-uncased''') self.assertIsInstance(__a , __a) def UpperCAmelCase ( self) -> Tuple: '''simple docstring''' _UpperCamelCase = AutoConfig.from_pretrained(__a) self.assertIsInstance(__a , __a) def UpperCAmelCase ( self) -> Optional[Any]: '''simple docstring''' _UpperCamelCase = AutoConfig.from_pretrained(__a) self.assertIsInstance(__a , __a) def UpperCAmelCase ( self) -> Union[str, Any]: '''simple docstring''' _UpperCamelCase = AutoConfig.for_model('''roberta''') self.assertIsInstance(__a , __a) def UpperCAmelCase ( self) -> Dict: '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: # This model name contains bert and roberta, but roberta ends up being picked. _UpperCamelCase = os.path.join(__a , '''fake-roberta''') os.makedirs(__a , exist_ok=__a) with open(os.path.join(__a , '''config.json''') , '''w''') as f: f.write(json.dumps({})) _UpperCamelCase = AutoConfig.from_pretrained(__a) self.assertEqual(type(__a) , __a) def UpperCAmelCase ( self) -> Tuple: '''simple docstring''' try: AutoConfig.register('''custom''' , __a) # Wrong model type will raise an error with self.assertRaises(__a): AutoConfig.register('''model''' , __a) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(__a): AutoConfig.register('''bert''' , __a) # Now that the config is registered, it can be used as any other config with the auto-API _UpperCamelCase = CustomConfig() with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(__a) _UpperCamelCase = AutoConfig.from_pretrained(__a) self.assertIsInstance(__a , __a) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] def UpperCAmelCase ( self) -> List[Any]: '''simple docstring''' with self.assertRaisesRegex( __a , '''bert-base is not a local folder and is not a valid model identifier'''): _UpperCamelCase = AutoConfig.from_pretrained('''bert-base''') def UpperCAmelCase ( self) -> List[Any]: '''simple docstring''' with self.assertRaisesRegex( __a , R'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)'''): _UpperCamelCase = AutoConfig.from_pretrained(__a , revision='''aaaaaa''') def UpperCAmelCase ( self) -> Optional[Any]: '''simple docstring''' with self.assertRaisesRegex( __a , '''hf-internal-testing/no-config-test-repo does not appear to have a file named config.json.''' , ): _UpperCamelCase = AutoConfig.from_pretrained('''hf-internal-testing/no-config-test-repo''') def UpperCAmelCase ( self) -> int: '''simple docstring''' # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(__a): _UpperCamelCase = AutoConfig.from_pretrained('''hf-internal-testing/test_dynamic_model''') # If remote code is disabled, we can't load this config. with self.assertRaises(__a): _UpperCamelCase = AutoConfig.from_pretrained('''hf-internal-testing/test_dynamic_model''' , trust_remote_code=__a) _UpperCamelCase = AutoConfig.from_pretrained('''hf-internal-testing/test_dynamic_model''' , trust_remote_code=__a) self.assertEqual(config.__class__.__name__ , '''NewModelConfig''') # Test config can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(__a) _UpperCamelCase = AutoConfig.from_pretrained(__a , trust_remote_code=__a) self.assertEqual(reloaded_config.__class__.__name__ , '''NewModelConfig''') def UpperCAmelCase ( self) -> Any: '''simple docstring''' class _UpperCAmelCase( lowerCamelCase ): lowercase__ = 'new-model' try: AutoConfig.register('''new-model''' , __a) # If remote code is not set, the default is to use local _UpperCamelCase = AutoConfig.from_pretrained('''hf-internal-testing/test_dynamic_model''') self.assertEqual(config.__class__.__name__ , '''NewModelConfigLocal''') # If remote code is disabled, we load the local one. _UpperCamelCase = AutoConfig.from_pretrained('''hf-internal-testing/test_dynamic_model''' , trust_remote_code=__a) self.assertEqual(config.__class__.__name__ , '''NewModelConfigLocal''') # If remote is enabled, we load from the Hub _UpperCamelCase = AutoConfig.from_pretrained('''hf-internal-testing/test_dynamic_model''' , trust_remote_code=__a) self.assertEqual(config.__class__.__name__ , '''NewModelConfig''') finally: if "new-model" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["new-model"]
352
"""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 _a = logging.get_logger(__name__) _a = { """facebook/levit-128S""": """https://huggingface.co/facebook/levit-128S/resolve/main/config.json""", # See all LeViT models at https://huggingface.co/models?filter=levit } class _UpperCAmelCase( lowerCamelCase ): lowercase__ = 'levit' def __init__( self , __a=2_24 , __a=3 , __a=3 , __a=2 , __a=1 , __a=16 , __a=[1_28, 2_56, 3_84] , __a=[4, 8, 12] , __a=[4, 4, 4] , __a=[16, 16, 16] , __a=0 , __a=[2, 2, 2] , __a=[2, 2, 2] , __a=0.02 , **__a , ) -> List[str]: '''simple docstring''' super().__init__(**__a) _UpperCamelCase = image_size _UpperCamelCase = num_channels _UpperCamelCase = kernel_size _UpperCamelCase = stride _UpperCamelCase = padding _UpperCamelCase = hidden_sizes _UpperCamelCase = num_attention_heads _UpperCamelCase = depths _UpperCamelCase = key_dim _UpperCamelCase = drop_path_rate _UpperCamelCase = patch_size _UpperCamelCase = attention_ratio _UpperCamelCase = mlp_ratio _UpperCamelCase = initializer_range _UpperCamelCase = [ ['''Subsample''', key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2], ['''Subsample''', key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2], ] class _UpperCAmelCase( lowerCamelCase ): lowercase__ = version.parse('1.11' ) @property def UpperCAmelCase ( self) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ]) @property def UpperCAmelCase ( self) -> float: '''simple docstring''' return 1e-4
100
0
"""simple docstring""" import gzip import hashlib import json import multiprocessing import os import re import shutil import time from pathlib import Path import numpy as np from arguments import PreprocessingArguments from datasets import load_dataset from minhash_deduplication import deduplicate_dataset from transformers import AutoTokenizer, HfArgumentParser _a = re.compile(r'\s+') def _A ( UpperCamelCase_ : List[str]) -> List[str]: '''simple docstring''' return {"hash": hashlib.mda(re.sub(lowerCAmelCase__, "", example["content"]).encode("utf-8")).hexdigest()} def _A ( UpperCamelCase_ : Any) -> str: '''simple docstring''' __lowercase = [len(lowerCAmelCase__) for line in example['''content'''].splitlines()] return {"line_mean": np.mean(lowerCAmelCase__), "line_max": max(lowerCAmelCase__)} def _A ( UpperCamelCase_ : int) -> int: '''simple docstring''' __lowercase = np.mean([c.isalnum() for c in example["content"]]) return {"alpha_frac": alpha_frac} def _A ( UpperCamelCase_ : List[str], UpperCamelCase_ : List[Any]) -> Optional[int]: '''simple docstring''' if example["hash"] in uniques: uniques.remove(example["hash"]) return True else: return False def _A ( UpperCamelCase_ : Optional[Any], UpperCamelCase_ : List[str]=5) -> Tuple: '''simple docstring''' __lowercase = ['''auto-generated''', '''autogenerated''', '''automatically generated'''] __lowercase = example['''content'''].splitlines() for _, line in zip(range(lowerCAmelCase__), lowerCAmelCase__): for keyword in keywords: if keyword in line.lower(): return {"autogenerated": True} else: return {"autogenerated": False} def _A ( UpperCamelCase_ : Dict, UpperCamelCase_ : List[Any]=5, UpperCamelCase_ : int=0.05) -> Tuple: '''simple docstring''' __lowercase = ['''unit tests''', '''test file''', '''configuration file'''] __lowercase = example['''content'''].splitlines() __lowercase = 0 __lowercase = 0 # first test for _, line in zip(range(lowerCAmelCase__), lowerCAmelCase__): for keyword in keywords: if keyword in line.lower(): return {"config_or_test": True} # second test __lowercase = example['''content'''].count("\n") __lowercase = int(coeff * nlines) for line in lines: count_config += line.lower().count("config") count_test += line.lower().count("test") if count_config > threshold or count_test > threshold: return {"config_or_test": True} return {"config_or_test": False} def _A ( UpperCamelCase_ : int) -> str: '''simple docstring''' __lowercase = ['''def ''', '''class ''', '''for ''', '''while '''] __lowercase = example['''content'''].splitlines() for line in lines: for keyword in keywords: if keyword in line.lower(): return {"has_no_keywords": False} return {"has_no_keywords": True} def _A ( UpperCamelCase_ : Dict, UpperCamelCase_ : Any=4) -> List[Any]: '''simple docstring''' __lowercase = example['''content'''].splitlines() __lowercase = 0 for line in lines: counter += line.lower().count("=") if counter > minimum: return {"has_few_assignments": False} return {"has_few_assignments": True} def _A ( UpperCamelCase_ : Tuple) -> Optional[int]: '''simple docstring''' __lowercase = tokenizer(example["content"], truncation=lowerCAmelCase__)['''input_ids'''] __lowercase = len(example["content"]) / len(lowerCAmelCase__) return {"ratio": ratio} def _A ( UpperCamelCase_ : List[str]) -> Optional[int]: '''simple docstring''' __lowercase = {} results.update(get_hash(lowerCAmelCase__)) results.update(line_stats(lowerCAmelCase__)) results.update(alpha_stats(lowerCAmelCase__)) results.update(char_token_ratio(lowerCAmelCase__)) results.update(is_autogenerated(lowerCAmelCase__)) results.update(is_config_or_test(lowerCAmelCase__)) results.update(has_no_keywords(lowerCAmelCase__)) results.update(has_few_assignments(lowerCAmelCase__)) return results def _A ( UpperCamelCase_ : Dict, UpperCamelCase_ : Tuple, UpperCamelCase_ : Any) -> List[Any]: '''simple docstring''' if not check_uniques(lowerCAmelCase__, lowerCAmelCase__): return False elif example["autogenerated"]: return False elif example["line_max"] > args.line_max: return False elif example["line_mean"] > args.line_mean: return False elif example["alpha_frac"] < args.alpha_frac: return False elif example["ratio"] < args.min_token_ratio: return False elif example["config_or_test"] and np.random.rand() <= args.filter_proba: return False elif example["has_no_keywords"] and np.random.rand() <= args.filter_proba: return False elif example["has_few_assignments"]: return False else: return True def _A ( UpperCamelCase_ : List[str]) -> int: '''simple docstring''' with open(lowerCAmelCase__, "rb") as f_in: with gzip.open(str(lowerCAmelCase__) + ".gz", "wb", compresslevel=6) as f_out: shutil.copyfileobj(lowerCAmelCase__, lowerCAmelCase__) os.unlink(lowerCAmelCase__) # Settings _a = HfArgumentParser(PreprocessingArguments) _a = parser.parse_args() if args.num_workers is None: _a = multiprocessing.cpu_count() _a = AutoTokenizer.from_pretrained(args.tokenizer_dir) # Load dataset _a = time.time() _a = load_dataset(args.dataset_name, split='train') print(F"Time to load dataset: {time.time()-t_start:.2f}") # Run preprocessing _a = time.time() _a = ds.map(preprocess, num_proc=args.num_workers) print(F"Time to preprocess dataset: {time.time()-t_start:.2f}") # Deduplicate hashes _a = set(ds.unique('hash')) _a = len(uniques) / len(ds) print(F"Fraction of duplicates: {1-frac:.2%}") # Deduplicate data and apply heuristics _a = time.time() _a = ds.filter(filter, fn_kwargs={'uniques': uniques, 'args': args}) print(F"Time to filter dataset: {time.time()-t_start:.2f}") print(F"Size of filtered dataset: {len(ds_filter)}") # Deduplicate with minhash and jaccard similarity if args.near_deduplication: _a = time.time() _a , _a = deduplicate_dataset(ds_filter, args.jaccard_threshold) print(F"Time to deduplicate dataset: {time.time()-t_start:.2f}") print(F"Size of deduplicate dataset: {len(ds_filter)}") # Save data in batches of samples_per_file _a = Path(args.output_dir) output_dir.mkdir(exist_ok=True) # save duplicate_clusters in the output_dir as artifacts # not sure it is the right place the save it if args.near_deduplication: with open(output_dir / 'duplicate_clusters.json', 'w') as f: json.dump(duplicate_clusters, f) _a = output_dir / 'data' data_dir.mkdir(exist_ok=True) _a = time.time() for file_number, index in enumerate(range(0, len(ds_filter), args.samples_per_file)): _a = str(data_dir / F"file-{file_number+1:012}.json") _a = min(len(ds_filter), index + args.samples_per_file) ds_filter.select(list(range(index, end_index))).to_json(file_path) compress_file(file_path) print(F"Time to save dataset: {time.time()-t_start:.2f}")
17
from __future__ import annotations def __UpperCamelCase ( lowerCAmelCase__ : list[float] , lowerCAmelCase__ : list[float] ): __a : Dict = sorted(numsa + numsa ) __a , __a : Optional[Any] = divmod(len(lowerCAmelCase__ ) , 2 ) if mod == 1: return all_numbers[div] else: return (all_numbers[div] + all_numbers[div - 1]) / 2 if __name__ == "__main__": import doctest doctest.testmod() lowercase__ =[float(x) for x in input('Enter the elements of first array: ').split()] lowercase__ =[float(x) for x in input('Enter the elements of second array: ').split()] print(F"""The median of two arrays is: {median_of_two_arrays(array_a, array_a)}""")
216
0
"""simple docstring""" import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _UpperCAmelCase ( lowerCAmelCase__): _lowerCAmelCase : Tuple = ["""image_processor""", """tokenizer"""] _lowerCAmelCase : Optional[int] = """ChineseCLIPImageProcessor""" _lowerCAmelCase : Optional[Any] = ("""BertTokenizer""", """BertTokenizerFast""") def __init__( self : Tuple , lowercase_ : str=None , lowercase_ : str=None , **lowercase_ : Optional[int] ): snake_case_ : Optional[Any] = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , lowercase_ , ) snake_case_ : List[str] = kwargs.pop('''feature_extractor''' ) snake_case_ : Dict = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('''You need to specify an `image_processor`.''' ) if tokenizer is None: raise ValueError('''You need to specify a `tokenizer`.''' ) super().__init__(lowercase_ , lowercase_ ) snake_case_ : Tuple = self.image_processor def __call__( self : List[str] , lowercase_ : Dict=None , lowercase_ : Optional[Any]=None , lowercase_ : List[str]=None , **lowercase_ : List[str] ): if text is None and images is None: raise ValueError('''You have to specify either text or images. Both cannot be none.''' ) if text is not None: snake_case_ : int = self.tokenizer(lowercase_ , return_tensors=lowercase_ , **lowercase_ ) if images is not None: snake_case_ : Dict = self.image_processor(lowercase_ , return_tensors=lowercase_ , **lowercase_ ) if text is not None and images is not None: snake_case_ : str = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**lowercase_ ) , tensor_type=lowercase_ ) def _snake_case ( self : Union[str, Any] , *lowercase_ : List[Any] , **lowercase_ : List[Any] ): return self.tokenizer.batch_decode(*lowercase_ , **lowercase_ ) def _snake_case ( self : Dict , *lowercase_ : Any , **lowercase_ : Optional[Any] ): return self.tokenizer.decode(*lowercase_ , **lowercase_ ) @property def _snake_case ( self : Optional[int] ): snake_case_ : Optional[Any] = self.tokenizer.model_input_names snake_case_ : List[str] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def _snake_case ( self : Dict ): warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , lowercase_ , ) return self.image_processor_class
360
"""simple docstring""" import math import sys def __lowercase ( _a ): if number != int(_a ): 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 snake_case_ : int = [-1] * (number + 1) snake_case_ : int = 0 for i in range(1 , number + 1 ): snake_case_ : Tuple = sys.maxsize snake_case_ : List[Any] = int(math.sqrt(_a ) ) for j in range(1 , root + 1 ): snake_case_ : Dict = 1 + answers[i - (j**2)] snake_case_ : int = min(_a , _a ) snake_case_ : Any = answer return answers[number] if __name__ == "__main__": import doctest doctest.testmod()
155
0
"""simple docstring""" import math import unittest def _a ( _SCREAMING_SNAKE_CASE ) -> bool: assert isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) and ( number >= 0 ), "'number' must been an int and positive" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or 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(_SCREAMING_SNAKE_CASE ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True class __A (unittest.TestCase): '''simple docstring''' def lowerCAmelCase ( self : List[str] ) ->List[str]: """simple docstring""" self.assertTrue(is_prime(2 ) ) self.assertTrue(is_prime(3 ) ) self.assertTrue(is_prime(5 ) ) self.assertTrue(is_prime(7 ) ) self.assertTrue(is_prime(11 ) ) self.assertTrue(is_prime(13 ) ) self.assertTrue(is_prime(17 ) ) self.assertTrue(is_prime(19 ) ) self.assertTrue(is_prime(23 ) ) self.assertTrue(is_prime(29 ) ) def lowerCAmelCase ( self : int ) ->Union[str, Any]: """simple docstring""" with self.assertRaises(UpperCAmelCase_ ): is_prime(-19 ) self.assertFalse( is_prime(0 ) , """Zero doesn't have any positive factors, primes must have exactly two.""" , ) self.assertFalse( is_prime(1 ) , """One only has 1 positive factor, primes must have exactly two.""" , ) self.assertFalse(is_prime(2 * 2 ) ) self.assertFalse(is_prime(2 * 3 ) ) self.assertFalse(is_prime(3 * 3 ) ) self.assertFalse(is_prime(3 * 5 ) ) self.assertFalse(is_prime(3 * 5 * 7 ) ) if __name__ == "__main__": unittest.main()
347
"""simple docstring""" from transformers import BertTokenizer, EncoderDecoderModel, SeqaSeqTrainer, SeqaSeqTrainingArguments from transformers.testing_utils import TestCasePlus, require_torch, slow from transformers.utils import is_datasets_available if is_datasets_available(): import datasets class __A (snake_case__): '''simple docstring''' @slow @require_torch def lowerCAmelCase ( self : Union[str, Any] ) ->Dict: """simple docstring""" snake_case_ = EncoderDecoderModel.from_encoder_decoder_pretrained("""prajjwal1/bert-tiny""" , """prajjwal1/bert-tiny""" ) snake_case_ = BertTokenizer.from_pretrained("""bert-base-uncased""" ) snake_case_ = bertabert.config.encoder.vocab_size snake_case_ = tokenizer.sep_token_id snake_case_ = tokenizer.cls_token_id snake_case_ = 128 snake_case_ = datasets.load_dataset("""cnn_dailymail""" , """3.0.0""" , split="""train[:1%]""" ) snake_case_ = datasets.load_dataset("""cnn_dailymail""" , """3.0.0""" , split="""validation[:1%]""" ) snake_case_ = train_dataset.select(range(32 ) ) snake_case_ = val_dataset.select(range(16 ) ) snake_case_ = 4 def _map_to_encoder_decoder_inputs(UpperCAmelCase_ : int ): # Tokenizer will automatically set [BOS] <text> [EOS] snake_case_ = tokenizer(batch["""article"""] , padding="""max_length""" , truncation=UpperCAmelCase_ , max_length=512 ) snake_case_ = tokenizer(batch["""highlights"""] , padding="""max_length""" , truncation=UpperCAmelCase_ , max_length=128 ) snake_case_ = inputs.input_ids snake_case_ = inputs.attention_mask snake_case_ = outputs.input_ids snake_case_ = outputs.input_ids.copy() snake_case_ = [ [-100 if token == tokenizer.pad_token_id else token for token in labels] for labels in batch["""labels"""] ] snake_case_ = outputs.attention_mask assert all(len(UpperCAmelCase_ ) == 512 for x in inputs.input_ids ) assert all(len(UpperCAmelCase_ ) == 128 for x in outputs.input_ids ) return batch def _compute_metrics(UpperCAmelCase_ : Union[str, Any] ): snake_case_ = pred.label_ids snake_case_ = pred.predictions # all unnecessary tokens are removed snake_case_ = tokenizer.batch_decode(UpperCAmelCase_ , skip_special_tokens=UpperCAmelCase_ ) snake_case_ = tokenizer.batch_decode(UpperCAmelCase_ , skip_special_tokens=UpperCAmelCase_ ) snake_case_ = sum([int(pred_str[i] == label_str[i] ) for i in range(len(UpperCAmelCase_ ) )] ) / len(UpperCAmelCase_ ) return {"accuracy": accuracy} # map train dataset snake_case_ = train_dataset.map( _map_to_encoder_decoder_inputs , batched=UpperCAmelCase_ , batch_size=UpperCAmelCase_ , remove_columns=["""article""", """highlights"""] , ) train_dataset.set_format( type="""torch""" , columns=["""input_ids""", """attention_mask""", """decoder_input_ids""", """decoder_attention_mask""", """labels"""] , ) # same for validation dataset snake_case_ = val_dataset.map( _map_to_encoder_decoder_inputs , batched=UpperCAmelCase_ , batch_size=UpperCAmelCase_ , remove_columns=["""article""", """highlights"""] , ) val_dataset.set_format( type="""torch""" , columns=["""input_ids""", """attention_mask""", """decoder_input_ids""", """decoder_attention_mask""", """labels"""] , ) snake_case_ = self.get_auto_remove_tmp_dir() snake_case_ = SeqaSeqTrainingArguments( output_dir=UpperCAmelCase_ , per_device_train_batch_size=UpperCAmelCase_ , per_device_eval_batch_size=UpperCAmelCase_ , predict_with_generate=UpperCAmelCase_ , evaluation_strategy="""steps""" , do_train=UpperCAmelCase_ , do_eval=UpperCAmelCase_ , warmup_steps=0 , eval_steps=2 , logging_steps=2 , ) # instantiate trainer snake_case_ = SeqaSeqTrainer( model=UpperCAmelCase_ , args=UpperCAmelCase_ , compute_metrics=_compute_metrics , train_dataset=UpperCAmelCase_ , eval_dataset=UpperCAmelCase_ , tokenizer=UpperCAmelCase_ , ) # start training trainer.train()
347
1
from datetime import datetime import matplotlib.pyplot as plt import torch def __a ( lowerCAmelCase_ : Union[str, Any] ) -> str: '''simple docstring''' for param in module.parameters(): UpperCAmelCase_= False def __a ( ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase_= """cuda""" if torch.cuda.is_available() else """cpu""" if torch.backends.mps.is_available() and torch.backends.mps.is_built(): UpperCAmelCase_= """mps""" if device == "mps": print( """WARNING: MPS currently doesn't seem to work, and messes up backpropagation without any visible torch""" """ errors. I recommend using CUDA on a colab notebook or CPU instead if you're facing inexplicable issues""" """ with generations.""" ) return device def __a ( lowerCAmelCase_ : Union[str, Any] ) -> Union[str, Any]: '''simple docstring''' UpperCAmelCase_= plt.imshow(lowerCAmelCase_ ) fig.axes.get_xaxis().set_visible(lowerCAmelCase_ ) fig.axes.get_yaxis().set_visible(lowerCAmelCase_ ) plt.show() def __a ( ) -> Optional[int]: '''simple docstring''' UpperCAmelCase_= datetime.now() UpperCAmelCase_= current_time.strftime("""%H:%M:%S""" ) return timestamp
277
import math import time from typing import Dict, List, Optional from torch.utils.data import Dataset from transformers import SeqaSeqTrainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput, speed_metrics if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class lowercase ( snake_case__): """simple docstring""" def __init__( self : Any , *__UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : List[str]=None , __UpperCAmelCase : Optional[int]=None , **__UpperCAmelCase : Dict ) -> Optional[int]: super().__init__(*__UpperCAmelCase , **__UpperCAmelCase ) UpperCAmelCase_= eval_examples UpperCAmelCase_= post_process_function def _SCREAMING_SNAKE_CASE ( self : Tuple , __UpperCAmelCase : Optional[Dataset] = None , __UpperCAmelCase : Optional[Any]=None , __UpperCAmelCase : Optional[List[str]] = None , __UpperCAmelCase : str = "eval" , **__UpperCAmelCase : Any , ) -> Dict[str, float]: UpperCAmelCase_= gen_kwargs.copy() UpperCAmelCase_= ( gen_kwargs["""max_length"""] if gen_kwargs.get("""max_length""" ) is not None else self.args.generation_max_length ) UpperCAmelCase_= ( gen_kwargs["""num_beams"""] if gen_kwargs.get("""num_beams""" ) is not None else self.args.generation_num_beams ) UpperCAmelCase_= gen_kwargs UpperCAmelCase_= self.eval_dataset if eval_dataset is None else eval_dataset UpperCAmelCase_= self.get_eval_dataloader(__UpperCAmelCase ) UpperCAmelCase_= self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. UpperCAmelCase_= self.compute_metrics UpperCAmelCase_= None UpperCAmelCase_= time.time() UpperCAmelCase_= self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: UpperCAmelCase_= eval_loop( __UpperCAmelCase , description="""Evaluation""" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__UpperCAmelCase , metric_key_prefix=__UpperCAmelCase , ) finally: UpperCAmelCase_= compute_metrics UpperCAmelCase_= self.args.eval_batch_size * self.args.world_size if F"""{metric_key_prefix}_jit_compilation_time""" in output.metrics: start_time += output.metrics[F"""{metric_key_prefix}_jit_compilation_time"""] output.metrics.update( speed_metrics( __UpperCAmelCase , __UpperCAmelCase , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save: # Only the main node write the results by default UpperCAmelCase_= self.post_process_function(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) UpperCAmelCase_= self.compute_metrics(__UpperCAmelCase ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F"""{metric_key_prefix}_""" ): UpperCAmelCase_= metrics.pop(__UpperCAmelCase ) metrics.update(output.metrics ) else: UpperCAmelCase_= output.metrics if self.args.should_log: # Only the main node log the results by default self.log(__UpperCAmelCase ) if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) UpperCAmelCase_= self.callback_handler.on_evaluate(self.args , self.state , self.control , __UpperCAmelCase ) return metrics def _SCREAMING_SNAKE_CASE ( self : int , __UpperCAmelCase : Dict , __UpperCAmelCase : int , __UpperCAmelCase : Optional[int]=None , __UpperCAmelCase : str = "test" , **__UpperCAmelCase : List[str] ) -> Tuple: UpperCAmelCase_= gen_kwargs.copy() UpperCAmelCase_= self.get_test_dataloader(__UpperCAmelCase ) # Temporarily disable metric computation, we will do it in the loop here. UpperCAmelCase_= self.compute_metrics UpperCAmelCase_= None UpperCAmelCase_= time.time() UpperCAmelCase_= self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: UpperCAmelCase_= eval_loop( __UpperCAmelCase , description="""Prediction""" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__UpperCAmelCase , metric_key_prefix=__UpperCAmelCase , ) finally: UpperCAmelCase_= compute_metrics UpperCAmelCase_= self.args.eval_batch_size * self.args.world_size if F"""{metric_key_prefix}_jit_compilation_time""" in output.metrics: start_time += output.metrics[F"""{metric_key_prefix}_jit_compilation_time"""] output.metrics.update( speed_metrics( __UpperCAmelCase , __UpperCAmelCase , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is None or self.compute_metrics is None: return output UpperCAmelCase_= self.post_process_function(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , """predict""" ) UpperCAmelCase_= self.compute_metrics(__UpperCAmelCase ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F"""{metric_key_prefix}_""" ): UpperCAmelCase_= metrics.pop(__UpperCAmelCase ) metrics.update(output.metrics ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=__UpperCAmelCase )
277
1
import math from typing import Callable, List, Optional, Union import numpy as np import PIL import torch from PIL import Image from transformers import CLIPTextModel, CLIPTokenizer from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline from diffusers.schedulers import DDIMScheduler, DDPMScheduler, LMSDiscreteScheduler, PNDMScheduler def UpperCAmelCase_ ( __snake_case , __snake_case , __snake_case=[] ) -> str: """simple docstring""" _lowercase =size[0] - overlap_pixels * 2 _lowercase =size[1] - overlap_pixels * 2 for letter in ["l", "r"]: if letter in remove_borders: size_x += overlap_pixels for letter in ["t", "b"]: if letter in remove_borders: size_y += overlap_pixels _lowercase =np.ones((size_y, size_x) , dtype=np.uinta ) * 255 _lowercase =np.pad(lowerCamelCase_ , mode='''linear_ramp''' , pad_width=lowerCamelCase_ , end_values=0 ) if "l" in remove_borders: _lowercase =mask[:, overlap_pixels : mask.shape[1]] if "r" in remove_borders: _lowercase =mask[:, 0 : mask.shape[1] - overlap_pixels] if "t" in remove_borders: _lowercase =mask[overlap_pixels : mask.shape[0], :] if "b" in remove_borders: _lowercase =mask[0 : mask.shape[0] - overlap_pixels, :] return mask def UpperCAmelCase_ ( __snake_case , __snake_case , __snake_case ) -> Dict: """simple docstring""" return max(lowerCamelCase_ , min(lowerCamelCase_ , lowerCamelCase_ ) ) def UpperCAmelCase_ ( __snake_case , __snake_case , __snake_case ) -> int: """simple docstring""" return ( clamp(rect[0] , min[0] , max[0] ), clamp(rect[1] , min[1] , max[1] ), clamp(rect[2] , min[0] , max[0] ), clamp(rect[3] , min[1] , max[1] ), ) def UpperCAmelCase_ ( __snake_case , __snake_case , __snake_case ) -> int: """simple docstring""" _lowercase =list(lowerCamelCase_ ) rect[0] -= overlap rect[1] -= overlap rect[2] += overlap rect[3] += overlap _lowercase =clamp_rect(lowerCamelCase_ , [0, 0] , [image_size[0], image_size[1]] ) return rect def UpperCAmelCase_ ( __snake_case , __snake_case , __snake_case , __snake_case ) -> Optional[int]: """simple docstring""" _lowercase =Image.new('''RGB''' , (tile.size[0] + original_slice, tile.size[1]) ) result.paste( original_image.resize((tile.size[0], tile.size[1]) , Image.BICUBIC ).crop( (slice_x, 0, slice_x + original_slice, tile.size[1]) ) , (0, 0) , ) result.paste(lowerCamelCase_ , (original_slice, 0) ) return result def UpperCAmelCase_ ( __snake_case , __snake_case ) -> str: """simple docstring""" _lowercase =(original_image_slice * 4, 0, tile.size[0], tile.size[1]) _lowercase =tile.crop(lowerCamelCase_ ) return tile def UpperCAmelCase_ ( __snake_case , __snake_case ) -> List[Any]: """simple docstring""" _lowercase =n % d return n - divisor class lowerCamelCase__ ( lowercase_): def __init__(self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = 3_5_0 , ) -> List[str]: super().__init__( vae=lowerCamelCase_ , text_encoder=lowerCamelCase_ , tokenizer=lowerCamelCase_ , unet=lowerCamelCase_ , low_res_scheduler=lowerCamelCase_ , scheduler=lowerCamelCase_ , max_noise_level=lowerCamelCase_ , ) def __A (self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , **UpperCAmelCase ) -> Union[str, Any]: torch.manual_seed(0 ) _lowercase =( min(image.size[0] - (tile_size + original_image_slice) , x * tile_size ), min(image.size[1] - (tile_size + original_image_slice) , y * tile_size ), min(image.size[0] , (x + 1) * tile_size ), min(image.size[1] , (y + 1) * tile_size ), ) _lowercase =add_overlap_rect(lowerCamelCase_ , lowerCamelCase_ , image.size ) _lowercase =image.crop(lowerCamelCase_ ) _lowercase =((crop_rect[0] + ((crop_rect[2] - crop_rect[0]) / 2)) / image.size[0]) * tile.size[0] _lowercase =translated_slice_x - (original_image_slice / 2) _lowercase =max(0 , lowerCamelCase_ ) _lowercase =squeeze_tile(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) _lowercase =to_input.size _lowercase =to_input.resize((tile_size, tile_size) , Image.BICUBIC ) _lowercase =super(lowerCamelCase_ , self ).__call__(image=lowerCamelCase_ , **lowerCamelCase_ ).images[0] _lowercase =upscaled_tile.resize((orig_input_size[0] * 4, orig_input_size[1] * 4) , Image.BICUBIC ) _lowercase =unsqueeze_tile(lowerCamelCase_ , lowerCamelCase_ ) _lowercase =upscaled_tile.resize((tile.size[0] * 4, tile.size[1] * 4) , Image.BICUBIC ) _lowercase =[] if x == 0: remove_borders.append('''l''' ) elif crop_rect[2] == image.size[0]: remove_borders.append('''r''' ) if y == 0: remove_borders.append('''t''' ) elif crop_rect[3] == image.size[1]: remove_borders.append('''b''' ) _lowercase =Image.fromarray( make_transparency_mask( (upscaled_tile.size[0], upscaled_tile.size[1]) , tile_border * 4 , remove_borders=lowerCamelCase_ ) , mode='''L''' , ) final_image.paste( lowerCamelCase_ , (crop_rect_with_overlap[0] * 4, crop_rect_with_overlap[1] * 4) , lowerCamelCase_ ) @torch.no_grad() def __call__(self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = 7_5 , UpperCAmelCase = 9.0 , UpperCAmelCase = 5_0 , UpperCAmelCase = None , UpperCAmelCase = 1 , UpperCAmelCase = 0.0 , UpperCAmelCase = None , UpperCAmelCase = None , UpperCAmelCase = None , UpperCAmelCase = 1 , UpperCAmelCase = 1_2_8 , UpperCAmelCase = 3_2 , UpperCAmelCase = 3_2 , ) -> Optional[int]: _lowercase =Image.new('''RGB''' , (image.size[0] * 4, image.size[1] * 4) ) _lowercase =math.ceil(image.size[0] / tile_size ) _lowercase =math.ceil(image.size[1] / tile_size ) _lowercase =tcx * tcy _lowercase =0 for y in range(lowerCamelCase_ ): for x in range(lowerCamelCase_ ): self._process_tile( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , prompt=lowerCamelCase_ , num_inference_steps=lowerCamelCase_ , guidance_scale=lowerCamelCase_ , noise_level=lowerCamelCase_ , negative_prompt=lowerCamelCase_ , num_images_per_prompt=lowerCamelCase_ , eta=lowerCamelCase_ , generator=lowerCamelCase_ , latents=lowerCamelCase_ , ) current_count += 1 if callback is not None: callback({'''progress''': current_count / total_tile_count, '''image''': final_image} ) return final_image def UpperCAmelCase_ ( ) -> Any: """simple docstring""" _lowercase ="""stabilityai/stable-diffusion-x4-upscaler""" _lowercase =StableDiffusionTiledUpscalePipeline.from_pretrained(lowerCamelCase_ , revision='''fp16''' , torch_dtype=torch.floataa ) _lowercase =pipe.to('''cuda''' ) _lowercase =Image.open('''../../docs/source/imgs/diffusers_library.jpg''' ) def callback(__snake_case ): print(F"progress: {obj['progress']:.4f}" ) obj["image"].save('''diffusers_library_progress.jpg''' ) _lowercase =pipe(image=lowerCamelCase_ , prompt='''Black font, white background, vector''' , noise_level=40 , callback=lowerCamelCase_ ) final_image.save('''diffusers_library.jpg''' ) if __name__ == "__main__": main()
5
'''simple docstring''' from typing import Optional from .. import Features, NamedSplit from ..packaged_modules.text.text import Text from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader class UpperCamelCase__ ( lowercase_ ): """simple docstring""" def __init__( self : Dict , lowerCamelCase_ : NestedDataStructureLike[PathLike] , lowerCamelCase_ : Optional[NamedSplit] = None , lowerCamelCase_ : Optional[Features] = None , lowerCamelCase_ : str = None , lowerCamelCase_ : bool = False , lowerCamelCase_ : bool = False , lowerCamelCase_ : Optional[int] = None , **lowerCamelCase_ : Union[str, Any] , ): '''simple docstring''' super().__init__( lowerCamelCase_ , split=lowerCamelCase_ , features=lowerCamelCase_ , cache_dir=lowerCamelCase_ , keep_in_memory=lowerCamelCase_ , streaming=lowerCamelCase_ , num_proc=lowerCamelCase_ , **lowerCamelCase_ , ) SCREAMING_SNAKE_CASE : int = path_or_paths if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else {self.split: path_or_paths} SCREAMING_SNAKE_CASE : Optional[int] = Text( cache_dir=lowerCamelCase_ , data_files=lowerCamelCase_ , features=lowerCamelCase_ , **lowerCamelCase_ , ) def lowerCamelCase_ ( self : Dict ): '''simple docstring''' if self.streaming: SCREAMING_SNAKE_CASE : int = self.builder.as_streaming_dataset(split=self.split ) # Build regular (map-style) dataset else: SCREAMING_SNAKE_CASE : List[str] = None SCREAMING_SNAKE_CASE : Union[str, Any] = None SCREAMING_SNAKE_CASE : Optional[int] = None SCREAMING_SNAKE_CASE : List[str] = None self.builder.download_and_prepare( download_config=lowerCamelCase_ , download_mode=lowerCamelCase_ , verification_mode=lowerCamelCase_ , base_path=lowerCamelCase_ , num_proc=self.num_proc , ) SCREAMING_SNAKE_CASE : int = self.builder.as_dataset( split=self.split , verification_mode=lowerCamelCase_ , in_memory=self.keep_in_memory ) return dataset
323
0
import itertools import random import unittest import numpy as np from transformers import is_speech_available from transformers.testing_utils import require_torch, require_torchaudio from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import SpeechaTextFeatureExtractor a_ = random.Random() def __lowercase ( lowerCamelCase : Optional[int] , lowerCamelCase : int=1.0 , lowerCamelCase : Optional[int]=None , lowerCamelCase : Optional[int]=None ): if rng is None: UpperCamelCase_ : Union[str, Any] = global_rng UpperCamelCase_ : Union[str, Any] = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch @require_torchaudio class _lowercase ( unittest.TestCase ): def __init__( self : Optional[Any] , snake_case : Tuple , snake_case : str=7 , snake_case : Tuple=4_0_0 , snake_case : List[Any]=2_0_0_0 , snake_case : Optional[Any]=2_4 , snake_case : Tuple=2_4 , snake_case : Dict=0.0 , snake_case : Any=1_6_0_0_0 , snake_case : Tuple=True , snake_case : List[str]=True , ) -> Optional[int]: """simple docstring""" UpperCamelCase_ : int = parent UpperCamelCase_ : int = batch_size UpperCamelCase_ : str = min_seq_length UpperCamelCase_ : str = max_seq_length UpperCamelCase_ : Optional[int] = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) UpperCamelCase_ : int = feature_size UpperCamelCase_ : Optional[int] = num_mel_bins UpperCamelCase_ : str = padding_value UpperCamelCase_ : Union[str, Any] = sampling_rate UpperCamelCase_ : Tuple = return_attention_mask UpperCamelCase_ : List[str] = do_normalize def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> Tuple: """simple docstring""" return { "feature_size": self.feature_size, "num_mel_bins": self.num_mel_bins, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def SCREAMING_SNAKE_CASE__ ( self : Any , snake_case : Dict=False , snake_case : List[str]=False ) -> int: """simple docstring""" def _flatten(snake_case : Optional[Any] ): return list(itertools.chain(*snake_case ) ) if equal_length: UpperCamelCase_ : Any = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size UpperCamelCase_ : Optional[Any] = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: UpperCamelCase_ : List[str] = [np.asarray(snake_case ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class _lowercase ( snake_case_ , unittest.TestCase ): lowercase = SpeechaTextFeatureExtractor if is_speech_available() else None def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> Tuple: """simple docstring""" UpperCamelCase_ : List[str] = SpeechaTextFeatureExtractionTester(self ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] , snake_case : str ) -> Tuple: """simple docstring""" self.assertTrue(np.all(np.mean(snake_case , axis=0 ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(snake_case , axis=0 ) - 1 ) < 1e-3 ) ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] ) -> List[str]: """simple docstring""" UpperCamelCase_ : List[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 UpperCamelCase_ : Union[str, Any] = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] UpperCamelCase_ : List[Any] = [np.asarray(snake_case ) for speech_input in speech_inputs] # Test feature size UpperCamelCase_ : Tuple = feature_extractor(snake_case , padding=snake_case , return_tensors='np' ).input_features self.assertTrue(input_features.ndim == 3 ) self.assertTrue(input_features.shape[-1] == feature_extractor.feature_size ) # Test not batched input UpperCamelCase_ : int = feature_extractor(speech_inputs[0] , return_tensors='np' ).input_features UpperCamelCase_ : str = feature_extractor(np_speech_inputs[0] , return_tensors='np' ).input_features self.assertTrue(np.allclose(snake_case , snake_case , atol=1e-3 ) ) # Test batched UpperCamelCase_ : Union[str, Any] = feature_extractor(snake_case , return_tensors='np' ).input_features UpperCamelCase_ : List[str] = feature_extractor(snake_case , return_tensors='np' ).input_features for enc_seq_a, enc_seq_a in zip(snake_case , snake_case ): self.assertTrue(np.allclose(snake_case , snake_case , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. UpperCamelCase_ : int = [floats_list((1, x) )[0] for x in (8_0_0, 8_0_0, 8_0_0)] UpperCamelCase_ : List[str] = np.asarray(snake_case ) UpperCamelCase_ : Any = feature_extractor(snake_case , return_tensors='np' ).input_features UpperCamelCase_ : str = feature_extractor(snake_case , return_tensors='np' ).input_features for enc_seq_a, enc_seq_a in zip(snake_case , snake_case ): self.assertTrue(np.allclose(snake_case , snake_case , atol=1e-3 ) ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] ) -> Tuple: """simple docstring""" UpperCamelCase_ : Tuple = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCamelCase_ : Optional[int] = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] UpperCamelCase_ : Union[str, Any] = ['longest', 'max_length', 'do_not_pad'] UpperCamelCase_ : Tuple = [None, 1_6, None] for max_length, padding in zip(snake_case , snake_case ): UpperCamelCase_ : Optional[Any] = feature_extractor( snake_case , padding=snake_case , max_length=snake_case , return_attention_mask=snake_case ) UpperCamelCase_ : List[str] = inputs.input_features UpperCamelCase_ : List[str] = inputs.attention_mask UpperCamelCase_ : Optional[int] = [np.sum(snake_case ) for x in attention_mask] self._check_zero_mean_unit_variance(input_features[0][: fbank_feat_lengths[0]] ) self._check_zero_mean_unit_variance(input_features[1][: fbank_feat_lengths[1]] ) self._check_zero_mean_unit_variance(input_features[2][: fbank_feat_lengths[2]] ) def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> List[str]: """simple docstring""" UpperCamelCase_ : Dict = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCamelCase_ : Any = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] UpperCamelCase_ : List[str] = ['longest', 'max_length', 'do_not_pad'] UpperCamelCase_ : Optional[Any] = [None, 1_6, None] for max_length, padding in zip(snake_case , snake_case ): UpperCamelCase_ : Any = feature_extractor( snake_case , max_length=snake_case , padding=snake_case , return_tensors='np' , return_attention_mask=snake_case ) UpperCamelCase_ : int = inputs.input_features UpperCamelCase_ : Optional[int] = inputs.attention_mask UpperCamelCase_ : str = [np.sum(snake_case ) for x in attention_mask] self._check_zero_mean_unit_variance(input_features[0][: fbank_feat_lengths[0]] ) self.assertTrue(input_features[0][fbank_feat_lengths[0] :].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_features[1][: fbank_feat_lengths[1]] ) self.assertTrue(input_features[0][fbank_feat_lengths[1] :].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_features[2][: fbank_feat_lengths[2]] ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] ) -> List[str]: """simple docstring""" UpperCamelCase_ : Tuple = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCamelCase_ : List[Any] = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] UpperCamelCase_ : str = feature_extractor( snake_case , padding='max_length' , max_length=4 , truncation=snake_case , return_tensors='np' , return_attention_mask=snake_case , ) UpperCamelCase_ : int = inputs.input_features UpperCamelCase_ : Union[str, Any] = inputs.attention_mask UpperCamelCase_ : Dict = np.sum(attention_mask == 1 , axis=1 ) self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]] ) self._check_zero_mean_unit_variance(input_features[1] ) self._check_zero_mean_unit_variance(input_features[2] ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> str: """simple docstring""" UpperCamelCase_ : str = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCamelCase_ : Optional[int] = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] UpperCamelCase_ : Any = feature_extractor( snake_case , padding='longest' , max_length=4 , truncation=snake_case , return_tensors='np' , return_attention_mask=snake_case , ) UpperCamelCase_ : Dict = inputs.input_features UpperCamelCase_ : List[Any] = inputs.attention_mask UpperCamelCase_ : Tuple = np.sum(attention_mask == 1 , axis=1 ) self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]] ) self._check_zero_mean_unit_variance(input_features[1, : fbank_feat_lengths[1]] ) self._check_zero_mean_unit_variance(input_features[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertEqual(input_features.shape , (3, 4, 2_4) ) UpperCamelCase_ : Dict = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] UpperCamelCase_ : int = feature_extractor( snake_case , padding='longest' , max_length=1_6 , truncation=snake_case , return_tensors='np' , return_attention_mask=snake_case , ) UpperCamelCase_ : Dict = inputs.input_features UpperCamelCase_ : Union[str, Any] = inputs.attention_mask UpperCamelCase_ : Dict = np.sum(attention_mask == 1 , axis=1 ) self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]] ) self._check_zero_mean_unit_variance(input_features[1, : fbank_feat_lengths[1]] ) self._check_zero_mean_unit_variance(input_features[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertEqual(input_features.shape , (3, 6, 2_4) ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> Tuple: """simple docstring""" import torch UpperCamelCase_ : Any = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCamelCase_ : Optional[Any] = np.random.rand(1_0_0 , 3_2 ).astype(np.floataa ) UpperCamelCase_ : int = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: UpperCamelCase_ : Tuple = feature_extractor.pad([{'input_features': inputs}] , return_tensors='np' ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) UpperCamelCase_ : Tuple = feature_extractor.pad([{'input_features': inputs}] , return_tensors='pt' ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def SCREAMING_SNAKE_CASE__ ( self : Tuple , snake_case : Tuple ) -> Dict: """simple docstring""" from datasets import load_dataset UpperCamelCase_ : Optional[int] = load_dataset('hf-internal-testing/librispeech_asr_dummy' , 'clean' , split='validation' ) # automatic decoding with librispeech UpperCamelCase_ : Optional[Any] = ds.sort('id' ).select(range(snake_case ) )[:num_samples]['audio'] return [x["array"] for x in speech_samples] def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> str: """simple docstring""" UpperCamelCase_ : Union[str, Any] = np.array([ -1.5745, -1.7713, -1.7020, -1.6069, -1.2250, -1.1105, -0.9072, -0.8241, -1.2310, -0.8098, -0.3320, -0.4101, -0.7985, -0.4996, -0.8213, -0.9128, -1.0420, -1.1286, -1.0440, -0.7999, -0.8405, -1.2275, -1.5443, -1.4625, ] ) # fmt: on UpperCamelCase_ : str = self._load_datasamples(1 ) UpperCamelCase_ : str = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCamelCase_ : str = feature_extractor(snake_case , return_tensors='pt' ).input_features self.assertEquals(input_features.shape , (1, 5_8_4, 2_4) ) self.assertTrue(np.allclose(input_features[0, 0, :3_0] , snake_case , atol=1e-4 ) )
50
a_ = [ 'DownloadConfig', 'DownloadManager', 'DownloadMode', 'StreamingDownloadManager', ] from .download_config import DownloadConfig from .download_manager import DownloadManager, DownloadMode from .streaming_download_manager import StreamingDownloadManager
50
1
import random import unittest import torch from diffusers import IFInpaintingSuperResolutionPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin from . import IFPipelineTesterMixin @skip_mps class __snake_case ( lowerCAmelCase , lowerCAmelCase , unittest.TestCase ): _a : Union[str, Any]= IFInpaintingSuperResolutionPipeline _a : Tuple= TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {"width", "height"} _a : str= TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS.union({"original_image"} ) _a : Tuple= PipelineTesterMixin.required_optional_params - {"latents"} def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' return self._get_superresolution_dummy_components() def _SCREAMING_SNAKE_CASE ( self ,snake_case ,snake_case=0 ): '''simple docstring''' if str(snake_case ).startswith("""mps""" ): lowercase : int = torch.manual_seed(snake_case ) else: lowercase : List[str] = torch.Generator(device=snake_case ).manual_seed(snake_case ) lowercase : str = floats_tensor((1, 3, 16, 16) ,rng=random.Random(snake_case ) ).to(snake_case ) lowercase : Union[str, Any] = floats_tensor((1, 3, 32, 32) ,rng=random.Random(snake_case ) ).to(snake_case ) lowercase : str = floats_tensor((1, 3, 32, 32) ,rng=random.Random(snake_case ) ).to(snake_case ) lowercase : int = { """prompt""": """A painting of a squirrel eating a burger""", """image""": image, """original_image""": original_image, """mask_image""": mask_image, """generator""": generator, """num_inference_steps""": 2, """output_type""": """numpy""", } return inputs @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() ,reason="""XFormers attention is only available with CUDA and `xformers` installed""" ,) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' self._test_save_load_optional_components() @unittest.skipIf(torch_device != """cuda""" ,reason="""float16 requires CUDA""" ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' super().test_save_load_floataa(expected_max_diff=1e-1 ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' self._test_attention_slicing_forward_pass(expected_max_diff=1e-2 ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' self._test_save_load_local() def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' self._test_inference_batch_single_identical( expected_max_diff=1e-2 ,)
20
"""simple docstring""" import tempfile import unittest from transformers import TaConfig, is_torch_available from transformers.testing_utils import ( require_sentencepiece, require_tokenizers, require_torch, slow, torch_device, ) from ...generation.test_utils import GenerationTesterMixin from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import AutoTokenizer, UMTaForConditionalGeneration, UMTaForQuestionAnswering, UMTaModel class __lowerCamelCase : '''simple docstring''' def __init__( self , __UpperCAmelCase , __UpperCAmelCase=99 , __UpperCAmelCase=13 , __UpperCAmelCase=7 , __UpperCAmelCase=9 , __UpperCAmelCase=True , __UpperCAmelCase=True , __UpperCAmelCase=False , __UpperCAmelCase=32 , __UpperCAmelCase=5 , __UpperCAmelCase=4 , __UpperCAmelCase=37 , __UpperCAmelCase=8 , __UpperCAmelCase=0.1 , __UpperCAmelCase=0.002 , __UpperCAmelCase=1 , __UpperCAmelCase=0 , __UpperCAmelCase=0 , __UpperCAmelCase=None , __UpperCAmelCase=None , ) -> Optional[int]: _a = parent _a = batch_size _a = encoder_seq_length _a = decoder_seq_length # For common tests _a = self.decoder_seq_length _a = is_training _a = use_attention_mask _a = use_labels _a = vocab_size _a = hidden_size _a = num_hidden_layers _a = num_attention_heads _a = d_ff _a = relative_attention_num_buckets _a = dropout_rate _a = initializer_factor _a = eos_token_id _a = pad_token_id _a = decoder_start_token_id _a = None _a = decoder_layers def _UpperCAmelCase ( self ) -> Dict: return TaConfig.from_pretrained('''google/umt5-base''' ) def _UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase=None , __UpperCAmelCase=None , __UpperCAmelCase=None , __UpperCAmelCase=None , __UpperCAmelCase=None , ) -> Optional[int]: if attention_mask is None: _a = input_ids.ne(config.pad_token_id ) if decoder_attention_mask is None: _a = decoder_input_ids.ne(config.pad_token_id ) if head_mask is None: _a = torch.ones(config.num_hidden_layers , config.num_attention_heads , device=__UpperCAmelCase ) if decoder_head_mask is None: _a = torch.ones(config.num_decoder_layers , config.num_attention_heads , device=__UpperCAmelCase ) if cross_attn_head_mask is None: _a = torch.ones( config.num_decoder_layers , config.num_attention_heads , device=__UpperCAmelCase ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } def _UpperCAmelCase ( self ) -> Tuple: _a = ids_tensor([self.batch_size, self.encoder_seq_length] , self.vocab_size ) _a = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) # we need to clamp the input ids here to avoid having pad token in between # this is because for NllbMoe the position_ids are prepared such that # all pad tokens have pos id = 2 and rest are between 2..seq_length # and the seq_length here is seq_length - num_pad_tokens # but when using past, there is no way of knowing if the past input ids had # pad tokens in them, which results in incorrect seq_lenth and which in turn results in # position_ids being off by num_pad_tokens in past input _a = input_ids.clamp(self.pad_token_id + 1 ) _a = decoder_input_ids.clamp(self.pad_token_id + 1 ) _a = self.get_config() _a = config.num_attention_heads _a = self.prepare_inputs_dict(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) return config, input_dict def _UpperCAmelCase ( self ) -> int: _a , _a = self.prepare_config_and_inputs() return config, inputs_dict def _UpperCAmelCase ( self ) -> Tuple: return TaConfig( vocab_size=166 , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def _UpperCAmelCase ( self ) -> List[str]: return TaConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def _UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , ) -> Dict: _a = UMTaModel(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() _a = model( input_ids=__UpperCAmelCase , decoder_input_ids=__UpperCAmelCase , attention_mask=__UpperCAmelCase , decoder_attention_mask=__UpperCAmelCase , ) _a = model(input_ids=__UpperCAmelCase , decoder_input_ids=__UpperCAmelCase ) _a = result.last_hidden_state _a = result.past_key_values _a = result.encoder_last_hidden_state self.parent.assertEqual(encoder_output.size() , (self.batch_size, self.encoder_seq_length, self.hidden_size) ) self.parent.assertEqual(decoder_output.size() , (self.batch_size, self.decoder_seq_length, self.hidden_size) ) # There should be `num_layers` key value embeddings stored in decoder_past self.parent.assertEqual(len(__UpperCAmelCase ) , config.num_layers ) # There should be a self attn key, a self attn value, a cross attn key and a cross attn value stored in each decoder_past tuple self.parent.assertEqual(len(decoder_past[0] ) , 4 ) def _UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , ) -> Optional[Any]: _a = UMTaModel(config=__UpperCAmelCase ).get_decoder().to(__UpperCAmelCase ).eval() # first forward pass _a = model(__UpperCAmelCase , use_cache=__UpperCAmelCase ) _a = model(__UpperCAmelCase ) _a = model(__UpperCAmelCase , use_cache=__UpperCAmelCase ) self.parent.assertTrue(len(__UpperCAmelCase ) == len(__UpperCAmelCase ) ) self.parent.assertTrue(len(__UpperCAmelCase ) == len(__UpperCAmelCase ) + 1 ) _a , _a = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids _a = ids_tensor((self.batch_size, 1) , config.vocab_size ) # append to next input_ids and _a = torch.cat([input_ids, next_tokens] , dim=-1 ) _a = model(__UpperCAmelCase )['''last_hidden_state'''] _a = model(__UpperCAmelCase , past_key_values=__UpperCAmelCase )['''last_hidden_state'''] # select random slice _a = ids_tensor((1,) , output_from_past.shape[-1] ).item() _a = output_from_no_past[:, -1, random_slice_idx].detach() _a = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(__UpperCAmelCase , __UpperCAmelCase , atol=1e-3 ) ) def _UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase , ) -> Union[str, Any]: _a = UMTaModel(config=__UpperCAmelCase ).to(__UpperCAmelCase ).half().eval() _a = model(**__UpperCAmelCase )['''last_hidden_state'''] self.parent.assertFalse(torch.isnan(__UpperCAmelCase ).any().item() ) @require_torch class __lowerCamelCase ( a__ , a__ , a__ , unittest.TestCase ): '''simple docstring''' A_ : Optional[Any] = ( (UMTaModel, UMTaForConditionalGeneration, UMTaForQuestionAnswering) if is_torch_available() else () ) A_ : Optional[Any] = (UMTaForConditionalGeneration,) if is_torch_available() else () A_ : int = ( { 'conversational': UMTaForConditionalGeneration, 'feature-extraction': UMTaModel, 'summarization': UMTaForConditionalGeneration, 'text2text-generation': UMTaForConditionalGeneration, 'translation': UMTaForConditionalGeneration, 'question-answering': UMTaForQuestionAnswering, } if is_torch_available() else {} ) A_ : str = True A_ : List[str] = False A_ : List[Any] = False A_ : str = True A_ : List[str] = True # The small UMT5 model needs higher percentages for CPU/MP tests A_ : Optional[Any] = [0.8, 0.9] def _UpperCAmelCase ( self ) -> Tuple: _a = UMTaModelTester(self ) @unittest.skip('''Test has a segmentation fault on torch 1.8.0''' ) def _UpperCAmelCase ( self ) -> int: _a = self.model_tester.prepare_config_and_inputs() _a = UMTaModel(config_and_inputs[0] ).to(__UpperCAmelCase ) with tempfile.TemporaryDirectory() as tmpdirname: torch.onnx.export( __UpperCAmelCase , (config_and_inputs[1], config_and_inputs[3], config_and_inputs[2]) , F'{tmpdirname}/t5_test.onnx' , export_params=__UpperCAmelCase , opset_version=9 , input_names=['''input_ids''', '''decoder_input_ids'''] , ) @unittest.skipIf(torch_device == '''cpu''' , '''Cant do half precision''' ) def _UpperCAmelCase ( self ) -> Union[str, Any]: _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model_fpaa_forward(*__UpperCAmelCase ) def _UpperCAmelCase ( self ) -> Union[str, Any]: _a = ['''encoder_attentions''', '''decoder_attentions''', '''cross_attentions'''] _a = self.model_tester.prepare_config_and_inputs() _a = config_and_inputs[0] _a = UMTaForConditionalGeneration(__UpperCAmelCase ).eval() model.to(__UpperCAmelCase ) _a = { '''head_mask''': torch.zeros(config.num_layers , config.num_heads , device=__UpperCAmelCase ), '''decoder_head_mask''': torch.zeros(config.num_decoder_layers , config.num_heads , device=__UpperCAmelCase ), '''cross_attn_head_mask''': torch.zeros(config.num_decoder_layers , config.num_heads , device=__UpperCAmelCase ), } for attn_name, (name, mask) in zip(__UpperCAmelCase , head_masking.items() ): _a = {name: mask} # Explicitly pass decoder_head_mask as it is required from T5 model when head_mask specified if name == "head_mask": _a = torch.ones( config.num_decoder_layers , config.num_heads , device=__UpperCAmelCase ) _a = model.generate( config_and_inputs[1]['''input_ids'''] , num_beams=1 , max_length=3 , output_attentions=__UpperCAmelCase , return_dict_in_generate=__UpperCAmelCase , **__UpperCAmelCase , ) # We check the state of decoder_attentions and cross_attentions just from the last step _a = out[attn_name] if attn_name == attention_names[0] else out[attn_name][-1] self.assertEqual(sum([w.sum().item() for w in attn_weights] ) , 0.0 ) @unittest.skip('''Does not work on the tiny model as we keep hitting edge cases.''' ) def _UpperCAmelCase ( self ) -> int: pass @require_torch @require_sentencepiece @require_tokenizers class __lowerCamelCase ( unittest.TestCase ): '''simple docstring''' @slow @unittest.skip( '''Unless we stop stripping left and right by default for all special tokens, the expected ids obtained here will not match the original ones. Wait for https://github.com/huggingface/transformers/pull/23909 to be merged''' ) def _UpperCAmelCase ( self ) -> Optional[int]: _a = UMTaForConditionalGeneration.from_pretrained('''google/umt5-small''' , return_dict=__UpperCAmelCase ).to(__UpperCAmelCase ) _a = AutoTokenizer.from_pretrained('''google/umt5-small''' , use_fast=__UpperCAmelCase , legacy=__UpperCAmelCase ) _a = [ '''Bonjour monsieur <extra_id_0> bien <extra_id_1>.''', '''No se como puedo <extra_id_0>.''', '''This is the reason why we <extra_id_0> them.''', '''The <extra_id_0> walks in <extra_id_1>, seats''', '''A <extra_id_0> walks into a bar and orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.''', ] _a = tokenizer(__UpperCAmelCase , return_tensors='''pt''' , padding=__UpperCAmelCase ).input_ids # fmt: off _a = torch.tensor( [ [ 38530, 210703, 256299, 1410, 256298, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 826, 321, 671, 25922, 256299, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 1460, 339, 312, 19014, 10620, 758, 256299, 2355,274, 1, 0, 0, 0, 0, 0, 0,0, 0], [ 517, 256299, 14869, 281, 301, 256298, 275, 119983,1, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 320, 256299, 14869, 281, 2234, 289, 2275, 333,61391, 289, 256298, 543, 256297, 168714, 329, 256296,274, 1], ] ) # fmt: on torch.testing.assert_allclose(__UpperCAmelCase , __UpperCAmelCase ) _a = model.generate(input_ids.to(__UpperCAmelCase ) ) _a = [ '''<pad><extra_id_0> et<extra_id_1> [eod] <extra_id_2><extra_id_55>.. [eod] 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 <extra_id_56>ajšietosto<extra_id_56>lleux<extra_id_19><extra_id_6>ajšie</s>''', '''<pad><extra_id_0>.<extra_id_1>.,<0x0A>...spech <0x0A><extra_id_20> <extra_id_21></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', '''<pad><extra_id_0> are not going to be a part of the world. We are not going to be a part of<extra_id_1> and<extra_id_2><0x0A><extra_id_48>.<extra_id_48></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', '''<pad><extra_id_0> door<extra_id_1>, the door<extra_id_2> 피해[/</s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', '''<pad><extra_id_0>nyone who<extra_id_1> drink<extra_id_2> a<extra_id_3> alcohol<extra_id_4> A<extra_id_5> A. This<extra_id_6> I<extra_id_7><extra_id_52><extra_id_53></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', ] _a = tokenizer.batch_decode(__UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , __UpperCAmelCase )
320
0
"""simple docstring""" from __future__ import annotations import unittest from transformers import EsmConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import numpy import tensorflow as tf from transformers.models.esm.modeling_tf_esm import ( TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST, TFEsmForMaskedLM, TFEsmForSequenceClassification, TFEsmForTokenClassification, TFEsmModel, ) class a : def __init__( self , _snake_case , ): """simple docstring""" lowerCAmelCase = parent lowerCAmelCase = 13 lowerCAmelCase = 7 lowerCAmelCase = True lowerCAmelCase = True lowerCAmelCase = True lowerCAmelCase = 99 lowerCAmelCase = 32 lowerCAmelCase = 2 lowerCAmelCase = 4 lowerCAmelCase = 37 lowerCAmelCase = 'gelu' lowerCAmelCase = 0.1 lowerCAmelCase = 0.1 lowerCAmelCase = 5_12 lowerCAmelCase = 16 lowerCAmelCase = 2 lowerCAmelCase = 0.02 lowerCAmelCase = 3 lowerCAmelCase = 4 lowerCAmelCase = None def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCAmelCase = None if self.use_input_mask: lowerCAmelCase = random_attention_mask([self.batch_size, self.seq_length] ) lowerCAmelCase = None lowerCAmelCase = None lowerCAmelCase = None if self.use_labels: lowerCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) lowerCAmelCase = ids_tensor([self.batch_size] , self.num_choices ) lowerCAmelCase = EsmConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , pad_token_id=1 , 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 config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCamelCase__ ( self ): """simple docstring""" ( ( lowerCAmelCase ) ,( lowerCAmelCase ) ,( lowerCAmelCase ) ,( lowerCAmelCase ) ,( lowerCAmelCase ) ,( lowerCAmelCase ) , ) = self.prepare_config_and_inputs() lowerCAmelCase = True lowerCAmelCase = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def UpperCamelCase__ ( self , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case ): """simple docstring""" lowerCAmelCase = TFEsmModel(config=_snake_case ) lowerCAmelCase = {'input_ids': input_ids, 'attention_mask': input_mask} lowerCAmelCase = model(_snake_case ) lowerCAmelCase = [input_ids, input_mask] lowerCAmelCase = model(_snake_case ) lowerCAmelCase = model(_snake_case ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase__ ( self , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , ): """simple docstring""" lowerCAmelCase = True lowerCAmelCase = TFEsmModel(config=_snake_case ) lowerCAmelCase = { 'input_ids': input_ids, 'attention_mask': input_mask, 'encoder_hidden_states': encoder_hidden_states, 'encoder_attention_mask': encoder_attention_mask, } lowerCAmelCase = model(_snake_case ) lowerCAmelCase = [input_ids, input_mask] lowerCAmelCase = model(_snake_case , encoder_hidden_states=_snake_case ) # Also check the case where encoder outputs are not passed lowerCAmelCase = model(_snake_case , attention_mask=_snake_case ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase__ ( self , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case ): """simple docstring""" lowerCAmelCase = TFEsmForMaskedLM(config=_snake_case ) lowerCAmelCase = model([input_ids, input_mask] ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCamelCase__ ( self , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case ): """simple docstring""" lowerCAmelCase = self.num_labels lowerCAmelCase = TFEsmForTokenClassification(config=_snake_case ) lowerCAmelCase = {'input_ids': input_ids, 'attention_mask': input_mask} lowerCAmelCase = model(_snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase = self.prepare_config_and_inputs() ( ( lowerCAmelCase ) ,( lowerCAmelCase ) ,( lowerCAmelCase ) ,( lowerCAmelCase ) ,( lowerCAmelCase ) ,( lowerCAmelCase ) , ) = config_and_inputs lowerCAmelCase = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_tf class a ( a__ , a__ , unittest.TestCase ): snake_case__ = ( ( TFEsmModel, TFEsmForMaskedLM, TFEsmForSequenceClassification, TFEsmForTokenClassification, ) if is_tf_available() else () ) snake_case__ = ( { '''feature-extraction''': TFEsmModel, '''fill-mask''': TFEsmForMaskedLM, '''text-classification''': TFEsmForSequenceClassification, '''token-classification''': TFEsmForTokenClassification, '''zero-shot''': TFEsmForSequenceClassification, } if is_tf_available() else {} ) snake_case__ = False snake_case__ = False def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase = TFEsmModelTester(self ) lowerCAmelCase = ConfigTester(self , config_class=_snake_case , hidden_size=37 ) def UpperCamelCase__ ( self ): """simple docstring""" self.config_tester.run_common_tests() def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_snake_case ) def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*_snake_case ) def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_snake_case ) def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_snake_case ) @slow def UpperCamelCase__ ( self ): """simple docstring""" for model_name in TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCAmelCase = TFEsmModel.from_pretrained(_snake_case ) self.assertIsNotNone(_snake_case ) @unittest.skip('Protein models do not support embedding resizing.' ) def UpperCamelCase__ ( self ): """simple docstring""" pass @unittest.skip('Protein models do not support embedding resizing.' ) def UpperCamelCase__ ( self ): """simple docstring""" pass def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase ,lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase = model_class(_snake_case ) assert isinstance(model.get_input_embeddings() , tf.keras.layers.Layer ) if model_class is TFEsmForMaskedLM: # Output embedding test differs from the main test because they're a matrix, not a layer lowerCAmelCase = model.get_bias() assert isinstance(_snake_case , _snake_case ) for k, v in name.items(): assert isinstance(_snake_case , tf.Variable ) else: lowerCAmelCase = model.get_output_embeddings() assert x is None lowerCAmelCase = model.get_bias() assert name is None @require_tf class a ( unittest.TestCase ): @slow def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase = TFEsmForMaskedLM.from_pretrained('facebook/esm2_t6_8M_UR50D' ) lowerCAmelCase = tf.constant([[0, 1, 2, 3, 4, 5]] ) lowerCAmelCase = model(_snake_case )[0] lowerCAmelCase = [1, 6, 33] self.assertEqual(list(output.numpy().shape ) , _snake_case ) # compare the actual values for a slice. lowerCAmelCase = tf.constant( [ [ [8.921_518, -10.589_814, -6.4_671_307], [-6.3_967_156, -13.911_377, -1.1_211_915], [-7.781_247, -13.951_557, -3.740_592], ] ] ) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-2 ) ) @slow def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase = TFEsmModel.from_pretrained('facebook/esm2_t6_8M_UR50D' ) lowerCAmelCase = tf.constant([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]] ) lowerCAmelCase = model(_snake_case )[0] # compare the actual values for a slice. lowerCAmelCase = tf.constant( [ [ [0.14_443_092, 0.54_125_327, 0.3_247_739], [0.30_340_484, 0.00_526_676, 0.31_077_722], [0.32_278_043, -0.24_987_096, 0.3_414_628], ] ] ) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-4 ) )
353
"""simple docstring""" def _SCREAMING_SNAKE_CASE (_UpperCAmelCase : list[int] , _UpperCAmelCase : str ): lowerCAmelCase = int(_UpperCAmelCase ) # Initialize Result lowerCAmelCase = [] # Traverse through all denomination for denomination in reversed(_UpperCAmelCase ): # Find denominations while int(_UpperCAmelCase ) >= int(_UpperCAmelCase ): total_value -= int(_UpperCAmelCase ) answer.append(_UpperCAmelCase ) # Append the "answers" array return answer # Driver Code if __name__ == "__main__": __UpperCamelCase : Any = [] __UpperCamelCase : List[Any] = '''0''' if ( input('''Do you want to enter your denominations ? (yY/n): ''').strip().lower() == "y" ): __UpperCamelCase : Any = int(input('''Enter the number of denominations you want to add: ''').strip()) for i in range(0, n): denominations.append(int(input(f'''Denomination {i}: ''').strip())) __UpperCamelCase : int = input('''Enter the change you want to make in Indian Currency: ''').strip() else: # All denominations of Indian Currency if user does not enter __UpperCamelCase : List[str] = [1, 2, 5, 10, 20, 50, 100, 500, 2000] __UpperCamelCase : Any = input('''Enter the change you want to make: ''').strip() if int(value) == 0 or int(value) < 0: print('''The total value cannot be zero or negative.''') else: print(f'''Following is minimal change for {value}: ''') __UpperCamelCase : List[str] = find_minimum_change(denominations, value) # Print result for i in range(len(answer)): print(answer[i], end=''' ''')
309
0
"""simple docstring""" import numpy as np import pandas as pd from sklearn.preprocessing import Normalizer from sklearn.svm import SVR from statsmodels.tsa.statespace.sarimax import SARIMAX def UpperCAmelCase__ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): """simple docstring""" A_ : Dict = np.array([[1, item, train_mtch[i]] for i, item in enumerate(__UpperCamelCase )] ) A_ : Optional[Any] = np.array(__UpperCamelCase ) A_ : Tuple = np.dot(np.dot(np.linalg.inv(np.dot(x.transpose() , __UpperCamelCase ) ) , x.transpose() ) , __UpperCamelCase ) return abs(beta[0] + test_dt[0] * beta[1] + test_mtch[0] + beta[2] ) def UpperCAmelCase__ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): """simple docstring""" A_ : Dict = (1, 2, 1) A_ : Optional[int] = (1, 1, 0, 7) A_ : str = SARIMAX( __UpperCamelCase , exog=__UpperCamelCase , order=__UpperCamelCase , seasonal_order=__UpperCamelCase ) A_ : List[str] = model.fit(disp=__UpperCamelCase , maxiter=600 , method='nm' ) A_ : Optional[int] = model_fit.predict(1 , len(__UpperCamelCase ) , exog=[test_match] ) return result[0] def UpperCAmelCase__ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): """simple docstring""" A_ : Union[str, Any] = SVR(kernel='rbf' , C=1 , gamma=0.1 , epsilon=0.1 ) regressor.fit(__UpperCamelCase , __UpperCamelCase ) A_ : int = regressor.predict(__UpperCamelCase ) return y_pred[0] def UpperCAmelCase__ ( _UpperCAmelCase ): """simple docstring""" train_user.sort() A_ : Tuple = np.percentile(__UpperCamelCase , 25 ) A_ : str = np.percentile(__UpperCamelCase , 75 ) A_ : Dict = qa - qa A_ : Union[str, Any] = qa - (iqr * 0.1) return low_lim def UpperCAmelCase__ ( _UpperCAmelCase , _UpperCAmelCase ): """simple docstring""" A_ : Any = 0 A_ : Dict = 0 for i in list_vote: if i > actual_result: A_ : str = not_safe + 1 else: if abs(abs(__UpperCamelCase ) - abs(__UpperCamelCase ) ) <= 0.1: safe += 1 else: not_safe += 1 return safe > not_safe if __name__ == "__main__": # data_input_df = pd.read_csv("ex_data.csv", header=None) lowerCamelCase_ : List[str] = [[1_82_31, 0.0, 1], [2_26_21, 1.0, 2], [1_56_75, 0.0, 3], [2_35_83, 1.0, 4]] lowerCamelCase_ : str = pd.DataFrame( data_input, columns=['total_user', 'total_even', 'days'] ) lowerCamelCase_ : Dict = Normalizer().fit_transform(data_input_df.values) # split data lowerCamelCase_ : Union[str, Any] = normalize_df[:, 2].tolist() lowerCamelCase_ : Any = normalize_df[:, 0].tolist() lowerCamelCase_ : int = normalize_df[:, 1].tolist() # for svr (input variable = total date and total match) lowerCamelCase_ : Optional[int] = normalize_df[:, [1, 2]].tolist() lowerCamelCase_ : Optional[int] = x[: len(x) - 1] lowerCamelCase_ : Optional[int] = x[len(x) - 1 :] # for linear regression & sarimax lowerCamelCase_ : Tuple = total_date[: len(total_date) - 1] lowerCamelCase_ : Any = total_user[: len(total_user) - 1] lowerCamelCase_ : int = total_match[: len(total_match) - 1] lowerCamelCase_ : int = total_date[len(total_date) - 1 :] lowerCamelCase_ : Optional[Any] = total_user[len(total_user) - 1 :] lowerCamelCase_ : str = total_match[len(total_match) - 1 :] # voting system with forecasting lowerCamelCase_ : str = [ linear_regression_prediction( trn_date, trn_user, trn_match, tst_date, tst_match ), sarimax_predictor(trn_user, trn_match, tst_match), support_vector_regressor(x_train, x_test, trn_user), ] # check the safety of today's data lowerCamelCase_ : List[Any] = '''''' if data_safety_checker(res_vote, tst_user) else '''not ''' print('Today\'s data is {not_str}safe.')
286
from datetime import datetime import requests from bsa import BeautifulSoup if __name__ == "__main__": __lowerCamelCase : str = input('''Enter image url: ''').strip() print(F"""Downloading image from {url} ...""") __lowerCamelCase : Any = BeautifulSoup(requests.get(url).content, '''html.parser''') # The image URL is in the content field of the first meta tag with property og:image __lowerCamelCase : List[Any] = soup.find('''meta''', {'''property''': '''og:image'''})['''content'''] __lowerCamelCase : Tuple = requests.get(image_url).content __lowerCamelCase : Union[str, Any] = F"""{datetime.now():%Y-%m-%d_%H:%M:%S}.jpg""" with open(file_name, '''wb''') as fp: fp.write(image_data) print(F"""Done. Image saved to disk as {file_name}.""")
219
0
import argparse import json import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinConfig, SwinForImageClassification def __lowerCamelCase ( lowerCamelCase__ : Tuple ): '''simple docstring''' lowerCamelCase = SwinConfig() lowerCamelCase = swin_name.split("""_""" ) lowerCamelCase = name_split[1] lowerCamelCase = int(name_split[4] ) lowerCamelCase = int(name_split[3][-1] ) if model_size == "tiny": lowerCamelCase = 96 lowerCamelCase = (2, 2, 6, 2) lowerCamelCase = (3, 6, 12, 24) elif model_size == "small": lowerCamelCase = 96 lowerCamelCase = (2, 2, 18, 2) lowerCamelCase = (3, 6, 12, 24) elif model_size == "base": lowerCamelCase = 128 lowerCamelCase = (2, 2, 18, 2) lowerCamelCase = (4, 8, 16, 32) else: lowerCamelCase = 192 lowerCamelCase = (2, 2, 18, 2) lowerCamelCase = (6, 12, 24, 48) if "in22k" in swin_name: lowerCamelCase = 21841 else: lowerCamelCase = 1000 lowerCamelCase = """huggingface/label-files""" lowerCamelCase = """imagenet-1k-id2label.json""" lowerCamelCase = json.load(open(hf_hub_download(lowerCamelCase__ , lowerCamelCase__ , repo_type="""dataset""" ) , """r""" ) ) lowerCamelCase = {int(lowerCamelCase__ ): v for k, v in idalabel.items()} lowerCamelCase = idalabel lowerCamelCase = {v: k for k, v in idalabel.items()} lowerCamelCase = img_size lowerCamelCase = num_classes lowerCamelCase = embed_dim lowerCamelCase = depths lowerCamelCase = num_heads lowerCamelCase = window_size return config def __lowerCamelCase ( lowerCamelCase__ : List[str] ): '''simple docstring''' if "patch_embed.proj" in name: lowerCamelCase = name.replace("""patch_embed.proj""" , """embeddings.patch_embeddings.projection""" ) if "patch_embed.norm" in name: lowerCamelCase = name.replace("""patch_embed.norm""" , """embeddings.norm""" ) if "layers" in name: lowerCamelCase = """encoder.""" + name if "attn.proj" in name: lowerCamelCase = name.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in name: lowerCamelCase = name.replace("""attn""" , """attention.self""" ) if "norm1" in name: lowerCamelCase = name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: lowerCamelCase = name.replace("""norm2""" , """layernorm_after""" ) if "mlp.fc1" in name: lowerCamelCase = name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: lowerCamelCase = name.replace("""mlp.fc2""" , """output.dense""" ) if name == "norm.weight": lowerCamelCase = """layernorm.weight""" if name == "norm.bias": lowerCamelCase = """layernorm.bias""" if "head" in name: lowerCamelCase = name.replace("""head""" , """classifier""" ) else: lowerCamelCase = """swin.""" + name return name def __lowerCamelCase ( lowerCamelCase__ : Optional[int] , lowerCamelCase__ : Optional[Any] ): '''simple docstring''' for key in orig_state_dict.copy().keys(): lowerCamelCase = orig_state_dict.pop(lowerCamelCase__ ) if "mask" in key: continue elif "qkv" in key: lowerCamelCase = key.split(""".""" ) lowerCamelCase = int(key_split[1] ) lowerCamelCase = int(key_split[3] ) lowerCamelCase = model.swin.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: lowerCamelCase = val[:dim, :] lowerCamelCase = val[ dim : dim * 2, : ] lowerCamelCase = val[-dim:, :] else: lowerCamelCase = val[ :dim ] lowerCamelCase = val[ dim : dim * 2 ] lowerCamelCase = val[ -dim: ] else: lowerCamelCase = val return orig_state_dict def __lowerCamelCase ( lowerCamelCase__ : Tuple , lowerCamelCase__ : str ): '''simple docstring''' lowerCamelCase = timm.create_model(lowerCamelCase__ , pretrained=lowerCamelCase__ ) timm_model.eval() lowerCamelCase = get_swin_config(lowerCamelCase__ ) lowerCamelCase = SwinForImageClassification(lowerCamelCase__ ) model.eval() lowerCamelCase = convert_state_dict(timm_model.state_dict() , lowerCamelCase__ ) model.load_state_dict(lowerCamelCase__ ) lowerCamelCase = """http://images.cocodataset.org/val2017/000000039769.jpg""" lowerCamelCase = AutoImageProcessor.from_pretrained("""microsoft/{}""".format(swin_name.replace("""_""" , """-""" ) ) ) lowerCamelCase = Image.open(requests.get(lowerCamelCase__ , stream=lowerCamelCase__ ).raw ) lowerCamelCase = image_processor(images=lowerCamelCase__ , return_tensors="""pt""" ) lowerCamelCase = timm_model(inputs["""pixel_values"""] ) lowerCamelCase = model(**lowerCamelCase__ ).logits assert torch.allclose(lowerCamelCase__ , lowerCamelCase__ , atol=1E-3 ) print(f'Saving model {swin_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(lowerCamelCase__ ) print(f'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(lowerCamelCase__ ) if __name__ == "__main__": UpperCAmelCase : Dict = argparse.ArgumentParser() # Required parameters parser.add_argument( "--swin_name", default="swin_tiny_patch4_window7_224", type=str, help="Name of the Swin timm model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) UpperCAmelCase : Tuple = parser.parse_args() convert_swin_checkpoint(args.swin_name, args.pytorch_dump_folder_path)
361
import math import tensorflow as tf from packaging import version def __lowerCamelCase ( lowerCamelCase__ : Optional[Any] ): '''simple docstring''' lowerCamelCase = tf.convert_to_tensor(lowerCamelCase__ ) lowerCamelCase = 0.5 * (1.0 + tf.math.erf(x / tf.cast(tf.sqrt(2.0 ) , x.dtype ) )) return x * cdf def __lowerCamelCase ( lowerCamelCase__ : Dict ): '''simple docstring''' lowerCamelCase = tf.convert_to_tensor(lowerCamelCase__ ) lowerCamelCase = tf.cast(math.pi , x.dtype ) lowerCamelCase = tf.cast(0.0_4_4_7_1_5 , x.dtype ) lowerCamelCase = 0.5 * (1.0 + tf.tanh(tf.sqrt(2.0 / pi ) * (x + coeff * tf.pow(lowerCamelCase__ , 3 )) )) return x * cdf def __lowerCamelCase ( lowerCamelCase__ : Any ): '''simple docstring''' lowerCamelCase = tf.convert_to_tensor(lowerCamelCase__ ) return x * tf.tanh(tf.math.softplus(lowerCamelCase__ ) ) def __lowerCamelCase ( lowerCamelCase__ : List[Any] ): '''simple docstring''' lowerCamelCase = tf.convert_to_tensor(lowerCamelCase__ ) lowerCamelCase = tf.cast(0.0_4_4_7_1_5 , x.dtype ) lowerCamelCase = tf.cast(0.7_9_7_8_8_4_5_6_0_8 , x.dtype ) return 0.5 * x * (1.0 + tf.tanh(x * coeffa * (1.0 + coeffa * x * x) )) def __lowerCamelCase ( lowerCamelCase__ : str ): '''simple docstring''' lowerCamelCase = tf.convert_to_tensor(lowerCamelCase__ ) lowerCamelCase = tf.cast(1.7_0_2 , x.dtype ) return x * tf.math.sigmoid(coeff * x ) def __lowerCamelCase ( lowerCamelCase__ : List[str] ): '''simple docstring''' return tf.clip_by_value(_gelu(lowerCamelCase__ ) , -10 , 10 ) def __lowerCamelCase ( lowerCamelCase__ : Any , lowerCamelCase__ : Optional[int]=-1 ): '''simple docstring''' lowerCamelCase , lowerCamelCase = tf.split(lowerCamelCase__ , 2 , axis=lowerCamelCase__ ) return a * tf.math.sigmoid(lowerCamelCase__ ) if version.parse(tf.version.VERSION) >= version.parse("2.4"): def __lowerCamelCase ( lowerCamelCase__ : List[str] ): '''simple docstring''' return tf.keras.activations.gelu(lowerCamelCase__ , approximate=lowerCamelCase__ ) UpperCAmelCase : Union[str, Any] = tf.keras.activations.gelu UpperCAmelCase : Optional[Any] = approximate_gelu_wrap else: UpperCAmelCase : List[Any] = _gelu UpperCAmelCase : str = _gelu_new UpperCAmelCase : Union[str, Any] = { "gelu": gelu, "gelu_10": gelu_aa, "gelu_fast": gelu_fast, "gelu_new": gelu_new, "glu": glu, "mish": mish, "quick_gelu": quick_gelu, "relu": tf.keras.activations.relu, "sigmoid": tf.keras.activations.sigmoid, "silu": tf.keras.activations.swish, "swish": tf.keras.activations.swish, "tanh": tf.keras.activations.tanh, } def __lowerCamelCase ( lowerCamelCase__ : List[Any] ): '''simple docstring''' if activation_string in ACTaFN: return ACTaFN[activation_string] else: raise KeyError(f'function {activation_string} not found in ACT2FN mapping {list(ACTaFN.keys() )}' )
66
0
import argparse import json from collections import OrderedDict import torch from huggingface_hub import cached_download, hf_hub_url from transformers import AutoImageProcessor, CvtConfig, CvtForImageClassification def a__ ( __UpperCamelCase ): SCREAMING_SNAKE_CASE_ = [] embed.append( ( F'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.weight''', F'''stage{idx}.patch_embed.proj.weight''', ) ) embed.append( ( F'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.bias''', F'''stage{idx}.patch_embed.proj.bias''', ) ) embed.append( ( F'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.weight''', F'''stage{idx}.patch_embed.norm.weight''', ) ) embed.append( ( F'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.bias''', F'''stage{idx}.patch_embed.norm.bias''', ) ) return embed def a__ ( __UpperCamelCase , __UpperCamelCase ): SCREAMING_SNAKE_CASE_ = [] attention_weights.append( ( F'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.convolution.weight''', F'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.conv.weight''', ) ) attention_weights.append( ( F'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.weight''', F'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.weight''', ) ) attention_weights.append( ( F'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.bias''', F'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.bias''', ) ) attention_weights.append( ( F'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_mean''', F'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_mean''', ) ) attention_weights.append( ( F'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_var''', F'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_var''', ) ) attention_weights.append( ( F'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.num_batches_tracked''', F'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.num_batches_tracked''', ) ) attention_weights.append( ( F'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.convolution.weight''', F'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.conv.weight''', ) ) attention_weights.append( ( F'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.weight''', F'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.weight''', ) ) attention_weights.append( ( F'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.bias''', F'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.bias''', ) ) attention_weights.append( ( F'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_mean''', F'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_mean''', ) ) attention_weights.append( ( F'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_var''', F'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_var''', ) ) attention_weights.append( ( F'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.num_batches_tracked''', F'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.num_batches_tracked''', ) ) attention_weights.append( ( F'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.convolution.weight''', F'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.conv.weight''', ) ) attention_weights.append( ( F'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.weight''', F'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.weight''', ) ) attention_weights.append( ( F'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.bias''', F'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.bias''', ) ) attention_weights.append( ( F'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_mean''', F'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_mean''', ) ) attention_weights.append( ( F'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_var''', F'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_var''', ) ) attention_weights.append( ( F'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.num_batches_tracked''', F'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.num_batches_tracked''', ) ) attention_weights.append( ( F'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.weight''', F'''stage{idx}.blocks.{cnt}.attn.proj_q.weight''', ) ) attention_weights.append( ( F'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.bias''', F'''stage{idx}.blocks.{cnt}.attn.proj_q.bias''', ) ) attention_weights.append( ( F'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.weight''', F'''stage{idx}.blocks.{cnt}.attn.proj_k.weight''', ) ) attention_weights.append( ( F'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.bias''', F'''stage{idx}.blocks.{cnt}.attn.proj_k.bias''', ) ) attention_weights.append( ( F'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.weight''', F'''stage{idx}.blocks.{cnt}.attn.proj_v.weight''', ) ) attention_weights.append( ( F'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.bias''', F'''stage{idx}.blocks.{cnt}.attn.proj_v.bias''', ) ) attention_weights.append( ( F'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.weight''', F'''stage{idx}.blocks.{cnt}.attn.proj.weight''', ) ) attention_weights.append( ( F'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.bias''', F'''stage{idx}.blocks.{cnt}.attn.proj.bias''', ) ) attention_weights.append( (F'''cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.weight''', F'''stage{idx}.blocks.{cnt}.mlp.fc1.weight''') ) attention_weights.append( (F'''cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.bias''', F'''stage{idx}.blocks.{cnt}.mlp.fc1.bias''') ) attention_weights.append( (F'''cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.weight''', F'''stage{idx}.blocks.{cnt}.mlp.fc2.weight''') ) attention_weights.append( (F'''cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.bias''', F'''stage{idx}.blocks.{cnt}.mlp.fc2.bias''') ) attention_weights.append( (F'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.weight''', F'''stage{idx}.blocks.{cnt}.norm1.weight''') ) attention_weights.append( (F'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.bias''', F'''stage{idx}.blocks.{cnt}.norm1.bias''') ) attention_weights.append( (F'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.weight''', F'''stage{idx}.blocks.{cnt}.norm2.weight''') ) attention_weights.append( (F'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.bias''', F'''stage{idx}.blocks.{cnt}.norm2.bias''') ) return attention_weights def a__ ( __UpperCamelCase ): SCREAMING_SNAKE_CASE_ = [] token.append((F'''cvt.encoder.stages.{idx}.cls_token''', "stage2.cls_token") ) return token def a__ ( ): SCREAMING_SNAKE_CASE_ = [] head.append(("layernorm.weight", "norm.weight") ) head.append(("layernorm.bias", "norm.bias") ) head.append(("classifier.weight", "head.weight") ) head.append(("classifier.bias", "head.bias") ) return head def a__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ): SCREAMING_SNAKE_CASE_ = "imagenet-1k-id2label.json" SCREAMING_SNAKE_CASE_ = 1_0_0_0 SCREAMING_SNAKE_CASE_ = "huggingface/label-files" SCREAMING_SNAKE_CASE_ = num_labels SCREAMING_SNAKE_CASE_ = json.load(open(cached_download(hf_hub_url(UpperCAmelCase__ , UpperCAmelCase__ , repo_type="dataset" ) ) , "r" ) ) SCREAMING_SNAKE_CASE_ = {int(UpperCAmelCase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE_ = idalabel SCREAMING_SNAKE_CASE_ = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE_ = SCREAMING_SNAKE_CASE_ = CvtConfig(num_labels=UpperCAmelCase__ , idalabel=UpperCAmelCase__ , labelaid=UpperCAmelCase__ ) # For depth size 13 (13 = 1+2+10) if cvt_model.rsplit("/" , 1 )[-1][4:6] == "13": SCREAMING_SNAKE_CASE_ = [1, 2, 1_0] # For depth size 21 (21 = 1+4+16) elif cvt_model.rsplit("/" , 1 )[-1][4:6] == "21": SCREAMING_SNAKE_CASE_ = [1, 4, 1_6] # For wide cvt (similar to wide-resnet) depth size 24 (w24 = 2 + 2 20) else: SCREAMING_SNAKE_CASE_ = [2, 2, 2_0] SCREAMING_SNAKE_CASE_ = [3, 1_2, 1_6] SCREAMING_SNAKE_CASE_ = [1_9_2, 7_6_8, 1_0_2_4] SCREAMING_SNAKE_CASE_ = CvtForImageClassification(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE_ = AutoImageProcessor.from_pretrained("facebook/convnext-base-224-22k-1k" ) SCREAMING_SNAKE_CASE_ = image_size SCREAMING_SNAKE_CASE_ = torch.load(UpperCAmelCase__ , map_location=torch.device("cpu" ) ) SCREAMING_SNAKE_CASE_ = OrderedDict() SCREAMING_SNAKE_CASE_ = [] for idx in range(len(config.depth ) ): if config.cls_token[idx]: SCREAMING_SNAKE_CASE_ = list_of_state_dict + cls_token(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE_ = list_of_state_dict + embeddings(UpperCAmelCase__ ) for cnt in range(config.depth[idx] ): SCREAMING_SNAKE_CASE_ = list_of_state_dict + attention(UpperCAmelCase__ , UpperCAmelCase__ ) SCREAMING_SNAKE_CASE_ = list_of_state_dict + final() for gg in list_of_state_dict: print(UpperCAmelCase__ ) for i in range(len(UpperCAmelCase__ ) ): SCREAMING_SNAKE_CASE_ = original_weights[list_of_state_dict[i][1]] model.load_state_dict(UpperCAmelCase__ ) model.save_pretrained(UpperCAmelCase__ ) image_processor.save_pretrained(UpperCAmelCase__ ) # Download the weights from zoo: https://1drv.ms/u/s!AhIXJn_J-blW9RzF3rMW7SsLHa8h?e=blQ0Al if __name__ == "__main__": A : List[str] = argparse.ArgumentParser() parser.add_argument( "--cvt_model", default="cvt-w24", type=str, help="Name of the cvt model you\'d like to convert.", ) parser.add_argument( "--image_size", default=3_84, type=int, help="Input Image Size", ) parser.add_argument( "--cvt_file_name", default=r"cvtmodels\CvT-w24-384x384-IN-22k.pth", type=str, help="Input Image Size", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) A : Tuple = parser.parse_args() convert_cvt_checkpoint(args.cvt_model, args.image_size, args.cvt_file_name, args.pytorch_dump_folder_path)
118
'''simple docstring''' import tempfile import unittest import numpy as np from diffusers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionPipeline, PNDMScheduler, ) from diffusers.utils.testing_utils import is_onnx_available, nightly, require_onnxruntime, require_torch_gpu from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class A__ ( _snake_case , unittest.TestCase ): lowercase = "hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline" def snake_case_ ( self , UpperCamelCase__=0 ) -> Tuple: '''simple docstring''' A_ = np.random.RandomState(UpperCamelCase__ ) A_ = { """prompt""": """A painting of a squirrel eating a burger""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 7.5, """output_type""": """numpy""", } return inputs def snake_case_ ( self ) -> Optional[Any]: '''simple docstring''' A_ = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) pipe.set_progress_bar_config(disable=UpperCamelCase__ ) A_ = self.get_dummy_inputs() A_ = pipe(**UpperCamelCase__ ).images A_ = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) A_ = np.array([0.65072, 0.58492, 0.48219, 0.55521, 0.53180, 0.55939, 0.50697, 0.39800, 0.46455] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def snake_case_ ( self ) -> List[str]: '''simple docstring''' A_ = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) A_ = PNDMScheduler.from_config(pipe.scheduler.config , skip_prk_steps=UpperCamelCase__ ) pipe.set_progress_bar_config(disable=UpperCamelCase__ ) A_ = self.get_dummy_inputs() A_ = pipe(**UpperCamelCase__ ).images A_ = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) A_ = np.array([0.65863, 0.59425, 0.49326, 0.56313, 0.53875, 0.56627, 0.51065, 0.39777, 0.46330] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def snake_case_ ( self ) -> List[str]: '''simple docstring''' A_ = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) A_ = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=UpperCamelCase__ ) A_ = self.get_dummy_inputs() A_ = pipe(**UpperCamelCase__ ).images A_ = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) A_ = np.array([0.53755, 0.60786, 0.47402, 0.49488, 0.51869, 0.49819, 0.47985, 0.38957, 0.44279] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def snake_case_ ( self ) -> Optional[int]: '''simple docstring''' A_ = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) A_ = EulerDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=UpperCamelCase__ ) A_ = self.get_dummy_inputs() A_ = pipe(**UpperCamelCase__ ).images A_ = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) A_ = np.array([0.53755, 0.60786, 0.47402, 0.49488, 0.51869, 0.49819, 0.47985, 0.38957, 0.44279] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def snake_case_ ( self ) -> List[Any]: '''simple docstring''' A_ = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) A_ = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=UpperCamelCase__ ) A_ = self.get_dummy_inputs() A_ = pipe(**UpperCamelCase__ ).images A_ = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) A_ = np.array([0.53817, 0.60812, 0.47384, 0.49530, 0.51894, 0.49814, 0.47984, 0.38958, 0.44271] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def snake_case_ ( self ) -> List[str]: '''simple docstring''' A_ = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) A_ = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=UpperCamelCase__ ) A_ = self.get_dummy_inputs() A_ = pipe(**UpperCamelCase__ ).images A_ = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) A_ = np.array([0.53895, 0.60808, 0.47933, 0.49608, 0.51886, 0.49950, 0.48053, 0.38957, 0.44200] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def snake_case_ ( self ) -> List[Any]: '''simple docstring''' A_ = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) pipe.set_progress_bar_config(disable=UpperCamelCase__ ) A_ = self.get_dummy_inputs() A_ = 3 * [inputs["""prompt"""]] # forward A_ = pipe(**UpperCamelCase__ ) A_ = output.images[0, -3:, -3:, -1] A_ = self.get_dummy_inputs() A_ = 3 * [inputs.pop("""prompt""" )] A_ = pipe.tokenizer( UpperCamelCase__ , padding="""max_length""" , max_length=pipe.tokenizer.model_max_length , truncation=UpperCamelCase__ , return_tensors="""np""" , ) A_ = text_inputs["""input_ids"""] A_ = pipe.text_encoder(input_ids=text_inputs.astype(np.intaa ) )[0] A_ = prompt_embeds # forward A_ = pipe(**UpperCamelCase__ ) A_ = output.images[0, -3:, -3:, -1] assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1e-4 def snake_case_ ( self ) -> List[str]: '''simple docstring''' A_ = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) pipe.set_progress_bar_config(disable=UpperCamelCase__ ) A_ = self.get_dummy_inputs() A_ = 3 * ["""this is a negative prompt"""] A_ = negative_prompt A_ = 3 * [inputs["""prompt"""]] # forward A_ = pipe(**UpperCamelCase__ ) A_ = output.images[0, -3:, -3:, -1] A_ = self.get_dummy_inputs() A_ = 3 * [inputs.pop("""prompt""" )] A_ = [] for p in [prompt, negative_prompt]: A_ = pipe.tokenizer( UpperCamelCase__ , padding="""max_length""" , max_length=pipe.tokenizer.model_max_length , truncation=UpperCamelCase__ , return_tensors="""np""" , ) A_ = text_inputs["""input_ids"""] embeds.append(pipe.text_encoder(input_ids=text_inputs.astype(np.intaa ) )[0] ) A_ , A_ = embeds # forward A_ = pipe(**UpperCamelCase__ ) A_ = output.images[0, -3:, -3:, -1] assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1e-4 @nightly @require_onnxruntime @require_torch_gpu class A__ ( unittest.TestCase ): @property def snake_case_ ( self ) -> List[Any]: '''simple docstring''' return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def snake_case_ ( self ) -> Union[str, Any]: '''simple docstring''' A_ = ort.SessionOptions() A_ = False return options def snake_case_ ( self ) -> Optional[int]: '''simple docstring''' # using the PNDM scheduler by default A_ = OnnxStableDiffusionPipeline.from_pretrained( """CompVis/stable-diffusion-v1-4""" , revision="""onnx""" , safety_checker=UpperCamelCase__ , feature_extractor=UpperCamelCase__ , provider=self.gpu_provider , sess_options=self.gpu_options , ) sd_pipe.set_progress_bar_config(disable=UpperCamelCase__ ) A_ = """A painting of a squirrel eating a burger""" np.random.seed(0 ) A_ = sd_pipe([prompt] , guidance_scale=6.0 , num_inference_steps=10 , output_type="""np""" ) A_ = output.images A_ = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) A_ = np.array([0.0452, 0.0390, 0.0087, 0.0350, 0.0617, 0.0364, 0.0544, 0.0523, 0.0720] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def snake_case_ ( self ) -> Any: '''simple docstring''' A_ = DDIMScheduler.from_pretrained( """runwayml/stable-diffusion-v1-5""" , subfolder="""scheduler""" , revision="""onnx""" ) A_ = OnnxStableDiffusionPipeline.from_pretrained( """runwayml/stable-diffusion-v1-5""" , revision="""onnx""" , scheduler=UpperCamelCase__ , safety_checker=UpperCamelCase__ , feature_extractor=UpperCamelCase__ , provider=self.gpu_provider , sess_options=self.gpu_options , ) sd_pipe.set_progress_bar_config(disable=UpperCamelCase__ ) A_ = """open neural network exchange""" A_ = np.random.RandomState(0 ) A_ = sd_pipe([prompt] , guidance_scale=7.5 , num_inference_steps=10 , generator=UpperCamelCase__ , output_type="""np""" ) A_ = output.images A_ = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) A_ = np.array([0.2867, 0.1974, 0.1481, 0.7294, 0.7251, 0.6667, 0.4194, 0.5642, 0.6486] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def snake_case_ ( self ) -> Dict: '''simple docstring''' A_ = LMSDiscreteScheduler.from_pretrained( """runwayml/stable-diffusion-v1-5""" , subfolder="""scheduler""" , revision="""onnx""" ) A_ = OnnxStableDiffusionPipeline.from_pretrained( """runwayml/stable-diffusion-v1-5""" , revision="""onnx""" , scheduler=UpperCamelCase__ , safety_checker=UpperCamelCase__ , feature_extractor=UpperCamelCase__ , provider=self.gpu_provider , sess_options=self.gpu_options , ) sd_pipe.set_progress_bar_config(disable=UpperCamelCase__ ) A_ = """open neural network exchange""" A_ = np.random.RandomState(0 ) A_ = sd_pipe([prompt] , guidance_scale=7.5 , num_inference_steps=10 , generator=UpperCamelCase__ , output_type="""np""" ) A_ = output.images A_ = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) A_ = np.array([0.2306, 0.1959, 0.1593, 0.6549, 0.6394, 0.5408, 0.5065, 0.6010, 0.6161] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def snake_case_ ( self ) -> Optional[Any]: '''simple docstring''' A_ = 0 def test_callback_fn(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> None: A_ = True nonlocal number_of_steps number_of_steps += 1 if step == 0: assert latents.shape == (1, 4, 64, 64) A_ = latents[0, -3:, -3:, -1] A_ = np.array( [-0.6772, -0.3835, -1.2456, 0.1905, -1.0974, 0.6967, -1.9353, 0.0178, 1.0167] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 1e-3 elif step == 5: assert latents.shape == (1, 4, 64, 64) A_ = latents[0, -3:, -3:, -1] A_ = np.array( [-0.3351, 0.2241, -0.1837, -0.2325, -0.6577, 0.3393, -0.0241, 0.5899, 1.3875] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 1e-3 A_ = False A_ = OnnxStableDiffusionPipeline.from_pretrained( """runwayml/stable-diffusion-v1-5""" , revision="""onnx""" , safety_checker=UpperCamelCase__ , feature_extractor=UpperCamelCase__ , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=UpperCamelCase__ ) A_ = """Andromeda galaxy in a bottle""" A_ = np.random.RandomState(0 ) pipe( prompt=UpperCamelCase__ , num_inference_steps=5 , guidance_scale=7.5 , generator=UpperCamelCase__ , callback=UpperCamelCase__ , callback_steps=1 , ) assert test_callback_fn.has_been_called assert number_of_steps == 6 def snake_case_ ( self ) -> Tuple: '''simple docstring''' A_ = OnnxStableDiffusionPipeline.from_pretrained( """runwayml/stable-diffusion-v1-5""" , revision="""onnx""" , safety_checker=UpperCamelCase__ , feature_extractor=UpperCamelCase__ , provider=self.gpu_provider , sess_options=self.gpu_options , ) assert isinstance(UpperCamelCase__ , UpperCamelCase__ ) assert pipe.safety_checker is None A_ = pipe("""example prompt""" , num_inference_steps=2 ).images[0] assert image is not None # check that there's no error when saving a pipeline with one of the models being None with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(UpperCamelCase__ ) A_ = OnnxStableDiffusionPipeline.from_pretrained(UpperCamelCase__ ) # sanity check that the pipeline still works assert pipe.safety_checker is None A_ = pipe("""example prompt""" , num_inference_steps=2 ).images[0] assert image is not None
162
0
from math import pow, sqrt def SCREAMING_SNAKE_CASE__ ( *_UpperCAmelCase ) -> bool: '''simple docstring''' lowerCAmelCase : List[str] = len(a__ ) > 0 and all(value > 0.0 for value in values ) return result def SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase, _UpperCAmelCase ) -> float | ValueError: '''simple docstring''' return ( round(sqrt(molar_mass_a / molar_mass_a ), 6 ) if validate(a__, a__ ) else ValueError('Input Error: Molar mass values must greater than 0.' ) ) def SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) -> float | ValueError: '''simple docstring''' return ( round(effusion_rate * sqrt(molar_mass_a / molar_mass_a ), 6 ) if validate(a__, a__, a__ ) else ValueError( 'Input Error: Molar mass and effusion rate values must greater than 0.' ) ) def SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) -> float | ValueError: '''simple docstring''' return ( round(effusion_rate / sqrt(molar_mass_a / molar_mass_a ), 6 ) if validate(a__, a__, a__ ) else ValueError( 'Input Error: Molar mass and effusion rate values must greater than 0.' ) ) def SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) -> float | ValueError: '''simple docstring''' return ( round(molar_mass / pow(effusion_rate_a / effusion_rate_a, 2 ), 6 ) if validate(a__, a__, a__ ) else ValueError( 'Input Error: Molar mass and effusion rate values must greater than 0.' ) ) def SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) -> float | ValueError: '''simple docstring''' return ( round(pow(effusion_rate_a / effusion_rate_a, 2 ) / molar_mass, 6 ) if validate(a__, a__, a__ ) else ValueError( 'Input Error: Molar mass and effusion rate values must greater than 0.' ) )
361
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices __A : Any = logging.get_logger(__name__) __A : Union[str, Any] = { '''shi-labs/dinat-mini-in1k-224''': '''https://huggingface.co/shi-labs/dinat-mini-in1k-224/resolve/main/config.json''', # See all Dinat models at https://huggingface.co/models?filter=dinat } class __A ( lowerCAmelCase , lowerCAmelCase ): lowerCAmelCase_ : Optional[Any] = "dinat" lowerCAmelCase_ : Dict = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self : Union[str, Any] , UpperCAmelCase_ : Optional[Any]=4 , UpperCAmelCase_ : Tuple=3 , UpperCAmelCase_ : Optional[Any]=64 , UpperCAmelCase_ : List[Any]=[3, 4, 6, 5] , UpperCAmelCase_ : Dict=[2, 4, 8, 16] , UpperCAmelCase_ : Dict=7 , UpperCAmelCase_ : Dict=[[1, 8, 1], [1, 4, 1, 4], [1, 2, 1, 2, 1, 2], [1, 1, 1, 1, 1]] , UpperCAmelCase_ : int=3.0 , UpperCAmelCase_ : int=True , UpperCAmelCase_ : Optional[Any]=0.0 , UpperCAmelCase_ : Optional[Any]=0.0 , UpperCAmelCase_ : List[str]=0.1 , UpperCAmelCase_ : List[str]="gelu" , UpperCAmelCase_ : List[Any]=0.02 , UpperCAmelCase_ : List[str]=1E-5 , UpperCAmelCase_ : Optional[int]=0.0 , UpperCAmelCase_ : int=None , UpperCAmelCase_ : Optional[int]=None , **UpperCAmelCase_ : Union[str, Any] , ): super().__init__(**UpperCAmelCase_ ) lowerCAmelCase : Union[str, Any] = patch_size lowerCAmelCase : Optional[Any] = num_channels lowerCAmelCase : str = embed_dim lowerCAmelCase : Any = depths lowerCAmelCase : List[Any] = len(UpperCAmelCase_ ) lowerCAmelCase : Union[str, Any] = num_heads lowerCAmelCase : Tuple = kernel_size lowerCAmelCase : List[str] = dilations lowerCAmelCase : Any = mlp_ratio lowerCAmelCase : Optional[int] = qkv_bias lowerCAmelCase : int = hidden_dropout_prob lowerCAmelCase : str = attention_probs_dropout_prob lowerCAmelCase : Union[str, Any] = drop_path_rate lowerCAmelCase : Any = hidden_act lowerCAmelCase : Union[str, Any] = layer_norm_eps lowerCAmelCase : Optional[int] = initializer_range # we set the hidden_size attribute in order to make Dinat work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model lowerCAmelCase : Union[str, Any] = int(embed_dim * 2 ** (len(UpperCAmelCase_ ) - 1) ) lowerCAmelCase : int = layer_scale_init_value lowerCAmelCase : Optional[Any] = ['stem'] + [f"stage{idx}" for idx in range(1 , len(UpperCAmelCase_ ) + 1 )] lowerCAmelCase , lowerCAmelCase : Tuple = get_aligned_output_features_output_indices( out_features=UpperCAmelCase_ , out_indices=UpperCAmelCase_ , stage_names=self.stage_names )
323
0
import json from typing import Iterator, List, Union from tokenizers import AddedToken, Regex, Tokenizer, decoders, normalizers, pre_tokenizers, trainers from tokenizers.implementations.base_tokenizer import BaseTokenizer from tokenizers.models import Unigram from tokenizers.processors import TemplateProcessing class _lowercase ( lowerCAmelCase ): """simple docstring""" def __init__(self , lowerCamelCase_ = "▁" , lowerCamelCase_ = True , lowerCamelCase_ = "<unk>" , lowerCamelCase_ = "</s>" , lowerCamelCase_ = "<pad>" , ): """simple docstring""" a = { "pad": {"id": 0, "token": pad_token}, "eos": {"id": 1, "token": eos_token}, "unk": {"id": 2, "token": unk_token}, } a = [None] * len(self.special_tokens ) for token_dict in self.special_tokens.values(): a = token_dict["token"] a = Tokenizer(Unigram() ) a = normalizers.Sequence( [ normalizers.Nmt(), normalizers.NFKC(), normalizers.Replace(Regex(" {2,}" ) , " " ), normalizers.Lowercase(), ] ) a = pre_tokenizers.Sequence( [ pre_tokenizers.Metaspace(replacement=_SCREAMING_SNAKE_CASE , add_prefix_space=_SCREAMING_SNAKE_CASE ), pre_tokenizers.Digits(individual_digits=_SCREAMING_SNAKE_CASE ), pre_tokenizers.Punctuation(), ] ) a = decoders.Metaspace(replacement=_SCREAMING_SNAKE_CASE , add_prefix_space=_SCREAMING_SNAKE_CASE ) a = TemplateProcessing( single=F'''$A {self.special_tokens['eos']['token']}''' , special_tokens=[(self.special_tokens["eos"]["token"], self.special_tokens["eos"]["id"])] , ) a = { "model": "SentencePieceUnigram", "replacement": replacement, "add_prefix_space": add_prefix_space, } super().__init__(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def UpperCamelCase_ (self , lowerCamelCase_ , lowerCamelCase_ = 8000 , lowerCamelCase_ = True , ): """simple docstring""" a = trainers.UnigramTrainer( vocab_size=_SCREAMING_SNAKE_CASE , special_tokens=self.special_tokens_list , show_progress=_SCREAMING_SNAKE_CASE , ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): a = [files] self._tokenizer.train(_SCREAMING_SNAKE_CASE , trainer=_SCREAMING_SNAKE_CASE ) self.add_unk_id() def UpperCamelCase_ (self , lowerCamelCase_ , lowerCamelCase_ = 8000 , lowerCamelCase_ = True , ): """simple docstring""" a = trainers.UnigramTrainer( vocab_size=_SCREAMING_SNAKE_CASE , special_tokens=self.special_tokens_list , show_progress=_SCREAMING_SNAKE_CASE , ) self._tokenizer.train_from_iterator(_SCREAMING_SNAKE_CASE , trainer=_SCREAMING_SNAKE_CASE ) self.add_unk_id() def UpperCamelCase_ (self ): """simple docstring""" a = json.loads(self._tokenizer.to_str() ) a = self.special_tokens["unk"]["id"] a = Tokenizer.from_str(json.dumps(_SCREAMING_SNAKE_CASE ) )
227
from urllib.parse import quote import pytest from datasets.utils.hub import hf_hub_url @pytest.mark.parametrize('repo_id' , ['canonical_dataset_name', 'org-name/dataset-name'] ) @pytest.mark.parametrize('path' , ['filename.csv', 'filename with blanks.csv'] ) @pytest.mark.parametrize('revision' , [None, 'v2'] ) def lowerCAmelCase__ ( a__: Any , a__: Tuple , a__: Union[str, Any] ) -> Tuple: '''simple docstring''' _UpperCAmelCase = hf_hub_url(repo_id=a__ , path=a__ , revision=a__ ) assert url == F'''https://huggingface.co/datasets/{repo_id}/resolve/{revision or "main"}/{quote(a__ )}'''
329
0
"""simple docstring""" import argparse import json import torch from diffusers import DDPMScheduler, LDMPipeline, UNetaDModel, VQModel def _snake_case ( lowercase__ : Any , lowercase__ : List[Any]=1 ) -> List[str]: '''simple docstring''' if n_shave_prefix_segments >= 0: return ".".join(path.split(""".""" )[n_shave_prefix_segments:] ) else: return ".".join(path.split(""".""" )[:n_shave_prefix_segments] ) def _snake_case ( lowercase__ : Dict , lowercase__ : Optional[int]=0 ) -> Union[str, Any]: '''simple docstring''' lowerCAmelCase_ :List[Any] = [] for old_item in old_list: lowerCAmelCase_ :Dict = old_item.replace("""in_layers.0""" , """norm1""" ) lowerCAmelCase_ :Dict = new_item.replace("""in_layers.2""" , """conv1""" ) lowerCAmelCase_ :Union[str, Any] = new_item.replace("""out_layers.0""" , """norm2""" ) lowerCAmelCase_ :str = new_item.replace("""out_layers.3""" , """conv2""" ) lowerCAmelCase_ :List[str] = new_item.replace("""emb_layers.1""" , """time_emb_proj""" ) lowerCAmelCase_ :Optional[Any] = new_item.replace("""skip_connection""" , """conv_shortcut""" ) lowerCAmelCase_ :Dict = shave_segments(lowercase__ , n_shave_prefix_segments=lowercase__ ) mapping.append({"""old""": old_item, """new""": new_item} ) return mapping def _snake_case ( lowercase__ : Any , lowercase__ : List[str]=0 ) -> Optional[Any]: '''simple docstring''' lowerCAmelCase_ :Any = [] for old_item in old_list: lowerCAmelCase_ :Optional[int] = old_item lowerCAmelCase_ :Any = new_item.replace("""norm.weight""" , """group_norm.weight""" ) lowerCAmelCase_ :Optional[int] = new_item.replace("""norm.bias""" , """group_norm.bias""" ) lowerCAmelCase_ :Union[str, Any] = new_item.replace("""proj_out.weight""" , """proj_attn.weight""" ) lowerCAmelCase_ :int = new_item.replace("""proj_out.bias""" , """proj_attn.bias""" ) lowerCAmelCase_ :Optional[Any] = shave_segments(lowercase__ , n_shave_prefix_segments=lowercase__ ) mapping.append({"""old""": old_item, """new""": new_item} ) return mapping def _snake_case ( lowercase__ : Tuple , lowercase__ : Union[str, Any] , lowercase__ : Union[str, Any] , lowercase__ : Optional[int]=None , lowercase__ : str=None , lowercase__ : List[Any]=None ) -> Optional[int]: '''simple docstring''' assert isinstance(lowercase__ , lowercase__ ), "Paths should be a list of dicts containing 'old' and 'new' keys." # Splits the attention layers into three variables. if attention_paths_to_split is not None: for path, path_map in attention_paths_to_split.items(): lowerCAmelCase_ :List[Any] = old_checkpoint[path] lowerCAmelCase_ :Optional[Any] = old_tensor.shape[0] // 3 lowerCAmelCase_ :Any = (-1, channels) if len(old_tensor.shape ) == 3 else (-1) lowerCAmelCase_ :int = old_tensor.shape[0] // config["""num_head_channels"""] // 3 lowerCAmelCase_ :Tuple = old_tensor.reshape((num_heads, 3 * channels // num_heads) + old_tensor.shape[1:] ) lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ :Dict = old_tensor.split(channels // num_heads , dim=1 ) lowerCAmelCase_ :str = query.reshape(lowercase__ ) lowerCAmelCase_ :int = key.reshape(lowercase__ ) lowerCAmelCase_ :List[str] = value.reshape(lowercase__ ) for path in paths: lowerCAmelCase_ :int = path["""new"""] # These have already been assigned if attention_paths_to_split is not None and new_path in attention_paths_to_split: continue # Global renaming happens here lowerCAmelCase_ :Tuple = new_path.replace("""middle_block.0""" , """mid_block.resnets.0""" ) lowerCAmelCase_ :Dict = new_path.replace("""middle_block.1""" , """mid_block.attentions.0""" ) lowerCAmelCase_ :int = new_path.replace("""middle_block.2""" , """mid_block.resnets.1""" ) if additional_replacements is not None: for replacement in additional_replacements: lowerCAmelCase_ :List[Any] = new_path.replace(replacement["""old"""] , replacement["""new"""] ) # proj_attn.weight has to be converted from conv 1D to linear if "proj_attn.weight" in new_path: lowerCAmelCase_ :Dict = old_checkpoint[path["""old"""]][:, :, 0] else: lowerCAmelCase_ :str = old_checkpoint[path["""old"""]] def _snake_case ( lowercase__ : Union[str, Any] , lowercase__ : Optional[Any] ) -> int: '''simple docstring''' lowerCAmelCase_ :Tuple = {} lowerCAmelCase_ :List[Any] = checkpoint["""time_embed.0.weight"""] lowerCAmelCase_ :Tuple = checkpoint["""time_embed.0.bias"""] lowerCAmelCase_ :int = checkpoint["""time_embed.2.weight"""] lowerCAmelCase_ :Optional[int] = checkpoint["""time_embed.2.bias"""] lowerCAmelCase_ :Tuple = checkpoint["""input_blocks.0.0.weight"""] lowerCAmelCase_ :Tuple = checkpoint["""input_blocks.0.0.bias"""] lowerCAmelCase_ :Tuple = checkpoint["""out.0.weight"""] lowerCAmelCase_ :str = checkpoint["""out.0.bias"""] lowerCAmelCase_ :Dict = checkpoint["""out.2.weight"""] lowerCAmelCase_ :int = checkpoint["""out.2.bias"""] # Retrieves the keys for the input blocks only lowerCAmelCase_ :Dict = len({""".""".join(layer.split(""".""" )[:2] ) for layer in checkpoint if """input_blocks""" in layer} ) lowerCAmelCase_ :Optional[int] = { layer_id: [key for key in checkpoint if f"""input_blocks.{layer_id}""" in key] for layer_id in range(lowercase__ ) } # Retrieves the keys for the middle blocks only lowerCAmelCase_ :Optional[int] = len({""".""".join(layer.split(""".""" )[:2] ) for layer in checkpoint if """middle_block""" in layer} ) lowerCAmelCase_ :Union[str, Any] = { layer_id: [key for key in checkpoint if f"""middle_block.{layer_id}""" in key] for layer_id in range(lowercase__ ) } # Retrieves the keys for the output blocks only lowerCAmelCase_ :List[Any] = len({""".""".join(layer.split(""".""" )[:2] ) for layer in checkpoint if """output_blocks""" in layer} ) lowerCAmelCase_ :Union[str, Any] = { layer_id: [key for key in checkpoint if f"""output_blocks.{layer_id}""" in key] for layer_id in range(lowercase__ ) } for i in range(1 , lowercase__ ): lowerCAmelCase_ :Any = (i - 1) // (config["""num_res_blocks"""] + 1) lowerCAmelCase_ :Any = (i - 1) % (config["""num_res_blocks"""] + 1) lowerCAmelCase_ :Optional[int] = [key for key in input_blocks[i] if f"""input_blocks.{i}.0""" in key] lowerCAmelCase_ :Optional[int] = [key for key in input_blocks[i] if f"""input_blocks.{i}.1""" in key] if f"""input_blocks.{i}.0.op.weight""" in checkpoint: lowerCAmelCase_ :Tuple = checkpoint[ f"""input_blocks.{i}.0.op.weight""" ] lowerCAmelCase_ :Optional[Any] = checkpoint[ f"""input_blocks.{i}.0.op.bias""" ] continue lowerCAmelCase_ :Tuple = renew_resnet_paths(lowercase__ ) lowerCAmelCase_ :int = {"""old""": f"""input_blocks.{i}.0""", """new""": f"""down_blocks.{block_id}.resnets.{layer_in_block_id}"""} lowerCAmelCase_ :Dict = {"""old""": """resnets.2.op""", """new""": """downsamplers.0.op"""} assign_to_checkpoint( lowercase__ , lowercase__ , lowercase__ , additional_replacements=[meta_path, resnet_op] , config=lowercase__ ) if len(lowercase__ ): lowerCAmelCase_ :Optional[Any] = renew_attention_paths(lowercase__ ) lowerCAmelCase_ :List[Any] = { """old""": f"""input_blocks.{i}.1""", """new""": f"""down_blocks.{block_id}.attentions.{layer_in_block_id}""", } lowerCAmelCase_ :List[str] = { f"""input_blocks.{i}.1.qkv.bias""": { """key""": f"""down_blocks.{block_id}.attentions.{layer_in_block_id}.key.bias""", """query""": f"""down_blocks.{block_id}.attentions.{layer_in_block_id}.query.bias""", """value""": f"""down_blocks.{block_id}.attentions.{layer_in_block_id}.value.bias""", }, f"""input_blocks.{i}.1.qkv.weight""": { """key""": f"""down_blocks.{block_id}.attentions.{layer_in_block_id}.key.weight""", """query""": f"""down_blocks.{block_id}.attentions.{layer_in_block_id}.query.weight""", """value""": f"""down_blocks.{block_id}.attentions.{layer_in_block_id}.value.weight""", }, } assign_to_checkpoint( lowercase__ , lowercase__ , lowercase__ , additional_replacements=[meta_path] , attention_paths_to_split=lowercase__ , config=lowercase__ , ) lowerCAmelCase_ :List[str] = middle_blocks[0] lowerCAmelCase_ :int = middle_blocks[1] lowerCAmelCase_ :Tuple = middle_blocks[2] lowerCAmelCase_ :Dict = renew_resnet_paths(lowercase__ ) assign_to_checkpoint(lowercase__ , lowercase__ , lowercase__ , config=lowercase__ ) lowerCAmelCase_ :List[str] = renew_resnet_paths(lowercase__ ) assign_to_checkpoint(lowercase__ , lowercase__ , lowercase__ , config=lowercase__ ) lowerCAmelCase_ :Optional[int] = renew_attention_paths(lowercase__ ) lowerCAmelCase_ :List[Any] = { """middle_block.1.qkv.bias""": { """key""": """mid_block.attentions.0.key.bias""", """query""": """mid_block.attentions.0.query.bias""", """value""": """mid_block.attentions.0.value.bias""", }, """middle_block.1.qkv.weight""": { """key""": """mid_block.attentions.0.key.weight""", """query""": """mid_block.attentions.0.query.weight""", """value""": """mid_block.attentions.0.value.weight""", }, } assign_to_checkpoint( lowercase__ , lowercase__ , lowercase__ , attention_paths_to_split=lowercase__ , config=lowercase__ ) for i in range(lowercase__ ): lowerCAmelCase_ :str = i // (config["""num_res_blocks"""] + 1) lowerCAmelCase_ :str = i % (config["""num_res_blocks"""] + 1) lowerCAmelCase_ :List[Any] = [shave_segments(lowercase__ , 2 ) for name in output_blocks[i]] lowerCAmelCase_ :Optional[Any] = {} for layer in output_block_layers: lowerCAmelCase_ , lowerCAmelCase_ :Optional[int] = layer.split(""".""" )[0], shave_segments(lowercase__ , 1 ) if layer_id in output_block_list: output_block_list[layer_id].append(lowercase__ ) else: lowerCAmelCase_ :Dict = [layer_name] if len(lowercase__ ) > 1: lowerCAmelCase_ :str = [key for key in output_blocks[i] if f"""output_blocks.{i}.0""" in key] lowerCAmelCase_ :Dict = [key for key in output_blocks[i] if f"""output_blocks.{i}.1""" in key] lowerCAmelCase_ :List[str] = renew_resnet_paths(lowercase__ ) lowerCAmelCase_ :Optional[Any] = renew_resnet_paths(lowercase__ ) lowerCAmelCase_ :List[str] = {"""old""": f"""output_blocks.{i}.0""", """new""": f"""up_blocks.{block_id}.resnets.{layer_in_block_id}"""} assign_to_checkpoint(lowercase__ , lowercase__ , lowercase__ , additional_replacements=[meta_path] , config=lowercase__ ) if ["conv.weight", "conv.bias"] in output_block_list.values(): lowerCAmelCase_ :int = list(output_block_list.values() ).index(["""conv.weight""", """conv.bias"""] ) lowerCAmelCase_ :int = checkpoint[ f"""output_blocks.{i}.{index}.conv.weight""" ] lowerCAmelCase_ :Optional[Any] = checkpoint[ f"""output_blocks.{i}.{index}.conv.bias""" ] # Clear attentions as they have been attributed above. if len(lowercase__ ) == 2: lowerCAmelCase_ :str = [] if len(lowercase__ ): lowerCAmelCase_ :List[Any] = renew_attention_paths(lowercase__ ) lowerCAmelCase_ :int = { """old""": f"""output_blocks.{i}.1""", """new""": f"""up_blocks.{block_id}.attentions.{layer_in_block_id}""", } lowerCAmelCase_ :Optional[int] = { f"""output_blocks.{i}.1.qkv.bias""": { """key""": f"""up_blocks.{block_id}.attentions.{layer_in_block_id}.key.bias""", """query""": f"""up_blocks.{block_id}.attentions.{layer_in_block_id}.query.bias""", """value""": f"""up_blocks.{block_id}.attentions.{layer_in_block_id}.value.bias""", }, f"""output_blocks.{i}.1.qkv.weight""": { """key""": f"""up_blocks.{block_id}.attentions.{layer_in_block_id}.key.weight""", """query""": f"""up_blocks.{block_id}.attentions.{layer_in_block_id}.query.weight""", """value""": f"""up_blocks.{block_id}.attentions.{layer_in_block_id}.value.weight""", }, } assign_to_checkpoint( lowercase__ , lowercase__ , lowercase__ , additional_replacements=[meta_path] , attention_paths_to_split=to_split if any("""qkv""" in key for key in attentions ) else None , config=lowercase__ , ) else: lowerCAmelCase_ :List[str] = renew_resnet_paths(lowercase__ , n_shave_prefix_segments=1 ) for path in resnet_0_paths: lowerCAmelCase_ :Optional[int] = """.""".join(["""output_blocks""", str(lowercase__ ), path["""old"""]] ) lowerCAmelCase_ :Optional[int] = """.""".join(["""up_blocks""", str(lowercase__ ), """resnets""", str(lowercase__ ), path["""new"""]] ) lowerCAmelCase_ :Optional[int] = checkpoint[old_path] return new_checkpoint if __name__ == "__main__": __UpperCAmelCase = argparse.ArgumentParser() parser.add_argument( '--checkpoint_path', default=None, type=str, required=True, help='Path to the checkpoint to convert.' ) parser.add_argument( '--config_file', default=None, type=str, required=True, help='The config json file corresponding to the architecture.', ) parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') __UpperCAmelCase = parser.parse_args() __UpperCAmelCase = torch.load(args.checkpoint_path) with open(args.config_file) as f: __UpperCAmelCase = json.loads(f.read()) __UpperCAmelCase = convert_ldm_checkpoint(checkpoint, config) if "ldm" in config: del config["ldm"] __UpperCAmelCase = UNetaDModel(**config) model.load_state_dict(converted_checkpoint) try: __UpperCAmelCase = DDPMScheduler.from_config('/'.join(args.checkpoint_path.split('/')[:-1])) __UpperCAmelCase = VQModel.from_pretrained('/'.join(args.checkpoint_path.split('/')[:-1])) __UpperCAmelCase = LDMPipeline(unet=model, scheduler=scheduler, vae=vqvae) pipe.save_pretrained(args.dump_path) except: # noqa: E722 model.save_pretrained(args.dump_path)
1
"""simple docstring""" import baseaa import io import json import os from copy import deepcopy from ..optimizer import AcceleratedOptimizer from ..scheduler import AcceleratedScheduler class _SCREAMING_SNAKE_CASE : def __init__( self , __A ) -> Union[str, Any]: if isinstance(__A , __A ): # Don't modify user's data should they want to reuse it (e.g. in tests), because once we # modified it, it will not be accepted here again, since `auto` values would have been overridden lowerCAmelCase_ :Tuple = deepcopy(__A ) elif os.path.exists(__A ): with io.open(__A , """r""" , encoding="""utf-8""" ) as f: lowerCAmelCase_ :str = json.load(__A ) else: try: lowerCAmelCase_ :Dict = baseaa.urlsafe_baadecode(__A ).decode("""utf-8""" ) lowerCAmelCase_ :int = json.loads(__A ) except (UnicodeDecodeError, AttributeError, ValueError): raise ValueError( f"""Expected a string path to an existing deepspeed config, or a dictionary, or a base64 encoded string. Received: {config_file_or_dict}""" ) lowerCAmelCase_ :Optional[Any] = config self.set_stage_and_offload() def __lowerCAmelCase ( self ) -> Tuple: # zero stage - this is done as early as possible, before model is created, to allow # ``is_deepspeed_zero3_enabled`` query and getting to the early deepspeed config object # during ``zero.Init()`` which needs to know the dtype, and some other hparams. lowerCAmelCase_ :Tuple = self.get_value("""zero_optimization.stage""" , -1 ) # offload lowerCAmelCase_ :Dict = False if self.is_zeroa() or self.is_zeroa(): lowerCAmelCase_ :Optional[int] = set(["""cpu""", """nvme"""] ) lowerCAmelCase_ :Union[str, Any] = set( [ self.get_value("""zero_optimization.offload_optimizer.device""" ), self.get_value("""zero_optimization.offload_param.device""" ), ] ) if len(offload_devices & offload_devices_valid ) > 0: lowerCAmelCase_ :Optional[int] = True def __lowerCAmelCase ( self , __A ) -> Optional[Any]: lowerCAmelCase_ :str = self.config # find the config node of interest if it exists lowerCAmelCase_ :Tuple = ds_key_long.split(""".""" ) lowerCAmelCase_ :List[str] = nodes.pop() for node in nodes: lowerCAmelCase_ :Tuple = config.get(__A ) if config is None: return None, ds_key return config, ds_key def __lowerCAmelCase ( self , __A , __A=None ) -> Optional[Any]: lowerCAmelCase_ , lowerCAmelCase_ :Optional[Any] = self.find_config_node(__A ) if config is None: return default return config.get(__A , __A ) def __lowerCAmelCase ( self , __A , __A=False ) -> Optional[Any]: lowerCAmelCase_ :Tuple = self.config # find the config node of interest if it exists lowerCAmelCase_ :Union[str, Any] = ds_key_long.split(""".""" ) for node in nodes: lowerCAmelCase_ :int = config lowerCAmelCase_ :Any = config.get(__A ) if config is None: if must_exist: raise ValueError(f"""Can't find {ds_key_long} entry in the config: {self.config}""" ) else: return # if found remove it if parent_config is not None: parent_config.pop(__A ) def __lowerCAmelCase ( self , __A ) -> Union[str, Any]: lowerCAmelCase_ :Optional[int] = self.get_value(__A ) return False if value is None else bool(__A ) def __lowerCAmelCase ( self , __A ) -> Optional[int]: lowerCAmelCase_ :List[str] = self.get_value(__A ) return False if value is None else not bool(__A ) def __lowerCAmelCase ( self ) -> str: return self._stage == 2 def __lowerCAmelCase ( self ) -> Union[str, Any]: return self._stage == 3 def __lowerCAmelCase ( self ) -> Union[str, Any]: return self._offload class _SCREAMING_SNAKE_CASE : def __init__( self , __A ) -> Optional[int]: lowerCAmelCase_ :Dict = engine def __lowerCAmelCase ( self , __A , **__A ) -> str: # runs backpropagation and handles mixed precision self.engine.backward(__A , **__A ) # Deepspeed's `engine.step` performs the following operations: # - gradient accumulation check # - gradient clipping # - optimizer step # - zero grad # - checking overflow # - lr_scheduler step (only if engine.lr_scheduler is not None) self.engine.step() # and this plugin overrides the above calls with no-ops when Accelerate runs under # Deepspeed, but allows normal functionality for non-Deepspeed cases thus enabling a simple # training loop that works transparently under many training regimes. class _SCREAMING_SNAKE_CASE ( A__ ): def __init__( self , __A ) -> List[str]: super().__init__(__A , device_placement=__A , scaler=__A ) lowerCAmelCase_ :List[str] = hasattr(self.optimizer , """overflow""" ) def __lowerCAmelCase ( self , __A=None ) -> Optional[Any]: pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed def __lowerCAmelCase ( self ) -> List[Any]: pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed @property def __lowerCAmelCase ( self ) -> int: if self.__has_overflow__: return self.optimizer.overflow return False class _SCREAMING_SNAKE_CASE ( A__ ): def __init__( self , __A , __A ) -> Optional[int]: super().__init__(__A , __A ) def __lowerCAmelCase ( self ) -> Any: pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed class _SCREAMING_SNAKE_CASE : def __init__( self , __A , __A=0.0_0_1 , __A=0 , **__A ) -> List[Any]: lowerCAmelCase_ :str = params lowerCAmelCase_ :Any = lr lowerCAmelCase_ :List[Any] = weight_decay lowerCAmelCase_ :Any = kwargs class _SCREAMING_SNAKE_CASE : def __init__( self , __A , __A=None , __A=0 , **__A ) -> List[str]: lowerCAmelCase_ :Optional[int] = optimizer lowerCAmelCase_ :int = total_num_steps lowerCAmelCase_ :List[Any] = warmup_num_steps lowerCAmelCase_ :int = kwargs
1
1
import inspect import unittest from transformers import ViTHybridConfig from transformers.testing_utils import require_accelerate, require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ViTHybridForImageClassification, ViTHybridImageProcessor, ViTHybridModel from transformers.models.vit_hybrid.modeling_vit_hybrid import VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image class __lowercase : def __init__( self , A_ , A_=13 , A_=64 , A_=2 , A_=3 , A_=True , A_=True , A_=32 , A_=5 , A_=4 , A_=37 , A_="gelu" , A_=0.1 , A_=0.1 , A_=10 , A_=0.02 , A_=[1, 16, 4, 4] , A_=None , ) ->Optional[Any]: '''simple docstring''' __lowerCAmelCase : Optional[Any] = parent __lowerCAmelCase : List[Any] = batch_size __lowerCAmelCase : Any = image_size __lowerCAmelCase : str = patch_size __lowerCAmelCase : Tuple = num_channels __lowerCAmelCase : Dict = is_training __lowerCAmelCase : Optional[Any] = use_labels __lowerCAmelCase : List[Any] = hidden_size __lowerCAmelCase : int = num_hidden_layers __lowerCAmelCase : int = num_attention_heads __lowerCAmelCase : Optional[Any] = intermediate_size __lowerCAmelCase : Any = hidden_act __lowerCAmelCase : Union[str, Any] = hidden_dropout_prob __lowerCAmelCase : Tuple = attention_probs_dropout_prob __lowerCAmelCase : int = type_sequence_label_size __lowerCAmelCase : List[str] = initializer_range __lowerCAmelCase : List[Any] = scope __lowerCAmelCase : List[str] = backbone_featmap_shape # in ViT hybrid, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) # the number of patches is based on the feature map of the backbone, which by default uses an output stride # of 32, which means that the feature map has a spatial resolution of 1/32 of the input image size __lowerCAmelCase : str = (self.image_size // 32) ** 2 __lowerCAmelCase : List[str] = num_patches + 1 def UpperCamelCase__ ( self ) ->Optional[Any]: '''simple docstring''' __lowerCAmelCase : str = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __lowerCAmelCase : Optional[int] = None if self.use_labels: __lowerCAmelCase : Union[str, Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCAmelCase : Dict = self.get_config() return config, pixel_values, labels def UpperCamelCase__ ( self ) ->str: '''simple docstring''' __lowerCAmelCase : Dict = { '''global_padding''': '''same''', '''layer_type''': '''bottleneck''', '''depths''': [3, 4, 9], '''out_features''': ['''stage1''', '''stage2''', '''stage3'''], '''embedding_dynamic_padding''': True, '''hidden_sizes''': [4, 8, 16, 32], '''num_groups''': 2, } return ViTHybridConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=UpperCAmelCase_ , initializer_range=self.initializer_range , backbone_featmap_shape=self.backbone_featmap_shape , backbone_config=UpperCAmelCase_ , ) def UpperCamelCase__ ( self , A_ , A_ , A_ ) ->Optional[Any]: '''simple docstring''' __lowerCAmelCase : str = ViTHybridModel(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() __lowerCAmelCase : List[str] = model(UpperCAmelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase__ ( self , A_ , A_ , A_ ) ->List[str]: '''simple docstring''' __lowerCAmelCase : List[str] = self.type_sequence_label_size __lowerCAmelCase : List[Any] = ViTHybridForImageClassification(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() __lowerCAmelCase : str = model(UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def UpperCamelCase__ ( self ) ->Any: '''simple docstring''' __lowerCAmelCase : str = self.prepare_config_and_inputs() __lowerCAmelCase, __lowerCAmelCase, __lowerCAmelCase : Tuple = config_and_inputs __lowerCAmelCase : Dict = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class __lowercase (_UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): _UpperCamelCase = (ViTHybridModel, ViTHybridForImageClassification) if is_torch_available() else () _UpperCamelCase = ( {"feature-extraction": ViTHybridModel, "image-classification": ViTHybridForImageClassification} if is_torch_available() else {} ) _UpperCamelCase = False _UpperCamelCase = False _UpperCamelCase = False def UpperCamelCase__ ( self ) ->List[Any]: '''simple docstring''' __lowerCAmelCase : List[Any] = ViTHybridModelTester(self ) __lowerCAmelCase : Optional[Any] = ConfigTester(self , config_class=UpperCAmelCase_ , has_text_modality=UpperCAmelCase_ , hidden_size=37 ) def UpperCamelCase__ ( self ) ->Union[str, Any]: '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason='''ViT does not use inputs_embeds''' ) def UpperCamelCase__ ( self ) ->Optional[Any]: '''simple docstring''' pass def UpperCamelCase__ ( self ) ->int: '''simple docstring''' __lowerCAmelCase, __lowerCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCAmelCase : str = model_class(UpperCAmelCase_ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) __lowerCAmelCase : Dict = model.get_output_embeddings() self.assertTrue(x is None or isinstance(UpperCAmelCase_ , nn.Linear ) ) def UpperCamelCase__ ( self ) ->Tuple: '''simple docstring''' __lowerCAmelCase, __lowerCAmelCase : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCAmelCase : Optional[Any] = model_class(UpperCAmelCase_ ) __lowerCAmelCase : List[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __lowerCAmelCase : List[Any] = [*signature.parameters.keys()] __lowerCAmelCase : Tuple = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , UpperCAmelCase_ ) def UpperCamelCase__ ( self ) ->Optional[int]: '''simple docstring''' __lowerCAmelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def UpperCamelCase__ ( self ) ->Any: '''simple docstring''' __lowerCAmelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase_ ) def UpperCamelCase__ ( self ) ->Tuple: '''simple docstring''' __lowerCAmelCase, __lowerCAmelCase : Tuple = self.model_tester.prepare_config_and_inputs_for_common() __lowerCAmelCase : Optional[int] = _config_zero_init(UpperCAmelCase_ ) for model_class in self.all_model_classes: __lowerCAmelCase : Dict = model_class(config=UpperCAmelCase_ ) # Skip the check for the backbone for name, module in model.named_modules(): if module.__class__.__name__ == "ViTHybridPatchEmbeddings": __lowerCAmelCase : Optional[Any] = [f"""{name}.{key}""" for key in module.state_dict().keys()] break for name, param in model.named_parameters(): if param.requires_grad: if name in backbone_params: continue self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=f"""Parameter {name} of model {model_class} seems not properly initialized""" , ) @slow def UpperCamelCase__ ( self ) ->str: '''simple docstring''' for model_name in VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCAmelCase : List[str] = ViTHybridModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) def _lowercase ( ): __lowerCAmelCase : Union[str, Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class __lowercase (unittest.TestCase ): @cached_property def UpperCamelCase__ ( self ) ->Optional[int]: '''simple docstring''' return ( ViTHybridImageProcessor.from_pretrained(VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def UpperCamelCase__ ( self ) ->Dict: '''simple docstring''' __lowerCAmelCase : Dict = ViTHybridForImageClassification.from_pretrained(VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to( UpperCAmelCase_ ) __lowerCAmelCase : str = self.default_image_processor __lowerCAmelCase : Tuple = prepare_img() __lowerCAmelCase : Optional[Any] = image_processor(images=UpperCAmelCase_ , return_tensors='''pt''' ).to(UpperCAmelCase_ ) # forward pass with torch.no_grad(): __lowerCAmelCase : Tuple = model(**UpperCAmelCase_ ) # verify the logits __lowerCAmelCase : Optional[int] = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , UpperCAmelCase_ ) __lowerCAmelCase : Optional[Any] = torch.tensor([-1.9_090, -0.4_993, -0.2_389] ).to(UpperCAmelCase_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCAmelCase_ , atol=1e-4 ) ) @slow @require_accelerate def UpperCamelCase__ ( self ) ->str: '''simple docstring''' __lowerCAmelCase : Union[str, Any] = ViTHybridImageProcessor.from_pretrained('''google/vit-hybrid-base-bit-384''' ) __lowerCAmelCase : List[str] = ViTHybridForImageClassification.from_pretrained('''google/vit-hybrid-base-bit-384''' , device_map='''auto''' ) __lowerCAmelCase : Dict = prepare_img() __lowerCAmelCase : int = image_processor(images=UpperCAmelCase_ , return_tensors='''pt''' ) __lowerCAmelCase : Union[str, Any] = model(**UpperCAmelCase_ ) __lowerCAmelCase : Tuple = outputs.logits # model predicts one of the 1000 ImageNet classes __lowerCAmelCase : List[str] = logits.argmax(-1 ).item() self.assertTrue(model.config.idalabel[predicted_class_idx] , '''tabby, tabby cat''' )
275
import random def __lowerCamelCase ( snake_case__ ) -> bool: """simple docstring""" _SCREAMING_SNAKE_CASE = num - 1 _SCREAMING_SNAKE_CASE = 0 while s % 2 == 0: _SCREAMING_SNAKE_CASE = s // 2 t += 1 for _ in range(5 ): _SCREAMING_SNAKE_CASE = random.randrange(2 ,num - 1 ) _SCREAMING_SNAKE_CASE = pow(snake_case__ ,snake_case__ ,snake_case__ ) if v != 1: _SCREAMING_SNAKE_CASE = 0 while v != (num - 1): if i == t - 1: return False else: _SCREAMING_SNAKE_CASE = i + 1 _SCREAMING_SNAKE_CASE = (v**2) % num return True def __lowerCamelCase ( snake_case__ ) -> bool: """simple docstring""" if num < 2: return False _SCREAMING_SNAKE_CASE = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 1_01, 1_03, 1_07, 1_09, 1_13, 1_27, 1_31, 1_37, 1_39, 1_49, 1_51, 1_57, 1_63, 1_67, 1_73, 1_79, 1_81, 1_91, 1_93, 1_97, 1_99, 2_11, 2_23, 2_27, 2_29, 2_33, 2_39, 2_41, 2_51, 2_57, 2_63, 2_69, 2_71, 2_77, 2_81, 2_83, 2_93, 3_07, 3_11, 3_13, 3_17, 3_31, 3_37, 3_47, 3_49, 3_53, 3_59, 3_67, 3_73, 3_79, 3_83, 3_89, 3_97, 4_01, 4_09, 4_19, 4_21, 4_31, 4_33, 4_39, 4_43, 4_49, 4_57, 4_61, 4_63, 4_67, 4_79, 4_87, 4_91, 4_99, 5_03, 5_09, 5_21, 5_23, 5_41, 5_47, 5_57, 5_63, 5_69, 5_71, 5_77, 5_87, 5_93, 5_99, 6_01, 6_07, 6_13, 6_17, 6_19, 6_31, 6_41, 6_43, 6_47, 6_53, 6_59, 6_61, 6_73, 6_77, 6_83, 6_91, 7_01, 7_09, 7_19, 7_27, 7_33, 7_39, 7_43, 7_51, 7_57, 7_61, 7_69, 7_73, 7_87, 7_97, 8_09, 8_11, 8_21, 8_23, 8_27, 8_29, 8_39, 8_53, 8_57, 8_59, 8_63, 8_77, 8_81, 8_83, 8_87, 9_07, 9_11, 9_19, 9_29, 9_37, 9_41, 9_47, 9_53, 9_67, 9_71, 9_77, 9_83, 9_91, 9_97, ] if num in low_primes: return True for prime in low_primes: if (num % prime) == 0: return False return rabin_miller(snake_case__ ) def __lowerCamelCase ( snake_case__ = 10_24 ) -> int: """simple docstring""" while True: _SCREAMING_SNAKE_CASE = random.randrange(2 ** (keysize - 1) ,2 ** (keysize) ) if is_prime_low_num(snake_case__ ): return num if __name__ == "__main__": UpperCamelCase = generate_large_prime() print(('''Prime number:''', num)) print(('''is_prime_low_num:''', is_prime_low_num(num)))
306
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_funnel import FunnelTokenizer lowercase : List[Any] = logging.get_logger(__name__) lowercase : Dict = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""} lowercase : Optional[Any] = [ """small""", """small-base""", """medium""", """medium-base""", """intermediate""", """intermediate-base""", """large""", """large-base""", """xlarge""", """xlarge-base""", ] lowercase : List[Any] = { """vocab_file""": { """funnel-transformer/small""": """https://huggingface.co/funnel-transformer/small/resolve/main/vocab.txt""", """funnel-transformer/small-base""": """https://huggingface.co/funnel-transformer/small-base/resolve/main/vocab.txt""", """funnel-transformer/medium""": """https://huggingface.co/funnel-transformer/medium/resolve/main/vocab.txt""", """funnel-transformer/medium-base""": ( """https://huggingface.co/funnel-transformer/medium-base/resolve/main/vocab.txt""" ), """funnel-transformer/intermediate""": ( """https://huggingface.co/funnel-transformer/intermediate/resolve/main/vocab.txt""" ), """funnel-transformer/intermediate-base""": ( """https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/vocab.txt""" ), """funnel-transformer/large""": """https://huggingface.co/funnel-transformer/large/resolve/main/vocab.txt""", """funnel-transformer/large-base""": """https://huggingface.co/funnel-transformer/large-base/resolve/main/vocab.txt""", """funnel-transformer/xlarge""": """https://huggingface.co/funnel-transformer/xlarge/resolve/main/vocab.txt""", """funnel-transformer/xlarge-base""": ( """https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/vocab.txt""" ), }, """tokenizer_file""": { """funnel-transformer/small""": """https://huggingface.co/funnel-transformer/small/resolve/main/tokenizer.json""", """funnel-transformer/small-base""": ( """https://huggingface.co/funnel-transformer/small-base/resolve/main/tokenizer.json""" ), """funnel-transformer/medium""": """https://huggingface.co/funnel-transformer/medium/resolve/main/tokenizer.json""", """funnel-transformer/medium-base""": ( """https://huggingface.co/funnel-transformer/medium-base/resolve/main/tokenizer.json""" ), """funnel-transformer/intermediate""": ( """https://huggingface.co/funnel-transformer/intermediate/resolve/main/tokenizer.json""" ), """funnel-transformer/intermediate-base""": ( """https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/tokenizer.json""" ), """funnel-transformer/large""": """https://huggingface.co/funnel-transformer/large/resolve/main/tokenizer.json""", """funnel-transformer/large-base""": ( """https://huggingface.co/funnel-transformer/large-base/resolve/main/tokenizer.json""" ), """funnel-transformer/xlarge""": """https://huggingface.co/funnel-transformer/xlarge/resolve/main/tokenizer.json""", """funnel-transformer/xlarge-base""": ( """https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/tokenizer.json""" ), }, } lowercase : Dict = {F"""funnel-transformer/{name}""": 5_1_2 for name in _model_names} lowercase : Optional[int] = {F"""funnel-transformer/{name}""": {"""do_lower_case""": True} for name in _model_names} class A__ ( UpperCAmelCase_ ): """simple docstring""" __A : List[str] = VOCAB_FILES_NAMES __A : List[str] = PRETRAINED_VOCAB_FILES_MAP __A : Any = PRETRAINED_INIT_CONFIGURATION __A : List[Any] = FunnelTokenizer __A : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __A : int = 2 def __init__( self , lowercase=None , lowercase=None , lowercase=True , lowercase="<unk>" , lowercase="<sep>" , lowercase="<pad>" , lowercase="<cls>" , lowercase="<mask>" , lowercase="<s>" , lowercase="</s>" , lowercase=True , lowercase=True , lowercase=None , lowercase="##" , **lowercase , ) -> Tuple: '''simple docstring''' 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 , bos_token=__lowercase , eos_token=__lowercase , clean_text=__lowercase , tokenize_chinese_chars=__lowercase , strip_accents=__lowercase , wordpieces_prefix=__lowercase , **__lowercase , ) a__ : int = 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 ): a__ : Optional[int] = getattr(__lowercase , normalizer_state.pop('type')) a__ : str = do_lower_case a__ : Dict = strip_accents a__ : Optional[int] = tokenize_chinese_chars a__ : Union[str, Any] = normalizer_class(**__lowercase) a__ : int = do_lower_case def __lowercase ( self , lowercase , lowercase=None) -> Any: '''simple docstring''' a__ : List[str] = [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 __lowercase ( self , lowercase , lowercase = None) -> List[int]: '''simple docstring''' a__ : Optional[int] = [self.sep_token_id] a__ : List[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls) * [self.cls_token_type_id] + len(token_ids_a + sep) * [0] return len(cls) * [self.cls_token_type_id] + len(token_ids_a + sep) * [0] + len(token_ids_a + sep) * [1] def __lowercase ( self , lowercase , lowercase = None) -> Tuple[str]: '''simple docstring''' a__ : Any = self._tokenizer.model.save(__lowercase , name=__lowercase) return tuple(__lowercase)
367
import unittest from transformers import AutoTokenizer, NystromformerConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( NystromformerForMaskedLM, NystromformerForMultipleChoice, NystromformerForQuestionAnswering, NystromformerForSequenceClassification, NystromformerForTokenClassification, NystromformerModel, ) from transformers.models.nystromformer.modeling_nystromformer import NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST class A__ : """simple docstring""" def __init__( self , lowercase , lowercase=13 , lowercase=7 , lowercase=True , lowercase=True , lowercase=True , lowercase=True , lowercase=99 , lowercase=32 , lowercase=5 , lowercase=4 , lowercase=37 , lowercase="gelu" , lowercase=0.1 , lowercase=0.1 , lowercase=512 , lowercase=16 , lowercase=2 , lowercase=0.02 , lowercase=3 , lowercase=4 , lowercase=None , ) -> List[Any]: '''simple docstring''' a__ : Any = parent a__ : int = batch_size a__ : Dict = seq_length a__ : Tuple = is_training a__ : Any = use_input_mask a__ : Optional[Any] = use_token_type_ids a__ : Dict = use_labels a__ : Optional[int] = vocab_size a__ : List[Any] = hidden_size a__ : int = num_hidden_layers a__ : Optional[Any] = num_attention_heads a__ : str = intermediate_size a__ : Optional[int] = hidden_act a__ : Dict = hidden_dropout_prob a__ : Optional[int] = attention_probs_dropout_prob a__ : Tuple = max_position_embeddings a__ : Dict = type_vocab_size a__ : Any = type_sequence_label_size a__ : List[str] = initializer_range a__ : List[str] = num_labels a__ : Optional[Any] = num_choices a__ : str = scope def __lowercase ( self) -> Union[str, Any]: '''simple docstring''' a__ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) a__ : Tuple = None if self.use_input_mask: a__ : Optional[int] = random_attention_mask([self.batch_size, self.seq_length]) a__ : Any = None if self.use_token_type_ids: a__ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size) a__ : str = None a__ : List[Any] = None a__ : List[str] = None if self.use_labels: a__ : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size) a__ : str = ids_tensor([self.batch_size, self.seq_length] , self.num_labels) a__ : str = ids_tensor([self.batch_size] , self.num_choices) a__ : Union[str, Any] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowercase ( self) -> Optional[int]: '''simple docstring''' return NystromformerConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=lowercase , initializer_range=self.initializer_range , ) def __lowercase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase) -> Optional[int]: '''simple docstring''' a__ : Union[str, Any] = NystromformerModel(config=lowercase) model.to(lowercase) model.eval() a__ : List[Any] = model(lowercase , attention_mask=lowercase , token_type_ids=lowercase) a__ : int = model(lowercase , token_type_ids=lowercase) a__ : Optional[Any] = model(lowercase) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def __lowercase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase) -> str: '''simple docstring''' a__ : List[str] = NystromformerForMaskedLM(config=lowercase) model.to(lowercase) model.eval() a__ : int = model(lowercase , attention_mask=lowercase , token_type_ids=lowercase , labels=lowercase) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def __lowercase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase) -> Union[str, Any]: '''simple docstring''' a__ : Any = NystromformerForQuestionAnswering(config=lowercase) model.to(lowercase) model.eval() a__ : str = model( lowercase , attention_mask=lowercase , token_type_ids=lowercase , start_positions=lowercase , end_positions=lowercase , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length)) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length)) def __lowercase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase) -> Optional[Any]: '''simple docstring''' a__ : int = self.num_labels a__ : Optional[Any] = NystromformerForSequenceClassification(lowercase) model.to(lowercase) model.eval() a__ : Tuple = model(lowercase , attention_mask=lowercase , token_type_ids=lowercase , labels=lowercase) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def __lowercase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase) -> List[str]: '''simple docstring''' a__ : Tuple = self.num_labels a__ : int = NystromformerForTokenClassification(config=lowercase) model.to(lowercase) model.eval() a__ : str = model(lowercase , attention_mask=lowercase , token_type_ids=lowercase , labels=lowercase) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels)) def __lowercase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase) -> Any: '''simple docstring''' a__ : Optional[int] = self.num_choices a__ : Tuple = NystromformerForMultipleChoice(config=lowercase) model.to(lowercase) model.eval() a__ : Optional[Any] = input_ids.unsqueeze(1).expand(-1 , self.num_choices , -1).contiguous() a__ : Tuple = token_type_ids.unsqueeze(1).expand(-1 , self.num_choices , -1).contiguous() a__ : str = input_mask.unsqueeze(1).expand(-1 , self.num_choices , -1).contiguous() a__ : Optional[int] = model( lowercase , attention_mask=lowercase , token_type_ids=lowercase , labels=lowercase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices)) def __lowercase ( self) -> Union[str, Any]: '''simple docstring''' a__ : List[Any] = self.prepare_config_and_inputs() ( ( a__ ) , ( a__ ) , ( a__ ) , ( a__ ) , ( a__ ) , ( a__ ) , ( a__ ) , ) : 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_torch class A__ ( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ): """simple docstring""" __A : Any = ( ( NystromformerModel, NystromformerForMaskedLM, NystromformerForMultipleChoice, NystromformerForQuestionAnswering, NystromformerForSequenceClassification, NystromformerForTokenClassification, ) if is_torch_available() else () ) __A : str = ( { '''feature-extraction''': NystromformerModel, '''fill-mask''': NystromformerForMaskedLM, '''question-answering''': NystromformerForQuestionAnswering, '''text-classification''': NystromformerForSequenceClassification, '''token-classification''': NystromformerForTokenClassification, '''zero-shot''': NystromformerForSequenceClassification, } if is_torch_available() else {} ) __A : Optional[Any] = False __A : Tuple = False def __lowercase ( self) -> Optional[Any]: '''simple docstring''' a__ : int = NystromformerModelTester(self) a__ : Any = ConfigTester(self , config_class=lowercase , hidden_size=37) def __lowercase ( self) -> Any: '''simple docstring''' self.config_tester.run_common_tests() def __lowercase ( self) -> int: '''simple docstring''' a__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase) def __lowercase ( self) -> Tuple: '''simple docstring''' a__ : Tuple = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: a__ : Optional[Any] = type self.model_tester.create_and_check_model(*lowercase) def __lowercase ( self) -> Tuple: '''simple docstring''' a__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*lowercase) def __lowercase ( self) -> Any: '''simple docstring''' a__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*lowercase) def __lowercase ( self) -> Any: '''simple docstring''' a__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*lowercase) def __lowercase ( self) -> Union[str, Any]: '''simple docstring''' a__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*lowercase) def __lowercase ( self) -> int: '''simple docstring''' a__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*lowercase) @slow def __lowercase ( self) -> Optional[int]: '''simple docstring''' for model_name in NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a__ : int = NystromformerModel.from_pretrained(lowercase) self.assertIsNotNone(lowercase) @require_torch class A__ ( unittest.TestCase ): """simple docstring""" @slow def __lowercase ( self) -> Optional[Any]: '''simple docstring''' a__ : List[str] = NystromformerModel.from_pretrained('uw-madison/nystromformer-512') a__ : Tuple = torch.tensor([[0, 1, 2, 3, 4, 5]]) with torch.no_grad(): a__ : List[Any] = model(lowercase)[0] a__ : str = torch.Size((1, 6, 768)) self.assertEqual(output.shape , lowercase) a__ : str = torch.tensor( [[[-0.45_32, -0.09_36, 0.51_37], [-0.26_76, 0.06_28, 0.61_86], [-0.36_29, -0.17_26, 0.47_16]]]) self.assertTrue(torch.allclose(output[:, :3, :3] , lowercase , atol=1e-4)) @slow def __lowercase ( self) -> Optional[int]: '''simple docstring''' a__ : Any = 'the [MASK] of Belgium is Brussels' a__ : List[str] = AutoTokenizer.from_pretrained('uw-madison/nystromformer-512') a__ : Optional[int] = NystromformerForMaskedLM.from_pretrained('uw-madison/nystromformer-512') a__ : List[Any] = tokenizer(lowercase , return_tensors='pt') with torch.no_grad(): a__ : Union[str, Any] = model(encoding.input_ids).logits a__ : str = token_logits[:, 2, :].argmax(-1)[0] self.assertEqual(tokenizer.decode(lowercase) , 'capital')
225
0
from collections import Counter from timeit import timeit def UpperCamelCase ( snake_case__ : str = "" , ) -> bool: return sum(c % 2 for c in Counter(input_str.replace(' ' , '' ).lower() ).values() ) < 2 def UpperCamelCase ( snake_case__ : str = "" ) -> bool: if len(snake_case__ ) == 0: return True UpperCamelCase : int = input_str.replace(' ' , '' ).lower() # character_freq_dict: Stores the frequency of every character in the input string UpperCamelCase : dict[str, int] = {} for character in lower_case_input_str: UpperCamelCase : Union[str, Any] = character_freq_dict.get(snake_case__ , 0 ) + 1 UpperCamelCase : str = 0 for character_count in character_freq_dict.values(): if character_count % 2: odd_char += 1 if odd_char > 1: return False return True def UpperCamelCase ( snake_case__ : str = "" ) -> None: print('\nFor string = ' , snake_case__ , ':' ) print( '> can_string_be_rearranged_as_palindrome_counter()' , '\tans =' , can_string_be_rearranged_as_palindrome_counter(snake_case__ ) , '\ttime =' , timeit( 'z.can_string_be_rearranged_as_palindrome_counter(z.check_str)' , setup='import __main__ as z' , ) , 'seconds' , ) print( '> can_string_be_rearranged_as_palindrome()' , '\tans =' , can_string_be_rearranged_as_palindrome(snake_case__ ) , '\ttime =' , timeit( 'z.can_string_be_rearranged_as_palindrome(z.check_str)' , setup='import __main__ as z' , ) , 'seconds' , ) if __name__ == "__main__": __UpperCAmelCase = input( '''Enter string to determine if it can be rearranged as a palindrome or not: ''' ).strip() benchmark(check_str) __UpperCAmelCase = can_string_be_rearranged_as_palindrome_counter(check_str) print(F"""{check_str} can {"" if status else "not "}be rearranged as a palindrome""")
119
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_ ( a__ ): def __init__( self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = True, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = False, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = True, SCREAMING_SNAKE_CASE_ = "arrow", **SCREAMING_SNAKE_CASE_, ) -> Optional[int]: 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_, ) UpperCamelCase : List[str] = load_from_cache_file UpperCamelCase : List[str] = file_format UpperCamelCase : Optional[int] = Spark( df=SCREAMING_SNAKE_CASE_, features=SCREAMING_SNAKE_CASE_, cache_dir=SCREAMING_SNAKE_CASE_, working_dir=SCREAMING_SNAKE_CASE_, **SCREAMING_SNAKE_CASE_, ) def snake_case_ ( self ) -> int: if self.streaming: return self.builder.as_streaming_dataset(split=self.split ) UpperCamelCase : Union[str, Any] = 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 )
119
1
from typing import Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_tf_outputs import ( TFBaseModelOutputWithNoAttention, TFBaseModelOutputWithPoolingAndNoAttention, TFSequenceClassifierOutput, ) from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs from ...tf_utils import shape_list from ...utils import logging from .configuration_regnet import RegNetConfig a__ = logging.get_logger(__name__) # General docstring a__ = '''RegNetConfig''' # Base docstring a__ = '''facebook/regnet-y-040''' a__ = [1, 1088, 7, 7] # Image classification docstring a__ = '''facebook/regnet-y-040''' a__ = '''tabby, tabby cat''' a__ = [ '''facebook/regnet-y-040''', # See all regnet models at https://huggingface.co/models?filter=regnet ] class UpperCAmelCase_ ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self , _a , _a = 3 , _a = 1 , _a = 1 , _a = "relu" , **_a , ) -> str: super().__init__(**_a ) # The padding and conv has been verified in # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb _a : Optional[Any] = tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2 ) _a : Tuple = tf.keras.layers.ConvaD( filters=_a , kernel_size=_a , strides=_a , padding='''VALID''' , groups=_a , use_bias=_a , name='''convolution''' , ) _a : Optional[Any] = tf.keras.layers.BatchNormalization(epsilon=1e-5 , momentum=0.9 , name='''normalization''' ) _a : List[str] = ACTaFN[activation] if activation is not None else tf.identity def __lowercase ( self , _a ) -> List[Any]: _a : List[Any] = self.convolution(self.padding(_a ) ) _a : Tuple = self.normalization(_a ) _a : Union[str, Any] = self.activation(_a ) return hidden_state class UpperCAmelCase_ ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self , _a , **_a ) -> Tuple: super().__init__(**_a ) _a : List[str] = config.num_channels _a : Dict = TFRegNetConvLayer( out_channels=config.embedding_size , kernel_size=3 , stride=2 , activation=config.hidden_act , name='''embedder''' , ) def __lowercase ( self , _a ) -> Union[str, Any]: _a : List[str] = shape_list(_a )[1] if tf.executing_eagerly() and num_channels != self.num_channels: raise ValueError( '''Make sure that the channel dimension of the pixel values match with the one set in the configuration.''' ) # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format. # So change the input format from `NCHW` to `NHWC`. # shape = (batch_size, in_height, in_width, in_channels=num_channels) _a : Dict = tf.transpose(_a , perm=(0, 2, 3, 1) ) _a : List[str] = self.embedder(_a ) return hidden_state class UpperCAmelCase_ ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self , _a , _a = 2 , **_a ) -> int: super().__init__(**_a ) _a : Optional[Any] = tf.keras.layers.ConvaD( filters=_a , kernel_size=1 , strides=_a , use_bias=_a , name='''convolution''' ) _a : str = tf.keras.layers.BatchNormalization(epsilon=1e-5 , momentum=0.9 , name='''normalization''' ) def __lowercase ( self , _a , _a = False ) -> tf.Tensor: return self.normalization(self.convolution(_a ) , training=_a ) class UpperCAmelCase_ ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self , _a , _a , **_a ) -> int: super().__init__(**_a ) _a : List[Any] = tf.keras.layers.GlobalAveragePoolingaD(keepdims=_a , name='''pooler''' ) _a : Optional[int] = [ tf.keras.layers.ConvaD(filters=_a , kernel_size=1 , activation='''relu''' , name='''attention.0''' ), tf.keras.layers.ConvaD(filters=_a , kernel_size=1 , activation='''sigmoid''' , name='''attention.2''' ), ] def __lowercase ( self , _a ) -> List[Any]: # [batch_size, h, w, num_channels] -> [batch_size, 1, 1, num_channels] _a : str = self.pooler(_a ) for layer_module in self.attention: _a : Dict = layer_module(_a ) _a : Optional[Any] = hidden_state * pooled return hidden_state class UpperCAmelCase_ ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self , _a , _a , _a , _a = 1 , **_a ) -> Union[str, Any]: super().__init__(**_a ) _a : Union[str, Any] = in_channels != out_channels or stride != 1 _a : str = max(1 , out_channels // config.groups_width ) _a : Tuple = ( TFRegNetShortCut(_a , stride=_a , name='''shortcut''' ) if should_apply_shortcut else tf.keras.layers.Activation('''linear''' , name='''shortcut''' ) ) # `self.layers` instead of `self.layer` because that is a reserved argument. _a : Tuple = [ TFRegNetConvLayer(_a , kernel_size=1 , activation=config.hidden_act , name='''layer.0''' ), TFRegNetConvLayer( _a , stride=_a , groups=_a , activation=config.hidden_act , name='''layer.1''' ), TFRegNetConvLayer(_a , kernel_size=1 , activation=_a , name='''layer.2''' ), ] _a : int = ACTaFN[config.hidden_act] def __lowercase ( self , _a ) -> Any: _a : Tuple = hidden_state for layer_module in self.layers: _a : List[str] = layer_module(_a ) _a : Optional[int] = self.shortcut(_a ) hidden_state += residual _a : Union[str, Any] = self.activation(_a ) return hidden_state class UpperCAmelCase_ ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self , _a , _a , _a , _a = 1 , **_a ) -> List[str]: super().__init__(**_a ) _a : List[str] = in_channels != out_channels or stride != 1 _a : Union[str, Any] = max(1 , out_channels // config.groups_width ) _a : int = ( TFRegNetShortCut(_a , stride=_a , name='''shortcut''' ) if should_apply_shortcut else tf.keras.layers.Activation('''linear''' , name='''shortcut''' ) ) _a : Any = [ TFRegNetConvLayer(_a , kernel_size=1 , activation=config.hidden_act , name='''layer.0''' ), TFRegNetConvLayer( _a , stride=_a , groups=_a , activation=config.hidden_act , name='''layer.1''' ), TFRegNetSELayer(_a , reduced_channels=int(round(in_channels / 4 ) ) , name='''layer.2''' ), TFRegNetConvLayer(_a , kernel_size=1 , activation=_a , name='''layer.3''' ), ] _a : Union[str, Any] = ACTaFN[config.hidden_act] def __lowercase ( self , _a ) -> List[str]: _a : Tuple = hidden_state for layer_module in self.layers: _a : str = layer_module(_a ) _a : int = self.shortcut(_a ) hidden_state += residual _a : List[Any] = self.activation(_a ) return hidden_state class UpperCAmelCase_ ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self , _a , _a , _a , _a = 2 , _a = 2 , **_a ) -> Union[str, Any]: super().__init__(**_a ) _a : Union[str, Any] = TFRegNetXLayer if config.layer_type == '''x''' else TFRegNetYLayer _a : Any = [ # downsampling is done in the first layer with stride of 2 layer(_a , _a , _a , stride=_a , name='''layers.0''' ), *[layer(_a , _a , _a , name=F"""layers.{i+1}""" ) for i in range(depth - 1 )], ] def __lowercase ( self , _a ) -> Any: for layer_module in self.layers: _a : Tuple = layer_module(_a ) return hidden_state class UpperCAmelCase_ ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self , _a , **_a ) -> List[str]: super().__init__(**_a ) _a : int = [] # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( TFRegNetStage( _a , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , name='''stages.0''' , ) ) _a : Any = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for i, ((in_channels, out_channels), depth) in enumerate(zip(_a , config.depths[1:] ) ): self.stages.append(TFRegNetStage(_a , _a , _a , depth=_a , name=F"""stages.{i+1}""" ) ) def __lowercase ( self , _a , _a = False , _a = True ) -> TFBaseModelOutputWithNoAttention: _a : List[Any] = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: _a : Optional[Any] = hidden_states + (hidden_state,) _a : Union[str, Any] = stage_module(_a ) if output_hidden_states: _a : Tuple = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return TFBaseModelOutputWithNoAttention(last_hidden_state=_a , hidden_states=_a ) @keras_serializable class UpperCAmelCase_ ( tf.keras.layers.Layer ): """simple docstring""" UpperCAmelCase__ : Optional[Any] = RegNetConfig def __init__( self , _a , **_a ) -> Optional[int]: super().__init__(**_a ) _a : List[Any] = config _a : Union[str, Any] = TFRegNetEmbeddings(_a , name='''embedder''' ) _a : List[str] = TFRegNetEncoder(_a , name='''encoder''' ) _a : Optional[int] = tf.keras.layers.GlobalAveragePoolingaD(keepdims=_a , name='''pooler''' ) @unpack_inputs def __lowercase ( self , _a , _a = None , _a = None , _a = False , ) -> TFBaseModelOutputWithPoolingAndNoAttention: _a : int = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) _a : Optional[Any] = return_dict if return_dict is not None else self.config.use_return_dict _a : Union[str, Any] = self.embedder(_a , training=_a ) _a : Any = self.encoder( _a , output_hidden_states=_a , return_dict=_a , training=_a ) _a : Tuple = encoder_outputs[0] _a : int = self.pooler(_a ) # Change to NCHW output format have uniformity in the modules _a : Union[str, Any] = tf.transpose(_a , perm=(0, 3, 1, 2) ) _a : Optional[int] = tf.transpose(_a , perm=(0, 3, 1, 2) ) # Change the other hidden state outputs to NCHW as well if output_hidden_states: _a : int = tuple([tf.transpose(_a , perm=(0, 3, 1, 2) ) for h in encoder_outputs[1]] ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=_a , pooler_output=_a , hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states , ) class UpperCAmelCase_ ( __lowercase ): """simple docstring""" UpperCAmelCase__ : Union[str, Any] = RegNetConfig UpperCAmelCase__ : int = "regnet" UpperCAmelCase__ : Dict = "pixel_values" @property def __lowercase ( self ) -> Tuple: return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 2_2_4, 2_2_4) , dtype=tf.floataa )} a__ = R''' Parameters: This model is a Tensorflow [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and behavior. config ([`RegNetConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights. ''' a__ = R''' Args: pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`ConveNextImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. ''' @add_start_docstrings( "The bare RegNet model outputting raw features without any specific head on top." , __lowercase , ) class UpperCAmelCase_ ( __lowercase ): """simple docstring""" def __init__( self , _a , *_a , **_a ) -> Any: super().__init__(_a , *_a , **_a ) _a : Optional[Any] = TFRegNetMainLayer(_a , name='''regnet''' ) @unpack_inputs @add_start_docstrings_to_model_forward(_a ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=_a , config_class=_CONFIG_FOR_DOC , modality='''vision''' , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def __lowercase ( self , _a , _a = None , _a = None , _a=False , ) -> Union[TFBaseModelOutputWithPoolingAndNoAttention, Tuple[tf.Tensor]]: _a : str = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) _a : Optional[int] = return_dict if return_dict is not None else self.config.use_return_dict _a : Tuple = self.regnet( pixel_values=_a , output_hidden_states=_a , return_dict=_a , training=_a , ) if not return_dict: return (outputs[0],) + outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=outputs.last_hidden_state , pooler_output=outputs.pooler_output , hidden_states=outputs.hidden_states , ) @add_start_docstrings( "\n RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n " , __lowercase , ) class UpperCAmelCase_ ( __lowercase , __lowercase ): """simple docstring""" def __init__( self , _a , *_a , **_a ) -> Tuple: super().__init__(_a , *_a , **_a ) _a : str = config.num_labels _a : int = TFRegNetMainLayer(_a , name='''regnet''' ) # classification head _a : Optional[int] = [ tf.keras.layers.Flatten(), tf.keras.layers.Dense(config.num_labels , name='''classifier.1''' ) if config.num_labels > 0 else tf.identity, ] @unpack_inputs @add_start_docstrings_to_model_forward(_a ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=_a , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def __lowercase ( self , _a = None , _a = None , _a = None , _a = None , _a=False , ) -> Union[TFSequenceClassifierOutput, Tuple[tf.Tensor]]: _a : int = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) _a : List[str] = return_dict if return_dict is not None else self.config.use_return_dict _a : List[str] = self.regnet( _a , output_hidden_states=_a , return_dict=_a , training=_a ) _a : Dict = outputs.pooler_output if return_dict else outputs[1] _a : Dict = self.classifier[0](_a ) _a : List[str] = self.classifier[1](_a ) _a : List[Any] = None if labels is None else self.hf_compute_loss(labels=_a , logits=_a ) if not return_dict: _a : int = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TFSequenceClassifierOutput(loss=_a , logits=_a , hidden_states=outputs.hidden_states )
362
def __UpperCAmelCase ( __a : int ,__a : int ,__a : int ) -> int: """simple docstring""" if exponent == 1: return base if exponent % 2 == 0: _a : List[Any] = _modexpt(__a ,exponent // 2 ,__a ) % modulo_value return (x * x) % modulo_value else: return (base * _modexpt(__a ,exponent - 1 ,__a )) % modulo_value def __UpperCAmelCase ( __a : int = 1_777 ,__a : int = 1_855 ,__a : int = 8 ) -> int: """simple docstring""" _a : List[Any] = base for _ in range(1 ,__a ): _a : Any = _modexpt(__a ,__a ,10**digits ) return result if __name__ == "__main__": print(f'''{solution() = }''')
15
0
"""simple docstring""" from __future__ import annotations from typing import Any class __A : def __init__( self , a__ = 6 ): _lowerCAmelCase : Union[str, Any] = None _lowerCAmelCase : str = None self.create_linked_list(__A ) def __A ( self , a__ ): _lowerCAmelCase : List[Any] = Node() _lowerCAmelCase : int = current_node _lowerCAmelCase : Tuple = current_node _lowerCAmelCase : str = current_node for _ in range(1 , __A ): _lowerCAmelCase : str = Node() _lowerCAmelCase : int = current_node _lowerCAmelCase : Optional[int] = previous_node _lowerCAmelCase : Union[str, Any] = current_node _lowerCAmelCase : Optional[Any] = self.front _lowerCAmelCase : Optional[int] = previous_node def __A ( self ): return ( self.front == self.rear and self.front is not None and self.front.data is None ) def __A ( self ): self.check_can_perform_operation() return self.front.data if self.front else None def __A ( self , a__ ): if self.rear is None: return self.check_is_full() if not self.is_empty(): _lowerCAmelCase : int = self.rear.next if self.rear: _lowerCAmelCase : int = data def __A ( self ): self.check_can_perform_operation() if self.rear is None or self.front is None: return None if self.front == self.rear: _lowerCAmelCase : Any = self.front.data _lowerCAmelCase : List[str] = None return data _lowerCAmelCase : str = self.front _lowerCAmelCase : Union[str, Any] = old_front.next _lowerCAmelCase : Tuple = old_front.data _lowerCAmelCase : Dict = None return data def __A ( self ): if self.is_empty(): raise Exception("""Empty Queue""" ) def __A ( self ): if self.rear and self.rear.next == self.front: raise Exception("""Full Queue""" ) class __A : def __init__( self ): _lowerCAmelCase : List[str] = None _lowerCAmelCase : Optional[Any] = None _lowerCAmelCase : List[Any] = None if __name__ == "__main__": import doctest doctest.testmod()
44
'''simple docstring''' from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('''>=''', '''4.25.0''')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( VersatileDiffusionDualGuidedPipeline, VersatileDiffusionImageVariationPipeline, VersatileDiffusionPipeline, VersatileDiffusionTextToImagePipeline, ) else: from .modeling_text_unet import UNetFlatConditionModel from .pipeline_versatile_diffusion import VersatileDiffusionPipeline from .pipeline_versatile_diffusion_dual_guided import VersatileDiffusionDualGuidedPipeline from .pipeline_versatile_diffusion_image_variation import VersatileDiffusionImageVariationPipeline from .pipeline_versatile_diffusion_text_to_image import VersatileDiffusionTextToImagePipeline
53
0
"""simple docstring""" from ...utils import logging from ..ta.modeling_tf_ta import TFTaEncoderModel, TFTaForConditionalGeneration, TFTaModel from .configuration_mta import MTaConfig A_ = logging.get_logger(__name__) A_ = 'T5Config' class lowercase( _lowerCamelCase ): '''simple docstring''' lowercase__ = "mt5" lowercase__ = MTaConfig class lowercase( _lowerCamelCase ): '''simple docstring''' lowercase__ = "mt5" lowercase__ = MTaConfig class lowercase( _lowerCamelCase ): '''simple docstring''' lowercase__ = "mt5" lowercase__ = MTaConfig
353
"""simple docstring""" from typing import Any class lowercase: '''simple docstring''' def __init__( self: Dict, a_: Any ): '''simple docstring''' _snake_case : Dict = data _snake_case : Optional[Any] = None class lowercase: '''simple docstring''' def __init__( self: str ): '''simple docstring''' _snake_case : Any = None def UpperCamelCase_ ( self: Any ): '''simple docstring''' _snake_case : List[Any] = self.head while temp is not None: print(temp.data, end=""" """ ) _snake_case : int = temp.next print() def UpperCamelCase_ ( self: Union[str, Any], a_: Any ): '''simple docstring''' _snake_case : Optional[Any] = Node(a_ ) _snake_case : Union[str, Any] = self.head _snake_case : List[Any] = new_node def UpperCamelCase_ ( self: Tuple, a_: List[str], a_: Union[str, Any] ): '''simple docstring''' if node_data_a == node_data_a: return else: _snake_case : int = self.head while node_a is not None and node_a.data != node_data_a: _snake_case : List[Any] = node_a.next _snake_case : List[Any] = self.head while node_a is not None and node_a.data != node_data_a: _snake_case : List[Any] = node_a.next if node_a is None or node_a is None: return _snake_case , _snake_case : int = node_a.data, node_a.data if __name__ == "__main__": A_ = LinkedList() for i in range(5, 0, -1): ll.push(i) ll.print_list() ll.swap_nodes(1, 4) print('''After swapping''') ll.print_list()
132
0
"""simple docstring""" from unittest import TestCase from datasets import Sequence, Value from datasets.arrow_dataset import Dataset class UpperCAmelCase (UpperCAmelCase__ ): """simple docstring""" def _snake_case ( self ): return [ {"col_1": 3, "col_2": "a"}, {"col_1": 2, "col_2": "b"}, {"col_1": 1, "col_2": "c"}, {"col_1": 0, "col_2": "d"}, ] def _snake_case ( self ): lowercase__: Any = {'''col_1''': [3, 2, 1, 0], '''col_2''': ['''a''', '''b''', '''c''', '''d''']} return Dataset.from_dict(SCREAMING_SNAKE_CASE__ ) def _snake_case ( self ): lowercase__: List[str] = self._create_example_records() lowercase__: List[Any] = Dataset.from_list(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(dset.column_names , ['''col_1''', '''col_2'''] ) for i, r in enumerate(SCREAMING_SNAKE_CASE__ ): self.assertDictEqual(SCREAMING_SNAKE_CASE__ , example_records[i] ) def _snake_case ( self ): lowercase__: Dict = self._create_example_records() lowercase__: List[Any] = Dataset.from_list(SCREAMING_SNAKE_CASE__ ) lowercase__: Dict = Dataset.from_dict({k: [r[k] for r in example_records] for k in example_records[0]} ) self.assertEqual(dset.info , dset_from_dict.info ) def _snake_case ( self ): # checks what happens with missing columns lowercase__: List[str] = [{'''col_1''': 1}, {'''col_2''': '''x'''}] lowercase__: int = Dataset.from_list(SCREAMING_SNAKE_CASE__ ) self.assertDictEqual(dset[0] , {'''col_1''': 1} ) self.assertDictEqual(dset[1] , {'''col_1''': None} ) # NB: first record is used for columns def _snake_case ( self ): # checks if the type can be inferred from the second record lowercase__: Union[str, Any] = [{'''col_1''': []}, {'''col_1''': [1, 2]}] lowercase__: List[Any] = Dataset.from_list(SCREAMING_SNAKE_CASE__ ) self.assertEqual(dset.info.features['''col_1'''] , Sequence(Value('''int64''' ) ) ) def _snake_case ( self ): lowercase__: str = Dataset.from_list([] ) self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , 0 ) self.assertListEqual(dset.column_names , [] )
177
'''simple docstring''' from abc import ABC, abstractmethod from argparse import ArgumentParser class _lowercase ( UpperCAmelCase__ ): '''simple docstring''' @staticmethod @abstractmethod def a ( SCREAMING_SNAKE_CASE__ : ArgumentParser ) -> Tuple: raise NotImplementedError() @abstractmethod def a ( self : int ) -> Union[str, Any]: raise NotImplementedError()
229
0
"""simple docstring""" from math import sqrt import numpy as np from sympy import symbols # Coefficient # Speed of light (m/s) UpperCamelCase_ =299_792_458 # Symbols UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ =symbols("""ct x y z""") def a_ ( _lowercase ): if velocity > c: raise ValueError('''Speed must not exceed light speed 299,792,458 [m/s]!''' ) elif velocity < 1: # Usually the speed should be much higher than 1 (c order of magnitude) raise ValueError('''Speed must be greater than or equal to 1!''' ) return velocity / c def a_ ( _lowercase ): return 1 / sqrt(1 - beta(_lowercase ) ** 2 ) def a_ ( _lowercase ): return np.array( [ [gamma(_lowercase ), -gamma(_lowercase ) * beta(_lowercase ), 0, 0], [-gamma(_lowercase ) * beta(_lowercase ), gamma(_lowercase ), 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], ] ) def a_ ( _lowercase , _lowercase = None ): # Ensure event is not empty if event is None: _UpperCamelCase : Dict = np.array([ct, x, y, z] ) # Symbolic four vector else: event[0] *= c # x0 is ct (speed of light * time) return transformation_matrix(_lowercase ) @ event if __name__ == "__main__": import doctest doctest.testmod() # Example of symbolic vector: UpperCamelCase_ =transform(29_979_245) print("""Example of four vector: """) print(F"ct' = {four_vector[0]}") print(F"x' = {four_vector[1]}") print(F"y' = {four_vector[2]}") print(F"z' = {four_vector[3]}") # Substitute symbols with numerical values UpperCamelCase_ ={ct: c, x: 1, y: 1, z: 1} UpperCamelCase_ =[four_vector[i].subs(sub_dict) for i in range(4)] print(F"\n{numerical_vector}")
128
"""simple docstring""" from ..utils import is_flax_available, is_torch_available if is_torch_available(): from .autoencoder_kl import AutoencoderKL from .controlnet import ControlNetModel from .dual_transformer_ad import DualTransformeraDModel from .modeling_utils import ModelMixin from .prior_transformer import PriorTransformer from .ta_film_transformer import TaFilmDecoder from .transformer_ad import TransformeraDModel from .unet_ad import UNetaDModel from .unet_ad import UNetaDModel from .unet_ad_condition import UNetaDConditionModel from .unet_ad_condition import UNetaDConditionModel from .vq_model import VQModel if is_flax_available(): from .controlnet_flax import FlaxControlNetModel from .unet_ad_condition_flax import FlaxUNetaDConditionModel from .vae_flax import FlaxAutoencoderKL
128
1
def UpperCamelCase__( UpperCamelCase__ : list[list[float]] )->Tuple: A__ = [] for data in source_data: for i, el in enumerate(SCREAMING_SNAKE_CASE_ ): if len(SCREAMING_SNAKE_CASE_ ) < i + 1: data_lists.append([] ) data_lists[i].append(float(SCREAMING_SNAKE_CASE_ ) ) return data_lists def UpperCamelCase__( UpperCamelCase__ : list[list[float]] , UpperCamelCase__ : list[int] )->int: A__ = [] for dlist, weight in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): A__ = min(SCREAMING_SNAKE_CASE_ ) A__ = max(SCREAMING_SNAKE_CASE_ ) A__ = [] # for weight 0 score is 1 - actual score if weight == 0: for item in dlist: try: score.append(1 - ((item - mind) / (maxd - mind)) ) except ZeroDivisionError: score.append(1 ) elif weight == 1: for item in dlist: try: score.append((item - mind) / (maxd - mind) ) except ZeroDivisionError: score.append(0 ) # weight not 0 or 1 else: A__ = f"Invalid weight of {weight:f} provided" raise ValueError(SCREAMING_SNAKE_CASE_ ) score_lists.append(SCREAMING_SNAKE_CASE_ ) return score_lists def UpperCamelCase__( UpperCamelCase__ : list[list[float]] )->Dict: A__ = [0 for i in range(len(score_lists[0] ) )] for slist in score_lists: for j, ele in enumerate(SCREAMING_SNAKE_CASE_ ): A__ = final_scores[j] + ele return final_scores def UpperCamelCase__( UpperCamelCase__ : list[list[float]] , UpperCamelCase__ : list[int] )->List[Any]: A__ = get_data(SCREAMING_SNAKE_CASE_ ) A__ = calculate_each_score(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) A__ = generate_final_scores(SCREAMING_SNAKE_CASE_ ) # append scores to source data for i, ele in enumerate(SCREAMING_SNAKE_CASE_ ): source_data[i].append(SCREAMING_SNAKE_CASE_ ) return source_data
193
'''simple docstring''' def __a(SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int ): '''simple docstring''' while a != 0: _lowerCAmelCase , _lowerCAmelCase = b % a, a return b def __a(SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int ): '''simple docstring''' if gcd(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) != 1: _lowerCAmelCase = F'''mod inverse of {a!r} and {m!r} does not exist''' raise ValueError(SCREAMING_SNAKE_CASE_ ) _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase = 1, 0, a _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase = 0, 1, m while va != 0: _lowerCAmelCase = ua // va _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase = (ua - q * va), (ua - q * va), (ua - q * va), va, va, va return ua % m
158
0
"""simple docstring""" import math from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase__ = logging.get_logger(__name__) lowercase__ = { """facebook/data2vec-base-960h""": """https://huggingface.co/facebook/data2vec-audio-base-960h/resolve/main/config.json""", # See all Data2VecAudio models at https://huggingface.co/models?filter=data2vec-audio } class lowerCAmelCase__ ( lowercase ): '''simple docstring''' lowerCamelCase__ = """data2vec-audio""" def __init__( self , lowercase=32 , lowercase=768 , lowercase=12 , lowercase=12 , lowercase=3072 , lowercase="gelu" , lowercase=0.1 , lowercase=0.1 , lowercase=0.1 , lowercase=0.0 , lowercase=0.1 , lowercase=0.1 , lowercase=0.02 , lowercase=1E-5 , lowercase="gelu" , lowercase=(512, 512, 512, 512, 512, 512, 512) , lowercase=(5, 2, 2, 2, 2, 2, 2) , lowercase=(10, 3, 3, 3, 3, 2, 2) , lowercase=False , lowercase=16 , lowercase=19 , lowercase=5 , lowercase=0.05 , lowercase=10 , lowercase=2 , lowercase=0.0 , lowercase=10 , lowercase=0 , lowercase="sum" , lowercase=False , lowercase=False , lowercase=256 , lowercase=(512, 512, 512, 512, 1500) , lowercase=(5, 3, 3, 1, 1) , lowercase=(1, 2, 3, 1, 1) , lowercase=512 , lowercase=0 , lowercase=1 , lowercase=2 , lowercase=False , lowercase=3 , lowercase=2 , lowercase=3 , lowercase=None , **lowercase , ): super().__init__(**lowercase , pad_token_id=lowercase , bos_token_id=lowercase , eos_token_id=lowercase ) _lowerCamelCase : str = hidden_size _lowerCamelCase : str = feat_extract_activation _lowerCamelCase : Optional[Any] = list(lowercase ) _lowerCamelCase : Dict = list(lowercase ) _lowerCamelCase : Dict = list(lowercase ) _lowerCamelCase : Optional[Any] = conv_bias _lowerCamelCase : Union[str, Any] = num_conv_pos_embeddings _lowerCamelCase : List[Any] = num_conv_pos_embedding_groups _lowerCamelCase : List[Any] = conv_pos_kernel_size _lowerCamelCase : Optional[int] = len(self.conv_dim ) _lowerCamelCase : List[str] = num_hidden_layers _lowerCamelCase : Any = intermediate_size _lowerCamelCase : List[str] = hidden_act _lowerCamelCase : Tuple = num_attention_heads _lowerCamelCase : Any = hidden_dropout _lowerCamelCase : Union[str, Any] = attention_dropout _lowerCamelCase : str = activation_dropout _lowerCamelCase : Any = feat_proj_dropout _lowerCamelCase : Tuple = final_dropout _lowerCamelCase : Union[str, Any] = layerdrop _lowerCamelCase : List[Any] = layer_norm_eps _lowerCamelCase : Optional[Any] = initializer_range _lowerCamelCase : Optional[int] = vocab_size _lowerCamelCase : Tuple = use_weighted_layer_sum if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( 'Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==' ' `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =' F''' {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`,''' F''' `len(config.conv_kernel) = {len(self.conv_kernel )}`.''' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 _lowerCamelCase : Optional[Any] = mask_time_prob _lowerCamelCase : List[Any] = mask_time_length _lowerCamelCase : List[Any] = mask_time_min_masks _lowerCamelCase : Tuple = mask_feature_prob _lowerCamelCase : Optional[Any] = mask_feature_length _lowerCamelCase : Dict = mask_feature_min_masks # ctc loss _lowerCamelCase : Tuple = ctc_loss_reduction _lowerCamelCase : str = ctc_zero_infinity # adapter _lowerCamelCase : Union[str, Any] = add_adapter _lowerCamelCase : List[Any] = adapter_kernel_size _lowerCamelCase : Optional[Any] = adapter_stride _lowerCamelCase : List[Any] = num_adapter_layers _lowerCamelCase : int = output_hidden_size or hidden_size # SequenceClassification-specific parameter. Feel free to ignore for other classes. _lowerCamelCase : Optional[int] = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. _lowerCamelCase : List[str] = list(lowercase ) _lowerCamelCase : Optional[Any] = list(lowercase ) _lowerCamelCase : Any = list(lowercase ) _lowerCamelCase : Optional[Any] = xvector_output_dim @property def A_ ( self ): return math.prod(self.conv_stride )
12
"""simple docstring""" import string # frequency taken from https://en.wikipedia.org/wiki/Letter_frequency lowercase__ = { """E""": 12.70, """T""": 9.06, """A""": 8.17, """O""": 7.51, """I""": 6.97, """N""": 6.75, """S""": 6.33, """H""": 6.09, """R""": 5.99, """D""": 4.25, """L""": 4.03, """C""": 2.78, """U""": 2.76, """M""": 2.41, """W""": 2.36, """F""": 2.23, """G""": 2.02, """Y""": 1.97, """P""": 1.93, """B""": 1.29, """V""": 0.98, """K""": 0.77, """J""": 0.15, """X""": 0.15, """Q""": 0.10, """Z""": 0.07, } lowercase__ = """ETAOINSHRDLCUMWFGYPBVKJXQZ""" lowercase__ = """ABCDEFGHIJKLMNOPQRSTUVWXYZ""" def _snake_case ( lowercase__ ): _lowerCamelCase : Tuple = {letter: 0 for letter in string.ascii_uppercase} for letter in message.upper(): if letter in LETTERS: letter_count[letter] += 1 return letter_count def _snake_case ( lowercase__ ): return x[0] def _snake_case ( lowercase__ ): _lowerCamelCase : List[Any] = get_letter_count(lowercase__ ) _lowerCamelCase : dict[int, list[str]] = { freq: [] for letter, freq in letter_to_freq.items() } for letter in LETTERS: freq_to_letter[letter_to_freq[letter]].append(lowercase__ ) _lowerCamelCase : dict[int, str] = {} for freq in freq_to_letter: freq_to_letter[freq].sort(key=ETAOIN.find , reverse=lowercase__ ) _lowerCamelCase : Optional[int] = ''.join(freq_to_letter[freq] ) _lowerCamelCase : Any = list(freq_to_letter_str.items() ) freq_pairs.sort(key=lowercase__ , reverse=lowercase__ ) _lowerCamelCase : list[str] = [freq_pair[1] for freq_pair in freq_pairs] return "".join(lowercase__ ) def _snake_case ( lowercase__ ): _lowerCamelCase : str = get_frequency_order(lowercase__ ) _lowerCamelCase : Union[str, Any] = 0 for common_letter in ETAOIN[:6]: if common_letter in freq_order[:6]: match_score += 1 for uncommon_letter in ETAOIN[-6:]: if uncommon_letter in freq_order[-6:]: match_score += 1 return match_score if __name__ == "__main__": import doctest doctest.testmod()
12
1
import heapq def _lowerCamelCase( lowercase__ ) -> List[str]: '''simple docstring''' __lowercase= [] # for each node and his adjacency list add them and the rank of the node to queue # using heapq module the queue will be filled like a Priority Queue # heapq works with a min priority queue, so I used -1*len(v) to build it for key, value in graph.items(): # O(log(n)) heapq.heappush(lowercase__ , [-1 * len(lowercase__ ), (key, value)] ) # chosen_vertices = set of chosen vertices __lowercase= set() # while queue isn't empty and there are still edges # (queue[0][0] is the rank of the node with max rank) while queue and queue[0][0] != 0: # extract vertex with max rank from queue and add it to chosen_vertices __lowercase= heapq.heappop(lowercase__ )[1][0] chosen_vertices.add(lowercase__ ) # Remove all arcs adjacent to argmax for elem in queue: # if v haven't adjacent node, skip if elem[0] == 0: continue # if argmax is reachable from elem # remove argmax from elem's adjacent list and update his rank if argmax in elem[1][1]: __lowercase= elem[1][1].index(lowercase__ ) del elem[1][1][index] elem[0] += 1 # re-order the queue heapq.heapify(lowercase__ ) return chosen_vertices if __name__ == "__main__": import doctest doctest.testmod() lowerCAmelCase = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} print(F'Minimum vertex cover:\n{greedy_min_vertex_cover(graph)}')
295
'''simple docstring''' import math class lowerCAmelCase : def snake_case ( self : Optional[int] , __lowercase : list[list[float]] , __lowercase : list[int] ): """simple docstring""" __lowercase =0.0 __lowercase =0.0 for i in range(len(__lowercase ) ): da += math.pow((sample[i] - weights[0][i]) , 2 ) da += math.pow((sample[i] - weights[1][i]) , 2 ) return 0 if da > da else 1 return 0 def snake_case ( self : Union[str, Any] , __lowercase : list[list[int | float]] , __lowercase : list[int] , __lowercase : int , __lowercase : float ): """simple docstring""" for i in range(len(__lowercase ) ): weights[j][i] += alpha * (sample[i] - weights[j][i]) return weights def __UpperCamelCase ( ): '''simple docstring''' __lowercase =[[1, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 0, 1, 1]] # weight initialization ( n, C ) __lowercase =[[0.2, 0.6, 0.5, 0.9], [0.8, 0.4, 0.7, 0.3]] # training __lowercase =SelfOrganizingMap() __lowercase =3 __lowercase =0.5 for _ in range(lowercase__ ): for j in range(len(lowercase__ ) ): # training sample __lowercase =training_samples[j] # Compute the winning vector __lowercase =self_organizing_map.get_winner(lowercase__, lowercase__ ) # Update the winning vector __lowercase =self_organizing_map.update(lowercase__, lowercase__, lowercase__, lowercase__ ) # classify test sample __lowercase =[0, 0, 0, 1] __lowercase =self_organizing_map.get_winner(lowercase__, lowercase__ ) # results print(F'''Clusters that the test sample belongs to : {winner}''' ) print(F'''Weights that have been trained : {weights}''' ) # running the main() function if __name__ == "__main__": main()
141
0
"""simple docstring""" import json import os import unittest from transformers.models.blenderbot_small.tokenization_blenderbot_small import ( VOCAB_FILES_NAMES, BlenderbotSmallTokenizer, ) from ...test_tokenization_common import TokenizerTesterMixin class __a (__a , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :int = BlenderbotSmallTokenizer _SCREAMING_SNAKE_CASE :Optional[int] = False def _a ( self ) -> List[Any]: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ : int = ["""__start__""", """adapt""", """act""", """ap@@""", """te""", """__end__""", """__unk__"""] SCREAMING_SNAKE_CASE__ : Dict = dict(zip(a__ , range(len(a__ ) ) ) ) SCREAMING_SNAKE_CASE__ : Tuple = ["""#version: 0.2""", """a p""", """t e</w>""", """ap t</w>""", """a d""", """ad apt</w>""", """a c""", """ac t</w>""", """"""] SCREAMING_SNAKE_CASE__ : Union[str, Any] = {"""unk_token""": """__unk__""", """bos_token""": """__start__""", """eos_token""": """__end__"""} SCREAMING_SNAKE_CASE__ : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) SCREAMING_SNAKE_CASE__ : Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(a__ ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(a__ ) ) def _a ( self , **_a ) -> int: """simple docstring""" kwargs.update(self.special_tokens_map ) return BlenderbotSmallTokenizer.from_pretrained(self.tmpdirname , **a__ ) def _a ( self , _a ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = """adapt act apte""" SCREAMING_SNAKE_CASE__ : Any = """adapt act apte""" return input_text, output_text def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = BlenderbotSmallTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = """adapt act apte""" SCREAMING_SNAKE_CASE__ : int = ["""adapt""", """act""", """ap@@""", """te"""] SCREAMING_SNAKE_CASE__ : str = tokenizer.tokenize(a__ ) self.assertListEqual(a__ , a__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = [tokenizer.bos_token] + tokens + [tokenizer.eos_token] SCREAMING_SNAKE_CASE__ : Dict = [0, 1, 2, 3, 4, 5] self.assertListEqual(tokenizer.convert_tokens_to_ids(a__ ) , a__ ) def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = BlenderbotSmallTokenizer.from_pretrained("""facebook/blenderbot-90M""" ) assert tok("""sam""" ).input_ids == [1_384] SCREAMING_SNAKE_CASE__ : int = """I am a small frog.""" SCREAMING_SNAKE_CASE__ : Optional[Any] = tok([src_text] , padding=a__ , truncation=a__ )["""input_ids"""] SCREAMING_SNAKE_CASE__ : Optional[int] = tok.batch_decode(a__ , skip_special_tokens=a__ , clean_up_tokenization_spaces=a__ )[0] assert src_text != decoded # I wish it did! assert decoded == "i am a small frog ." def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = BlenderbotSmallTokenizer.from_pretrained("""facebook/blenderbot-90M""" ) SCREAMING_SNAKE_CASE__ : List[Any] = """I am a small frog .""" SCREAMING_SNAKE_CASE__ : int = """.""" SCREAMING_SNAKE_CASE__ : Tuple = tok(a__ )["""input_ids"""] SCREAMING_SNAKE_CASE__ : List[str] = tok(a__ )["""input_ids"""] assert encoded[-1] == encoded_dot[0]
359
"""simple docstring""" import importlib.metadata import warnings from copy import deepcopy from packaging import version from ..utils import logging from .import_utils import is_accelerate_available, is_bitsandbytes_available if is_bitsandbytes_available(): import bitsandbytes as bnb import torch import torch.nn as nn from ..pytorch_utils import ConvaD if is_accelerate_available(): from accelerate import init_empty_weights from accelerate.utils import find_tied_parameters a :Optional[Any] = logging.get_logger(__name__) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase=None , __lowerCAmelCase=None ) -> List[str]: # Recurse if needed if "." in tensor_name: SCREAMING_SNAKE_CASE__ : List[Any] = tensor_name.split(""".""" ) for split in splits[:-1]: SCREAMING_SNAKE_CASE__ : Dict = getattr(__lowerCAmelCase , __lowerCAmelCase ) if new_module is None: raise ValueError(F'''{module} has no attribute {split}.''' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = new_module SCREAMING_SNAKE_CASE__ : Any = splits[-1] if tensor_name not in module._parameters and tensor_name not in module._buffers: raise ValueError(F'''{module} does not have a parameter or a buffer named {tensor_name}.''' ) SCREAMING_SNAKE_CASE__ : List[str] = tensor_name in module._buffers SCREAMING_SNAKE_CASE__ : Dict = getattr(__lowerCAmelCase , __lowerCAmelCase ) if old_value.device == torch.device("""meta""" ) and device not in ["meta", torch.device("""meta""" )] and value is None: raise ValueError(F'''{tensor_name} is on the meta device, we need a `value` to put in on {device}.''' ) SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : str = False if is_buffer or not is_bitsandbytes_available(): SCREAMING_SNAKE_CASE__ : Optional[int] = False SCREAMING_SNAKE_CASE__ : List[Any] = False else: SCREAMING_SNAKE_CASE__ : str = hasattr(bnb.nn , """Params4bit""" ) and isinstance(module._parameters[tensor_name] , bnb.nn.Paramsabit ) SCREAMING_SNAKE_CASE__ : str = isinstance(module._parameters[tensor_name] , bnb.nn.IntaParams ) if is_abit or is_abit: SCREAMING_SNAKE_CASE__ : Dict = module._parameters[tensor_name] if param.device.type != "cuda": if value is None: SCREAMING_SNAKE_CASE__ : Tuple = old_value.to(__lowerCAmelCase ) elif isinstance(__lowerCAmelCase , torch.Tensor ): SCREAMING_SNAKE_CASE__ : int = value.to("""cpu""" ) if value.dtype == torch.inta: SCREAMING_SNAKE_CASE__ : str = version.parse(importlib.metadata.version("""bitsandbytes""" ) ) > version.parse( """0.37.2""" ) if not is_abit_serializable: raise ValueError( """Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. """ """Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`.""" ) else: SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor(__lowerCAmelCase , device="""cpu""" ) # Support models using `Conv1D` in place of `nn.Linear` (e.g. gpt2) by transposing the weight matrix prior to quantization. # Since weights are saved in the correct "orientation", we skip transposing when loading. if issubclass(module.source_cls , __lowerCAmelCase ) and fpaa_statistics is None: SCREAMING_SNAKE_CASE__ : Optional[int] = new_value.T SCREAMING_SNAKE_CASE__ : Union[str, Any] = old_value.__dict__ if is_abit: SCREAMING_SNAKE_CASE__ : str = bnb.nn.IntaParams(__lowerCAmelCase , requires_grad=__lowerCAmelCase , **__lowerCAmelCase ).to(__lowerCAmelCase ) elif is_abit: SCREAMING_SNAKE_CASE__ : Union[str, Any] = bnb.nn.Paramsabit(__lowerCAmelCase , requires_grad=__lowerCAmelCase , **__lowerCAmelCase ).to(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = new_value if fpaa_statistics is not None: setattr(module.weight , """SCB""" , fpaa_statistics.to(__lowerCAmelCase ) ) else: if value is None: SCREAMING_SNAKE_CASE__ : str = old_value.to(__lowerCAmelCase ) elif isinstance(__lowerCAmelCase , torch.Tensor ): SCREAMING_SNAKE_CASE__ : List[str] = value.to(__lowerCAmelCase ) else: SCREAMING_SNAKE_CASE__ : Optional[int] = torch.tensor(__lowerCAmelCase , device=__lowerCAmelCase ) if is_buffer: SCREAMING_SNAKE_CASE__ : List[str] = new_value else: SCREAMING_SNAKE_CASE__ : List[Any] = nn.Parameter(__lowerCAmelCase , requires_grad=old_value.requires_grad ) SCREAMING_SNAKE_CASE__ : Dict = new_value def _lowercase ( __lowerCAmelCase , __lowerCAmelCase=None , __lowerCAmelCase=None , __lowerCAmelCase=None , __lowerCAmelCase=False ) -> List[Any]: for name, module in model.named_children(): if current_key_name is None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] current_key_name.append(__lowerCAmelCase ) if (isinstance(__lowerCAmelCase , nn.Linear ) or isinstance(__lowerCAmelCase , __lowerCAmelCase )) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` if not any(key in """.""".join(__lowerCAmelCase ) for key in modules_to_not_convert ): with init_empty_weights(): if isinstance(__lowerCAmelCase , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple = module.weight.shape else: SCREAMING_SNAKE_CASE__ : str = module.in_features SCREAMING_SNAKE_CASE__ : Dict = module.out_features if quantization_config.quantization_method() == "llm_int8": SCREAMING_SNAKE_CASE__ : Dict = bnb.nn.LinearabitLt( __lowerCAmelCase , __lowerCAmelCase , module.bias is not None , has_fpaa_weights=quantization_config.llm_inta_has_fpaa_weight , threshold=quantization_config.llm_inta_threshold , ) SCREAMING_SNAKE_CASE__ : Tuple = True else: if ( quantization_config.llm_inta_skip_modules is not None and name in quantization_config.llm_inta_skip_modules ): pass else: SCREAMING_SNAKE_CASE__ : Optional[int] = bnb.nn.Linearabit( __lowerCAmelCase , __lowerCAmelCase , module.bias is not None , quantization_config.bnb_abit_compute_dtype , compress_statistics=quantization_config.bnb_abit_use_double_quant , quant_type=quantization_config.bnb_abit_quant_type , ) SCREAMING_SNAKE_CASE__ : int = True # Store the module class in case we need to transpose the weight later SCREAMING_SNAKE_CASE__ : Dict = type(__lowerCAmelCase ) # Force requires grad to False to avoid unexpected errors model._modules[name].requires_grad_(__lowerCAmelCase ) if len(list(module.children() ) ) > 0: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple = _replace_with_bnb_linear( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , has_been_replaced=__lowerCAmelCase , ) # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def _lowercase ( __lowerCAmelCase , __lowerCAmelCase=None , __lowerCAmelCase=None , __lowerCAmelCase=None ) -> str: SCREAMING_SNAKE_CASE__ : int = ["""lm_head"""] if modules_to_not_convert is None else modules_to_not_convert SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = _replace_with_bnb_linear( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) if not has_been_replaced: logger.warning( """You are loading your model in 8bit or 4bit but no linear modules were found in your model.""" """ Please double check your model architecture, or submit an issue on github if you think this is""" """ a bug.""" ) return model def _lowercase ( *__lowerCAmelCase , **__lowerCAmelCase ) -> Any: warnings.warn( """`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead""" , __lowerCAmelCase , ) return replace_with_bnb_linear(*__lowerCAmelCase , **__lowerCAmelCase ) def _lowercase ( *__lowerCAmelCase , **__lowerCAmelCase ) -> Union[str, Any]: warnings.warn( """`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead""" , __lowerCAmelCase , ) return set_module_quantized_tensor_to_device(*__lowerCAmelCase , **__lowerCAmelCase ) def _lowercase ( __lowerCAmelCase ) -> Tuple: SCREAMING_SNAKE_CASE__ : List[Any] = deepcopy(__lowerCAmelCase ) # this has 0 cost since it is done inside `init_empty_weights` context manager` tied_model.tie_weights() SCREAMING_SNAKE_CASE__ : List[str] = find_tied_parameters(__lowerCAmelCase ) # For compatibility with Accelerate < 0.18 if isinstance(__lowerCAmelCase , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() ) else: SCREAMING_SNAKE_CASE__ : List[Any] = sum(__lowerCAmelCase , [] ) SCREAMING_SNAKE_CASE__ : str = len(__lowerCAmelCase ) > 0 # Check if it is a base model SCREAMING_SNAKE_CASE__ : Optional[int] = not hasattr(__lowerCAmelCase , model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head SCREAMING_SNAKE_CASE__ : int = list(model.named_children() ) SCREAMING_SNAKE_CASE__ : str = [list_modules[-1][0]] # add last module together with tied weights SCREAMING_SNAKE_CASE__ : Any = set(__lowerCAmelCase ) - set(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = list(set(__lowerCAmelCase ) ) + list(__lowerCAmelCase ) # remove ".weight" from the keys SCREAMING_SNAKE_CASE__ : Any = [""".weight""", """.bias"""] SCREAMING_SNAKE_CASE__ : Optional[Any] = [] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: SCREAMING_SNAKE_CASE__ : Optional[int] = name.replace(__lowerCAmelCase , """""" ) filtered_module_names.append(__lowerCAmelCase ) return filtered_module_names
56
0
"""simple docstring""" import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import SPIECE_UNDERLINE, logging _a : str= logging.get_logger(__name__) _a : str= {"vocab_file": "spiece.model"} _a : Tuple= { "vocab_file": { "xlnet-base-cased": "https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model", "xlnet-large-cased": "https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model", } } _a : int= { "xlnet-base-cased": None, "xlnet-large-cased": None, } # Segments (not really needed) _a : Optional[int]= 0 _a : str= 1 _a : Tuple= 2 _a : str= 3 _a : Optional[Any]= 4 class UpperCamelCase ( lowercase ): UpperCAmelCase : Union[str, Any] = VOCAB_FILES_NAMES UpperCAmelCase : int = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase : str = """left""" def __init__(self : List[Any] , _A : List[str] , _A : int=False , _A : Tuple=True , _A : Optional[Any]=False , _A : List[Any]="<s>" , _A : Dict="</s>" , _A : str="<unk>" , _A : Optional[Any]="<sep>" , _A : Optional[Any]="<pad>" , _A : Optional[Any]="<cls>" , _A : Dict="<mask>" , _A : List[Any]=["<eop>", "<eod>"] , _A : Optional[Dict[str, Any]] = None , **_A : List[str] , ) -> None: # Mask token behave like a normal word, i.e. include the space before it __snake_case : str = AddedToken(_A , lstrip=_A , rstrip=_A) if isinstance(_A , _A) else mask_token __snake_case : Dict = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=_A , remove_space=_A , keep_accents=_A , bos_token=_A , eos_token=_A , unk_token=_A , sep_token=_A , pad_token=_A , cls_token=_A , mask_token=_A , additional_special_tokens=_A , sp_model_kwargs=self.sp_model_kwargs , **_A , ) __snake_case : Tuple = 3 __snake_case : Optional[int] = do_lower_case __snake_case : Union[str, Any] = remove_space __snake_case : Dict = keep_accents __snake_case : str = vocab_file __snake_case : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(_A) @property def _lowercase (self : Dict) -> List[str]: return len(self.sp_model) def _lowercase (self : Dict) -> Union[str, Any]: __snake_case : str = {self.convert_ids_to_tokens(_A): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def __getstate__(self : Union[str, Any]) -> List[str]: __snake_case : Optional[Any] = self.__dict__.copy() __snake_case : Union[str, Any] = None return state def __setstate__(self : Union[str, Any] , _A : Optional[Any]) -> str: __snake_case : Optional[int] = d # for backward compatibility if not hasattr(self , 'sp_model_kwargs'): __snake_case : List[Any] = {} __snake_case : Any = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(self.vocab_file) def _lowercase (self : Any , _A : Tuple) -> List[str]: if self.remove_space: __snake_case : List[Any] = ' '.join(inputs.strip().split()) else: __snake_case : Tuple = inputs __snake_case : int = outputs.replace('``' , '"').replace('\'\'' , '"') if not self.keep_accents: __snake_case : str = unicodedata.normalize('NFKD' , _A) __snake_case : Tuple = ''.join([c for c in outputs if not unicodedata.combining(_A)]) if self.do_lower_case: __snake_case : Union[str, Any] = outputs.lower() return outputs def _lowercase (self : List[Any] , _A : str) -> List[str]: __snake_case : int = self.preprocess_text(_A) __snake_case : Dict = self.sp_model.encode(_A , out_type=_A) __snake_case : Union[str, Any] = [] for piece in pieces: if len(_A) > 1 and piece[-1] == str(',') and piece[-2].isdigit(): __snake_case : List[str] = self.sp_model.EncodeAsPieces(piece[:-1].replace(_A , '')) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0]) == 1: __snake_case : List[str] = cur_pieces[1:] else: __snake_case : Union[str, Any] = cur_pieces[0][1:] cur_pieces.append(piece[-1]) new_pieces.extend(_A) else: new_pieces.append(_A) return new_pieces def _lowercase (self : Union[str, Any] , _A : Union[str, Any]) -> Any: return self.sp_model.PieceToId(_A) def _lowercase (self : Tuple , _A : str) -> Optional[int]: return self.sp_model.IdToPiece(_A) def _lowercase (self : List[str] , _A : Dict) -> List[Any]: __snake_case : str = ''.join(_A).replace(_A , ' ').strip() return out_string def _lowercase (self : Dict , _A : List[int] , _A : bool = False , _A : bool = None , _A : bool = True , **_A : str , ) -> str: __snake_case : Tuple = kwargs.pop('use_source_tokenizer' , _A) __snake_case : Tuple = self.convert_ids_to_tokens(_A , skip_special_tokens=_A) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 __snake_case : List[str] = [] __snake_case : str = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(_A)) __snake_case : List[Any] = [] sub_texts.append(_A) else: current_sub_text.append(_A) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(_A)) # Mimic the behavior of the Rust tokenizer: # By default, there are no spaces between special tokens __snake_case : Optional[int] = ''.join(_A) __snake_case : str = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: __snake_case : str = self.clean_up_tokenization(_A) return clean_text else: return text def _lowercase (self : Dict , _A : List[int] , _A : Optional[List[int]] = None) -> List[int]: __snake_case : int = [self.sep_token_id] __snake_case : Any = [self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def _lowercase (self : List[str] , _A : List[int] , _A : Optional[List[int]] = None , _A : bool = False) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_A , token_ids_a=_A , already_has_special_tokens=_A) if token_ids_a is not None: return ([0] * len(_A)) + [1] + ([0] * len(_A)) + [1, 1] return ([0] * len(_A)) + [1, 1] def _lowercase (self : Dict , _A : List[int] , _A : Optional[List[int]] = None) -> List[int]: __snake_case : Tuple = [self.sep_token_id] __snake_case : Optional[int] = [2] if token_ids_a is None: return len(token_ids_a + sep) * [0] + cls_segment_id return len(token_ids_a + sep) * [0] + len(token_ids_a + sep) * [1] + cls_segment_id def _lowercase (self : Tuple , _A : str , _A : Optional[str] = None) -> Tuple[str]: if not os.path.isdir(_A): logger.error(f"Vocabulary path ({save_directory}) should be a directory") return __snake_case : str = os.path.join( _A , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']) if os.path.abspath(self.vocab_file) != os.path.abspath(_A) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file , _A) elif not os.path.isfile(self.vocab_file): with open(_A , 'wb') as fi: __snake_case : Tuple = self.sp_model.serialized_model_proto() fi.write(_A) return (out_vocab_file,)
172
"""simple docstring""" import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import SPIECE_UNDERLINE, logging _a : str= logging.get_logger(__name__) _a : str= {"vocab_file": "spiece.model"} _a : Tuple= { "vocab_file": { "xlnet-base-cased": "https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model", "xlnet-large-cased": "https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model", } } _a : int= { "xlnet-base-cased": None, "xlnet-large-cased": None, } # Segments (not really needed) _a : Optional[int]= 0 _a : str= 1 _a : Tuple= 2 _a : str= 3 _a : Optional[Any]= 4 class UpperCamelCase ( lowercase ): UpperCAmelCase : Union[str, Any] = VOCAB_FILES_NAMES UpperCAmelCase : int = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase : str = """left""" def __init__(self : List[Any] , _A : List[str] , _A : int=False , _A : Tuple=True , _A : Optional[Any]=False , _A : List[Any]="<s>" , _A : Dict="</s>" , _A : str="<unk>" , _A : Optional[Any]="<sep>" , _A : Optional[Any]="<pad>" , _A : Optional[Any]="<cls>" , _A : Dict="<mask>" , _A : List[Any]=["<eop>", "<eod>"] , _A : Optional[Dict[str, Any]] = None , **_A : List[str] , ) -> None: # Mask token behave like a normal word, i.e. include the space before it __snake_case : str = AddedToken(_A , lstrip=_A , rstrip=_A) if isinstance(_A , _A) else mask_token __snake_case : Dict = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=_A , remove_space=_A , keep_accents=_A , bos_token=_A , eos_token=_A , unk_token=_A , sep_token=_A , pad_token=_A , cls_token=_A , mask_token=_A , additional_special_tokens=_A , sp_model_kwargs=self.sp_model_kwargs , **_A , ) __snake_case : Tuple = 3 __snake_case : Optional[int] = do_lower_case __snake_case : Union[str, Any] = remove_space __snake_case : Dict = keep_accents __snake_case : str = vocab_file __snake_case : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(_A) @property def _lowercase (self : Dict) -> List[str]: return len(self.sp_model) def _lowercase (self : Dict) -> Union[str, Any]: __snake_case : str = {self.convert_ids_to_tokens(_A): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def __getstate__(self : Union[str, Any]) -> List[str]: __snake_case : Optional[Any] = self.__dict__.copy() __snake_case : Union[str, Any] = None return state def __setstate__(self : Union[str, Any] , _A : Optional[Any]) -> str: __snake_case : Optional[int] = d # for backward compatibility if not hasattr(self , 'sp_model_kwargs'): __snake_case : List[Any] = {} __snake_case : Any = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(self.vocab_file) def _lowercase (self : Any , _A : Tuple) -> List[str]: if self.remove_space: __snake_case : List[Any] = ' '.join(inputs.strip().split()) else: __snake_case : Tuple = inputs __snake_case : int = outputs.replace('``' , '"').replace('\'\'' , '"') if not self.keep_accents: __snake_case : str = unicodedata.normalize('NFKD' , _A) __snake_case : Tuple = ''.join([c for c in outputs if not unicodedata.combining(_A)]) if self.do_lower_case: __snake_case : Union[str, Any] = outputs.lower() return outputs def _lowercase (self : List[Any] , _A : str) -> List[str]: __snake_case : int = self.preprocess_text(_A) __snake_case : Dict = self.sp_model.encode(_A , out_type=_A) __snake_case : Union[str, Any] = [] for piece in pieces: if len(_A) > 1 and piece[-1] == str(',') and piece[-2].isdigit(): __snake_case : List[str] = self.sp_model.EncodeAsPieces(piece[:-1].replace(_A , '')) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0]) == 1: __snake_case : List[str] = cur_pieces[1:] else: __snake_case : Union[str, Any] = cur_pieces[0][1:] cur_pieces.append(piece[-1]) new_pieces.extend(_A) else: new_pieces.append(_A) return new_pieces def _lowercase (self : Union[str, Any] , _A : Union[str, Any]) -> Any: return self.sp_model.PieceToId(_A) def _lowercase (self : Tuple , _A : str) -> Optional[int]: return self.sp_model.IdToPiece(_A) def _lowercase (self : List[str] , _A : Dict) -> List[Any]: __snake_case : str = ''.join(_A).replace(_A , ' ').strip() return out_string def _lowercase (self : Dict , _A : List[int] , _A : bool = False , _A : bool = None , _A : bool = True , **_A : str , ) -> str: __snake_case : Tuple = kwargs.pop('use_source_tokenizer' , _A) __snake_case : Tuple = self.convert_ids_to_tokens(_A , skip_special_tokens=_A) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 __snake_case : List[str] = [] __snake_case : str = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(_A)) __snake_case : List[Any] = [] sub_texts.append(_A) else: current_sub_text.append(_A) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(_A)) # Mimic the behavior of the Rust tokenizer: # By default, there are no spaces between special tokens __snake_case : Optional[int] = ''.join(_A) __snake_case : str = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: __snake_case : str = self.clean_up_tokenization(_A) return clean_text else: return text def _lowercase (self : Dict , _A : List[int] , _A : Optional[List[int]] = None) -> List[int]: __snake_case : int = [self.sep_token_id] __snake_case : Any = [self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def _lowercase (self : List[str] , _A : List[int] , _A : Optional[List[int]] = None , _A : bool = False) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_A , token_ids_a=_A , already_has_special_tokens=_A) if token_ids_a is not None: return ([0] * len(_A)) + [1] + ([0] * len(_A)) + [1, 1] return ([0] * len(_A)) + [1, 1] def _lowercase (self : Dict , _A : List[int] , _A : Optional[List[int]] = None) -> List[int]: __snake_case : Tuple = [self.sep_token_id] __snake_case : Optional[int] = [2] if token_ids_a is None: return len(token_ids_a + sep) * [0] + cls_segment_id return len(token_ids_a + sep) * [0] + len(token_ids_a + sep) * [1] + cls_segment_id def _lowercase (self : Tuple , _A : str , _A : Optional[str] = None) -> Tuple[str]: if not os.path.isdir(_A): logger.error(f"Vocabulary path ({save_directory}) should be a directory") return __snake_case : str = os.path.join( _A , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']) if os.path.abspath(self.vocab_file) != os.path.abspath(_A) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file , _A) elif not os.path.isfile(self.vocab_file): with open(_A , 'wb') as fi: __snake_case : Tuple = self.sp_model.serialized_model_proto() fi.write(_A) return (out_vocab_file,)
172
1
'''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 ( a__ , a__ , unittest.TestCase ): __lowercase = StableDiffusionPanoramaPipeline __lowercase = TEXT_TO_IMAGE_PARAMS __lowercase = TEXT_TO_IMAGE_BATCH_PARAMS __lowercase = TEXT_TO_IMAGE_IMAGE_PARAMS __lowercase = TEXT_TO_IMAGE_IMAGE_PARAMS def lowerCamelCase ( self ): """simple docstring""" torch.manual_seed(0 ) _snake_case = 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 , ) _snake_case = DDIMScheduler() torch.manual_seed(0 ) _snake_case = 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 ) _snake_case = 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=10_00 , ) _snake_case = CLIPTextModel(lowerCAmelCase__ ) _snake_case = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) _snake_case = { "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "safety_checker": None, "feature_extractor": None, } return components def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_=0 ): """simple docstring""" _snake_case = torch.manual_seed(lowerCAmelCase__ ) _snake_case = { "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 ): """simple docstring""" _snake_case = "cpu" # ensure determinism for the device-dependent torch.Generator _snake_case = self.get_dummy_components() _snake_case = StableDiffusionPanoramaPipeline(**lowerCAmelCase__ ) _snake_case = sd_pipe.to(lowerCAmelCase__ ) sd_pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) _snake_case = self.get_dummy_inputs(lowerCAmelCase__ ) _snake_case = sd_pipe(**lowerCAmelCase__ ).images _snake_case = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _snake_case = 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 ): """simple docstring""" super().test_inference_batch_consistent(batch_sizes=[1, 2] ) def lowerCamelCase ( self ): """simple docstring""" super().test_inference_batch_single_identical(batch_size=2 , expected_max_diff=3.25E-3 ) def lowerCamelCase ( self ): """simple docstring""" _snake_case = "cpu" # ensure determinism for the device-dependent torch.Generator _snake_case = self.get_dummy_components() _snake_case = StableDiffusionPanoramaPipeline(**lowerCAmelCase__ ) _snake_case = sd_pipe.to(lowerCAmelCase__ ) sd_pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) _snake_case = self.get_dummy_inputs(lowerCAmelCase__ ) _snake_case = "french fries" _snake_case = sd_pipe(**lowerCAmelCase__ , negative_prompt=lowerCAmelCase__ ) _snake_case = output.images _snake_case = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _snake_case = 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 ): """simple docstring""" _snake_case = "cpu" # ensure determinism for the device-dependent torch.Generator _snake_case = self.get_dummy_components() _snake_case = StableDiffusionPanoramaPipeline(**lowerCAmelCase__ ) _snake_case = sd_pipe.to(lowerCAmelCase__ ) sd_pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) _snake_case = self.get_dummy_inputs(lowerCAmelCase__ ) _snake_case = sd_pipe(**lowerCAmelCase__ , view_batch_size=2 ) _snake_case = output.images _snake_case = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _snake_case = 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 ): """simple docstring""" _snake_case = "cpu" # ensure determinism for the device-dependent torch.Generator _snake_case = self.get_dummy_components() _snake_case = EulerAncestralDiscreteScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule='scaled_linear' ) _snake_case = StableDiffusionPanoramaPipeline(**lowerCAmelCase__ ) _snake_case = sd_pipe.to(lowerCAmelCase__ ) sd_pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) _snake_case = self.get_dummy_inputs(lowerCAmelCase__ ) _snake_case = sd_pipe(**lowerCAmelCase__ ).images _snake_case = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _snake_case = 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 ): """simple docstring""" _snake_case = "cpu" # ensure determinism for the device-dependent torch.Generator _snake_case = self.get_dummy_components() _snake_case = PNDMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule='scaled_linear' , skip_prk_steps=lowerCAmelCase__ ) _snake_case = StableDiffusionPanoramaPipeline(**lowerCAmelCase__ ) _snake_case = sd_pipe.to(lowerCAmelCase__ ) sd_pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) _snake_case = self.get_dummy_inputs(lowerCAmelCase__ ) _snake_case = sd_pipe(**lowerCAmelCase__ ).images _snake_case = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _snake_case = 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 ): def lowerCamelCase ( self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCamelCase ( self , lowerCAmelCase_=0 ): """simple docstring""" _snake_case = torch.manual_seed(lowerCAmelCase__ ) _snake_case = { "prompt": "a photo of the dolomites", "generator": generator, "num_inference_steps": 3, "guidance_scale": 7.5, "output_type": "numpy", } return inputs def lowerCamelCase ( self ): """simple docstring""" _snake_case = "stabilityai/stable-diffusion-2-base" _snake_case = DDIMScheduler.from_pretrained(lowerCAmelCase__ , subfolder='scheduler' ) _snake_case = StableDiffusionPanoramaPipeline.from_pretrained(lowerCAmelCase__ , scheduler=lowerCAmelCase__ , safety_checker=lowerCAmelCase__ ) pipe.to(lowerCAmelCase__ ) pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) pipe.enable_attention_slicing() _snake_case = self.get_inputs() _snake_case = pipe(**lowerCAmelCase__ ).images _snake_case = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_12, 20_48, 3) _snake_case = 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 ): """simple docstring""" _snake_case = StableDiffusionPanoramaPipeline.from_pretrained( 'stabilityai/stable-diffusion-2-base' , safety_checker=lowerCAmelCase__ ) _snake_case = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.to(lowerCAmelCase__ ) pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) pipe.enable_attention_slicing() _snake_case = self.get_inputs() _snake_case = pipe(**lowerCAmelCase__ ).images _snake_case = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_12, 20_48, 3) _snake_case = 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 ): """simple docstring""" _snake_case = 0 def callback_fn(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) -> None: _snake_case = True nonlocal number_of_steps number_of_steps += 1 if step == 1: _snake_case = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 2_56) _snake_case = latents[0, -3:, -3:, -1] _snake_case = 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: _snake_case = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 2_56) _snake_case = latents[0, -3:, -3:, -1] _snake_case = 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 _snake_case = False _snake_case = "stabilityai/stable-diffusion-2-base" _snake_case = DDIMScheduler.from_pretrained(lowerCAmelCase__ , subfolder='scheduler' ) _snake_case = StableDiffusionPanoramaPipeline.from_pretrained(lowerCAmelCase__ , scheduler=lowerCAmelCase__ , safety_checker=lowerCAmelCase__ ) _snake_case = pipe.to(lowerCAmelCase__ ) pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) pipe.enable_attention_slicing() _snake_case = self.get_inputs() pipe(**lowerCAmelCase__ , callback=lowerCAmelCase__ , callback_steps=1 ) assert callback_fn.has_been_called assert number_of_steps == 3 def lowerCamelCase ( self ): """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() _snake_case = "stabilityai/stable-diffusion-2-base" _snake_case = DDIMScheduler.from_pretrained(lowerCAmelCase__ , subfolder='scheduler' ) _snake_case = StableDiffusionPanoramaPipeline.from_pretrained(lowerCAmelCase__ , scheduler=lowerCAmelCase__ , safety_checker=lowerCAmelCase__ ) _snake_case = pipe.to(lowerCAmelCase__ ) pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() _snake_case = self.get_inputs() _snake_case = pipe(**lowerCAmelCase__ ) _snake_case = torch.cuda.max_memory_allocated() # make sure that less than 5.2 GB is allocated assert mem_bytes < 5.5 * 10**9
363
'''simple docstring''' import dataclasses import json import sys import types from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, ArgumentTypeError from copy import copy from enum import Enum from inspect import isclass from pathlib import Path from typing import Any, Callable, Dict, Iterable, List, Literal, NewType, Optional, Tuple, Union, get_type_hints import yaml lowercase : int = NewType("DataClass", Any) lowercase : Dict = NewType("DataClassType", Any) def SCREAMING_SNAKE_CASE__ ( __A ) -> Optional[Any]: if isinstance(__A , __A ): return v if v.lower() in ("yes", "true", "t", "y", "1"): return True elif v.lower() in ("no", "false", "f", "n", "0"): return False else: raise ArgumentTypeError( F'Truthy value expected: got {v} but expected one of yes/no, true/false, t/f, y/n, 1/0 (case insensitive).' ) def SCREAMING_SNAKE_CASE__ ( __A ) -> Callable[[str], Any]: _snake_case = {str(__A ): choice for choice in choices} return lambda __A : str_to_choice.get(__A , __A ) def SCREAMING_SNAKE_CASE__ ( *, __A = None , __A = None , __A = dataclasses.MISSING , __A = dataclasses.MISSING , __A = None , **__A , ) -> dataclasses.Field: if metadata is None: # Important, don't use as default param in function signature because dict is mutable and shared across function calls _snake_case = {} if aliases is not None: _snake_case = aliases if help is not None: _snake_case = help return dataclasses.field(metadata=__A , default=__A , default_factory=__A , **__A ) class __UpperCAmelCase ( _lowerCamelCase ): __lowercase = 42 def __init__( self , lowerCAmelCase_ , **lowerCAmelCase_ ): """simple docstring""" if "formatter_class" not in kwargs: _snake_case = ArgumentDefaultsHelpFormatter super().__init__(**lowerCAmelCase_ ) if dataclasses.is_dataclass(lowerCAmelCase_ ): _snake_case = [dataclass_types] _snake_case = list(lowerCAmelCase_ ) for dtype in self.dataclass_types: self._add_dataclass_arguments(lowerCAmelCase_ ) @staticmethod def lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ): """simple docstring""" _snake_case = F'--{field.name}' _snake_case = field.metadata.copy() # field.metadata is not used at all by Data Classes, # it is provided as a third-party extension mechanism. if isinstance(field.type , lowerCAmelCase_ ): raise RuntimeError( 'Unresolved type detected, which should have been done with the help of ' '`typing.get_type_hints` method by default' ) _snake_case = kwargs.pop('aliases' , [] ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): _snake_case = [aliases] _snake_case = getattr(field.type , '__origin__' , field.type ) if origin_type is Union or (hasattr(lowerCAmelCase_ , 'UnionType' ) and isinstance(lowerCAmelCase_ , types.UnionType )): if str not in field.type.__args__ and ( len(field.type.__args__ ) != 2 or type(lowerCAmelCase_ ) not in field.type.__args__ ): raise ValueError( 'Only `Union[X, NoneType]` (i.e., `Optional[X]`) is allowed for `Union` because' ' the argument parser only supports one type per argument.' F' Problem encountered in field \'{field.name}\'.' ) if type(lowerCAmelCase_ ) not in field.type.__args__: # filter `str` in Union _snake_case = field.type.__args__[0] if field.type.__args__[1] == str else field.type.__args__[1] _snake_case = getattr(field.type , '__origin__' , field.type ) elif bool not in field.type.__args__: # filter `NoneType` in Union (except for `Union[bool, NoneType]`) _snake_case = ( field.type.__args__[0] if isinstance(lowerCAmelCase_ , field.type.__args__[1] ) else field.type.__args__[1] ) _snake_case = getattr(field.type , '__origin__' , field.type ) # A variable to store kwargs for a boolean field, if needed # so that we can init a `no_*` complement argument (see below) _snake_case = {} if origin_type is Literal or (isinstance(field.type , lowerCAmelCase_ ) and issubclass(field.type , lowerCAmelCase_ )): if origin_type is Literal: _snake_case = field.type.__args__ else: _snake_case = [x.value for x in field.type] _snake_case = make_choice_type_function(kwargs['choices'] ) if field.default is not dataclasses.MISSING: _snake_case = field.default else: _snake_case = True elif field.type is bool or field.type == Optional[bool]: # Copy the currect kwargs to use to instantiate a `no_*` complement argument below. # We do not initialize it here because the `no_*` alternative must be instantiated after the real argument _snake_case = copy(lowerCAmelCase_ ) # Hack because type=bool in argparse does not behave as we want. _snake_case = string_to_bool if field.type is bool or (field.default is not None and field.default is not dataclasses.MISSING): # Default value is False if we have no default when of type bool. _snake_case = False if field.default is dataclasses.MISSING else field.default # This is the value that will get picked if we don't include --field_name in any way _snake_case = default # This tells argparse we accept 0 or 1 value after --field_name _snake_case = '?' # This is the value that will get picked if we do --field_name (without value) _snake_case = True elif isclass(lowerCAmelCase_ ) and issubclass(lowerCAmelCase_ , lowerCAmelCase_ ): _snake_case = field.type.__args__[0] _snake_case = '+' if field.default_factory is not dataclasses.MISSING: _snake_case = field.default_factory() elif field.default is dataclasses.MISSING: _snake_case = True else: _snake_case = field.type if field.default is not dataclasses.MISSING: _snake_case = field.default elif field.default_factory is not dataclasses.MISSING: _snake_case = field.default_factory() else: _snake_case = True parser.add_argument(lowerCAmelCase_ , *lowerCAmelCase_ , **lowerCAmelCase_ ) # Add a complement `no_*` argument for a boolean field AFTER the initial field has already been added. # Order is important for arguments with the same destination! # We use a copy of earlier kwargs because the original kwargs have changed a lot before reaching down # here and we do not need those changes/additional keys. if field.default is True and (field.type is bool or field.type == Optional[bool]): _snake_case = False parser.add_argument(F'--no_{field.name}' , action='store_false' , dest=field.name , **lowerCAmelCase_ ) def lowerCamelCase ( self , lowerCAmelCase_ ): """simple docstring""" if hasattr(lowerCAmelCase_ , '_argument_group_name' ): _snake_case = self.add_argument_group(dtype._argument_group_name ) else: _snake_case = self try: _snake_case = get_type_hints(lowerCAmelCase_ ) except NameError: raise RuntimeError( F'Type resolution failed for {dtype}. Try declaring the class in global scope or ' 'removing line of `from __future__ import annotations` which opts in Postponed ' 'Evaluation of Annotations (PEP 563)' ) except TypeError as ex: # Remove this block when we drop Python 3.9 support if sys.version_info[:2] < (3, 10) and "unsupported operand type(s) for |" in str(lowerCAmelCase_ ): _snake_case = '.'.join(map(lowerCAmelCase_ , sys.version_info[:3] ) ) raise RuntimeError( F'Type resolution failed for {dtype} on Python {python_version}. Try removing ' 'line of `from __future__ import annotations` which opts in union types as ' '`X | Y` (PEP 604) via Postponed Evaluation of Annotations (PEP 563). To ' 'support Python versions that lower than 3.10, you need to use ' '`typing.Union[X, Y]` instead of `X | Y` and `typing.Optional[X]` instead of ' '`X | None`.' ) from ex raise for field in dataclasses.fields(lowerCAmelCase_ ): if not field.init: continue _snake_case = type_hints[field.name] self._parse_dataclass_field(lowerCAmelCase_ , lowerCAmelCase_ ) def lowerCamelCase ( self , lowerCAmelCase_=None , lowerCAmelCase_=False , lowerCAmelCase_=True , lowerCAmelCase_=None , lowerCAmelCase_=None , ): """simple docstring""" if args_file_flag or args_filename or (look_for_args_file and len(sys.argv )): _snake_case = [] if args_filename: args_files.append(Path(lowerCAmelCase_ ) ) elif look_for_args_file and len(sys.argv ): args_files.append(Path(sys.argv[0] ).with_suffix('.args' ) ) # args files specified via command line flag should overwrite default args files so we add them last if args_file_flag: # Create special parser just to extract the args_file_flag values _snake_case = ArgumentParser() args_file_parser.add_argument(lowerCAmelCase_ , type=lowerCAmelCase_ , action='append' ) # Use only remaining args for further parsing (remove the args_file_flag) _snake_case , _snake_case = args_file_parser.parse_known_args(args=lowerCAmelCase_ ) _snake_case = vars(lowerCAmelCase_ ).get(args_file_flag.lstrip('-' ) , lowerCAmelCase_ ) if cmd_args_file_paths: args_files.extend([Path(lowerCAmelCase_ ) for p in cmd_args_file_paths] ) _snake_case = [] for args_file in args_files: if args_file.exists(): file_args += args_file.read_text().split() # in case of duplicate arguments the last one has precedence # args specified via the command line should overwrite args from files, so we add them last _snake_case = file_args + args if args is not None else file_args + sys.argv[1:] _snake_case , _snake_case = self.parse_known_args(args=lowerCAmelCase_ ) _snake_case = [] for dtype in self.dataclass_types: _snake_case = {f.name for f in dataclasses.fields(lowerCAmelCase_ ) if f.init} _snake_case = {k: v for k, v in vars(lowerCAmelCase_ ).items() if k in keys} for k in keys: delattr(lowerCAmelCase_ , lowerCAmelCase_ ) _snake_case = dtype(**lowerCAmelCase_ ) outputs.append(lowerCAmelCase_ ) if len(namespace.__dict__ ) > 0: # additional namespace. outputs.append(lowerCAmelCase_ ) if return_remaining_strings: return (*outputs, remaining_args) else: if remaining_args: raise ValueError(F'Some specified arguments are not used by the HfArgumentParser: {remaining_args}' ) return (*outputs,) def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ = False ): """simple docstring""" _snake_case = set(args.keys() ) _snake_case = [] for dtype in self.dataclass_types: _snake_case = {f.name for f in dataclasses.fields(lowerCAmelCase_ ) if f.init} _snake_case = {k: v for k, v in args.items() if k in keys} unused_keys.difference_update(inputs.keys() ) _snake_case = dtype(**lowerCAmelCase_ ) outputs.append(lowerCAmelCase_ ) if not allow_extra_keys and unused_keys: raise ValueError(F'Some keys are not used by the HfArgumentParser: {sorted(lowerCAmelCase_ )}' ) return tuple(lowerCAmelCase_ ) def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ = False ): """simple docstring""" with open(Path(lowerCAmelCase_ ) , encoding='utf-8' ) as open_json_file: _snake_case = json.loads(open_json_file.read() ) _snake_case = self.parse_dict(lowerCAmelCase_ , allow_extra_keys=lowerCAmelCase_ ) return tuple(lowerCAmelCase_ ) def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ = False ): """simple docstring""" _snake_case = self.parse_dict(yaml.safe_load(Path(lowerCAmelCase_ ).read_text() ) , allow_extra_keys=lowerCAmelCase_ ) return tuple(lowerCAmelCase_ )
160
0
from dataclasses import dataclass, field from typing import Tuple from ..utils import cached_property, is_torch_available, is_torch_tpu_available, logging, requires_backends from .benchmark_args_utils import BenchmarkArguments if is_torch_available(): import torch if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm lowercase : List[str] = logging.get_logger(__name__) @dataclass class A__ ( __UpperCAmelCase ): """simple docstring""" __A : Optional[Any] = [ '''no_inference''', '''no_cuda''', '''no_tpu''', '''no_speed''', '''no_memory''', '''no_env_print''', '''no_multi_process''', ] def __init__( self , **lowercase) -> Tuple: '''simple docstring''' for deprecated_arg in self.deprecated_args: if deprecated_arg in kwargs: a__ : Union[str, Any] = deprecated_arg[3:] setattr(self , lowercase , not kwargs.pop(lowercase)) logger.warning( F'{deprecated_arg} is depreciated. Please use --no_{positive_arg} or' F' {positive_arg}={kwargs[positive_arg]}') a__ : Union[str, Any] = kwargs.pop('torchscript' , self.torchscript) a__ : Tuple = kwargs.pop('torch_xla_tpu_print_metrics' , self.torch_xla_tpu_print_metrics) a__ : Tuple = kwargs.pop('fp16_opt_level' , self.fpaa_opt_level) super().__init__(**lowercase) __A : bool = field(default=__UpperCAmelCase , metadata={'''help''': '''Trace the models using torchscript'''} ) __A : bool = field(default=__UpperCAmelCase , metadata={'''help''': '''Print Xla/PyTorch tpu metrics'''} ) __A : str = field( default='''O1''' , metadata={ '''help''': ( '''For fp16: Apex AMP optimization level selected in [\'O0\', \'O1\', \'O2\', and \'O3\']. ''' '''See details at https://nvidia.github.io/apex/amp.html''' ) } , ) @cached_property def __lowercase ( self) -> Tuple["torch.device", int]: '''simple docstring''' requires_backends(self , ['torch']) logger.info('PyTorch: setting up devices') if not self.cuda: a__ : List[str] = torch.device('cpu') a__ : Optional[Any] = 0 elif is_torch_tpu_available(): a__ : List[str] = xm.xla_device() a__ : Union[str, Any] = 0 else: a__ : List[Any] = torch.device('cuda' if torch.cuda.is_available() else 'cpu') a__ : Optional[int] = torch.cuda.device_count() return device, n_gpu @property def __lowercase ( self) -> List[str]: '''simple docstring''' return is_torch_tpu_available() and self.tpu @property def __lowercase ( self) -> int: '''simple docstring''' requires_backends(self , ['torch']) # TODO(PVP): currently only single GPU is supported return torch.cuda.current_device() @property def __lowercase ( self) -> "torch.device": '''simple docstring''' requires_backends(self , ['torch']) return self._setup_devices[0] @property def __lowercase ( self) -> Dict: '''simple docstring''' requires_backends(self , ['torch']) return self._setup_devices[1] @property def __lowercase ( self) -> Optional[int]: '''simple docstring''' return self.n_gpu > 0
99
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging __A : Dict = logging.get_logger(__name__) __A : Union[str, Any] = { '''facebook/vit-mae-base''': '''https://huggingface.co/facebook/vit-mae-base/resolve/main/config.json''', # See all ViT MAE models at https://huggingface.co/models?filter=vit-mae } class _UpperCAmelCase ( _A ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = "vit_mae" def __init__( self : Dict , A : List[str]=7_68 , A : Any=12 , A : Union[str, Any]=12 , A : Tuple=30_72 , A : Any="gelu" , A : Tuple=0.0 , A : List[str]=0.0 , A : Tuple=0.02 , A : Tuple=1e-12 , A : int=2_24 , A : Dict=16 , A : int=3 , A : Tuple=True , A : Tuple=16 , A : Optional[Any]=5_12 , A : Union[str, Any]=8 , A : List[Any]=20_48 , A : Dict=0.75 , A : Any=False , **A : Optional[int] , ) -> Union[str, Any]: super().__init__(**A ) lowercase_ : List[Any] = hidden_size lowercase_ : str = num_hidden_layers lowercase_ : List[Any] = num_attention_heads lowercase_ : Any = intermediate_size lowercase_ : Optional[int] = hidden_act lowercase_ : List[Any] = hidden_dropout_prob lowercase_ : int = attention_probs_dropout_prob lowercase_ : int = initializer_range lowercase_ : Dict = layer_norm_eps lowercase_ : Optional[Any] = image_size lowercase_ : str = patch_size lowercase_ : Dict = num_channels lowercase_ : Any = qkv_bias lowercase_ : Union[str, Any] = decoder_num_attention_heads lowercase_ : Optional[Any] = decoder_hidden_size lowercase_ : List[str] = decoder_num_hidden_layers lowercase_ : List[Any] = decoder_intermediate_size lowercase_ : Optional[Any] = mask_ratio lowercase_ : Optional[Any] = norm_pix_loss
33
0
def snake_case_ (UpperCamelCase : int , UpperCamelCase : int , UpperCamelCase : int ): '''simple docstring''' _a = (num_of_terms / 2) * (2 * first_term + (num_of_terms - 1) * common_diff) # formula for sum of series return total def snake_case_ (): '''simple docstring''' print(sum_of_series(1 , 1 , 10 ) ) if __name__ == "__main__": import doctest doctest.testmod()
360
'''simple docstring''' from ..utils import DummyObject, requires_backends class A ( metaclass=_a ): lowercase_ = ['torch', 'scipy'] def __init__( self : Tuple , *lowerCAmelCase_ : str , **lowerCAmelCase_ : Any ) -> Tuple: """simple docstring""" requires_backends(self , ['''torch''', '''scipy'''] ) @classmethod def __lowerCAmelCase ( cls : Dict , *lowerCAmelCase_ : Dict , **lowerCAmelCase_ : str ) -> Tuple: """simple docstring""" requires_backends(cls , ['''torch''', '''scipy'''] ) @classmethod def __lowerCAmelCase ( cls : Optional[int] , *lowerCAmelCase_ : str , **lowerCAmelCase_ : List[str] ) -> str: """simple docstring""" requires_backends(cls , ['''torch''', '''scipy'''] )
179
0
import tempfile import unittest from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from transformers.testing_utils import ( is_torch_available, require_optimum, require_torch, slow, ) if is_torch_available(): import torch @require_torch @require_optimum @slow class lowerCamelCase_ ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase__ ( self) -> str: __UpperCamelCase :List[str] = '''hf-internal-testing/tiny-random-t5''' __UpperCamelCase :str = AutoTokenizer.from_pretrained(__lowercase) __UpperCamelCase :Dict = AutoModelForSeqaSeqLM.from_pretrained(__lowercase) __UpperCamelCase :List[Any] = tokenizer('''This is me''' , return_tensors='''pt''') __UpperCamelCase :Dict = model.to_bettertransformer() self.assertTrue(any('''BetterTransformer''' in mod.__class__.__name__ for _, mod in model.named_modules())) __UpperCamelCase :Union[str, Any] = model.generate(**__lowercase) __UpperCamelCase :Any = model.reverse_bettertransformer() self.assertFalse(any('''BetterTransformer''' in mod.__class__.__name__ for _, mod in model.named_modules())) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(__lowercase) __UpperCamelCase :List[Any] = AutoModelForSeqaSeqLM.from_pretrained(__lowercase) self.assertFalse( any('''BetterTransformer''' in mod.__class__.__name__ for _, mod in model_reloaded.named_modules())) __UpperCamelCase :str = model_reloaded.generate(**__lowercase) self.assertTrue(torch.allclose(__lowercase , __lowercase)) def UpperCamelCase__ ( self) -> Any: __UpperCamelCase :Union[str, Any] = '''hf-internal-testing/tiny-random-t5''' __UpperCamelCase :List[str] = AutoModelForSeqaSeqLM.from_pretrained(__lowercase) __UpperCamelCase :Tuple = model.to_bettertransformer() with tempfile.TemporaryDirectory() as tmpdirname: with self.assertRaises(__lowercase): model.save_pretrained(__lowercase) __UpperCamelCase :Tuple = model.reverse_bettertransformer() model.save_pretrained(__lowercase)
43
from typing import List, Optional, Union import numpy as np import PIL.Image from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, PILImageResampling, get_image_size, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging __lowercase = logging.get_logger(__name__) class lowerCamelCase_ ( UpperCAmelCase_ ): '''simple docstring''' a__ : Optional[Any] = ["""pixel_values"""] def __init__( self , __lowercase = True , __lowercase = 32 , __lowercase=PILImageResampling.BILINEAR , __lowercase = True , **__lowercase , ) -> None: __UpperCamelCase :Optional[int] = do_resize __UpperCamelCase :Any = do_rescale __UpperCamelCase :str = size_divisor __UpperCamelCase :Dict = resample super().__init__(**__lowercase) def UpperCamelCase__ ( self , __lowercase , __lowercase , __lowercase , __lowercase = None , **__lowercase) -> np.ndarray: __UpperCamelCase , __UpperCamelCase :int = get_image_size(__lowercase) # Rounds the height and width down to the closest multiple of size_divisor __UpperCamelCase :List[Any] = height // size_divisor * size_divisor __UpperCamelCase :List[str] = width // size_divisor * size_divisor __UpperCamelCase :str = resize(__lowercase , (new_h, new_w) , resample=__lowercase , data_format=__lowercase , **__lowercase) return image def UpperCamelCase__ ( self , __lowercase , __lowercase , __lowercase = None , **__lowercase) -> np.ndarray: return rescale(image=__lowercase , scale=__lowercase , data_format=__lowercase , **__lowercase) def UpperCamelCase__ ( self , __lowercase , __lowercase = None , __lowercase = None , __lowercase=None , __lowercase = None , __lowercase = None , __lowercase = ChannelDimension.FIRST , **__lowercase , ) -> BatchFeature: __UpperCamelCase :Union[str, Any] = do_resize if do_resize is not None else self.do_resize __UpperCamelCase :Tuple = do_rescale if do_rescale is not None else self.do_rescale __UpperCamelCase :List[str] = size_divisor if size_divisor is not None else self.size_divisor __UpperCamelCase :List[Any] = resample if resample is not None else self.resample if do_resize and size_divisor is None: raise ValueError('''size_divisor is required for resizing''') __UpperCamelCase :List[Any] = make_list_of_images(__lowercase) if not valid_images(__lowercase): raise ValueError('''Invalid image(s)''') # All transformations expect numpy arrays. __UpperCamelCase :Optional[Any] = [to_numpy_array(__lowercase) for img in images] if do_resize: __UpperCamelCase :List[str] = [self.resize(__lowercase , size_divisor=__lowercase , resample=__lowercase) for image in images] if do_rescale: __UpperCamelCase :Dict = [self.rescale(__lowercase , scale=1 / 255) for image in images] __UpperCamelCase :str = [to_channel_dimension_format(__lowercase , __lowercase) for image in images] __UpperCamelCase :int = {'''pixel_values''': images} return BatchFeature(data=__lowercase , tensor_type=__lowercase)
43
1
from math import ceil def __lowerCAmelCase ( __SCREAMING_SNAKE_CASE : int = 1_0_0_1 ): '''simple docstring''' __snake_case : Optional[Any] = 1 for i in range(1 , int(ceil(n / 2.0 ) ) ): __snake_case : Tuple = 2 * i + 1 __snake_case : Optional[Any] = 2 * i __snake_case : Optional[Any] = total + 4 * odd**2 - 6 * even return total if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution()) else: try: lowercase_ = int(sys.argv[1]) print(solution(n)) except ValueError: print("Invalid entry - please enter a number")
20
from __future__ import annotations def __lowerCAmelCase ( __SCREAMING_SNAKE_CASE : list , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : int ): '''simple docstring''' __snake_case : str = [] __snake_case , __snake_case : List[str] = input_list[low:mid], input_list[mid : high + 1] while left and right: result.append((left if left[0] <= right[0] else right).pop(0 ) ) __snake_case : List[Any] = result + left + right return input_list def __lowerCAmelCase ( __SCREAMING_SNAKE_CASE : list ): '''simple docstring''' if len(__SCREAMING_SNAKE_CASE ) <= 1: return input_list __snake_case : Union[str, Any] = list(__SCREAMING_SNAKE_CASE ) # iteration for two-way merging __snake_case : Tuple = 2 while p <= len(__SCREAMING_SNAKE_CASE ): # getting low, high and middle value for merge-sort of single list for i in range(0 , len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ): __snake_case : List[str] = i __snake_case : str = i + p - 1 __snake_case : Optional[Any] = (low + high + 1) // 2 __snake_case : str = merge(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # final merge of last two parts if p * 2 >= len(__SCREAMING_SNAKE_CASE ): __snake_case : List[str] = i __snake_case : str = merge(__SCREAMING_SNAKE_CASE , 0 , __SCREAMING_SNAKE_CASE , len(__SCREAMING_SNAKE_CASE ) - 1 ) break p *= 2 return input_list if __name__ == "__main__": lowercase_ = input("Enter numbers separated by a comma:\n").strip() if user_input == "": lowercase_ = [] else: lowercase_ = [int(item.strip()) for item in user_input.split(",")] print(iter_merge_sort(unsorted))
20
1
'''simple docstring''' from argparse import ArgumentParser from .add_new_model import AddNewModelCommand from .add_new_model_like import AddNewModelLikeCommand from .convert import ConvertCommand from .download import DownloadCommand from .env import EnvironmentCommand from .lfs import LfsCommands from .pt_to_tf import PTtoTFCommand from .run import RunCommand from .serving import ServeCommand from .user import UserCommands def lowercase ( ): '''simple docstring''' UpperCAmelCase : Tuple = ArgumentParser("Transformers CLI tool" , usage="transformers-cli <command> [<args>]" ) UpperCAmelCase : Tuple = parser.add_subparsers(help="transformers-cli command helpers" ) # Register commands ConvertCommand.register_subcommand(_A ) DownloadCommand.register_subcommand(_A ) EnvironmentCommand.register_subcommand(_A ) RunCommand.register_subcommand(_A ) ServeCommand.register_subcommand(_A ) UserCommands.register_subcommand(_A ) AddNewModelCommand.register_subcommand(_A ) AddNewModelLikeCommand.register_subcommand(_A ) LfsCommands.register_subcommand(_A ) PTtoTFCommand.register_subcommand(_A ) # Let's go UpperCAmelCase : int = parser.parse_args() if not hasattr(_A , "func" ): parser.print_help() exit(1 ) # Run UpperCAmelCase : Optional[int] = args.func(_A ) service.run() if __name__ == "__main__": main()
311
import argparse import hashlib # hashlib is only used inside the Test class import struct class __magic_name__ : '''simple docstring''' def __init__( self, lowercase_ ) -> List[str]: """simple docstring""" a__ =data a__ =[0X67452301, 0Xefcdab89, 0X98badcfe, 0X10325476, 0Xc3d2e1f0] @staticmethod def _UpperCAmelCase ( lowercase_, lowercase_ ) -> Union[str, Any]: """simple docstring""" return ((n << b) | (n >> (32 - b))) & 0Xffffffff def _UpperCAmelCase ( self ) -> Optional[int]: """simple docstring""" a__ =b'''\x80''' + b'''\x00''' * (63 - (len(self.data ) + 8) % 64) a__ =self.data + padding + struct.pack('''>Q''', 8 * len(self.data ) ) return padded_data def _UpperCAmelCase ( self ) -> Any: """simple docstring""" return [ self.padded_data[i : i + 64] for i in range(0, len(self.padded_data ), 64 ) ] def _UpperCAmelCase ( self, lowercase_ ) -> List[Any]: """simple docstring""" a__ =list(struct.unpack('''>16L''', lowercase_ ) ) + [0] * 64 for i in range(16, 80 ): a__ =self.rotate((w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]), 1 ) return w def _UpperCAmelCase ( self ) -> Any: """simple docstring""" a__ =self.padding() a__ =self.split_blocks() for block in self.blocks: a__ =self.expand_block(lowercase_ ) a__, a__, a__, a__, a__ =self.h for i in range(0, 80 ): if 0 <= i < 20: a__ =(b & c) | ((~b) & d) a__ =0X5a827999 elif 20 <= i < 40: a__ =b ^ c ^ d a__ =0X6ed9eba1 elif 40 <= i < 60: a__ =(b & c) | (b & d) | (c & d) a__ =0X8f1bbcdc elif 60 <= i < 80: a__ =b ^ c ^ d a__ =0Xca62c1d6 a__, a__, a__, a__, a__ =( self.rotate(lowercase_, 5 ) + f + e + k + expanded_block[i] & 0Xffffffff, a, self.rotate(lowercase_, 30 ), c, d, ) a__ =( self.h[0] + a & 0Xffffffff, self.h[1] + b & 0Xffffffff, self.h[2] + c & 0Xffffffff, self.h[3] + d & 0Xffffffff, self.h[4] + e & 0Xffffffff, ) return ("{:08x}" * 5).format(*self.h ) def UpperCAmelCase__ ( ): '''simple docstring''' a__ =b'''Test String''' assert SHAaHash(_A ).final_hash() == hashlib.shaa(_A ).hexdigest() # noqa: S324 def UpperCAmelCase__ ( ): '''simple docstring''' a__ =argparse.ArgumentParser(description='''Process some strings or files''' ) parser.add_argument( '''--string''' , dest='''input_string''' , default='''Hello World!! Welcome to Cryptography''' , help='''Hash the string''' , ) parser.add_argument('''--file''' , dest='''input_file''' , help='''Hash contents of a file''' ) a__ =parser.parse_args() a__ =args.input_string # In any case hash input should be a bytestring if args.input_file: with open(args.input_file , '''rb''' ) as f: a__ =f.read() else: a__ =bytes(_A , '''utf-8''' ) print(SHAaHash(_A ).final_hash() ) if __name__ == "__main__": main() import doctest doctest.testmod()
188
0
"""simple docstring""" import argparse from collections import defaultdict def UpperCamelCase_ ( lowerCAmelCase__ : Any , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : int , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Optional[int] ) -> Any: """simple docstring""" lowerCAmelCase_ : Optional[int] = f"{file}_{class_name}_{test_name}" done_test[_id] += 1 with open(lowerCAmelCase__ , 'r' ) as f: lowerCAmelCase_ : List[Any] = f.readlines() lowerCAmelCase_ : str = f"class {class_name}(" lowerCAmelCase_ : Any = f"{4 * ' '}def {test_name}(" lowerCAmelCase_ : Optional[Any] = f"{8 * ' '}{correct_line.split()[0]}" lowerCAmelCase_ : List[str] = f"{16 * ' '}{correct_line.split()[0]}" lowerCAmelCase_ : Optional[Any] = False lowerCAmelCase_ : Tuple = False lowerCAmelCase_ : List[Any] = False lowerCAmelCase_ : Any = False lowerCAmelCase_ : Union[str, Any] = 0 lowerCAmelCase_ : Tuple = 0 lowerCAmelCase_ : str = [] for line in lines: if line.startswith(lowerCAmelCase__ ): lowerCAmelCase_ : List[str] = True elif in_class and line.startswith(lowerCAmelCase__ ): lowerCAmelCase_ : List[str] = True elif in_class and in_func and (line.startswith(lowerCAmelCase__ ) or line.startswith(lowerCAmelCase__ )): lowerCAmelCase_ : List[Any] = len(line.split(correct_line.split()[0] )[0] ) count += 1 if count == done_test[_id]: lowerCAmelCase_ : Any = True if in_class and in_func and in_line: if ")" not in line: continue else: lowerCAmelCase_ : str = True if in_class and in_func and in_line and insert_line: new_lines.append(f"{spaces * ' '}{correct_line}" ) lowerCAmelCase_ : Union[str, Any] = False else: new_lines.append(lowerCAmelCase__ ) with open(lowerCAmelCase__ , 'w' ) as f: for line in new_lines: f.write(lowerCAmelCase__ ) def UpperCamelCase_ ( lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : List[str]=None ) -> int: """simple docstring""" if fail is not None: with open(lowerCAmelCase__ , 'r' ) as f: lowerCAmelCase_ : str = {l.strip() for l in f.readlines()} else: lowerCAmelCase_ : int = None with open(lowerCAmelCase__ , 'r' ) as f: lowerCAmelCase_ : str = f.readlines() lowerCAmelCase_ : List[Any] = defaultdict(lowerCAmelCase__ ) for line in correct_lines: lowerCAmelCase_ ,lowerCAmelCase_ ,lowerCAmelCase_ ,lowerCAmelCase_ : List[str] = line.split(';' ) if test_failures is None or "::".join([file, class_name, test_name] ) in test_failures: overwrite_file(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) if __name__ == "__main__": lowercase__ : List[Any] = argparse.ArgumentParser() parser.add_argument("""--correct_filename""", help="""filename of tests with expected result""") parser.add_argument("""--fail_filename""", help="""filename of test failures""", type=str, default=None) lowercase__ : Dict = parser.parse_args() main(args.correct_filename, args.fail_filename)
289
"""simple docstring""" def UpperCamelCase_ ( lowerCAmelCase__ : str , lowerCAmelCase__ : str ) -> int: """simple docstring""" if len(lowerCAmelCase__ ) != len(lowerCAmelCase__ ): raise ValueError('String lengths must match!' ) lowerCAmelCase_ : List[Any] = 0 for chara, chara in zip(lowerCAmelCase__ , lowerCAmelCase__ ): if chara != chara: count += 1 return count if __name__ == "__main__": import doctest doctest.testmod()
289
1
from __future__ import annotations def lowerCamelCase__ ( _a , _a): print(f"Vertex\tShortest Distance from vertex {src}") for i, d in enumerate(snake_case__): print(f"{i}\t\t{d}") def lowerCamelCase__ ( _a , _a , _a): for j in range(snake_case__): SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : str = (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 lowerCamelCase__ ( _a , _a , _a , _a): SCREAMING_SNAKE_CASE : List[str] = [float("inf")] * vertex_count SCREAMING_SNAKE_CASE : List[Any] = 0.0 for _ in range(vertex_count - 1): for j in range(snake_case__): SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Dict = (graph[j][k] for k in ["src", "dst", "weight"]) if distance[u] != float("inf") and distance[u] + w < distance[v]: SCREAMING_SNAKE_CASE : Optional[Any] = distance[u] + w SCREAMING_SNAKE_CASE : int = 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() a_ = int(input('Enter number of vertices: ').strip()) a_ = int(input('Enter number of edges: ').strip()) a_ = [{} for _ in range(E)] for i in range(E): print('Edge ', i + 1) a_ , a_ , a_ = ( int(x) for x in input('Enter source, destination, weight: ').strip().split(' ') ) a_ = {'src': src, 'dst': dest, 'weight': weight} a_ = int(input('\nEnter shortest path source:').strip()) a_ = bellman_ford(graph, V, E, source) print_distance(shortest_distance, 0)
76
"""simple docstring""" from itertools import permutations def lowercase (snake_case__ : tuple ) -> bool: '''simple docstring''' if num[3] % 2 != 0: return False if (num[2] + num[3] + num[4]) % 3 != 0: return False if num[5] % 5 != 0: return False lowerCAmelCase = [7, 11, 13, 17] for i, test in enumerate(snake_case__ ): if (num[i + 4] * 100 + num[i + 5] * 10 + num[i + 6]) % test != 0: return False return True def lowercase (snake_case__ : int = 10 ) -> int: '''simple docstring''' return sum( int("""""".join(map(snake_case__ , snake_case__ ) ) ) for num in permutations(range(snake_case__ ) ) if is_substring_divisible(snake_case__ ) ) if __name__ == "__main__": print(f"""{solution() = }""")
155
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A : str = { 'configuration_jukebox': [ 'JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP', 'JukeboxConfig', 'JukeboxPriorConfig', 'JukeboxVQVAEConfig', ], 'tokenization_jukebox': ['JukeboxTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : int = [ 'JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST', 'JukeboxModel', 'JukeboxPreTrainedModel', 'JukeboxVQVAE', 'JukeboxPrior', ] if TYPE_CHECKING: from .configuration_jukebox import ( JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP, JukeboxConfig, JukeboxPriorConfig, JukeboxVQVAEConfig, ) from .tokenization_jukebox import JukeboxTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_jukebox import ( JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST, JukeboxModel, JukeboxPreTrainedModel, JukeboxPrior, JukeboxVQVAE, ) else: import sys A : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
370
from __future__ import annotations def __lowerCAmelCase ( a__ , a__ = None ) -> list[list[str]]: __a = word_bank or [] # create a table __a = len(a__ ) + 1 __a = [] for _ in range(a__ ): table.append([] ) # seed value __a = [[]] # because empty string has empty combination # iterate through the indices for i in range(a__ ): # condition if table[i] != []: for word in word_bank: # slice condition if target[i : i + len(a__ )] == word: __a = [ [word, *way] for way in table[i] ] # adds the word to every combination the current position holds # now,push that combination to the table[i+len(word)] table[i + len(a__ )] += new_combinations # combinations are in reverse order so reverse for better output for combination in table[len(a__ )]: combination.reverse() return table[len(a__ )] if __name__ == "__main__": print(all_construct('jwajalapa', ['jwa', 'j', 'w', 'a', 'la', 'lapa'])) print(all_construct('rajamati', ['s', 'raj', 'amat', 'raja', 'ma', 'i', 't'])) print( all_construct( 'hexagonosaurus', ['h', 'ex', 'hex', 'ag', 'ago', 'ru', 'auru', 'rus', 'go', 'no', 'o', 's'], ) )
33
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 __A : '''simple docstring''' @staticmethod def a__ (*A , **A ) -> Optional[Any]: """simple docstring""" pass @is_pipeline_test @require_vision @require_timm @require_torch class __A ( unittest.TestCase ): '''simple docstring''' __lowerCamelCase : List[str] = MODEL_FOR_OBJECT_DETECTION_MAPPING def a__ (self , A , A , A ) -> List[Any]: """simple docstring""" _a = ObjectDetectionPipeline(model=snake_case_ , image_processor=snake_case_ ) return object_detector, ["./tests/fixtures/tests_samples/COCO/000000039769.png"] def a__ (self , A , A ) -> Dict: """simple docstring""" _a = object_detector('''./tests/fixtures/tests_samples/COCO/000000039769.png''' , threshold=0.0 ) self.assertGreater(len(snake_case_ ) , 0 ) for detected_object in outputs: self.assertEqual( snake_case_ , { '''score''': ANY(snake_case_ ), '''label''': ANY(snake_case_ ), '''box''': {'''xmin''': ANY(snake_case_ ), '''ymin''': ANY(snake_case_ ), '''xmax''': ANY(snake_case_ ), '''ymax''': ANY(snake_case_ )}, } , ) import datasets _a = datasets.load_dataset('''hf-internal-testing/fixtures_image_utils''' , '''image''' , split='''test''' ) _a = [ 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'''], ] _a = object_detector(snake_case_ , threshold=0.0 ) self.assertEqual(len(snake_case_ ) , len(snake_case_ ) ) for outputs in batch_outputs: self.assertGreater(len(snake_case_ ) , 0 ) for detected_object in outputs: self.assertEqual( snake_case_ , { '''score''': ANY(snake_case_ ), '''label''': ANY(snake_case_ ), '''box''': {'''xmin''': ANY(snake_case_ ), '''ymin''': ANY(snake_case_ ), '''xmax''': ANY(snake_case_ ), '''ymax''': ANY(snake_case_ )}, } , ) @require_tf @unittest.skip('''Object detection not implemented in TF''' ) def a__ (self ) -> Dict: """simple docstring""" pass @require_torch def a__ (self ) -> Any: """simple docstring""" _a = '''hf-internal-testing/tiny-detr-mobilenetsv3''' _a = AutoModelForObjectDetection.from_pretrained(snake_case_ ) _a = AutoFeatureExtractor.from_pretrained(snake_case_ ) _a = ObjectDetectionPipeline(model=snake_case_ , feature_extractor=snake_case_ ) _a = object_detector('''http://images.cocodataset.org/val2017/000000039769.jpg''' , threshold=0.0 ) self.assertEqual( nested_simplify(snake_case_ , decimals=4 ) , [ {'''score''': 0.3376, '''label''': '''LABEL_0''', '''box''': {'''xmin''': 159, '''ymin''': 120, '''xmax''': 480, '''ymax''': 359}}, {'''score''': 0.3376, '''label''': '''LABEL_0''', '''box''': {'''xmin''': 159, '''ymin''': 120, '''xmax''': 480, '''ymax''': 359}}, ] , ) _a = object_detector( [ '''http://images.cocodataset.org/val2017/000000039769.jpg''', '''http://images.cocodataset.org/val2017/000000039769.jpg''', ] , threshold=0.0 , ) self.assertEqual( nested_simplify(snake_case_ , decimals=4 ) , [ [ {'''score''': 0.3376, '''label''': '''LABEL_0''', '''box''': {'''xmin''': 159, '''ymin''': 120, '''xmax''': 480, '''ymax''': 359}}, {'''score''': 0.3376, '''label''': '''LABEL_0''', '''box''': {'''xmin''': 159, '''ymin''': 120, '''xmax''': 480, '''ymax''': 359}}, ], [ {'''score''': 0.3376, '''label''': '''LABEL_0''', '''box''': {'''xmin''': 159, '''ymin''': 120, '''xmax''': 480, '''ymax''': 359}}, {'''score''': 0.3376, '''label''': '''LABEL_0''', '''box''': {'''xmin''': 159, '''ymin''': 120, '''xmax''': 480, '''ymax''': 359}}, ], ] , ) @require_torch @slow def a__ (self ) -> Dict: """simple docstring""" _a = '''facebook/detr-resnet-50''' _a = AutoModelForObjectDetection.from_pretrained(snake_case_ ) _a = AutoFeatureExtractor.from_pretrained(snake_case_ ) _a = ObjectDetectionPipeline(model=snake_case_ , feature_extractor=snake_case_ ) _a = object_detector('''http://images.cocodataset.org/val2017/000000039769.jpg''' ) self.assertEqual( nested_simplify(snake_case_ , decimals=4 ) , [ {'''score''': 0.9982, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 70, '''xmax''': 175, '''ymax''': 117}}, {'''score''': 0.9960, '''label''': '''remote''', '''box''': {'''xmin''': 333, '''ymin''': 72, '''xmax''': 368, '''ymax''': 187}}, {'''score''': 0.9955, '''label''': '''couch''', '''box''': {'''xmin''': 0, '''ymin''': 1, '''xmax''': 639, '''ymax''': 473}}, {'''score''': 0.9988, '''label''': '''cat''', '''box''': {'''xmin''': 13, '''ymin''': 52, '''xmax''': 314, '''ymax''': 470}}, {'''score''': 0.9987, '''label''': '''cat''', '''box''': {'''xmin''': 345, '''ymin''': 23, '''xmax''': 640, '''ymax''': 368}}, ] , ) _a = object_detector( [ '''http://images.cocodataset.org/val2017/000000039769.jpg''', '''http://images.cocodataset.org/val2017/000000039769.jpg''', ] ) self.assertEqual( nested_simplify(snake_case_ , decimals=4 ) , [ [ {'''score''': 0.9982, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 70, '''xmax''': 175, '''ymax''': 117}}, {'''score''': 0.9960, '''label''': '''remote''', '''box''': {'''xmin''': 333, '''ymin''': 72, '''xmax''': 368, '''ymax''': 187}}, {'''score''': 0.9955, '''label''': '''couch''', '''box''': {'''xmin''': 0, '''ymin''': 1, '''xmax''': 639, '''ymax''': 473}}, {'''score''': 0.9988, '''label''': '''cat''', '''box''': {'''xmin''': 13, '''ymin''': 52, '''xmax''': 314, '''ymax''': 470}}, {'''score''': 0.9987, '''label''': '''cat''', '''box''': {'''xmin''': 345, '''ymin''': 23, '''xmax''': 640, '''ymax''': 368}}, ], [ {'''score''': 0.9982, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 70, '''xmax''': 175, '''ymax''': 117}}, {'''score''': 0.9960, '''label''': '''remote''', '''box''': {'''xmin''': 333, '''ymin''': 72, '''xmax''': 368, '''ymax''': 187}}, {'''score''': 0.9955, '''label''': '''couch''', '''box''': {'''xmin''': 0, '''ymin''': 1, '''xmax''': 639, '''ymax''': 473}}, {'''score''': 0.9988, '''label''': '''cat''', '''box''': {'''xmin''': 13, '''ymin''': 52, '''xmax''': 314, '''ymax''': 470}}, {'''score''': 0.9987, '''label''': '''cat''', '''box''': {'''xmin''': 345, '''ymin''': 23, '''xmax''': 640, '''ymax''': 368}}, ], ] , ) @require_torch @slow def a__ (self ) -> str: """simple docstring""" _a = '''facebook/detr-resnet-50''' _a = pipeline('''object-detection''' , model=snake_case_ ) _a = object_detector('''http://images.cocodataset.org/val2017/000000039769.jpg''' ) self.assertEqual( nested_simplify(snake_case_ , decimals=4 ) , [ {'''score''': 0.9982, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 70, '''xmax''': 175, '''ymax''': 117}}, {'''score''': 0.9960, '''label''': '''remote''', '''box''': {'''xmin''': 333, '''ymin''': 72, '''xmax''': 368, '''ymax''': 187}}, {'''score''': 0.9955, '''label''': '''couch''', '''box''': {'''xmin''': 0, '''ymin''': 1, '''xmax''': 639, '''ymax''': 473}}, {'''score''': 0.9988, '''label''': '''cat''', '''box''': {'''xmin''': 13, '''ymin''': 52, '''xmax''': 314, '''ymax''': 470}}, {'''score''': 0.9987, '''label''': '''cat''', '''box''': {'''xmin''': 345, '''ymin''': 23, '''xmax''': 640, '''ymax''': 368}}, ] , ) _a = object_detector( [ '''http://images.cocodataset.org/val2017/000000039769.jpg''', '''http://images.cocodataset.org/val2017/000000039769.jpg''', ] ) self.assertEqual( nested_simplify(snake_case_ , decimals=4 ) , [ [ {'''score''': 0.9982, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 70, '''xmax''': 175, '''ymax''': 117}}, {'''score''': 0.9960, '''label''': '''remote''', '''box''': {'''xmin''': 333, '''ymin''': 72, '''xmax''': 368, '''ymax''': 187}}, {'''score''': 0.9955, '''label''': '''couch''', '''box''': {'''xmin''': 0, '''ymin''': 1, '''xmax''': 639, '''ymax''': 473}}, {'''score''': 0.9988, '''label''': '''cat''', '''box''': {'''xmin''': 13, '''ymin''': 52, '''xmax''': 314, '''ymax''': 470}}, {'''score''': 0.9987, '''label''': '''cat''', '''box''': {'''xmin''': 345, '''ymin''': 23, '''xmax''': 640, '''ymax''': 368}}, ], [ {'''score''': 0.9982, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 70, '''xmax''': 175, '''ymax''': 117}}, {'''score''': 0.9960, '''label''': '''remote''', '''box''': {'''xmin''': 333, '''ymin''': 72, '''xmax''': 368, '''ymax''': 187}}, {'''score''': 0.9955, '''label''': '''couch''', '''box''': {'''xmin''': 0, '''ymin''': 1, '''xmax''': 639, '''ymax''': 473}}, {'''score''': 0.9988, '''label''': '''cat''', '''box''': {'''xmin''': 13, '''ymin''': 52, '''xmax''': 314, '''ymax''': 470}}, {'''score''': 0.9987, '''label''': '''cat''', '''box''': {'''xmin''': 345, '''ymin''': 23, '''xmax''': 640, '''ymax''': 368}}, ], ] , ) @require_torch @slow def a__ (self ) -> Union[str, Any]: """simple docstring""" _a = 0.9985 _a = '''facebook/detr-resnet-50''' _a = pipeline('''object-detection''' , model=snake_case_ ) _a = object_detector('''http://images.cocodataset.org/val2017/000000039769.jpg''' , threshold=snake_case_ ) self.assertEqual( nested_simplify(snake_case_ , decimals=4 ) , [ {'''score''': 0.9988, '''label''': '''cat''', '''box''': {'''xmin''': 13, '''ymin''': 52, '''xmax''': 314, '''ymax''': 470}}, {'''score''': 0.9987, '''label''': '''cat''', '''box''': {'''xmin''': 345, '''ymin''': 23, '''xmax''': 640, '''ymax''': 368}}, ] , ) @require_torch @require_pytesseract @slow def a__ (self ) -> str: """simple docstring""" _a = '''Narsil/layoutlmv3-finetuned-funsd''' _a = 0.9993 _a = pipeline('''object-detection''' , model=snake_case_ , threshold=snake_case_ ) _a = object_detector( '''https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png''' ) self.assertEqual( nested_simplify(snake_case_ , decimals=4 ) , [ {'''score''': 0.9993, '''label''': '''I-ANSWER''', '''box''': {'''xmin''': 294, '''ymin''': 254, '''xmax''': 343, '''ymax''': 264}}, {'''score''': 0.9993, '''label''': '''I-ANSWER''', '''box''': {'''xmin''': 294, '''ymin''': 254, '''xmax''': 343, '''ymax''': 264}}, ] , )
211
'''simple docstring''' from __future__ import annotations from collections.abc import Callable from typing import Any, Generic, TypeVar __SCREAMING_SNAKE_CASE :Optional[int] = TypeVar('''T''') class A_ ( Generic[T] ): def __init__( self : List[Any] , snake_case_ : list[T] , snake_case_ : Callable[[T, T], T] ): _UpperCAmelCase = None _UpperCAmelCase = len(snake_case_ ) _UpperCAmelCase = [any_type for _ in range(self.N )] + arr _UpperCAmelCase = fnc self.build() def lowercase ( self : List[Any] ): for p in range(self.N - 1 , 0 , -1 ): _UpperCAmelCase = self.fn(self.st[p * 2] , self.st[p * 2 + 1] ) def lowercase ( self : Optional[Any] , snake_case_ : int , snake_case_ : T ): p += self.N _UpperCAmelCase = v while p > 1: _UpperCAmelCase = p // 2 _UpperCAmelCase = self.fn(self.st[p * 2] , self.st[p * 2 + 1] ) def lowercase ( self : Any , snake_case_ : int , snake_case_ : int ): # noqa: E741 _UpperCAmelCase , _UpperCAmelCase = l + self.N, r + self.N _UpperCAmelCase = None while l <= r: if l % 2 == 1: _UpperCAmelCase = self.st[l] if res is None else self.fn(snake_case_ , self.st[l] ) if r % 2 == 0: _UpperCAmelCase = self.st[r] if res is None else self.fn(snake_case_ , self.st[r] ) _UpperCAmelCase , _UpperCAmelCase = (l + 1) // 2, (r - 1) // 2 return res if __name__ == "__main__": from functools import reduce __SCREAMING_SNAKE_CASE :Union[str, Any] = [1, 10, -2, 9, -3, 8, 4, -7, 5, 6, 11, -12] __SCREAMING_SNAKE_CASE :List[str] = { 0: 7, 1: 2, 2: 6, 3: -14, 4: 5, 5: 4, 6: 7, 7: -10, 8: 9, 9: 10, 10: 12, 11: 1, } __SCREAMING_SNAKE_CASE :Any = SegmentTree(test_array, min) __SCREAMING_SNAKE_CASE :Any = SegmentTree(test_array, max) __SCREAMING_SNAKE_CASE :Any = SegmentTree(test_array, lambda a, b: a + b) def UpperCAmelCase_ ( ) -> None: '''simple docstring''' for i in range(len(__lowercase ) ): for j in range(__lowercase , len(__lowercase ) ): _UpperCAmelCase = reduce(__lowercase , test_array[i : j + 1] ) _UpperCAmelCase = reduce(__lowercase , test_array[i : j + 1] ) _UpperCAmelCase = reduce(lambda __lowercase , __lowercase : a + b , test_array[i : j + 1] ) assert min_range == min_segment_tree.query(__lowercase , __lowercase ) assert max_range == max_segment_tree.query(__lowercase , __lowercase ) assert sum_range == sum_segment_tree.query(__lowercase , __lowercase ) test_all_segments() for index, value in test_updates.items(): __SCREAMING_SNAKE_CASE :str = value min_segment_tree.update(index, value) max_segment_tree.update(index, value) sum_segment_tree.update(index, value) test_all_segments()
22
0
import json import os import torch from diffusers import UNetaDModel os.makedirs('hub/hopper-medium-v2/unet/hor32', exist_ok=True) os.makedirs('hub/hopper-medium-v2/unet/hor128', exist_ok=True) os.makedirs('hub/hopper-medium-v2/value_function', exist_ok=True) def lowerCAmelCase_ ( snake_case_ : Dict ) -> Any: '''simple docstring''' if hor == 1_28: UpperCAmelCase_ = ('DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D') UpperCAmelCase_ = (32, 1_28, 2_56) UpperCAmelCase_ = ('UpResnetBlock1D', 'UpResnetBlock1D') elif hor == 32: UpperCAmelCase_ = ('DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D') UpperCAmelCase_ = (32, 64, 1_28, 2_56) UpperCAmelCase_ = ('UpResnetBlock1D', 'UpResnetBlock1D', 'UpResnetBlock1D') UpperCAmelCase_ = torch.load(f"""/Users/bglickenhaus/Documents/diffuser/temporal_unet-hopper-mediumv2-hor{hor}.torch""" ) UpperCAmelCase_ = model.state_dict() UpperCAmelCase_ = { 'down_block_types': down_block_types, 'block_out_channels': block_out_channels, 'up_block_types': up_block_types, 'layers_per_block': 1, 'use_timestep_embedding': True, 'out_block_type': 'OutConv1DBlock', 'norm_num_groups': 8, 'downsample_each_block': False, 'in_channels': 14, 'out_channels': 14, 'extra_in_channels': 0, 'time_embedding_type': 'positional', 'flip_sin_to_cos': False, 'freq_shift': 1, 'sample_size': 6_55_36, 'mid_block_type': 'MidResTemporalBlock1D', 'act_fn': 'mish', } UpperCAmelCase_ = UNetaDModel(**_A ) print(f"""length of state dict: {len(state_dict.keys() )}""" ) print(f"""length of value function dict: {len(hf_value_function.state_dict().keys() )}""" ) UpperCAmelCase_ = dict(zip(model.state_dict().keys() , hf_value_function.state_dict().keys() ) ) for k, v in mapping.items(): UpperCAmelCase_ = state_dict.pop(_A ) hf_value_function.load_state_dict(_A ) torch.save(hf_value_function.state_dict() , f"""hub/hopper-medium-v2/unet/hor{hor}/diffusion_pytorch_model.bin""" ) with open(f"""hub/hopper-medium-v2/unet/hor{hor}/config.json""" , "w" ) as f: json.dump(_A , _A ) def lowerCAmelCase_ ( ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase_ = { 'in_channels': 14, 'down_block_types': ('DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D'), 'up_block_types': (), 'out_block_type': 'ValueFunction', 'mid_block_type': 'ValueFunctionMidBlock1D', 'block_out_channels': (32, 64, 1_28, 2_56), 'layers_per_block': 1, 'downsample_each_block': True, 'sample_size': 6_55_36, 'out_channels': 14, 'extra_in_channels': 0, 'time_embedding_type': 'positional', 'use_timestep_embedding': True, 'flip_sin_to_cos': False, 'freq_shift': 1, 'norm_num_groups': 8, 'act_fn': 'mish', } UpperCAmelCase_ = torch.load("/Users/bglickenhaus/Documents/diffuser/value_function-hopper-mediumv2-hor32.torch" ) UpperCAmelCase_ = model UpperCAmelCase_ = UNetaDModel(**_A ) print(f"""length of state dict: {len(state_dict.keys() )}""" ) print(f"""length of value function dict: {len(hf_value_function.state_dict().keys() )}""" ) UpperCAmelCase_ = dict(zip(state_dict.keys() , hf_value_function.state_dict().keys() ) ) for k, v in mapping.items(): UpperCAmelCase_ = state_dict.pop(_A ) hf_value_function.load_state_dict(_A ) torch.save(hf_value_function.state_dict() , "hub/hopper-medium-v2/value_function/diffusion_pytorch_model.bin" ) with open("hub/hopper-medium-v2/value_function/config.json" , "w" ) as f: json.dump(_A , _A ) if __name__ == "__main__": unet(32) # unet(128) value_function()
353
'''simple docstring''' from unittest import TestCase from datasets import Dataset from minhash_deduplication import deduplicate_dataset, make_duplicate_clusters def lowerCAmelCase_ ( ) -> str: '''simple docstring''' UpperCAmelCase_ = { "repo_name": ["test_repo1", "test_repo2", "test_repo3"], "path": ["test_1.py", "test_2.py", "unit_test.py"], "content": ["a " * 20, "a " * 30, "b " * 7], } UpperCAmelCase_ = Dataset.from_dict(snake_case_ ) return dataset class __A ( UpperCamelCase__ ): def _lowercase (self : str ): UpperCAmelCase_ = get_dataset() UpperCAmelCase_ = make_duplicate_clusters(__a , 0.85 ) self.assertEqual(len(duplicate_clusters[0] ) , 2 ) def _lowercase (self : Optional[Any] ): UpperCAmelCase_ = get_dataset() UpperCAmelCase_ , UpperCAmelCase_ = deduplicate_dataset(__a ) self.assertEqual(len(__a ) , 2 ) print(__a ) self.assertEqual(duplicate_clusters[0][0]["copies"] , 2 ) self.assertEqual(duplicate_clusters[0][0]["is_extreme"] , __a )
106
0