code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase : List[str] = logging.get_logger(__name__) UpperCAmelCase : List[Any] = { '''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 _A( snake_case__ ): """simple docstring""" UpperCamelCase : int = '''levit''' def __init__( self , _A=224 , _A=3 , _A=3 , _A=2 , _A=1 , _A=16 , _A=[128, 256, 384] , _A=[4, 8, 12] , _A=[4, 4, 4] , _A=[16, 16, 16] , _A=0 , _A=[2, 2, 2] , _A=[2, 2, 2] , _A=0.0_2 , **_A , ): super().__init__(**_A ) __A : Tuple = image_size __A : int = num_channels __A : List[str] = kernel_size __A : Union[str, Any] = stride __A : Optional[int] = padding __A : Tuple = hidden_sizes __A : Optional[int] = num_attention_heads __A : List[str] = depths __A : Tuple = key_dim __A : str = drop_path_rate __A : str = patch_size __A : Dict = attention_ratio __A : Union[str, Any] = mlp_ratio __A : List[str] = initializer_range __A : Dict = [ ['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 _A( snake_case__ ): """simple docstring""" UpperCamelCase : int = version.parse('''1.11''' ) @property def UpperCAmelCase_ ( self ): return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def UpperCAmelCase_ ( self ): return 1e-4
280
from heapq import heappop, heappush import numpy as np def _SCREAMING_SNAKE_CASE ( a , a , a , a , ) -> tuple[float | int, list[tuple[int, int]]]: __A , __A : int = grid.shape __A : Any = [-1, 1, 0, 0] __A : Optional[Any] = [0, 0, -1, 1] if allow_diagonal: dx += [-1, -1, 1, 1] dy += [-1, 1, -1, 1] __A , __A : Optional[int] = [(0, source)], set() __A : Any = np.full((rows, cols) , np.inf ) __A : Any = 0 __A : Any = np.empty((rows, cols) , dtype=a ) __A : Optional[Any] = None while queue: ((__A) , (__A)) : List[str] = heappop(a ) if (x, y) in visited: continue visited.add((x, y) ) if (x, y) == destination: __A : int = [] while (x, y) != source: path.append((x, y) ) __A , __A : Optional[int] = predecessors[x, y] path.append(a ) # add the source manually path.reverse() return matrix[destination], path for i in range(len(a ) ): __A , __A : Union[str, Any] = x + dx[i], y + dy[i] if 0 <= nx < rows and 0 <= ny < cols: __A : Optional[int] = grid[nx][ny] if next_node == 1 and matrix[nx, ny] > dist + 1: heappush(a , (dist + 1, (nx, ny)) ) __A : List[Any] = dist + 1 __A : Union[str, Any] = (x, y) return np.inf, [] if __name__ == "__main__": import doctest doctest.testmod()
280
1
import argparse from pathlib import Path import fairseq import torch from fairseq.models.xmod import XMODModel as FairseqXmodModel from packaging import version from transformers import XmodConfig, XmodForMaskedLM, XmodForSequenceClassification from transformers.utils import logging if version.parse(fairseq.__version__) < version.parse('''0.12.2'''): raise Exception('''requires fairseq >= 0.12.2''') if version.parse(fairseq.__version__) > version.parse('''2'''): raise Exception('''requires fairseq < v2''') logging.set_verbosity_info() UpperCAmelCase : List[str] = logging.get_logger(__name__) UpperCAmelCase : List[str] = '''Hello, World!''' UpperCAmelCase : str = '''en_XX''' def _SCREAMING_SNAKE_CASE ( a , a , a ) -> Optional[int]: __A : Any = Path('data_bin' ) __A : Any = FairseqXmodModel.from_pretrained( model_name_or_path=str(Path(a ).parent ) , checkpoint_file=Path(a ).name , _name='xmod_base' , arch='xmod_base' , task='multilingual_masked_lm' , data_name_or_path=str(a ) , bpe='sentencepiece' , sentencepiece_model=str(Path(a ).parent / 'sentencepiece.bpe.model' ) , src_dict=str(data_dir / 'dict.txt' ) , ) xmod.eval() # disable dropout print(a ) __A : Dict = xmod.model.encoder.sentence_encoder __A : str = XmodConfig( vocab_size=xmod_sent_encoder.embed_tokens.num_embeddings , hidden_size=xmod.cfg.model.encoder_embed_dim , num_hidden_layers=xmod.cfg.model.encoder_layers , num_attention_heads=xmod.cfg.model.encoder_attention_heads , intermediate_size=xmod.cfg.model.encoder_ffn_embed_dim , max_position_embeddings=5_14 , type_vocab_size=1 , layer_norm_eps=1e-5 , pre_norm=xmod.cfg.model.encoder_normalize_before , adapter_reduction_factor=getattr(xmod.cfg.model , 'bottleneck' , 2 ) , adapter_layer_norm=xmod.cfg.model.adapter_layer_norm , adapter_reuse_layer_norm=xmod.cfg.model.adapter_reuse_layer_norm , ln_before_adapter=xmod.cfg.model.ln_before_adapter , languages=xmod.cfg.model.languages , ) if classification_head: __A : Tuple = xmod.model.classification_heads['mnli'].out_proj.weight.shape[0] print('Our X-MOD config:' , a ) __A : Any = XmodForSequenceClassification(a ) if classification_head else XmodForMaskedLM(a ) model.eval() # Now let's copy all the weights. # Embeddings __A : str = xmod_sent_encoder.embed_tokens.weight __A : Optional[Any] = xmod_sent_encoder.embed_positions.weight __A : Any = torch.zeros_like( model.roberta.embeddings.token_type_embeddings.weight ) # just zero them out b/c xmod doesn't use them. __A : Dict = xmod_sent_encoder.layernorm_embedding.weight __A : List[str] = xmod_sent_encoder.layernorm_embedding.bias for i in range(config.num_hidden_layers ): # Encoder: start of layer __A : Optional[int] = model.roberta.encoder.layer[i] __A : Optional[int] = xmod_sent_encoder.layers[i] # self attention __A : Union[str, Any] = layer.attention.self if not ( xmod_layer.self_attn.k_proj.weight.data.shape == xmod_layer.self_attn.q_proj.weight.data.shape == xmod_layer.self_attn.v_proj.weight.data.shape == torch.Size((config.hidden_size, config.hidden_size) ) ): raise AssertionError('Dimensions of self-attention weights do not match.' ) __A : Tuple = xmod_layer.self_attn.q_proj.weight __A : Optional[Any] = xmod_layer.self_attn.q_proj.bias __A : Optional[int] = xmod_layer.self_attn.k_proj.weight __A : str = xmod_layer.self_attn.k_proj.bias __A : int = xmod_layer.self_attn.v_proj.weight __A : Optional[Any] = xmod_layer.self_attn.v_proj.bias # self-attention output __A : Dict = layer.attention.output if self_output.dense.weight.shape != xmod_layer.self_attn.out_proj.weight.shape: raise AssertionError('Dimensions of self-attention output weights do not match.' ) __A : int = xmod_layer.self_attn.out_proj.weight __A : Dict = xmod_layer.self_attn.out_proj.bias __A : List[str] = xmod_layer.self_attn_layer_norm.weight __A : str = xmod_layer.self_attn_layer_norm.bias # intermediate __A : Optional[Any] = layer.intermediate if intermediate.dense.weight.shape != xmod_layer.fca.weight.shape: raise AssertionError('Dimensions of intermediate weights do not match.' ) __A : Any = xmod_layer.fca.weight __A : Tuple = xmod_layer.fca.bias # output __A : List[Any] = layer.output if bert_output.dense.weight.shape != xmod_layer.fca.weight.shape: raise AssertionError('Dimensions of feed-forward weights do not match.' ) __A : str = xmod_layer.fca.weight __A : Tuple = xmod_layer.fca.bias __A : List[Any] = xmod_layer.final_layer_norm.weight __A : int = xmod_layer.final_layer_norm.bias if bert_output.adapter_layer_norm is not None: __A : List[str] = xmod_layer.adapter_layer_norm.weight __A : Dict = xmod_layer.adapter_layer_norm.bias if sorted(bert_output.adapter_modules.keys() ) != sorted(xmod_layer.adapter_modules.keys() ): raise AssertionError('Lists of language adapters do not match.' ) for lang_code, adapter in xmod_layer.adapter_modules.items(): __A : str = bert_output.adapter_modules[lang_code] __A : List[str] = xmod_layer.adapter_modules[lang_code] __A : List[str] = from_adapter.fca.weight __A : Tuple = from_adapter.fca.bias __A : Optional[int] = from_adapter.fca.weight __A : int = from_adapter.fca.bias # end of layer if xmod_sent_encoder.layer_norm is not None: __A : List[Any] = xmod_sent_encoder.layer_norm.weight __A : str = xmod_sent_encoder.layer_norm.bias if classification_head: __A : Any = xmod.model.classification_heads['mnli'].dense.weight __A : Dict = xmod.model.classification_heads['mnli'].dense.bias __A : Any = xmod.model.classification_heads['mnli'].out_proj.weight __A : Any = xmod.model.classification_heads['mnli'].out_proj.bias else: # LM Head __A : List[Any] = xmod.model.encoder.lm_head.dense.weight __A : str = xmod.model.encoder.lm_head.dense.bias __A : Optional[int] = xmod.model.encoder.lm_head.layer_norm.weight __A : Union[str, Any] = xmod.model.encoder.lm_head.layer_norm.bias __A : Dict = xmod.model.encoder.lm_head.weight __A : int = xmod.model.encoder.lm_head.bias # Let's check that we get the same results. __A : List[str] = xmod.encode(a ).unsqueeze(0 ) # batch of size 1 model.roberta.set_default_language(a ) __A : Optional[Any] = model(a )[0] if classification_head: __A : Optional[int] = xmod.model.classification_heads['mnli'](xmod.extract_features(a ) ) else: __A : Any = xmod.model(a , lang_id=[SAMPLE_LANGUAGE] )[0] print(our_output.shape , their_output.shape ) __A : int = torch.max(torch.abs(our_output - their_output ) ).item() print(F"""max_absolute_diff = {max_absolute_diff}""" ) # ~ 1e-7 __A : Union[str, Any] = torch.allclose(a , a , atol=1e-3 ) print('Do both models output the same tensors?' , '🔥' if success else '💩' ) if not success: raise Exception('Something went wRoNg' ) Path(a ).mkdir(parents=a , exist_ok=a ) print(F"""Saving model to {pytorch_dump_folder_path}""" ) model.save_pretrained(a ) if __name__ == "__main__": UpperCAmelCase : str = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--xmod_checkpoint_path''', default=None, type=str, required=True, help='''Path the official PyTorch dump.''' ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) parser.add_argument( '''--classification_head''', action='''store_true''', help='''Whether to convert a final classification head.''' ) UpperCAmelCase : Any = parser.parse_args() convert_xmod_checkpoint_to_pytorch( args.xmod_checkpoint_path, args.pytorch_dump_folder_path, args.classification_head )
280
from typing import List, Optional, Union import numpy as np import PIL import torch from PIL import Image from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) UpperCAmelCase : List[Any] = logging.get_logger(__name__) # pylint: disable=invalid-name UpperCAmelCase : Dict = ''' Examples: ```py >>> from diffusers import KandinskyV22Img2ImgPipeline, KandinskyV22PriorPipeline >>> from diffusers.utils import load_image >>> import torch >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained( ... "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16 ... ) >>> pipe_prior.to("cuda") >>> prompt = "A red cartoon frog, 4k" >>> image_emb, zero_image_emb = pipe_prior(prompt, return_dict=False) >>> pipe = KandinskyV22Img2ImgPipeline.from_pretrained( ... "kandinsky-community/kandinsky-2-2-decoder", torch_dtype=torch.float16 ... ) >>> pipe.to("cuda") >>> init_image = load_image( ... "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" ... "/kandinsky/frog.png" ... ) >>> image = pipe( ... image=init_image, ... image_embeds=image_emb, ... negative_image_embeds=zero_image_emb, ... height=768, ... width=768, ... num_inference_steps=100, ... strength=0.2, ... ).images >>> image[0].save("red_frog.png") ``` ''' def _SCREAMING_SNAKE_CASE ( a , a , a=8 ) -> Tuple: __A : List[str] = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 __A : Optional[int] = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor def _SCREAMING_SNAKE_CASE ( a , a=5_12 , a=5_12 ) -> int: __A : Optional[Any] = pil_image.resize((w, h) , resample=Image.BICUBIC , reducing_gap=1 ) __A : Union[str, Any] = np.array(pil_image.convert('RGB' ) ) __A : Optional[int] = arr.astype(np.floataa ) / 127.5 - 1 __A : int = np.transpose(a , [2, 0, 1] ) __A : Tuple = torch.from_numpy(a ).unsqueeze(0 ) return image class _A( snake_case__ ): """simple docstring""" def __init__( self , _A , _A , _A , ): super().__init__() self.register_modules( unet=_A , scheduler=_A , movq=_A , ) __A : Tuple = 2 ** (len(self.movq.config.block_out_channels ) - 1) def UpperCAmelCase_ ( self , _A , _A , _A ): # get the original timestep using init_timestep __A : Optional[int] = min(int(num_inference_steps * strength ) , _A ) __A : Dict = max(num_inference_steps - init_timestep , 0 ) __A : Tuple = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A=None ): if not isinstance(_A , (torch.Tensor, PIL.Image.Image, list) ): raise ValueError( F"""`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(_A )}""" ) __A : Union[str, Any] = image.to(device=_A , dtype=_A ) __A : Optional[Any] = batch_size * num_images_per_prompt if image.shape[1] == 4: __A : int = image else: if isinstance(_A , _A ) and len(_A ) != batch_size: raise ValueError( F"""You have passed a list of generators of length {len(_A )}, but requested an effective batch""" F""" size of {batch_size}. Make sure the batch size matches the length of the generators.""" ) elif isinstance(_A , _A ): __A : str = [ self.movq.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(_A ) ] __A : str = torch.cat(_A , dim=0 ) else: __A : List[str] = self.movq.encode(_A ).latent_dist.sample(_A ) __A : Tuple = self.movq.config.scaling_factor * init_latents __A : Optional[int] = torch.cat([init_latents] , dim=0 ) __A : Union[str, Any] = init_latents.shape __A : List[str] = randn_tensor(_A , generator=_A , device=_A , dtype=_A ) # get latents __A : Optional[Any] = self.scheduler.add_noise(_A , _A , _A ) __A : Optional[int] = init_latents return latents def UpperCAmelCase_ ( self , _A=0 ): if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('Please install accelerate via `pip install accelerate`' ) __A : Optional[int] = torch.device(F"""cuda:{gpu_id}""" ) __A : Union[str, Any] = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(_A , _A ) def UpperCAmelCase_ ( self , _A=0 ): if is_accelerate_available() and is_accelerate_version('>=' , '0.17.0.dev0' ): from accelerate import cpu_offload_with_hook else: raise ImportError('`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.' ) __A : List[Any] = torch.device(F"""cuda:{gpu_id}""" ) if self.device.type != "cpu": self.to('cpu' , silence_dtype_warnings=_A ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) __A : int = None for cpu_offloaded_model in [self.unet, self.movq]: __A , __A : Optional[int] = cpu_offload_with_hook(_A , _A , prev_module_hook=_A ) # We'll offload the last model manually. __A : List[str] = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def UpperCAmelCase_ ( self ): if not hasattr(self.unet , '_hf_hook' ): return self.device for module in self.unet.modules(): if ( hasattr(_A , '_hf_hook' ) and hasattr(module._hf_hook , 'execution_device' ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(_A ) def __call__( self , _A , _A , _A , _A = 512 , _A = 512 , _A = 100 , _A = 4.0 , _A = 0.3 , _A = 1 , _A = None , _A = "pil" , _A = True , ): __A : List[Any] = self._execution_device __A : Optional[Any] = guidance_scale > 1.0 if isinstance(_A , _A ): __A : Optional[Any] = torch.cat(_A , dim=0 ) __A : Tuple = image_embeds.shape[0] if isinstance(_A , _A ): __A : List[Any] = torch.cat(_A , dim=0 ) if do_classifier_free_guidance: __A : Union[str, Any] = image_embeds.repeat_interleave(_A , dim=0 ) __A : Optional[int] = negative_image_embeds.repeat_interleave(_A , dim=0 ) __A : List[str] = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=_A ) if not isinstance(_A , _A ): __A : List[Any] = [image] if not all(isinstance(_A , (PIL.Image.Image, torch.Tensor) ) for i in image ): raise ValueError( F"""Input is in incorrect format: {[type(_A ) for i in image]}. Currently, we only support PIL image and pytorch tensor""" ) __A : Dict = torch.cat([prepare_image(_A , _A , _A ) for i in image] , dim=0 ) __A : Any = image.to(dtype=image_embeds.dtype , device=_A ) __A : Tuple = self.movq.encode(_A )['latents'] __A : int = latents.repeat_interleave(_A , dim=0 ) self.scheduler.set_timesteps(_A , device=_A ) __A , __A : int = self.get_timesteps(_A , _A , _A ) __A : Union[str, Any] = timesteps[:1].repeat(batch_size * num_images_per_prompt ) __A , __A : Any = downscale_height_and_width(_A , _A , self.movq_scale_factor ) __A : Tuple = self.prepare_latents( _A , _A , _A , _A , image_embeds.dtype , _A , _A ) for i, t in enumerate(self.progress_bar(_A ) ): # expand the latents if we are doing classifier free guidance __A : Optional[int] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents __A : Dict = {'image_embeds': image_embeds} __A : List[str] = self.unet( sample=_A , timestep=_A , encoder_hidden_states=_A , added_cond_kwargs=_A , return_dict=_A , )[0] if do_classifier_free_guidance: __A , __A : Dict = noise_pred.split(latents.shape[1] , dim=1 ) __A , __A : Optional[Any] = noise_pred.chunk(2 ) __A , __A : List[str] = variance_pred.chunk(2 ) __A : str = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) __A : List[str] = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , 'variance_type' ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): __A , __A : Optional[Any] = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 __A : List[str] = self.scheduler.step( _A , _A , _A , generator=_A , )[0] # post-processing __A : List[Any] = self.movq.decode(_A , force_not_quantize=_A )['sample'] if output_type not in ["pt", "np", "pil"]: raise ValueError(F"""Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}""" ) if output_type in ["np", "pil"]: __A : List[str] = image * 0.5 + 0.5 __A : List[str] = image.clamp(0 , 1 ) __A : Optional[Any] = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": __A : Any = self.numpy_to_pil(_A ) if not return_dict: return (image,) return ImagePipelineOutput(images=_A )
280
1
def _SCREAMING_SNAKE_CASE ( a , a ) -> int: while a != 0: __A , __A : Dict = b % a, a return b def _SCREAMING_SNAKE_CASE ( a , a ) -> int: if gcd(a , a ) != 1: __A : List[Any] = F"""mod inverse of {a!r} and {m!r} does not exist""" raise ValueError(a ) __A , __A , __A : Optional[Any] = 1, 0, a __A , __A , __A : List[str] = 0, 1, m while va != 0: __A : str = ua // va __A , __A , __A , __A , __A , __A : Union[str, Any] = (ua - q * va), (ua - q * va), (ua - q * va), va, va, va return ua % m
280
import argparse import os import gluonnlp as nlp import mxnet as mx import numpy as np import torch from gluonnlp.base import get_home_dir from gluonnlp.model.bert import BERTEncoder from gluonnlp.model.utils import _load_vocab from gluonnlp.vocab import Vocab from packaging import version from torch import nn from transformers import BertConfig, BertForMaskedLM, BertModel, RobertaTokenizer from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertSelfAttention, BertSelfOutput, ) from transformers.utils import logging if version.parse(nlp.__version__) != version.parse('''0.8.3'''): raise Exception('''requires gluonnlp == 0.8.3''') if version.parse(mx.__version__) != version.parse('''1.5.0'''): raise Exception('''requires mxnet == 1.5.0''') logging.set_verbosity_info() UpperCAmelCase : List[Any] = logging.get_logger(__name__) UpperCAmelCase : Optional[Any] = '''The Nymphenburg Palace is a beautiful palace in Munich!''' def _SCREAMING_SNAKE_CASE ( a , a ) -> Optional[Any]: __A : Any = { 'attention_cell': 'multi_head', 'num_layers': 4, 'units': 10_24, 'hidden_size': 7_68, 'max_length': 5_12, 'num_heads': 8, 'scaled': True, 'dropout': 0.1, 'use_residual': True, 'embed_size': 10_24, 'embed_dropout': 0.1, 'word_embed': None, 'layer_norm_eps': 1e-5, 'token_type_vocab_size': 2, } __A : str = bort_4_8_768_1024_hparams # Let's construct the original Bort model here # Taken from official BERT implementation, see: # https://github.com/alexa/bort/blob/master/bort/bort.py __A : Optional[int] = BERTEncoder( attention_cell=predefined_args['attention_cell'] , num_layers=predefined_args['num_layers'] , units=predefined_args['units'] , hidden_size=predefined_args['hidden_size'] , max_length=predefined_args['max_length'] , num_heads=predefined_args['num_heads'] , scaled=predefined_args['scaled'] , dropout=predefined_args['dropout'] , output_attention=a , output_all_encodings=a , use_residual=predefined_args['use_residual'] , activation=predefined_args.get('activation' , 'gelu' ) , layer_norm_eps=predefined_args.get('layer_norm_eps' , a ) , ) # Vocab information needs to be fetched first # It's the same as RoBERTa, so RobertaTokenizer can be used later __A : Union[str, Any] = 'openwebtext_ccnews_stories_books_cased' # Specify download folder to Gluonnlp's vocab __A : Any = os.path.join(get_home_dir() , 'models' ) __A : List[Any] = _load_vocab(a , a , a , cls=a ) __A : Dict = nlp.model.BERTModel( a , len(a ) , units=predefined_args['units'] , embed_size=predefined_args['embed_size'] , embed_dropout=predefined_args['embed_dropout'] , word_embed=predefined_args['word_embed'] , use_pooler=a , use_token_type_embed=a , token_type_vocab_size=predefined_args['token_type_vocab_size'] , use_classifier=a , use_decoder=a , ) original_bort.load_parameters(a , cast_dtype=a , ignore_extra=a ) __A : Union[str, Any] = original_bort._collect_params_with_prefix() # Build our config 🤗 __A : Any = { 'architectures': ['BertForMaskedLM'], 'attention_probs_dropout_prob': predefined_args['dropout'], 'hidden_act': 'gelu', 'hidden_dropout_prob': predefined_args['dropout'], 'hidden_size': predefined_args['embed_size'], 'initializer_range': 0.02, 'intermediate_size': predefined_args['hidden_size'], 'layer_norm_eps': predefined_args['layer_norm_eps'], 'max_position_embeddings': predefined_args['max_length'], 'model_type': 'bort', 'num_attention_heads': predefined_args['num_heads'], 'num_hidden_layers': predefined_args['num_layers'], 'pad_token_id': 1, # 2 = BERT, 1 = RoBERTa 'type_vocab_size': 1, # 2 = BERT, 1 = RoBERTa 'vocab_size': len(a ), } __A : int = BertConfig.from_dict(a ) __A : Union[str, Any] = BertForMaskedLM(a ) hf_bort_model.eval() # Parameter mapping table (Gluonnlp to Transformers) # * denotes layer index # # | Gluon Parameter | Transformers Parameter # | -------------------------------------------------------------- | ---------------------- # | `encoder.layer_norm.beta` | `bert.embeddings.LayerNorm.bias` # | `encoder.layer_norm.gamma` | `bert.embeddings.LayerNorm.weight` # | `encoder.position_weight` | `bert.embeddings.position_embeddings.weight` # | `word_embed.0.weight` | `bert.embeddings.word_embeddings.weight` # | `encoder.transformer_cells.*.attention_cell.proj_key.bias` | `bert.encoder.layer.*.attention.self.key.bias` # | `encoder.transformer_cells.*.attention_cell.proj_key.weight` | `bert.encoder.layer.*.attention.self.key.weight` # | `encoder.transformer_cells.*.attention_cell.proj_query.bias` | `bert.encoder.layer.*.attention.self.query.bias` # | `encoder.transformer_cells.*.attention_cell.proj_query.weight` | `bert.encoder.layer.*.attention.self.query.weight` # | `encoder.transformer_cells.*.attention_cell.proj_value.bias` | `bert.encoder.layer.*.attention.self.value.bias` # | `encoder.transformer_cells.*.attention_cell.proj_value.weight` | `bert.encoder.layer.*.attention.self.value.weight` # | `encoder.transformer_cells.*.ffn.ffn_2.bias` | `bert.encoder.layer.*.attention.output.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_2.weight` | `bert.encoder.layer.*.attention.output.dense.weight` # | `encoder.transformer_cells.*.layer_norm.beta` | `bert.encoder.layer.*.attention.output.LayerNorm.bias` # | `encoder.transformer_cells.*.layer_norm.gamma` | `bert.encoder.layer.*.attention.output.LayerNorm.weight` # | `encoder.transformer_cells.*.ffn.ffn_1.bias` | `bert.encoder.layer.*.intermediate.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_1.weight` | `bert.encoder.layer.*.intermediate.dense.weight` # | `encoder.transformer_cells.*.ffn.layer_norm.beta` | `bert.encoder.layer.*.output.LayerNorm.bias` # | `encoder.transformer_cells.*.ffn.layer_norm.gamma` | `bert.encoder.layer.*.output.LayerNorm.weight` # | `encoder.transformer_cells.*.proj.bias` | `bert.encoder.layer.*.output.dense.bias` # | `encoder.transformer_cells.*.proj.weight` | `bert.encoder.layer.*.output.dense.weight` # Helper function to convert MXNET Arrays to PyTorch def to_torch(a ) -> nn.Parameter: return nn.Parameter(torch.FloatTensor(mx_array.data().asnumpy() ) ) # Check param shapes and map new HF param back def check_and_map_params(a , a ): __A : Tuple = hf_param.shape __A : str = to_torch(params[gluon_param] ) __A : Union[str, Any] = gluon_param.shape assert ( shape_hf == shape_gluon ), F"""The gluon parameter {gluon_param} has shape {shape_gluon}, but expects shape {shape_hf} for Transformers""" return gluon_param __A : str = check_and_map_params( hf_bort_model.bert.embeddings.word_embeddings.weight , 'word_embed.0.weight' ) __A : Tuple = check_and_map_params( hf_bort_model.bert.embeddings.position_embeddings.weight , 'encoder.position_weight' ) __A : List[str] = check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.bias , 'encoder.layer_norm.beta' ) __A : Tuple = check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.weight , 'encoder.layer_norm.gamma' ) # Inspired by RoBERTa conversion script, we just zero them out (Bort does not use them) __A : Tuple = torch.zeros_like( hf_bort_model.bert.embeddings.token_type_embeddings.weight.data ) for i in range(hf_bort_config.num_hidden_layers ): __A : BertLayer = hf_bort_model.bert.encoder.layer[i] # self attention __A : BertSelfAttention = layer.attention.self __A : Optional[Any] = check_and_map_params( self_attn.key.bias.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_key.bias""" ) __A : Optional[int] = check_and_map_params( self_attn.key.weight.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_key.weight""" ) __A : Union[str, Any] = check_and_map_params( self_attn.query.bias.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_query.bias""" ) __A : Optional[Any] = check_and_map_params( self_attn.query.weight.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_query.weight""" ) __A : Union[str, Any] = check_and_map_params( self_attn.value.bias.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_value.bias""" ) __A : Optional[int] = check_and_map_params( self_attn.value.weight.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_value.weight""" ) # self attention output __A : BertSelfOutput = layer.attention.output __A : Tuple = check_and_map_params( self_output.dense.bias , F"""encoder.transformer_cells.{i}.proj.bias""" ) __A : int = check_and_map_params( self_output.dense.weight , F"""encoder.transformer_cells.{i}.proj.weight""" ) __A : List[Any] = check_and_map_params( self_output.LayerNorm.bias , F"""encoder.transformer_cells.{i}.layer_norm.beta""" ) __A : str = check_and_map_params( self_output.LayerNorm.weight , F"""encoder.transformer_cells.{i}.layer_norm.gamma""" ) # intermediate __A : BertIntermediate = layer.intermediate __A : int = check_and_map_params( intermediate.dense.bias , F"""encoder.transformer_cells.{i}.ffn.ffn_1.bias""" ) __A : List[Any] = check_and_map_params( intermediate.dense.weight , F"""encoder.transformer_cells.{i}.ffn.ffn_1.weight""" ) # output __A : BertOutput = layer.output __A : List[Any] = check_and_map_params( bert_output.dense.bias , F"""encoder.transformer_cells.{i}.ffn.ffn_2.bias""" ) __A : Dict = check_and_map_params( bert_output.dense.weight , F"""encoder.transformer_cells.{i}.ffn.ffn_2.weight""" ) __A : Optional[int] = check_and_map_params( bert_output.LayerNorm.bias , F"""encoder.transformer_cells.{i}.ffn.layer_norm.beta""" ) __A : Dict = check_and_map_params( bert_output.LayerNorm.weight , F"""encoder.transformer_cells.{i}.ffn.layer_norm.gamma""" ) # Save space and energy 🎄 hf_bort_model.half() # Compare output of both models __A : Any = RobertaTokenizer.from_pretrained('roberta-base' ) __A : List[str] = tokenizer.encode_plus(a )['input_ids'] # Get gluon output __A : List[str] = mx.nd.array([input_ids] ) __A : Union[str, Any] = original_bort(inputs=a , token_types=[] ) # Get Transformer output (save and reload model again) hf_bort_model.save_pretrained(a ) __A : Optional[Any] = BertModel.from_pretrained(a ) hf_bort_model.eval() __A : Tuple = tokenizer.encode_plus(a , return_tensors='pt' ) __A : Any = hf_bort_model(**a )[0] __A : Union[str, Any] = output_gluon[0].asnumpy() __A : Tuple = output_hf[0].detach().numpy() __A : int = np.max(np.abs(hf_layer - gluon_layer ) ).item() __A : int = np.allclose(a , a , atol=1e-3 ) if success: print('✔️ Both model do output the same tensors' ) else: print('❌ Both model do **NOT** output the same tensors' ) print('Absolute difference is:' , a ) if __name__ == "__main__": UpperCAmelCase : int = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--bort_checkpoint_path''', default=None, type=str, required=True, help='''Path the official Bort params file.''' ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) UpperCAmelCase : Dict = parser.parse_args() convert_bort_checkpoint_to_pytorch(args.bort_checkpoint_path, args.pytorch_dump_folder_path)
280
1
import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert from transformers.utils import logging logging.set_verbosity_info() def _SCREAMING_SNAKE_CASE ( a , a , a ) -> Union[str, Any]: # Initialise PyTorch model __A : Dict = BertConfig.from_json_file(a ) print(F"""Building PyTorch model from configuration: {config}""" ) __A : str = BertForPreTraining(a ) # Load weights from tf checkpoint load_tf_weights_in_bert(a , a , a ) # Save pytorch-model print(F"""Save PyTorch model to {pytorch_dump_path}""" ) torch.save(model.state_dict() , a ) if __name__ == "__main__": UpperCAmelCase : List[str] = 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.''' ) UpperCAmelCase : Tuple = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
280
import colorsys from PIL import Image # type: ignore def _SCREAMING_SNAKE_CASE ( a , a , a ) -> float: __A : List[str] = x __A : str = y for step in range(a ): # noqa: B007 __A : Union[str, Any] = a * a - b * b + x __A : Optional[int] = 2 * a * b + y __A : List[str] = a_new # divergence happens for all complex number with an absolute value # greater than 4 if a * a + b * b > 4: break return step / (max_step - 1) def _SCREAMING_SNAKE_CASE ( a ) -> tuple: if distance == 1: return (0, 0, 0) else: return (2_55, 2_55, 2_55) def _SCREAMING_SNAKE_CASE ( a ) -> tuple: if distance == 1: return (0, 0, 0) else: return tuple(round(i * 2_55 ) for i in colorsys.hsv_to_rgb(a , 1 , 1 ) ) def _SCREAMING_SNAKE_CASE ( a = 8_00 , a = 6_00 , a = -0.6 , a = 0 , a = 3.2 , a = 50 , a = True , ) -> Image.Image: __A : str = Image.new('RGB' , (image_width, image_height) ) __A : Dict = img.load() # loop through the image-coordinates for image_x in range(a ): for image_y in range(a ): # determine the figure-coordinates based on the image-coordinates __A : Dict = figure_width / image_width * image_height __A : Union[str, Any] = figure_center_x + (image_x / image_width - 0.5) * figure_width __A : Optional[Any] = figure_center_y + (image_y / image_height - 0.5) * figure_height __A : Union[str, Any] = get_distance(a , a , a ) # color the corresponding pixel based on the selected coloring-function if use_distance_color_coding: __A : Optional[Any] = get_color_coded_rgb(a ) else: __A : Dict = get_black_and_white_rgb(a ) return img if __name__ == "__main__": import doctest doctest.testmod() # colored version, full figure UpperCAmelCase : str = get_image() # uncomment for colored version, different section, zoomed in # img = get_image(figure_center_x = -0.6, figure_center_y = -0.4, # figure_width = 0.8) # uncomment for black and white version, full figure # img = get_image(use_distance_color_coding = False) # uncomment to save the image # img.save("mandelbrot.png") img.show()
280
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 : Tuple = MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING UpperCamelCase : Optional[int] = TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING def UpperCAmelCase_ ( self , _A , _A , _A ): __A : Union[str, Any] = AudioClassificationPipeline(model=_A , feature_extractor=_A ) # test with a raw waveform __A : Any = np.zeros((34000,) ) __A : Optional[int] = np.zeros((14000,) ) return audio_classifier, [audioa, audio] def UpperCAmelCase_ ( self , _A , _A ): __A , __A : int = examples __A : int = audio_classifier(_A ) # by default a model is initialized with num_labels=2 self.assertEqual( _A , [ {'score': ANY(_A ), 'label': ANY(_A )}, {'score': ANY(_A ), 'label': ANY(_A )}, ] , ) __A : Union[str, Any] = audio_classifier(_A , top_k=1 ) self.assertEqual( _A , [ {'score': ANY(_A ), 'label': ANY(_A )}, ] , ) self.run_torchaudio(_A ) @require_torchaudio def UpperCAmelCase_ ( self , _A ): import datasets # test with a local file __A : Any = datasets.load_dataset('hf-internal-testing/librispeech_asr_dummy' , 'clean' , split='validation' ) __A : Optional[Any] = dataset[0]['audio']['array'] __A : Union[str, Any] = audio_classifier(_A ) self.assertEqual( _A , [ {'score': ANY(_A ), 'label': ANY(_A )}, {'score': ANY(_A ), 'label': ANY(_A )}, ] , ) @require_torch def UpperCAmelCase_ ( self ): __A : Tuple = 'anton-l/wav2vec2-random-tiny-classifier' __A : List[str] = pipeline('audio-classification' , model=_A ) __A : Dict = np.ones((8000,) ) __A : int = audio_classifier(_A , top_k=4 ) __A : List[str] = [ {'score': 0.0_8_4_2, 'label': 'no'}, {'score': 0.0_8_3_8, 'label': 'up'}, {'score': 0.0_8_3_7, 'label': 'go'}, {'score': 0.0_8_3_4, 'label': 'right'}, ] __A : List[str] = [ {'score': 0.0_8_4_5, 'label': 'stop'}, {'score': 0.0_8_4_4, 'label': 'on'}, {'score': 0.0_8_4_1, 'label': 'right'}, {'score': 0.0_8_3_4, 'label': 'left'}, ] self.assertIn(nested_simplify(_A , decimals=4 ) , [EXPECTED_OUTPUT, EXPECTED_OUTPUT_PT_2] ) __A : Tuple = {'array': np.ones((8000,) ), 'sampling_rate': audio_classifier.feature_extractor.sampling_rate} __A : List[str] = audio_classifier(_A , top_k=4 ) self.assertIn(nested_simplify(_A , decimals=4 ) , [EXPECTED_OUTPUT, EXPECTED_OUTPUT_PT_2] ) @require_torch @slow def UpperCAmelCase_ ( self ): import datasets __A : Union[str, Any] = 'superb/wav2vec2-base-superb-ks' __A : Any = pipeline('audio-classification' , model=_A ) __A : Tuple = datasets.load_dataset('anton-l/superb_dummy' , 'ks' , split='test' ) __A : Any = np.array(dataset[3]['speech'] , dtype=np.floataa ) __A : Optional[int] = audio_classifier(_A , top_k=4 ) self.assertEqual( nested_simplify(_A , decimals=3 ) , [ {'score': 0.9_8_1, 'label': 'go'}, {'score': 0.0_0_7, 'label': 'up'}, {'score': 0.0_0_6, 'label': '_unknown_'}, {'score': 0.0_0_1, 'label': 'down'}, ] , ) @require_tf @unittest.skip('Audio classification is not implemented for TF' ) def UpperCAmelCase_ ( self ): pass
280
from __future__ import annotations def _SCREAMING_SNAKE_CASE ( a , a , a ) -> float: if days_between_payments <= 0: raise ValueError('days_between_payments must be > 0' ) if daily_interest_rate < 0: raise ValueError('daily_interest_rate must be >= 0' ) if principal <= 0: raise ValueError('principal must be > 0' ) return principal * daily_interest_rate * days_between_payments def _SCREAMING_SNAKE_CASE ( a , a , a , ) -> float: if number_of_compounding_periods <= 0: raise ValueError('number_of_compounding_periods must be > 0' ) if nominal_annual_interest_rate_percentage < 0: raise ValueError('nominal_annual_interest_rate_percentage must be >= 0' ) if principal <= 0: raise ValueError('principal must be > 0' ) return principal * ( (1 + nominal_annual_interest_rate_percentage) ** number_of_compounding_periods - 1 ) def _SCREAMING_SNAKE_CASE ( a , a , a , ) -> float: if number_of_years <= 0: raise ValueError('number_of_years must be > 0' ) if nominal_annual_percentage_rate < 0: raise ValueError('nominal_annual_percentage_rate must be >= 0' ) if principal <= 0: raise ValueError('principal must be > 0' ) return compound_interest( a , nominal_annual_percentage_rate / 3_65 , number_of_years * 3_65 ) if __name__ == "__main__": import doctest doctest.testmod()
280
1
from __future__ import annotations import math def _SCREAMING_SNAKE_CASE ( a , a , a , a , a ) -> int: if depth < 0: raise ValueError('Depth cannot be less than 0' ) if len(a ) == 0: raise ValueError('Scores cannot be empty' ) if depth == height: return scores[node_index] if is_max: return max( minimax(depth + 1 , node_index * 2 , a , a , a ) , minimax(depth + 1 , node_index * 2 + 1 , a , a , a ) , ) return min( minimax(depth + 1 , node_index * 2 , a , a , a ) , minimax(depth + 1 , node_index * 2 + 1 , a , a , a ) , ) def _SCREAMING_SNAKE_CASE ( ) -> None: __A : Union[str, Any] = [90, 23, 6, 33, 21, 65, 1_23, 3_44_23] __A : Tuple = math.log(len(a ) , 2 ) print('Optimal value : ' , end='' ) print(minimax(0 , 0 , a , a , a ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
280
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) UpperCAmelCase : Any = { '''configuration_falcon''': ['''FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''FalconConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Any = [ '''FALCON_PRETRAINED_MODEL_ARCHIVE_LIST''', '''FalconForCausalLM''', '''FalconModel''', '''FalconPreTrainedModel''', '''FalconForSequenceClassification''', '''FalconForTokenClassification''', '''FalconForQuestionAnswering''', ] if TYPE_CHECKING: from .configuration_falcon import FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP, FalconConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_falcon import ( FALCON_PRETRAINED_MODEL_ARCHIVE_LIST, FalconForCausalLM, FalconForQuestionAnswering, FalconForSequenceClassification, FalconForTokenClassification, FalconModel, FalconPreTrainedModel, ) else: import sys UpperCAmelCase : List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
280
1
# Author: OMKAR PATHAK, Nwachukwu Chidiebere # Use a Python dictionary to construct the graph. from __future__ import annotations from pprint import pformat from typing import Generic, TypeVar UpperCAmelCase : Optional[int] = TypeVar('''T''') class _A( Generic[T] ): """simple docstring""" def __init__( self , _A = True ): __A : dict[T, list[T]] = {} # dictionary of lists __A : str = directed def UpperCAmelCase_ ( self , _A , _A ): if not self.directed: # For undirected graphs # if both source vertex and destination vertex are both present in the # adjacency list, add destination vertex to source vertex list of adjacent # vertices and add source vertex to destination vertex list of adjacent # vertices. if source_vertex in self.adj_list and destination_vertex in self.adj_list: self.adj_list[source_vertex].append(_A ) self.adj_list[destination_vertex].append(_A ) # if only source vertex is present in adjacency list, add destination vertex # to source vertex list of adjacent vertices, then create a new vertex with # destination vertex as key and assign a list containing the source vertex # as it's first adjacent vertex. elif source_vertex in self.adj_list: self.adj_list[source_vertex].append(_A ) __A : Union[str, Any] = [source_vertex] # if only destination vertex is present in adjacency list, add source vertex # to destination vertex list of adjacent vertices, then create a new vertex # with source vertex as key and assign a list containing the source vertex # as it's first adjacent vertex. elif destination_vertex in self.adj_list: self.adj_list[destination_vertex].append(_A ) __A : Union[str, Any] = [destination_vertex] # if both source vertex and destination vertex are not present in adjacency # list, create a new vertex with source vertex as key and assign a list # containing the destination vertex as it's first adjacent vertex also # create a new vertex with destination vertex as key and assign a list # containing the source vertex as it's first adjacent vertex. else: __A : Optional[Any] = [destination_vertex] __A : str = [source_vertex] else: # For directed graphs # if both source vertex and destination vertex are present in adjacency # list, add destination vertex to source vertex list of adjacent vertices. if source_vertex in self.adj_list and destination_vertex in self.adj_list: self.adj_list[source_vertex].append(_A ) # if only source vertex is present in adjacency list, add destination # vertex to source vertex list of adjacent vertices and create a new vertex # with destination vertex as key, which has no adjacent vertex elif source_vertex in self.adj_list: self.adj_list[source_vertex].append(_A ) __A : List[str] = [] # if only destination vertex is present in adjacency list, create a new # vertex with source vertex as key and assign a list containing destination # vertex as first adjacent vertex elif destination_vertex in self.adj_list: __A : str = [destination_vertex] # if both source vertex and destination vertex are not present in adjacency # list, create a new vertex with source vertex as key and a list containing # destination vertex as it's first adjacent vertex. Then create a new vertex # with destination vertex as key, which has no adjacent vertex else: __A : Tuple = [destination_vertex] __A : str = [] return self def __repr__( self ): return pformat(self.adj_list )
280
def _SCREAMING_SNAKE_CASE ( a ) -> bool: return str(a ) == str(a )[::-1] def _SCREAMING_SNAKE_CASE ( a ) -> int: return int(a ) + int(str(a )[::-1] ) def _SCREAMING_SNAKE_CASE ( a = 1_00_00 ) -> int: __A : int = [] for num in range(1 , a ): __A : List[str] = 0 __A : List[Any] = num while iterations < 50: __A : str = sum_reverse(a ) iterations += 1 if is_palindrome(a ): break else: lychrel_nums.append(a ) return len(a ) if __name__ == "__main__": print(F"""{solution() = }""")
280
1
from argparse import ArgumentParser from .env import EnvironmentCommand def _SCREAMING_SNAKE_CASE ( ) -> str: __A : List[str] = ArgumentParser('Diffusers CLI tool' , usage='diffusers-cli <command> [<args>]' ) __A : Optional[Any] = parser.add_subparsers(help='diffusers-cli command helpers' ) # Register commands EnvironmentCommand.register_subcommand(a ) # Let's go __A : List[str] = parser.parse_args() if not hasattr(a , 'func' ): parser.print_help() exit(1 ) # Run __A : Optional[int] = args.func(a ) service.run() if __name__ == "__main__": main()
280
from __future__ import annotations import math import random from collections.abc import Collection from typing import overload class _A: """simple docstring""" def __init__( self , _A = None ): if components is None: __A : int = [] __A : Tuple = list(_A ) def __len__( self ): return len(self.__components ) def __str__( self ): return "(" + ",".join(map(_A , self.__components ) ) + ")" def __add__( self , _A ): __A : Optional[int] = len(self ) if size == len(_A ): __A : Any = [self.__components[i] + other.component(_A ) for i in range(_A )] return Vector(_A ) else: raise Exception('must have the same size' ) def __sub__( self , _A ): __A : Tuple = len(self ) if size == len(_A ): __A : Union[str, Any] = [self.__components[i] - other.component(_A ) for i in range(_A )] return Vector(_A ) else: # error case raise Exception('must have the same size' ) @overload def __mul__( self , _A ): ... @overload def __mul__( self , _A ): ... def __mul__( self , _A ): if isinstance(_A , (float, int) ): __A : str = [c * other for c in self.__components] return Vector(_A ) elif isinstance(_A , _A ) and len(self ) == len(_A ): __A : Union[str, Any] = len(self ) __A : Dict = [self.__components[i] * other.component(_A ) for i in range(_A )] return sum(_A ) else: # error case raise Exception('invalid operand!' ) def UpperCAmelCase_ ( self ): return Vector(self.__components ) def UpperCAmelCase_ ( self , _A ): if isinstance(_A , _A ) and -len(self.__components ) <= i < len(self.__components ): return self.__components[i] else: raise Exception('index out of range' ) def UpperCAmelCase_ ( self , _A , _A ): assert -len(self.__components ) <= pos < len(self.__components ) __A : Optional[int] = value def UpperCAmelCase_ ( self ): if len(self.__components ) == 0: raise Exception('Vector is empty' ) __A : Optional[Any] = [c**2 for c in self.__components] return math.sqrt(sum(_A ) ) def UpperCAmelCase_ ( self , _A , _A = False ): __A : Optional[Any] = self * other __A : Optional[Any] = self.euclidean_length() * other.euclidean_length() if deg: return math.degrees(math.acos(num / den ) ) else: return math.acos(num / den ) def _SCREAMING_SNAKE_CASE ( a ) -> Vector: assert isinstance(a , a ) return Vector([0] * dimension ) def _SCREAMING_SNAKE_CASE ( a , a ) -> Vector: assert isinstance(a , a ) and (isinstance(a , a )) __A : Optional[Any] = [0] * dimension __A : Tuple = 1 return Vector(a ) def _SCREAMING_SNAKE_CASE ( a , a , a ) -> Vector: assert ( isinstance(a , a ) and isinstance(a , a ) and (isinstance(a , (int, float) )) ) return x * scalar + y def _SCREAMING_SNAKE_CASE ( a , a , a ) -> Vector: random.seed(a ) __A : str = [random.randint(a , a ) for _ in range(a )] return Vector(a ) class _A: """simple docstring""" def __init__( self , _A , _A , _A ): __A : Optional[Any] = matrix __A : Dict = w __A : Optional[int] = h def __str__( self ): __A : Tuple = '' for i in range(self.__height ): ans += "|" for j in range(self.__width ): if j < self.__width - 1: ans += str(self.__matrix[i][j] ) + "," else: ans += str(self.__matrix[i][j] ) + "|\n" return ans def __add__( self , _A ): if self.__width == other.width() and self.__height == other.height(): __A : Optional[Any] = [] for i in range(self.__height ): __A : Optional[Any] = [ self.__matrix[i][j] + other.component(_A , _A ) for j in range(self.__width ) ] matrix.append(_A ) return Matrix(_A , self.__width , self.__height ) else: raise Exception('matrix must have the same dimension!' ) def __sub__( self , _A ): if self.__width == other.width() and self.__height == other.height(): __A : Tuple = [] for i in range(self.__height ): __A : str = [ self.__matrix[i][j] - other.component(_A , _A ) for j in range(self.__width ) ] matrix.append(_A ) return Matrix(_A , self.__width , self.__height ) else: raise Exception('matrices must have the same dimension!' ) @overload def __mul__( self , _A ): ... @overload def __mul__( self , _A ): ... def __mul__( self , _A ): if isinstance(_A , _A ): # matrix-vector if len(_A ) == self.__width: __A : List[Any] = zero_vector(self.__height ) for i in range(self.__height ): __A : List[str] = [ self.__matrix[i][j] * other.component(_A ) for j in range(self.__width ) ] ans.change_component(_A , sum(_A ) ) return ans else: raise Exception( 'vector must have the same size as the ' 'number of columns of the matrix!' ) elif isinstance(_A , (int, float) ): # matrix-scalar __A : List[str] = [ [self.__matrix[i][j] * other for j in range(self.__width )] for i in range(self.__height ) ] return Matrix(_A , self.__width , self.__height ) return None def UpperCAmelCase_ ( self ): return self.__height def UpperCAmelCase_ ( self ): return self.__width def UpperCAmelCase_ ( self , _A , _A ): if 0 <= x < self.__height and 0 <= y < self.__width: return self.__matrix[x][y] else: raise Exception('change_component: indices out of bounds' ) def UpperCAmelCase_ ( self , _A , _A , _A ): if 0 <= x < self.__height and 0 <= y < self.__width: __A : int = value else: raise Exception('change_component: indices out of bounds' ) def UpperCAmelCase_ ( self , _A , _A ): if self.__height != self.__width: raise Exception('Matrix is not square' ) __A : List[str] = self.__matrix[:x] + self.__matrix[x + 1 :] for i in range(len(_A ) ): __A : Optional[int] = minor[i][:y] + minor[i][y + 1 :] return Matrix(_A , self.__width - 1 , self.__height - 1 ).determinant() def UpperCAmelCase_ ( self , _A , _A ): if self.__height != self.__width: raise Exception('Matrix is not square' ) if 0 <= x < self.__height and 0 <= y < self.__width: return (-1) ** (x + y) * self.minor(_A , _A ) else: raise Exception('Indices out of bounds' ) def UpperCAmelCase_ ( self ): if self.__height != self.__width: raise Exception('Matrix is not square' ) if self.__height < 1: raise Exception('Matrix has no element' ) elif self.__height == 1: return self.__matrix[0][0] elif self.__height == 2: return ( self.__matrix[0][0] * self.__matrix[1][1] - self.__matrix[0][1] * self.__matrix[1][0] ) else: __A : List[str] = [ self.__matrix[0][y] * self.cofactor(0 , _A ) for y in range(self.__width ) ] return sum(_A ) def _SCREAMING_SNAKE_CASE ( a ) -> Matrix: __A : list[list[float]] = [[0] * n for _ in range(a )] return Matrix(a , a , a ) def _SCREAMING_SNAKE_CASE ( a , a , a , a ) -> Matrix: random.seed(a ) __A : list[list[float]] = [ [random.randint(a , a ) for _ in range(a )] for _ in range(a ) ] return Matrix(a , a , a )
280
1
import copy import tempfile import unittest from huggingface_hub import HfFolder, delete_repo from parameterized import parameterized from requests.exceptions import HTTPError from transformers import AutoConfig, GenerationConfig from transformers.testing_utils import TOKEN, USER, is_staging_test class _A( unittest.TestCase ): """simple docstring""" @parameterized.expand([(None,), ('foo.json',)] ) def UpperCAmelCase_ ( self , _A ): __A : Any = GenerationConfig( do_sample=_A , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(_A , config_name=_A ) __A : int = GenerationConfig.from_pretrained(_A , config_name=_A ) # Checks parameters that were specified self.assertEqual(loaded_config.do_sample , _A ) self.assertEqual(loaded_config.temperature , 0.7 ) self.assertEqual(loaded_config.length_penalty , 1.0 ) self.assertEqual(loaded_config.bad_words_ids , [[1, 2, 3], [4, 5]] ) # Checks parameters that were not specified (defaults) self.assertEqual(loaded_config.top_k , 50 ) self.assertEqual(loaded_config.max_length , 20 ) self.assertEqual(loaded_config.max_time , _A ) def UpperCAmelCase_ ( self ): __A : Dict = AutoConfig.from_pretrained('gpt2' ) __A : str = GenerationConfig.from_model_config(_A ) __A : int = GenerationConfig() # The generation config has loaded a few non-default parameters from the model config self.assertNotEqual(_A , _A ) # One of those parameters is eos_token_id -- check if it matches self.assertNotEqual(generation_config_from_model.eos_token_id , default_generation_config.eos_token_id ) self.assertEqual(generation_config_from_model.eos_token_id , model_config.eos_token_id ) def UpperCAmelCase_ ( self ): __A : Tuple = GenerationConfig() __A : Any = { 'max_new_tokens': 1024, 'foo': 'bar', } __A : List[str] = copy.deepcopy(_A ) __A : Union[str, Any] = generation_config.update(**_A ) # update_kwargs was not modified (no side effects) self.assertEqual(_A , _A ) # update_kwargs was used to update the config on valid attributes self.assertEqual(generation_config.max_new_tokens , 1024 ) # `.update()` returns a dictionary of unused kwargs self.assertEqual(_A , {'foo': 'bar'} ) def UpperCAmelCase_ ( self ): __A : List[Any] = GenerationConfig() __A : Optional[int] = 'bar' with tempfile.TemporaryDirectory('test-generation-config' ) as tmp_dir: generation_config.save_pretrained(_A ) __A : List[Any] = GenerationConfig.from_pretrained(_A ) # update_kwargs was used to update the config on valid attributes self.assertEqual(new_config.foo , 'bar' ) __A : Any = GenerationConfig.from_model_config(_A ) assert not hasattr(_A , 'foo' ) # no new kwargs should be initialized if from config def UpperCAmelCase_ ( self ): __A : str = GenerationConfig() self.assertEqual(default_config.temperature , 1.0 ) self.assertEqual(default_config.do_sample , _A ) self.assertEqual(default_config.num_beams , 1 ) __A : Optional[int] = GenerationConfig( do_sample=_A , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) self.assertEqual(config.temperature , 0.7 ) self.assertEqual(config.do_sample , _A ) self.assertEqual(config.num_beams , 1 ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(_A ) __A : List[Any] = GenerationConfig.from_pretrained(_A , temperature=1.0 ) self.assertEqual(loaded_config.temperature , 1.0 ) self.assertEqual(loaded_config.do_sample , _A ) self.assertEqual(loaded_config.num_beams , 1 ) # default value @is_staging_test class _A( unittest.TestCase ): """simple docstring""" @classmethod def UpperCAmelCase_ ( cls ): __A : Optional[int] = TOKEN HfFolder.save_token(_A ) @classmethod def UpperCAmelCase_ ( cls ): try: delete_repo(token=cls._token , repo_id='test-generation-config' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='valid_org/test-generation-config-org' ) except HTTPError: pass def UpperCAmelCase_ ( self ): __A : Optional[Any] = GenerationConfig( do_sample=_A , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub('test-generation-config' , use_auth_token=self._token ) __A : List[Any] = GenerationConfig.from_pretrained(F"""{USER}/test-generation-config""" ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(_A , getattr(_A , _A ) ) # Reset repo delete_repo(token=self._token , repo_id='test-generation-config' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( _A , repo_id='test-generation-config' , push_to_hub=_A , use_auth_token=self._token ) __A : Optional[Any] = GenerationConfig.from_pretrained(F"""{USER}/test-generation-config""" ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(_A , getattr(_A , _A ) ) def UpperCAmelCase_ ( self ): __A : Union[str, Any] = GenerationConfig( do_sample=_A , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub('valid_org/test-generation-config-org' , use_auth_token=self._token ) __A : str = GenerationConfig.from_pretrained('valid_org/test-generation-config-org' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(_A , getattr(_A , _A ) ) # Reset repo delete_repo(token=self._token , repo_id='valid_org/test-generation-config-org' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( _A , repo_id='valid_org/test-generation-config-org' , push_to_hub=_A , use_auth_token=self._token ) __A : Union[str, Any] = GenerationConfig.from_pretrained('valid_org/test-generation-config-org' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(_A , getattr(_A , _A ) )
280
import unittest from transformers import BertGenerationTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin UpperCAmelCase : List[str] = '''▁''' UpperCAmelCase : Optional[Any] = get_tests_dir('''fixtures/test_sentencepiece.model''') @require_sentencepiece class _A( snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Optional[int] = BertGenerationTokenizer UpperCamelCase : str = False UpperCamelCase : Tuple = True def UpperCAmelCase_ ( self ): super().setUp() __A : Tuple = BertGenerationTokenizer(_A , keep_accents=_A ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCAmelCase_ ( self ): __A : str = '<s>' __A : str = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_A ) , _A ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_A ) , _A ) def UpperCAmelCase_ ( self ): __A : int = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<unk>' ) self.assertEqual(vocab_keys[1] , '<s>' ) self.assertEqual(vocab_keys[-1] , '<pad>' ) self.assertEqual(len(_A ) , 1002 ) def UpperCAmelCase_ ( self ): self.assertEqual(self.get_tokenizer().vocab_size , 1000 ) def UpperCAmelCase_ ( self ): __A : str = BertGenerationTokenizer(_A , keep_accents=_A ) __A : Dict = tokenizer.tokenize('This is a test' ) self.assertListEqual(_A , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(_A ) , [285, 46, 10, 170, 382] , ) __A : int = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( _A , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.', ] , ) __A : Dict = tokenizer.convert_tokens_to_ids(_A ) self.assertListEqual( _A , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] , ) __A : Optional[int] = tokenizer.convert_ids_to_tokens(_A ) self.assertListEqual( _A , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.', ] , ) @cached_property def UpperCAmelCase_ ( self ): return BertGenerationTokenizer.from_pretrained('google/bert_for_seq_generation_L-24_bbc_encoder' ) @slow def UpperCAmelCase_ ( self ): __A : List[Any] = 'Hello World!' __A : Optional[Any] = [18536, 2260, 101] self.assertListEqual(_A , self.big_tokenizer.encode(_A ) ) @slow def UpperCAmelCase_ ( self ): __A : Dict = ( 'This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will' ' add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth' ) __A : int = [ 871, 419, 358, 946, 991, 2521, 452, 358, 1357, 387, 7751, 3536, 112, 985, 456, 126, 865, 938, 5400, 5734, 458, 1368, 467, 786, 2462, 5246, 1159, 633, 865, 4519, 457, 582, 852, 2557, 427, 916, 508, 405, 34324, 497, 391, 408, 11342, 1244, 385, 100, 938, 985, 456, 574, 362, 12597, 3200, 3129, 1172, ] self.assertListEqual(_A , self.big_tokenizer.encode(_A ) ) @require_torch @slow def UpperCAmelCase_ ( self ): import torch from transformers import BertGenerationConfig, BertGenerationEncoder # Build sequence __A : Tuple = list(self.big_tokenizer.get_vocab().keys() )[:10] __A : List[Any] = ' '.join(_A ) __A : Union[str, Any] = self.big_tokenizer.encode_plus(_A , return_tensors='pt' , return_token_type_ids=_A ) __A : Optional[Any] = self.big_tokenizer.batch_encode_plus( [sequence + ' ' + sequence] , return_tensors='pt' , return_token_type_ids=_A ) __A : int = BertGenerationConfig() __A : List[str] = BertGenerationEncoder(_A ) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**_A ) model(**_A ) @slow def UpperCAmelCase_ ( self ): # fmt: off __A : str = {'input_ids': [[39286, 458, 36335, 2001, 456, 13073, 13266, 455, 113, 7746, 1741, 11157, 391, 13073, 13266, 455, 113, 3967, 35412, 113, 4936, 109, 3870, 2377, 113, 30084, 45720, 458, 134, 17496, 112, 503, 11672, 113, 118, 112, 5665, 13347, 38687, 112, 1496, 31389, 112, 3268, 47264, 134, 962, 112, 16377, 8035, 23130, 430, 12169, 15518, 28592, 458, 146, 41697, 109, 391, 12169, 15518, 16689, 458, 146, 41358, 109, 452, 726, 4034, 111, 763, 35412, 5082, 388, 1903, 111, 9051, 391, 2870, 48918, 1900, 1123, 550, 998, 112, 9586, 15985, 455, 391, 410, 22955, 37636, 114], [448, 17496, 419, 3663, 385, 763, 113, 27533, 2870, 3283, 13043, 1639, 24713, 523, 656, 24013, 18550, 2521, 517, 27014, 21244, 420, 1212, 1465, 391, 927, 4833, 388, 578, 11786, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [484, 2169, 7687, 21932, 18146, 726, 363, 17032, 3391, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=_A , model_name='google/bert_for_seq_generation_L-24_bbc_encoder' , revision='c817d1fd1be2ffa69431227a1fe320544943d4db' , )
280
1
import argparse import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## UpperCAmelCase : Union[str, Any] = 16 UpperCAmelCase : Optional[Any] = 32 def _SCREAMING_SNAKE_CASE ( a , a = 16 ) -> Tuple: __A : int = AutoTokenizer.from_pretrained('bert-base-cased' ) __A : Optional[Any] = load_dataset('glue' , 'mrpc' ) def tokenize_function(a ): # max_length=None => use the model max length (it's actually the default) __A : Tuple = 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(): __A : str = 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 __A : str = 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. __A : Optional[Any] = 1_28 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": __A : List[str] = 16 elif accelerator.mixed_precision != "no": __A : List[Any] = 8 else: __A : List[Any] = None return tokenizer.pad( a , padding='longest' , max_length=a , pad_to_multiple_of=a , return_tensors='pt' , ) # Instantiate dataloaders. __A : Optional[int] = DataLoader( tokenized_datasets['train'] , shuffle=a , collate_fn=a , batch_size=a , drop_last=a ) __A : Optional[Any] = DataLoader( tokenized_datasets['validation'] , shuffle=a , collate_fn=a , batch_size=a , drop_last=(accelerator.mixed_precision == 'fp8') , ) return train_dataloader, eval_dataloader def _SCREAMING_SNAKE_CASE ( a , a ) -> int: # Initialize accelerator __A : int = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs __A : Union[str, Any] = config['lr'] __A : Optional[Any] = int(config['num_epochs'] ) __A : Union[str, Any] = int(config['seed'] ) __A : List[Any] = int(config['batch_size'] ) __A : int = evaluate.load('glue' , 'mrpc' ) # If the batch size is too big we use gradient accumulation __A : List[Any] = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: __A : List[Any] = batch_size // MAX_GPU_BATCH_SIZE __A : int = MAX_GPU_BATCH_SIZE set_seed(a ) __A , __A : List[Any] = get_dataloaders(a , a ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) __A : int = 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). __A : Dict = model.to(accelerator.device ) # Instantiate optimizer __A : Union[str, Any] = AdamW(params=model.parameters() , lr=a ) # Instantiate scheduler __A : Tuple = get_linear_schedule_with_warmup( optimizer=a , num_warmup_steps=1_00 , num_training_steps=(len(a ) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. __A , __A , __A , __A , __A : Optional[int] = 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 ) __A : Tuple = model(**a ) __A : Union[str, Any] = outputs.loss __A : str = loss / gradient_accumulation_steps accelerator.backward(a ) if step % gradient_accumulation_steps == 0: 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(): __A : Optional[int] = model(**a ) __A : int = outputs.logits.argmax(dim=-1 ) __A , __A : List[Any] = accelerator.gather_for_metrics((predictions, batch['labels']) ) metric.add_batch( predictions=a , references=a , ) __A : Optional[Any] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F"""epoch {epoch}:""" , a ) def _SCREAMING_SNAKE_CASE ( ) -> Dict: __A : Union[str, Any] = 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.' ) __A : Tuple = parser.parse_args() __A : int = {'lr': 2e-5, 'num_epochs': 3, 'seed': 42, 'batch_size': 16} training_function(a , a ) if __name__ == "__main__": main()
280
import hashlib import unittest from typing import Dict import numpy as np from transformers import ( MODEL_FOR_MASK_GENERATION_MAPPING, TF_MODEL_FOR_MASK_GENERATION_MAPPING, is_vision_available, pipeline, ) from transformers.pipelines import MaskGenerationPipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) if is_vision_available(): from PIL import Image else: class _A: """simple docstring""" @staticmethod def UpperCAmelCase_ ( *_A , **_A ): pass def _SCREAMING_SNAKE_CASE ( a ) -> str: __A : str = hashlib.mda(image.tobytes() ) return m.hexdigest()[:10] def _SCREAMING_SNAKE_CASE ( a ) -> Dict: __A : Dict = np.array(a ) __A : List[Any] = npimg.shape return {"hash": hashimage(a ), "shape": shape} @is_pipeline_test @require_vision @require_torch class _A( unittest.TestCase ): """simple docstring""" UpperCamelCase : str = dict( (list(MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if MODEL_FOR_MASK_GENERATION_MAPPING else []) ) UpperCamelCase : int = dict( (list(TF_MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if TF_MODEL_FOR_MASK_GENERATION_MAPPING else []) ) def UpperCAmelCase_ ( self , _A , _A , _A ): __A : Dict = MaskGenerationPipeline(model=_A , image_processor=_A ) return image_segmenter, [ "./tests/fixtures/tests_samples/COCO/000000039769.png", "./tests/fixtures/tests_samples/COCO/000000039769.png", ] def UpperCAmelCase_ ( self , _A , _A ): pass @require_tf @unittest.skip('Image segmentation not implemented in TF' ) def UpperCAmelCase_ ( self ): pass @slow @require_torch def UpperCAmelCase_ ( self ): __A : Union[str, Any] = pipeline('mask-generation' , model='facebook/sam-vit-huge' ) __A : List[str] = image_segmenter('http://images.cocodataset.org/val2017/000000039769.jpg' , points_per_batch=256 ) # Shortening by hashing __A : List[Any] = [] for i, o in enumerate(outputs['masks'] ): new_outupt += [{"mask": mask_to_test_readable(_A ), "scores": outputs["scores"][i]}] # fmt: off self.assertEqual( nested_simplify(_A , decimals=4 ) , [ {'mask': {'hash': '115ad19f5f', 'shape': (480, 640)}, 'scores': 1.0_4_4_4}, {'mask': {'hash': '6affa964c6', 'shape': (480, 640)}, 'scores': 1.0_2_1}, {'mask': {'hash': 'dfe28a0388', 'shape': (480, 640)}, 'scores': 1.0_1_6_7}, {'mask': {'hash': 'c0a5f4a318', 'shape': (480, 640)}, 'scores': 1.0_1_3_2}, {'mask': {'hash': 'fe8065c197', 'shape': (480, 640)}, 'scores': 1.0_0_5_3}, {'mask': {'hash': 'e2d0b7a0b7', 'shape': (480, 640)}, 'scores': 0.9_9_6_7}, {'mask': {'hash': '453c7844bd', 'shape': (480, 640)}, 'scores': 0.9_9_3}, {'mask': {'hash': '3d44f2926d', 'shape': (480, 640)}, 'scores': 0.9_9_0_9}, {'mask': {'hash': '64033ddc3f', 'shape': (480, 640)}, 'scores': 0.9_8_7_9}, {'mask': {'hash': '801064ff79', 'shape': (480, 640)}, 'scores': 0.9_8_3_4}, {'mask': {'hash': '6172f276ef', 'shape': (480, 640)}, 'scores': 0.9_7_1_6}, {'mask': {'hash': 'b49e60e084', 'shape': (480, 640)}, 'scores': 0.9_6_1_2}, {'mask': {'hash': 'a811e775fd', 'shape': (480, 640)}, 'scores': 0.9_5_9_9}, {'mask': {'hash': 'a6a8ebcf4b', 'shape': (480, 640)}, 'scores': 0.9_5_5_2}, {'mask': {'hash': '9d8257e080', 'shape': (480, 640)}, 'scores': 0.9_5_3_2}, {'mask': {'hash': '32de6454a8', 'shape': (480, 640)}, 'scores': 0.9_5_1_6}, {'mask': {'hash': 'af3d4af2c8', 'shape': (480, 640)}, 'scores': 0.9_4_9_9}, {'mask': {'hash': '3c6db475fb', 'shape': (480, 640)}, 'scores': 0.9_4_8_3}, {'mask': {'hash': 'c290813fb9', 'shape': (480, 640)}, 'scores': 0.9_4_6_4}, {'mask': {'hash': 'b6f0b8f606', 'shape': (480, 640)}, 'scores': 0.9_4_3}, {'mask': {'hash': '92ce16bfdf', 'shape': (480, 640)}, 'scores': 0.9_4_3}, {'mask': {'hash': 'c749b25868', 'shape': (480, 640)}, 'scores': 0.9_4_0_8}, {'mask': {'hash': 'efb6cab859', 'shape': (480, 640)}, 'scores': 0.9_3_3_5}, {'mask': {'hash': '1ff2eafb30', 'shape': (480, 640)}, 'scores': 0.9_3_2_6}, {'mask': {'hash': '788b798e24', 'shape': (480, 640)}, 'scores': 0.9_2_6_2}, {'mask': {'hash': 'abea804f0e', 'shape': (480, 640)}, 'scores': 0.8_9_9_9}, {'mask': {'hash': '7b9e8ddb73', 'shape': (480, 640)}, 'scores': 0.8_9_8_6}, {'mask': {'hash': 'cd24047c8a', 'shape': (480, 640)}, 'scores': 0.8_9_8_4}, {'mask': {'hash': '6943e6bcbd', 'shape': (480, 640)}, 'scores': 0.8_8_7_3}, {'mask': {'hash': 'b5f47c9191', 'shape': (480, 640)}, 'scores': 0.8_8_7_1} ] , ) # fmt: on @require_torch @slow def UpperCAmelCase_ ( self ): __A : Optional[Any] = 'facebook/sam-vit-huge' __A : List[str] = pipeline('mask-generation' , model=_A ) __A : Tuple = image_segmenter( 'http://images.cocodataset.org/val2017/000000039769.jpg' , pred_iou_thresh=1 , points_per_batch=256 ) # Shortening by hashing __A : List[str] = [] for i, o in enumerate(outputs['masks'] ): new_outupt += [{"mask": mask_to_test_readable(_A ), "scores": outputs["scores"][i]}] self.assertEqual( nested_simplify(_A , decimals=4 ) , [ {'mask': {'hash': '115ad19f5f', 'shape': (480, 640)}, 'scores': 1.0_4_4_4}, {'mask': {'hash': '6affa964c6', 'shape': (480, 640)}, 'scores': 1.0_2_1_0}, {'mask': {'hash': 'dfe28a0388', 'shape': (480, 640)}, 'scores': 1.0_1_6_7}, {'mask': {'hash': 'c0a5f4a318', 'shape': (480, 640)}, 'scores': 1.0_1_3_2}, {'mask': {'hash': 'fe8065c197', 'shape': (480, 640)}, 'scores': 1.0_0_5_3}, ] , )
280
1
import numpy as np from nltk.translate import meteor_score import datasets from datasets.config import importlib_metadata, version UpperCAmelCase : Optional[Any] = version.parse(importlib_metadata.version('''nltk''')) if NLTK_VERSION >= version.Version('''3.6.4'''): from nltk import word_tokenize UpperCAmelCase : List[Any] = '''\ @inproceedings{banarjee2005, title = {{METEOR}: An Automatic Metric for {MT} Evaluation with Improved Correlation with Human Judgments}, author = {Banerjee, Satanjeev and Lavie, Alon}, booktitle = {Proceedings of the {ACL} Workshop on Intrinsic and Extrinsic Evaluation Measures for Machine Translation and/or Summarization}, month = jun, year = {2005}, address = {Ann Arbor, Michigan}, publisher = {Association for Computational Linguistics}, url = {https://www.aclweb.org/anthology/W05-0909}, pages = {65--72}, } ''' UpperCAmelCase : str = '''\ METEOR, an automatic metric for machine translation evaluation that is based on a generalized concept of unigram matching between the machine-produced translation and human-produced reference translations. Unigrams can be matched based on their surface forms, stemmed forms, and meanings; furthermore, METEOR can be easily extended to include more advanced matching strategies. Once all generalized unigram matches between the two strings have been found, METEOR computes a score for this matching using a combination of unigram-precision, unigram-recall, and a measure of fragmentation that is designed to directly capture how well-ordered the matched words in the machine translation are in relation to the reference. METEOR gets an R correlation value of 0.347 with human evaluation on the Arabic data and 0.331 on the Chinese data. This is shown to be an improvement on using simply unigram-precision, unigram-recall and their harmonic F1 combination. ''' UpperCAmelCase : Optional[Any] = ''' Computes METEOR score of translated segments against one or more references. Args: predictions: list of predictions to score. Each prediction should be a string with tokens separated by spaces. references: list of reference for each prediction. Each reference should be a string with tokens separated by spaces. alpha: Parameter for controlling relative weights of precision and recall. default: 0.9 beta: Parameter for controlling shape of penalty as a function of fragmentation. default: 3 gamma: Relative weight assigned to fragmentation penalty. default: 0.5 Returns: \'meteor\': meteor score. Examples: >>> meteor = datasets.load_metric(\'meteor\') >>> predictions = ["It is a guide to action which ensures that the military always obeys the commands of the party"] >>> references = ["It is a guide to action that ensures that the military will forever heed Party commands"] >>> results = meteor.compute(predictions=predictions, references=references) >>> print(round(results["meteor"], 4)) 0.6944 ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _A( datasets.Metric ): """simple docstring""" def UpperCAmelCase_ ( self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('string' , id='sequence' ), 'references': datasets.Value('string' , id='sequence' ), } ) , codebase_urls=['https://github.com/nltk/nltk/blob/develop/nltk/translate/meteor_score.py'] , reference_urls=[ 'https://www.nltk.org/api/nltk.translate.html#module-nltk.translate.meteor_score', 'https://en.wikipedia.org/wiki/METEOR', ] , ) def UpperCAmelCase_ ( self , _A ): import nltk nltk.download('wordnet' ) if NLTK_VERSION >= version.Version('3.6.5' ): nltk.download('punkt' ) if NLTK_VERSION >= version.Version('3.6.6' ): nltk.download('omw-1.4' ) def UpperCAmelCase_ ( self , _A , _A , _A=0.9 , _A=3 , _A=0.5 ): if NLTK_VERSION >= version.Version('3.6.5' ): __A : Tuple = [ meteor_score.single_meteor_score( word_tokenize(_A ) , word_tokenize(_A ) , alpha=_A , beta=_A , gamma=_A ) for ref, pred in zip(_A , _A ) ] else: __A : Dict = [ meteor_score.single_meteor_score(_A , _A , alpha=_A , beta=_A , gamma=_A ) for ref, pred in zip(_A , _A ) ] return {"meteor": np.mean(_A )}
280
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import OwlViTImageProcessor, OwlViTProcessor @require_vision class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): __A : List[Any] = tempfile.mkdtemp() # fmt: off __A : List[str] = ['', 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'lo', 'l</w>', 'w</w>', 'r</w>', 't</w>', 'low</w>', 'er</w>', 'lowest</w>', 'newer</w>', 'wider', '<unk>', '<|startoftext|>', '<|endoftext|>'] # fmt: on __A : Union[str, Any] = dict(zip(_A , range(len(_A ) ) ) ) __A : Optional[int] = ['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>', ''] __A : int = {'unk_token': '<unk>'} __A : Optional[int] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) __A : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(_A ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(_A ) ) __A : List[Any] = { 'do_resize': True, 'size': 20, 'do_center_crop': True, 'crop_size': 18, 'do_normalize': True, 'image_mean': [0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3], 'image_std': [0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1], } __A : Optional[int] = os.path.join(self.tmpdirname , _A ) with open(self.image_processor_file , 'w' , encoding='utf-8' ) as fp: json.dump(_A , _A ) def UpperCAmelCase_ ( self , **_A ): return CLIPTokenizer.from_pretrained(self.tmpdirname , pad_token='!' , **_A ) def UpperCAmelCase_ ( self , **_A ): return CLIPTokenizerFast.from_pretrained(self.tmpdirname , pad_token='!' , **_A ) def UpperCAmelCase_ ( self , **_A ): return OwlViTImageProcessor.from_pretrained(self.tmpdirname , **_A ) def UpperCAmelCase_ ( self ): shutil.rmtree(self.tmpdirname ) def UpperCAmelCase_ ( self ): __A : int = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __A : Optional[int] = [Image.fromarray(np.moveaxis(_A , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCAmelCase_ ( self ): __A : List[Any] = self.get_tokenizer() __A : str = self.get_rust_tokenizer() __A : List[str] = self.get_image_processor() __A : Optional[int] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) processor_slow.save_pretrained(self.tmpdirname ) __A : int = OwlViTProcessor.from_pretrained(self.tmpdirname , use_fast=_A ) __A : Optional[Any] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) processor_fast.save_pretrained(self.tmpdirname ) __A : Optional[Any] = OwlViTProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , _A ) self.assertIsInstance(processor_fast.tokenizer , _A ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , _A ) self.assertIsInstance(processor_fast.image_processor , _A ) def UpperCAmelCase_ ( self ): __A : List[str] = OwlViTProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __A : Optional[int] = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) __A : Optional[int] = self.get_image_processor(do_normalize=_A ) __A : Any = OwlViTProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=_A ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , _A ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _A ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.get_image_processor() __A : Optional[Any] = self.get_tokenizer() __A : Union[str, Any] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Union[str, Any] = self.prepare_image_inputs() __A : int = image_processor(_A , return_tensors='np' ) __A : str = processor(images=_A , return_tensors='np' ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1e-2 ) def UpperCAmelCase_ ( self ): __A : str = self.get_image_processor() __A : str = self.get_tokenizer() __A : Tuple = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : str = 'lower newer' __A : str = processor(text=_A , return_tensors='np' ) __A : List[str] = tokenizer(_A , return_tensors='np' ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key][0].tolist() , encoded_processor[key][0].tolist() ) def UpperCAmelCase_ ( self ): __A : int = self.get_image_processor() __A : Optional[int] = self.get_tokenizer() __A : List[str] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Any = 'lower newer' __A : Optional[Any] = self.prepare_image_inputs() __A : List[Any] = processor(text=_A , images=_A ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Any = 'google/owlvit-base-patch32' __A : int = OwlViTProcessor.from_pretrained(_A ) __A : Dict = ['cat', 'nasa badge'] __A : Optional[Any] = processor(text=_A ) __A : Optional[int] = 16 self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (2, seq_length) ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Tuple = 'google/owlvit-base-patch32' __A : Any = OwlViTProcessor.from_pretrained(_A ) __A : Dict = [['cat', 'nasa badge'], ['person']] __A : Dict = processor(text=_A ) __A : Optional[int] = 16 __A : Any = len(_A ) __A : Union[str, Any] = max([len(_A ) for texts in input_texts] ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (batch_size * num_max_text_queries, seq_length) ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : List[Any] = 'google/owlvit-base-patch32' __A : str = OwlViTProcessor.from_pretrained(_A ) __A : Union[str, Any] = ['cat', 'nasa badge'] __A : Tuple = processor(text=_A ) __A : str = 16 __A : int = inputs['input_ids'] __A : List[Any] = [ [49406, 2368, 49407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [49406, 6841, 11301, 49407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (2, seq_length) ) self.assertListEqual(list(input_ids[0] ) , predicted_ids[0] ) self.assertListEqual(list(input_ids[1] ) , predicted_ids[1] ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.get_image_processor() __A : List[str] = self.get_tokenizer() __A : Optional[Any] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Optional[int] = self.prepare_image_inputs() __A : Optional[int] = self.prepare_image_inputs() __A : Optional[int] = processor(images=_A , query_images=_A ) self.assertListEqual(list(inputs.keys() ) , ['query_pixel_values', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.get_image_processor() __A : Union[str, Any] = self.get_tokenizer() __A : str = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Optional[Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __A : Any = processor.batch_decode(_A ) __A : Tuple = tokenizer.batch_decode(_A ) self.assertListEqual(_A , _A )
280
1
import csv import tweepy # Twitter API credentials UpperCAmelCase : int = '''''' UpperCAmelCase : Any = '''''' UpperCAmelCase : Optional[int] = '''''' UpperCAmelCase : Optional[int] = '''''' def _SCREAMING_SNAKE_CASE ( a ) -> None: # authorize twitter, initialize tweepy __A : List[Any] = tweepy.OAuthHandler(a , a ) auth.set_access_token(a , a ) __A : Any = tweepy.API(a ) # initialize a list to hold all the tweepy Tweets __A : Optional[int] = [] # make initial request for most recent tweets (200 is the maximum allowed count) __A : Any = api.user_timeline(screen_name=a , count=2_00 ) # save most recent tweets alltweets.extend(a ) # save the id of the oldest tweet less one __A : str = alltweets[-1].id - 1 # keep grabbing tweets until there are no tweets left to grab while len(a ) > 0: print(F"""getting tweets before {oldest}""" ) # all subsequent requests use the max_id param to prevent duplicates __A : str = api.user_timeline( screen_name=a , count=2_00 , max_id=a ) # save most recent tweets alltweets.extend(a ) # update the id of the oldest tweet less one __A : Optional[Any] = alltweets[-1].id - 1 print(F"""...{len(a )} tweets downloaded so far""" ) # transform the tweepy tweets into a 2D array that will populate the csv __A : int = [[tweet.id_str, tweet.created_at, tweet.text] for tweet in alltweets] # write the csv with open(F"""new_{screen_name}_tweets.csv""" , 'w' ) as f: __A : List[str] = csv.writer(a ) writer.writerow(['id', 'created_at', 'text'] ) writer.writerows(a ) if __name__ == "__main__": # pass in the username of the account you want to download get_all_tweets('''FirePing32''')
280
import math def _SCREAMING_SNAKE_CASE ( a ) -> list[int]: __A : List[str] = [] __A : Any = 2 __A : Union[str, Any] = int(math.sqrt(a ) ) # Size of every segment __A : Any = [True] * (end + 1) __A : List[Any] = [] while start <= end: if temp[start] is True: in_prime.append(a ) for i in range(start * start , end + 1 , a ): __A : Optional[int] = False start += 1 prime += in_prime __A : Any = end + 1 __A : Any = min(2 * end , a ) while low <= n: __A : List[Any] = [True] * (high - low + 1) for each in in_prime: __A : List[str] = math.floor(low / each ) * each if t < low: t += each for j in range(a , high + 1 , a ): __A : Optional[int] = False for j in range(len(a ) ): if temp[j] is True: prime.append(j + low ) __A : Optional[int] = high + 1 __A : Tuple = min(high + end , a ) return prime print(sieve(10**6))
280
1
from __future__ import annotations from collections import Counter from random import random class _A: """simple docstring""" def __init__( self ): __A : Optional[int] = {} def UpperCAmelCase_ ( self , _A ): __A : List[str] = {} def UpperCAmelCase_ ( self , _A , _A , _A ): if nodea not in self.connections: self.add_node(_A ) if nodea not in self.connections: self.add_node(_A ) __A : Union[str, Any] = probability def UpperCAmelCase_ ( self ): return list(self.connections ) def UpperCAmelCase_ ( self , _A ): __A : Optional[int] = 0 __A : Any = random() for dest in self.connections[node]: current_probability += self.connections[node][dest] if current_probability > random_value: return dest return "" def _SCREAMING_SNAKE_CASE ( a , a , a ) -> dict[str, int]: __A : Union[str, Any] = MarkovChainGraphUndirectedUnweighted() for nodea, nodea, probability in transitions: graph.add_transition_probability(a , a , a ) __A : Optional[int] = Counter(graph.get_nodes() ) __A : List[Any] = start for _ in range(a ): __A : Optional[int] = graph.transition(a ) visited[node] += 1 return visited if __name__ == "__main__": import doctest doctest.testmod()
280
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available UpperCAmelCase : Any = { '''configuration_mvp''': ['''MVP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MvpConfig''', '''MvpOnnxConfig'''], '''tokenization_mvp''': ['''MvpTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : int = ['''MvpTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : str = [ '''MVP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MvpForCausalLM''', '''MvpForConditionalGeneration''', '''MvpForQuestionAnswering''', '''MvpForSequenceClassification''', '''MvpModel''', '''MvpPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_mvp import MVP_PRETRAINED_CONFIG_ARCHIVE_MAP, MvpConfig, MvpOnnxConfig from .tokenization_mvp import MvpTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mvp_fast import MvpTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mvp import ( MVP_PRETRAINED_MODEL_ARCHIVE_LIST, MvpForCausalLM, MvpForConditionalGeneration, MvpForQuestionAnswering, MvpForSequenceClassification, MvpModel, MvpPreTrainedModel, ) else: import sys UpperCAmelCase : List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
280
1
from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, apply_forward_hook from .modeling_utils import ModelMixin from .vae import Decoder, DecoderOutput, Encoder, VectorQuantizer @dataclass class _A( snake_case__ ): """simple docstring""" UpperCamelCase : torch.FloatTensor class _A( snake_case__ , snake_case__ ): """simple docstring""" @register_to_config def __init__( self , _A = 3 , _A = 3 , _A = ("DownEncoderBlock2D",) , _A = ("UpDecoderBlock2D",) , _A = (64,) , _A = 1 , _A = "silu" , _A = 3 , _A = 32 , _A = 256 , _A = 32 , _A = None , _A = 0.1_8_2_1_5 , _A = "group" , ): super().__init__() # pass init params to Encoder __A : Optional[Any] = Encoder( in_channels=_A , out_channels=_A , down_block_types=_A , block_out_channels=_A , layers_per_block=_A , act_fn=_A , norm_num_groups=_A , double_z=_A , ) __A : List[Any] = vq_embed_dim if vq_embed_dim is not None else latent_channels __A : Union[str, Any] = nn.Convad(_A , _A , 1 ) __A : Optional[Any] = VectorQuantizer(_A , _A , beta=0.2_5 , remap=_A , sane_index_shape=_A ) __A : int = nn.Convad(_A , _A , 1 ) # pass init params to Decoder __A : Union[str, Any] = Decoder( in_channels=_A , out_channels=_A , up_block_types=_A , block_out_channels=_A , layers_per_block=_A , act_fn=_A , norm_num_groups=_A , norm_type=_A , ) @apply_forward_hook def UpperCAmelCase_ ( self , _A , _A = True ): __A : List[str] = self.encoder(_A ) __A : Tuple = self.quant_conv(_A ) if not return_dict: return (h,) return VQEncoderOutput(latents=_A ) @apply_forward_hook def UpperCAmelCase_ ( self , _A , _A = False , _A = True ): # also go through quantization layer if not force_not_quantize: __A , __A , __A : Dict = self.quantize(_A ) else: __A : List[str] = h __A : int = self.post_quant_conv(_A ) __A : Optional[Any] = self.decoder(_A , quant if self.config.norm_type == 'spatial' else None ) if not return_dict: return (dec,) return DecoderOutput(sample=_A ) def UpperCAmelCase_ ( self , _A , _A = True ): __A : Tuple = sample __A : List[str] = self.encode(_A ).latents __A : Tuple = self.decode(_A ).sample if not return_dict: return (dec,) return DecoderOutput(sample=_A )
280
def _SCREAMING_SNAKE_CASE ( a ) -> Tuple: __A , __A : Optional[Any] = [], [] while len(a ) > 1: __A , __A : Any = min(a ), max(a ) start.append(a ) end.append(a ) collection.remove(a ) collection.remove(a ) end.reverse() return start + collection + end if __name__ == "__main__": UpperCAmelCase : int = input('''Enter numbers separated by a comma:\n''').strip() UpperCAmelCase : Dict = [int(item) for item in user_input.split(''',''')] print(*merge_sort(unsorted), sep=''',''')
280
1
from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL from ...utils import BaseOutput, OptionalDependencyNotAvailable, is_torch_available, is_transformers_available from .timesteps import ( fastaa_timesteps, smartaa_timesteps, smartaa_timesteps, smartaaa_timesteps, smartaaa_timesteps, superaa_timesteps, superaa_timesteps, superaaa_timesteps, ) @dataclass class _A( snake_case__ ): """simple docstring""" UpperCamelCase : Union[List[PIL.Image.Image], np.ndarray] UpperCamelCase : Optional[List[bool]] UpperCamelCase : Optional[List[bool]] 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 .pipeline_if import IFPipeline from .pipeline_if_imgaimg import IFImgaImgPipeline from .pipeline_if_imgaimg_superresolution import IFImgaImgSuperResolutionPipeline from .pipeline_if_inpainting import IFInpaintingPipeline from .pipeline_if_inpainting_superresolution import IFInpaintingSuperResolutionPipeline from .pipeline_if_superresolution import IFSuperResolutionPipeline from .safety_checker import IFSafetyChecker from .watermark import IFWatermarker
280
def _SCREAMING_SNAKE_CASE ( a , a = 0 ) -> list: __A : int = length or len(a ) __A : str = False for i in range(length - 1 ): if list_data[i] > list_data[i + 1]: __A , __A : Optional[int] = list_data[i + 1], list_data[i] __A : Union[str, Any] = True return list_data if not swapped else bubble_sort(a , length - 1 ) if __name__ == "__main__": import doctest doctest.testmod()
280
1
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase : Any = logging.get_logger(__name__) UpperCAmelCase : str = { '''bigcode/gpt_bigcode-santacoder''': '''https://huggingface.co/bigcode/gpt_bigcode-santacoder/resolve/main/config.json''', } class _A( snake_case__ ): """simple docstring""" UpperCamelCase : Tuple = '''gpt_bigcode''' UpperCamelCase : str = ['''past_key_values'''] UpperCamelCase : List[str] = { '''hidden_size''': '''n_embd''', '''max_position_embeddings''': '''n_positions''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self , _A=50257 , _A=1024 , _A=768 , _A=12 , _A=12 , _A=None , _A="gelu_pytorch_tanh" , _A=0.1 , _A=0.1 , _A=0.1 , _A=1e-5 , _A=0.0_2 , _A=True , _A=True , _A=50256 , _A=50256 , _A=True , _A=True , _A=True , **_A , ): __A : str = vocab_size __A : Optional[Any] = n_positions __A : Optional[int] = n_embd __A : Union[str, Any] = n_layer __A : Union[str, Any] = n_head __A : Dict = n_inner __A : Tuple = activation_function __A : List[Any] = resid_pdrop __A : Optional[int] = embd_pdrop __A : Optional[int] = attn_pdrop __A : List[Any] = layer_norm_epsilon __A : int = initializer_range __A : int = scale_attn_weights __A : int = use_cache __A : int = attention_softmax_in_fpaa __A : Union[str, Any] = scale_attention_softmax_in_fpaa __A : List[str] = multi_query __A : Union[str, Any] = bos_token_id __A : str = eos_token_id super().__init__(bos_token_id=_A , eos_token_id=_A , **_A )
280
from __future__ import annotations def _SCREAMING_SNAKE_CASE ( a ) -> int: if not nums: return 0 __A : Optional[int] = nums[0] __A : str = 0 for num in nums[1:]: __A , __A : Tuple = ( max_excluding + num, max(a , a ), ) return max(a , a ) if __name__ == "__main__": import doctest doctest.testmod()
280
1
from ..utils import DummyObject, requires_backends class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : Optional[int] = ['''torch''', '''scipy'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch', 'scipy'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch', 'scipy'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch', 'scipy'] )
280
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available UpperCAmelCase : Optional[int] = { '''configuration_xlm''': ['''XLM_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XLMConfig''', '''XLMOnnxConfig'''], '''tokenization_xlm''': ['''XLMTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Union[str, Any] = [ '''XLM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XLMForMultipleChoice''', '''XLMForQuestionAnswering''', '''XLMForQuestionAnsweringSimple''', '''XLMForSequenceClassification''', '''XLMForTokenClassification''', '''XLMModel''', '''XLMPreTrainedModel''', '''XLMWithLMHeadModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Optional[Any] = [ '''TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFXLMForMultipleChoice''', '''TFXLMForQuestionAnsweringSimple''', '''TFXLMForSequenceClassification''', '''TFXLMForTokenClassification''', '''TFXLMMainLayer''', '''TFXLMModel''', '''TFXLMPreTrainedModel''', '''TFXLMWithLMHeadModel''', ] if TYPE_CHECKING: from .configuration_xlm import XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMConfig, XLMOnnxConfig from .tokenization_xlm import XLMTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm import ( XLM_PRETRAINED_MODEL_ARCHIVE_LIST, XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMPreTrainedModel, XLMWithLMHeadModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlm import ( TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLMForMultipleChoice, TFXLMForQuestionAnsweringSimple, TFXLMForSequenceClassification, TFXLMForTokenClassification, TFXLMMainLayer, TFXLMModel, TFXLMPreTrainedModel, TFXLMWithLMHeadModel, ) else: import sys UpperCAmelCase : str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
280
1
import pandas as pd from matplotlib import pyplot as plt from sklearn.linear_model import LinearRegression # Splitting the dataset into the Training set and Test set from sklearn.model_selection import train_test_split # Fitting Polynomial Regression to the dataset from sklearn.preprocessing import PolynomialFeatures # Importing the dataset UpperCAmelCase : Tuple = pd.read_csv( '''https://s3.us-west-2.amazonaws.com/public.gamelab.fun/dataset/''' '''position_salaries.csv''' ) UpperCAmelCase : List[Any] = dataset.iloc[:, 1:2].values UpperCAmelCase : List[Any] = dataset.iloc[:, 2].values UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase : Union[str, Any] = train_test_split(X, y, test_size=0.2, random_state=0) UpperCAmelCase : List[Any] = PolynomialFeatures(degree=4) UpperCAmelCase : List[str] = poly_reg.fit_transform(X) UpperCAmelCase : List[str] = LinearRegression() pol_reg.fit(X_poly, y) def _SCREAMING_SNAKE_CASE ( ) -> Tuple: plt.scatter(a , a , color='red' ) plt.plot(a , pol_reg.predict(poly_reg.fit_transform(a ) ) , color='blue' ) plt.title('Truth or Bluff (Linear Regression)' ) plt.xlabel('Position level' ) plt.ylabel('Salary' ) plt.show() if __name__ == "__main__": viz_polymonial() # Predicting a new result with Polymonial Regression pol_reg.predict(poly_reg.fit_transform([[5.5]])) # output should be 132148.43750003
280
def _SCREAMING_SNAKE_CASE ( a ) -> str: if number > 0: raise ValueError('input must be a negative integer' ) __A : Optional[int] = len(bin(a )[3:] ) __A : Dict = bin(abs(a ) - (1 << binary_number_length) )[3:] __A : int = ( ( '1' + '0' * (binary_number_length - len(a )) + twos_complement_number ) if number < 0 else '0' ) return "0b" + twos_complement_number if __name__ == "__main__": import doctest doctest.testmod()
280
1
import shutil import tempfile import unittest from transformers import ClapFeatureExtractor, ClapProcessor, RobertaTokenizer, RobertaTokenizerFast from transformers.testing_utils import require_sentencepiece, require_torchaudio from .test_feature_extraction_clap import floats_list @require_torchaudio @require_sentencepiece class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): __A : str = 'laion/clap-htsat-unfused' __A : Dict = tempfile.mkdtemp() def UpperCAmelCase_ ( self , **_A ): return RobertaTokenizer.from_pretrained(self.checkpoint , **_A ) def UpperCAmelCase_ ( self , **_A ): return ClapFeatureExtractor.from_pretrained(self.checkpoint , **_A ) def UpperCAmelCase_ ( self ): shutil.rmtree(self.tmpdirname ) def UpperCAmelCase_ ( self ): __A : Tuple = self.get_tokenizer() __A : Any = self.get_feature_extractor() __A : Union[str, Any] = ClapProcessor(tokenizer=_A , feature_extractor=_A ) processor.save_pretrained(self.tmpdirname ) __A : Any = ClapProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , _A ) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor.to_json_string() ) self.assertIsInstance(processor.feature_extractor , _A ) def UpperCAmelCase_ ( self ): __A : str = ClapProcessor(tokenizer=self.get_tokenizer() , feature_extractor=self.get_feature_extractor() ) processor.save_pretrained(self.tmpdirname ) __A : Optional[Any] = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) __A : List[Any] = self.get_feature_extractor(do_normalize=_A , padding_value=1.0 ) __A : Any = ClapProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=_A , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , _A ) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.feature_extractor , _A ) def UpperCAmelCase_ ( self ): __A : Tuple = self.get_feature_extractor() __A : Optional[Any] = self.get_tokenizer() __A : Optional[int] = ClapProcessor(tokenizer=_A , feature_extractor=_A ) __A : int = floats_list((3, 1000) ) __A : List[Any] = feature_extractor(_A , return_tensors='np' ) __A : List[str] = processor(audios=_A , 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 UpperCAmelCase_ ( self ): __A : Any = self.get_feature_extractor() __A : str = self.get_tokenizer() __A : Dict = ClapProcessor(tokenizer=_A , feature_extractor=_A ) __A : Optional[Any] = 'This is a test string' __A : Any = processor(text=_A ) __A : Optional[int] = tokenizer(_A ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def UpperCAmelCase_ ( self ): __A : List[Any] = self.get_feature_extractor() __A : Union[str, Any] = self.get_tokenizer() __A : str = ClapProcessor(tokenizer=_A , feature_extractor=_A ) __A : Optional[Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __A : Dict = processor.batch_decode(_A ) __A : List[Any] = tokenizer.batch_decode(_A ) self.assertListEqual(_A , _A ) def UpperCAmelCase_ ( self ): __A : List[str] = self.get_feature_extractor() __A : Any = self.get_tokenizer() __A : Any = ClapProcessor(tokenizer=_A , feature_extractor=_A ) self.assertListEqual( processor.model_input_names[2:] , feature_extractor.model_input_names , msg='`processor` and `feature_extractor` model input names do not match' , )
280
import warnings from pathlib import Path from typing import List, Tuple, Union import fire from torch import nn from transformers import AutoModelForSeqaSeqLM, AutoTokenizer, PreTrainedModel from transformers.utils import logging UpperCAmelCase : Any = logging.get_logger(__name__) def _SCREAMING_SNAKE_CASE ( a , a , a ) -> None: __A : int = nn.ModuleList([src_layers[i] for i in layers_to_copy] ) assert len(a ) == len(a ), F"""{len(a )} != {len(a )}""" dest_layers.load_state_dict(layers_to_copy.state_dict() ) UpperCAmelCase : List[Any] = { # maps num layers in teacher -> num_layers in student -> which teacher layers to copy. # 12: bart, 16: pegasus, 6: marian/Helsinki-NLP 12: { 1: [0], # This says that if the teacher has 12 layers and the student has 1, copy layer 0 of the teacher 2: [0, 6], 3: [0, 6, 11], 4: [0, 4, 8, 11], 6: [0, 2, 4, 7, 9, 11], 9: [0, 1, 2, 4, 5, 7, 9, 10, 11], 12: list(range(12)), }, 16: { # maps num layers in student -> which teacher layers to copy 1: [0], 2: [0, 15], 3: [0, 8, 15], 4: [0, 5, 10, 15], 6: [0, 3, 6, 9, 12, 15], 8: [0, 2, 4, 6, 8, 10, 12, 15], 9: [0, 1, 3, 5, 7, 9, 11, 13, 15], 12: [0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 15], 16: list(range(16)), }, 6: {1: [0], 2: [0, 5], 3: [0, 2, 5], 4: [0, 1, 3, 5], 6: list(range(6))}, } UpperCAmelCase : Optional[int] = { # maps num layers in student -> which teacher layers to copy. 6: {1: [5], 2: [3, 5], 3: [1, 4, 5], 4: [1, 2, 4, 5]}, 12: {1: [11], 2: [5, 11], 3: [3, 7, 11], 6: [1, 3, 5, 8, 10, 11]}, 16: {1: [15], 4: [4, 9, 12, 15], 8: [1, 3, 5, 7, 9, 11, 13, 15]}, } def _SCREAMING_SNAKE_CASE ( a , a ) -> Dict: try: __A : int = LAYERS_TO_COPY[n_teacher][n_student] return val except KeyError: if n_student != n_teacher: warnings.warn( F"""no hardcoded layers to copy for teacher {n_teacher} -> student {n_student}, defaulting to first""" F""" {n_student}""" ) return list(range(a ) ) def _SCREAMING_SNAKE_CASE ( a , a ) -> List[int]: if n_student > n_teacher: raise ValueError(F"""Cannot perform intermediate supervision for student {n_student} > teacher {n_teacher}""" ) elif n_teacher == n_student: return list(range(a ) ) elif n_student == 1: return [n_teacher - 1] else: return LAYERS_TO_SUPERVISE[n_teacher][n_student] def _SCREAMING_SNAKE_CASE ( a , a = "student" , a = None , a = None , a=False , a=None , a=None , **a , ) -> Tuple[PreTrainedModel, List[int], List[int]]: __A : List[str] = 'encoder_layers and decoder_layers cannot be both None-- you would just have an identical teacher.' assert (e is not None) or (d is not None), _msg if isinstance(a , a ): AutoTokenizer.from_pretrained(a ).save_pretrained(a ) # purely for convenience __A : Optional[int] = AutoModelForSeqaSeqLM.from_pretrained(a ).eval() else: assert isinstance(a , a ), F"""teacher must be a model or string got type {type(a )}""" __A : int = teacher.config.to_diff_dict() try: __A , __A : List[Any] = teacher.config.encoder_layers, teacher.config.decoder_layers if e is None: __A : str = teacher_e if d is None: __A : List[Any] = teacher_d init_kwargs.update({'encoder_layers': e, 'decoder_layers': d} ) except AttributeError: # T5 if hasattr(teacher.config , 'num_encoder_layers' ): __A , __A : List[Any] = teacher.config.num_encoder_layers, teacher.config.num_decoder_layers else: __A , __A : Optional[int] = teacher.config.num_layers, teacher.config.num_decoder_layers if e is None: __A : int = teacher_e if d is None: __A : Optional[Any] = teacher_d if hasattr(teacher.config , 'num_encoder_layers' ): init_kwargs.update({'num_encoder_layers': e, 'num_decoder_layers': d} ) else: init_kwargs.update({'num_layers': e, 'num_decoder_layers': d} ) # Kwargs to instantiate student: teacher kwargs with updated layer numbers + **extra_config_kwargs init_kwargs.update(a ) # Copy weights __A : Dict = teacher.config_class(**a ) __A : int = AutoModelForSeqaSeqLM.from_config(a ) # Start by copying the full teacher state dict this will copy the first N teacher layers to the student. __A : Any = student.load_state_dict(teacher.state_dict() , strict=a ) assert info.missing_keys == [], info.missing_keys # every student key should have a teacher keys. if copy_first_teacher_layers: # Our copying is done. We just log and save __A , __A : Optional[int] = list(range(a ) ), list(range(a ) ) logger.info( F"""Copied encoder layers {e_layers_to_copy} and decoder layers {d_layers_to_copy}. Saving them to""" F""" {save_path}""" ) student.save_pretrained(a ) return student, e_layers_to_copy, d_layers_to_copy # Decide which layers of the teacher to copy. Not exactly alternating -- we try to keep first and last layer. if e_layers_to_copy is None: __A : List[int] = pick_layers_to_copy(a , a ) if d_layers_to_copy is None: __A : List[int] = pick_layers_to_copy(a , a ) try: if hasattr( a , 'prophetnet' ): # For ProphetNet, student.model.encoder.layers is called student.prophetnet.encoder.layers copy_layers(teacher.prophetnet.encoder.layers , student.prophetnet.encoder.layers , a ) copy_layers(teacher.prophetnet.decoder.layers , student.prophetnet.decoder.layers , a ) else: copy_layers(teacher.model.encoder.layers , student.model.encoder.layers , a ) copy_layers(teacher.model.decoder.layers , student.model.decoder.layers , a ) except AttributeError: # For t5, student.model.encoder.layers is called student.encoder.block copy_layers(teacher.encoder.block , student.encoder.block , a ) copy_layers(teacher.decoder.block , student.decoder.block , a ) logger.info( F"""Copied encoder layers {e_layers_to_copy} and decoder layers {d_layers_to_copy}. Saving them to {save_path}""" ) __A : Optional[int] = { 'teacher_type': teacher.config.model_type, 'copied_encoder_layers': e_layers_to_copy, 'copied_decoder_layers': d_layers_to_copy, } student.save_pretrained(a ) # Save information about copying for easier reproducibility return student, e_layers_to_copy, d_layers_to_copy if __name__ == "__main__": fire.Fire(create_student_by_copying_alternating_layers)
280
1
import os import warnings from typing import List, Optional from ...tokenization_utils_base import BatchEncoding from ...utils import logging from .configuration_rag import RagConfig UpperCAmelCase : Any = logging.get_logger(__name__) class _A: """simple docstring""" def __init__( self , _A , _A ): __A : Optional[int] = question_encoder __A : Dict = generator __A : Optional[Any] = self.question_encoder def UpperCAmelCase_ ( self , _A ): if os.path.isfile(_A ): raise ValueError(F"""Provided path ({save_directory}) should be a directory, not a file""" ) os.makedirs(_A , exist_ok=_A ) __A : str = os.path.join(_A , 'question_encoder_tokenizer' ) __A : List[str] = os.path.join(_A , 'generator_tokenizer' ) self.question_encoder.save_pretrained(_A ) self.generator.save_pretrained(_A ) @classmethod def UpperCAmelCase_ ( cls , _A , **_A ): # dynamically import AutoTokenizer from ..auto.tokenization_auto import AutoTokenizer __A : Optional[int] = kwargs.pop('config' , _A ) if config is None: __A : int = RagConfig.from_pretrained(_A ) __A : str = AutoTokenizer.from_pretrained( _A , config=config.question_encoder , subfolder='question_encoder_tokenizer' ) __A : Optional[Any] = AutoTokenizer.from_pretrained( _A , config=config.generator , subfolder='generator_tokenizer' ) return cls(question_encoder=_A , generator=_A ) def __call__( self , *_A , **_A ): return self.current_tokenizer(*_A , **_A ) def UpperCAmelCase_ ( self , *_A , **_A ): return self.generator.batch_decode(*_A , **_A ) def UpperCAmelCase_ ( self , *_A , **_A ): return self.generator.decode(*_A , **_A ) def UpperCAmelCase_ ( self ): __A : Tuple = self.question_encoder def UpperCAmelCase_ ( self ): __A : str = self.generator def UpperCAmelCase_ ( self , _A , _A = None , _A = None , _A = None , _A = "longest" , _A = None , _A = True , **_A , ): warnings.warn( '`prepare_seq2seq_batch` is deprecated and will be removed in version 5 of 🤗 Transformers. Use the ' 'regular `__call__` method to prepare your inputs and the tokenizer under the `with_target_tokenizer` ' 'context manager to prepare your targets. See the documentation of your specific tokenizer for more ' 'details' , _A , ) if max_length is None: __A : str = self.current_tokenizer.model_max_length __A : List[str] = self( _A , add_special_tokens=_A , return_tensors=_A , max_length=_A , padding=_A , truncation=_A , **_A , ) if tgt_texts is None: return model_inputs # Process tgt_texts if max_target_length is None: __A : Optional[int] = self.current_tokenizer.model_max_length __A : Any = self( text_target=_A , add_special_tokens=_A , return_tensors=_A , padding=_A , max_length=_A , truncation=_A , **_A , ) __A : Union[str, Any] = labels['input_ids'] return model_inputs
280
def _SCREAMING_SNAKE_CASE ( a , a ) -> list[int]: __A : Optional[int] = int(a ) # Initialize Result __A : Optional[int] = [] # Traverse through all denomination for denomination in reversed(a ): # Find denominations while int(a ) >= int(a ): total_value -= int(a ) answer.append(a ) # Append the "answers" array return answer # Driver Code if __name__ == "__main__": UpperCAmelCase : List[str] = [] UpperCAmelCase : Optional[int] = '''0''' if ( input('''Do you want to enter your denominations ? (yY/n): ''').strip().lower() == "y" ): UpperCAmelCase : List[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 : Optional[int] = [1, 2, 5, 10, 20, 50, 1_00, 5_00, 20_00] UpperCAmelCase : Tuple = 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 : Optional[int] = find_minimum_change(denominations, value) # Print result for i in range(len(answer)): print(answer[i], end=''' ''')
280
1
import enum import shutil import sys UpperCAmelCase , UpperCAmelCase : Tuple = shutil.get_terminal_size() UpperCAmelCase : Optional[Any] = {'''UP''': '''A''', '''DOWN''': '''B''', '''RIGHT''': '''C''', '''LEFT''': '''D'''} class _A( enum.Enum ): """simple docstring""" UpperCamelCase : Dict = 0 UpperCamelCase : int = 1 def _SCREAMING_SNAKE_CASE ( a , a="" ) -> List[str]: sys.stdout.write(str(a ) + end ) sys.stdout.flush() def _SCREAMING_SNAKE_CASE ( a , a , a="" ) -> Tuple: forceWrite(F"""\u001b[{color}m{content}\u001b[0m""" , a ) def _SCREAMING_SNAKE_CASE ( ) -> Optional[int]: forceWrite('\r' ) def _SCREAMING_SNAKE_CASE ( a , a ) -> str: forceWrite(F"""\033[{num_lines}{CURSOR_TO_CHAR[direction.upper()]}""" ) def _SCREAMING_SNAKE_CASE ( ) -> Tuple: forceWrite(' ' * TERMINAL_WIDTH ) reset_cursor() def _SCREAMING_SNAKE_CASE ( ) -> Optional[int]: reset_cursor() forceWrite('-' * TERMINAL_WIDTH )
280
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 YolosImageProcessor class _A( unittest.TestCase ): """simple docstring""" def __init__( self , _A , _A=7 , _A=3 , _A=30 , _A=400 , _A=True , _A=None , _A=True , _A=[0.5, 0.5, 0.5] , _A=[0.5, 0.5, 0.5] , _A=True , _A=1 / 255 , _A=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __A : List[Any] = size if size is not None else {'shortest_edge': 18, 'longest_edge': 1333} __A : Union[str, Any] = parent __A : Optional[int] = batch_size __A : int = num_channels __A : int = min_resolution __A : Any = max_resolution __A : List[Any] = do_resize __A : List[Any] = size __A : Union[str, Any] = do_normalize __A : Optional[int] = image_mean __A : Optional[int] = image_std __A : int = do_rescale __A : str = rescale_factor __A : Tuple = do_pad def UpperCAmelCase_ ( self ): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def UpperCAmelCase_ ( self , _A , _A=False ): if not batched: __A : List[str] = image_inputs[0] if isinstance(_A , Image.Image ): __A , __A : int = image.size else: __A , __A : Any = image.shape[1], image.shape[2] if w < h: __A : List[Any] = int(self.size['shortest_edge'] * h / w ) __A : List[Any] = self.size['shortest_edge'] elif w > h: __A : Union[str, Any] = self.size['shortest_edge'] __A : str = int(self.size['shortest_edge'] * w / h ) else: __A : Dict = self.size['shortest_edge'] __A : str = self.size['shortest_edge'] else: __A : int = [] for image in image_inputs: __A , __A : Optional[Any] = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __A : List[str] = max(_A , key=lambda _A : item[0] )[0] __A : str = max(_A , key=lambda _A : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class _A( snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : List[str] = YolosImageProcessor if is_vision_available() else None def UpperCAmelCase_ ( self ): __A : Dict = YolosImageProcessingTester(self ) @property def UpperCAmelCase_ ( self ): return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase_ ( self ): __A : str = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_A , 'image_mean' ) ) self.assertTrue(hasattr(_A , 'image_std' ) ) self.assertTrue(hasattr(_A , 'do_normalize' ) ) self.assertTrue(hasattr(_A , 'do_resize' ) ) self.assertTrue(hasattr(_A , 'size' ) ) def UpperCAmelCase_ ( self ): __A : Tuple = 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 , _A ) __A : Dict = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=_A ) self.assertEqual(image_processor.size , {'shortest_edge': 42, 'longest_edge': 84} ) self.assertEqual(image_processor.do_pad , _A ) def UpperCAmelCase_ ( self ): pass def UpperCAmelCase_ ( self ): # Initialize image_processing __A : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __A : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A ) for image in image_inputs: self.assertIsInstance(_A , Image.Image ) # Test not batched input __A : Any = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values __A , __A : Optional[int] = self.image_processor_tester.get_expected_values(_A ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __A , __A : Optional[Any] = self.image_processor_tester.get_expected_values(_A , batched=_A ) __A : str = image_processing(_A , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def UpperCAmelCase_ ( self ): # Initialize image_processing __A : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __A : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A , numpify=_A ) for image in image_inputs: self.assertIsInstance(_A , np.ndarray ) # Test not batched input __A : str = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values __A , __A : List[Any] = self.image_processor_tester.get_expected_values(_A ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __A : Tuple = image_processing(_A , return_tensors='pt' ).pixel_values __A , __A : Optional[int] = self.image_processor_tester.get_expected_values(_A , batched=_A ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def UpperCAmelCase_ ( self ): # Initialize image_processing __A : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __A : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A , torchify=_A ) for image in image_inputs: self.assertIsInstance(_A , torch.Tensor ) # Test not batched input __A : Union[str, Any] = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values __A , __A : Union[str, Any] = self.image_processor_tester.get_expected_values(_A ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __A : Optional[int] = image_processing(_A , return_tensors='pt' ).pixel_values __A , __A : Optional[int] = self.image_processor_tester.get_expected_values(_A , batched=_A ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def UpperCAmelCase_ ( self ): # Initialize image_processings __A : Tuple = self.image_processing_class(**self.image_processor_dict ) __A : Any = self.image_processing_class(do_resize=_A , do_normalize=_A , do_rescale=_A ) # create random PyTorch tensors __A : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A , torchify=_A ) for image in image_inputs: self.assertIsInstance(_A , torch.Tensor ) # Test whether the method "pad" and calling the image processor return the same tensors __A : Optional[int] = image_processing_a.pad(_A , return_tensors='pt' ) __A : Optional[int] = image_processing_a(_A , return_tensors='pt' ) self.assertTrue( torch.allclose(encoded_images_with_method['pixel_values'] , encoded_images['pixel_values'] , atol=1e-4 ) ) @slow def UpperCAmelCase_ ( self ): # prepare image and target __A : List[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' , 'r' ) as f: __A : Optional[Any] = json.loads(f.read() ) __A : Optional[Any] = {'image_id': 39769, 'annotations': target} # encode them __A : str = YolosImageProcessor.from_pretrained('hustvl/yolos-small' ) __A : List[Any] = image_processing(images=_A , annotations=_A , return_tensors='pt' ) # verify pixel values __A : List[Any] = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding['pixel_values'].shape , _A ) __A : Union[str, Any] = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , _A , atol=1e-4 ) ) # verify area __A : List[Any] = torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , _A ) ) # verify boxes __A : Any = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , _A ) __A : Optional[Any] = torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , _A , atol=1e-3 ) ) # verify image_id __A : Optional[int] = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , _A ) ) # verify is_crowd __A : str = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , _A ) ) # verify class_labels __A : Any = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , _A ) ) # verify orig_size __A : int = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , _A ) ) # verify size __A : str = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , _A ) ) @slow def UpperCAmelCase_ ( self ): # prepare image, target and masks_path __A : Dict = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' , 'r' ) as f: __A : Tuple = json.loads(f.read() ) __A : Any = {'file_name': '000000039769.png', 'image_id': 39769, 'segments_info': target} __A : List[Any] = pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic' ) # encode them __A : Any = YolosImageProcessor(format='coco_panoptic' ) __A : List[Any] = image_processing(images=_A , annotations=_A , masks_path=_A , return_tensors='pt' ) # verify pixel values __A : Any = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding['pixel_values'].shape , _A ) __A : Union[str, Any] = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , _A , atol=1e-4 ) ) # verify area __A : int = torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , _A ) ) # verify boxes __A : Optional[int] = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , _A ) __A : Optional[Any] = torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , _A , atol=1e-3 ) ) # verify image_id __A : Union[str, Any] = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , _A ) ) # verify is_crowd __A : Tuple = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , _A ) ) # verify class_labels __A : List[str] = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , _A ) ) # verify masks __A : Tuple = 822873 self.assertEqual(encoding['labels'][0]['masks'].sum().item() , _A ) # verify orig_size __A : str = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , _A ) ) # verify size __A : int = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , _A ) )
280
1
# This is the module that test_patching.py uses to test patch_submodule() import os # noqa: this is just for tests import os as renamed_os # noqa: this is just for tests from os import path # noqa: this is just for tests from os import path as renamed_path # noqa: this is just for tests from os.path import join # noqa: this is just for tests from os.path import join as renamed_join # noqa: this is just for tests UpperCAmelCase : str = open # noqa: we just need to have a builtin inside this module to test it properly
280
import argparse import json from tqdm import tqdm def _SCREAMING_SNAKE_CASE ( ) -> List[Any]: __A : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( '--src_path' , type=a , default='biencoder-nq-dev.json' , help='Path to raw DPR training data' , ) parser.add_argument( '--evaluation_set' , type=a , help='where to store parsed evaluation_set file' , ) parser.add_argument( '--gold_data_path' , type=a , help='where to store parsed gold_data_path file' , ) __A : Optional[int] = parser.parse_args() with open(args.src_path , 'r' ) as src_file, open(args.evaluation_set , 'w' ) as eval_file, open( args.gold_data_path , 'w' ) as gold_file: __A : List[Any] = json.load(a ) for dpr_record in tqdm(a ): __A : Dict = dpr_record['question'] __A : Any = [context['title'] for context in dpr_record['positive_ctxs']] eval_file.write(question + '\n' ) gold_file.write('\t'.join(a ) + '\n' ) if __name__ == "__main__": main()
280
1
from collections import defaultdict from pathlib import Path import pandas as pd from rouge_cli import calculate_rouge_path from utils import calculate_rouge UpperCAmelCase : List[Any] = [ '''Prosecutor: "No videos were used in the crash investigation" German papers say they saw a cell phone video of the''' ''' final seconds on board Flight 9525. The Germanwings co-pilot says he had a "previous episode of severe''' ''' depression\" German airline confirms it knew of Andreas Lubitz\'s depression years before he took control.''', '''The Palestinian Authority officially becomes the 123rd member of the International Criminal Court. The formal''' ''' accession was marked with a ceremony at The Hague, in the Netherlands. The Palestinians signed the ICC\'s''' ''' founding Rome Statute in January. Israel and the United States opposed the Palestinians\' efforts to join the''' ''' body.''', '''Amnesty International releases its annual report on the death penalty. The report catalogs the use of''' ''' state-sanctioned killing as a punitive measure across the globe. At least 607 people were executed around the''' ''' world in 2014, compared to 778 in 2013. The U.S. remains one of the worst offenders for imposing capital''' ''' punishment.''', ] UpperCAmelCase : str = [ '''Marseille prosecutor says "so far no videos were used in the crash investigation" despite media reports .''' ''' Journalists at Bild and Paris Match are "very confident" the video clip is real, an editor says . Andreas Lubitz''' ''' had informed his Lufthansa training school of an episode of severe depression, airline says .''', '''Membership gives the ICC jurisdiction over alleged crimes committed in Palestinian territories since last June .''' ''' Israel and the United States opposed the move, which could open the door to war crimes investigations against''' ''' Israelis .''', '''Amnesty\'s annual death penalty report catalogs encouraging signs, but setbacks in numbers of those sentenced to''' ''' death . Organization claims that governments around the world are using the threat of terrorism to advance''' ''' executions . The number of executions worldwide has gone down by almost 22% compared with 2013, but death''' ''' sentences up by 28% .''', ] def _SCREAMING_SNAKE_CASE ( ) -> Optional[Any]: __A : int = calculate_rouge(a , a , bootstrap_aggregation=a , rouge_keys=['rouge2', 'rougeL'] ) assert isinstance(a , a ) __A : List[Any] = calculate_rouge(a , a , bootstrap_aggregation=a , rouge_keys=['rouge2'] ) assert ( pd.DataFrame(no_aggregation['rouge2'] ).fmeasure.mean() == pd.DataFrame(no_aggregation_just_ra['rouge2'] ).fmeasure.mean() ) def _SCREAMING_SNAKE_CASE ( ) -> Dict: __A : List[str] = 'rougeLsum' __A : int = calculate_rouge(a , a , newline_sep=a , rouge_keys=[k] )[k] __A : int = calculate_rouge(a , a , newline_sep=a , rouge_keys=[k] )[k] assert score > score_no_sep def _SCREAMING_SNAKE_CASE ( ) -> str: __A : int = ['rouge1', 'rouge2', 'rougeL'] __A : str = calculate_rouge(a , a , newline_sep=a , rouge_keys=a ) __A : List[str] = calculate_rouge(a , a , newline_sep=a , rouge_keys=a ) assert score_sep == score_no_sep def _SCREAMING_SNAKE_CASE ( ) -> int: __A : Tuple = [ 'Her older sister, Margot Frank, died in 1945, a month earlier than previously thought.', 'Marseille prosecutor says "so far no videos were used in the crash investigation" despite media reports .', ] __A : str = [ 'Margot Frank, died in 1945, a month earlier than previously thought.', 'Prosecutor: "No videos were used in the crash investigation" German papers say they saw a cell phone video of' ' the final seconds on board Flight 9525.', ] assert calculate_rouge(a , a , newline_sep=a ) == calculate_rouge(a , a , newline_sep=a ) def _SCREAMING_SNAKE_CASE ( ) -> List[str]: __A : Union[str, Any] = [ '" "a person who has such a video needs to immediately give it to the investigators," prosecutor says .<n> "it is a very disturbing scene," editor-in-chief of bild online tells "erin burnett: outfront" ' ] __A : Dict = [ ' Marseille prosecutor says "so far no videos were used in the crash investigation" despite media reports . Journalists at Bild and Paris Match are "very confident" the video clip is real, an editor says . Andreas Lubitz had informed his Lufthansa training school of an episode of severe depression, airline says .' ] __A : Optional[int] = calculate_rouge(a , a , rouge_keys=['rougeLsum'] , newline_sep=a )['rougeLsum'] __A : Tuple = calculate_rouge(a , a , rouge_keys=['rougeLsum'] )['rougeLsum'] assert new_score > prev_score def _SCREAMING_SNAKE_CASE ( ) -> Tuple: __A : int = Path('examples/seq2seq/test_data/wmt_en_ro' ) __A : List[str] = calculate_rouge_path(data_dir.joinpath('test.source' ) , data_dir.joinpath('test.target' ) ) assert isinstance(a , a ) __A : Optional[int] = calculate_rouge_path( data_dir.joinpath('test.source' ) , data_dir.joinpath('test.target' ) , bootstrap_aggregation=a ) assert isinstance(a , a )
280
from heapq import heappop, heappush import numpy as np def _SCREAMING_SNAKE_CASE ( a , a , a , a , ) -> tuple[float | int, list[tuple[int, int]]]: __A , __A : int = grid.shape __A : Any = [-1, 1, 0, 0] __A : Optional[Any] = [0, 0, -1, 1] if allow_diagonal: dx += [-1, -1, 1, 1] dy += [-1, 1, -1, 1] __A , __A : Optional[int] = [(0, source)], set() __A : Any = np.full((rows, cols) , np.inf ) __A : Any = 0 __A : Any = np.empty((rows, cols) , dtype=a ) __A : Optional[Any] = None while queue: ((__A) , (__A)) : List[str] = heappop(a ) if (x, y) in visited: continue visited.add((x, y) ) if (x, y) == destination: __A : int = [] while (x, y) != source: path.append((x, y) ) __A , __A : Optional[int] = predecessors[x, y] path.append(a ) # add the source manually path.reverse() return matrix[destination], path for i in range(len(a ) ): __A , __A : Union[str, Any] = x + dx[i], y + dy[i] if 0 <= nx < rows and 0 <= ny < cols: __A : Optional[int] = grid[nx][ny] if next_node == 1 and matrix[nx, ny] > dist + 1: heappush(a , (dist + 1, (nx, ny)) ) __A : List[Any] = dist + 1 __A : Union[str, Any] = (x, y) return np.inf, [] if __name__ == "__main__": import doctest doctest.testmod()
280
1
def _SCREAMING_SNAKE_CASE ( a ) -> list[int]: __A : List[Any] = [0 for i in range(len(a ) )] # initialize interval's left pointer and right pointer __A , __A : List[Any] = 0, 0 for i in range(1 , len(a ) ): # case when current index is inside the interval if i <= right_pointer: __A : Optional[Any] = min(right_pointer - i + 1 , z_result[i - left_pointer] ) __A : Dict = min_edge while go_next(a , a , a ): z_result[i] += 1 # if new index's result gives us more right interval, # we've to update left_pointer and right_pointer if i + z_result[i] - 1 > right_pointer: __A , __A : Optional[Any] = i, i + z_result[i] - 1 return z_result def _SCREAMING_SNAKE_CASE ( a , a , a ) -> bool: return i + z_result[i] < len(a ) and s[z_result[i]] == s[i + z_result[i]] def _SCREAMING_SNAKE_CASE ( a , a ) -> int: __A : Union[str, Any] = 0 # concatenate 'pattern' and 'input_str' and call z_function # with concatenated string __A : Optional[Any] = z_function(pattern + input_str ) for val in z_result: # if value is greater then length of the pattern string # that means this index is starting position of substring # which is equal to pattern string if val >= len(a ): answer += 1 return answer if __name__ == "__main__": import doctest doctest.testmod()
280
from typing import List, Optional, Union import numpy as np import PIL import torch from PIL import Image from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) UpperCAmelCase : List[Any] = logging.get_logger(__name__) # pylint: disable=invalid-name UpperCAmelCase : Dict = ''' Examples: ```py >>> from diffusers import KandinskyV22Img2ImgPipeline, KandinskyV22PriorPipeline >>> from diffusers.utils import load_image >>> import torch >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained( ... "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16 ... ) >>> pipe_prior.to("cuda") >>> prompt = "A red cartoon frog, 4k" >>> image_emb, zero_image_emb = pipe_prior(prompt, return_dict=False) >>> pipe = KandinskyV22Img2ImgPipeline.from_pretrained( ... "kandinsky-community/kandinsky-2-2-decoder", torch_dtype=torch.float16 ... ) >>> pipe.to("cuda") >>> init_image = load_image( ... "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" ... "/kandinsky/frog.png" ... ) >>> image = pipe( ... image=init_image, ... image_embeds=image_emb, ... negative_image_embeds=zero_image_emb, ... height=768, ... width=768, ... num_inference_steps=100, ... strength=0.2, ... ).images >>> image[0].save("red_frog.png") ``` ''' def _SCREAMING_SNAKE_CASE ( a , a , a=8 ) -> Tuple: __A : List[str] = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 __A : Optional[int] = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor def _SCREAMING_SNAKE_CASE ( a , a=5_12 , a=5_12 ) -> int: __A : Optional[Any] = pil_image.resize((w, h) , resample=Image.BICUBIC , reducing_gap=1 ) __A : Union[str, Any] = np.array(pil_image.convert('RGB' ) ) __A : Optional[int] = arr.astype(np.floataa ) / 127.5 - 1 __A : int = np.transpose(a , [2, 0, 1] ) __A : Tuple = torch.from_numpy(a ).unsqueeze(0 ) return image class _A( snake_case__ ): """simple docstring""" def __init__( self , _A , _A , _A , ): super().__init__() self.register_modules( unet=_A , scheduler=_A , movq=_A , ) __A : Tuple = 2 ** (len(self.movq.config.block_out_channels ) - 1) def UpperCAmelCase_ ( self , _A , _A , _A ): # get the original timestep using init_timestep __A : Optional[int] = min(int(num_inference_steps * strength ) , _A ) __A : Dict = max(num_inference_steps - init_timestep , 0 ) __A : Tuple = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A=None ): if not isinstance(_A , (torch.Tensor, PIL.Image.Image, list) ): raise ValueError( F"""`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(_A )}""" ) __A : Union[str, Any] = image.to(device=_A , dtype=_A ) __A : Optional[Any] = batch_size * num_images_per_prompt if image.shape[1] == 4: __A : int = image else: if isinstance(_A , _A ) and len(_A ) != batch_size: raise ValueError( F"""You have passed a list of generators of length {len(_A )}, but requested an effective batch""" F""" size of {batch_size}. Make sure the batch size matches the length of the generators.""" ) elif isinstance(_A , _A ): __A : str = [ self.movq.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(_A ) ] __A : str = torch.cat(_A , dim=0 ) else: __A : List[str] = self.movq.encode(_A ).latent_dist.sample(_A ) __A : Tuple = self.movq.config.scaling_factor * init_latents __A : Optional[int] = torch.cat([init_latents] , dim=0 ) __A : Union[str, Any] = init_latents.shape __A : List[str] = randn_tensor(_A , generator=_A , device=_A , dtype=_A ) # get latents __A : Optional[Any] = self.scheduler.add_noise(_A , _A , _A ) __A : Optional[int] = init_latents return latents def UpperCAmelCase_ ( self , _A=0 ): if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('Please install accelerate via `pip install accelerate`' ) __A : Optional[int] = torch.device(F"""cuda:{gpu_id}""" ) __A : Union[str, Any] = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(_A , _A ) def UpperCAmelCase_ ( self , _A=0 ): if is_accelerate_available() and is_accelerate_version('>=' , '0.17.0.dev0' ): from accelerate import cpu_offload_with_hook else: raise ImportError('`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.' ) __A : List[Any] = torch.device(F"""cuda:{gpu_id}""" ) if self.device.type != "cpu": self.to('cpu' , silence_dtype_warnings=_A ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) __A : int = None for cpu_offloaded_model in [self.unet, self.movq]: __A , __A : Optional[int] = cpu_offload_with_hook(_A , _A , prev_module_hook=_A ) # We'll offload the last model manually. __A : List[str] = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def UpperCAmelCase_ ( self ): if not hasattr(self.unet , '_hf_hook' ): return self.device for module in self.unet.modules(): if ( hasattr(_A , '_hf_hook' ) and hasattr(module._hf_hook , 'execution_device' ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(_A ) def __call__( self , _A , _A , _A , _A = 512 , _A = 512 , _A = 100 , _A = 4.0 , _A = 0.3 , _A = 1 , _A = None , _A = "pil" , _A = True , ): __A : List[Any] = self._execution_device __A : Optional[Any] = guidance_scale > 1.0 if isinstance(_A , _A ): __A : Optional[Any] = torch.cat(_A , dim=0 ) __A : Tuple = image_embeds.shape[0] if isinstance(_A , _A ): __A : List[Any] = torch.cat(_A , dim=0 ) if do_classifier_free_guidance: __A : Union[str, Any] = image_embeds.repeat_interleave(_A , dim=0 ) __A : Optional[int] = negative_image_embeds.repeat_interleave(_A , dim=0 ) __A : List[str] = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=_A ) if not isinstance(_A , _A ): __A : List[Any] = [image] if not all(isinstance(_A , (PIL.Image.Image, torch.Tensor) ) for i in image ): raise ValueError( F"""Input is in incorrect format: {[type(_A ) for i in image]}. Currently, we only support PIL image and pytorch tensor""" ) __A : Dict = torch.cat([prepare_image(_A , _A , _A ) for i in image] , dim=0 ) __A : Any = image.to(dtype=image_embeds.dtype , device=_A ) __A : Tuple = self.movq.encode(_A )['latents'] __A : int = latents.repeat_interleave(_A , dim=0 ) self.scheduler.set_timesteps(_A , device=_A ) __A , __A : int = self.get_timesteps(_A , _A , _A ) __A : Union[str, Any] = timesteps[:1].repeat(batch_size * num_images_per_prompt ) __A , __A : Any = downscale_height_and_width(_A , _A , self.movq_scale_factor ) __A : Tuple = self.prepare_latents( _A , _A , _A , _A , image_embeds.dtype , _A , _A ) for i, t in enumerate(self.progress_bar(_A ) ): # expand the latents if we are doing classifier free guidance __A : Optional[int] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents __A : Dict = {'image_embeds': image_embeds} __A : List[str] = self.unet( sample=_A , timestep=_A , encoder_hidden_states=_A , added_cond_kwargs=_A , return_dict=_A , )[0] if do_classifier_free_guidance: __A , __A : Dict = noise_pred.split(latents.shape[1] , dim=1 ) __A , __A : Optional[Any] = noise_pred.chunk(2 ) __A , __A : List[str] = variance_pred.chunk(2 ) __A : str = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) __A : List[str] = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , 'variance_type' ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): __A , __A : Optional[Any] = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 __A : List[str] = self.scheduler.step( _A , _A , _A , generator=_A , )[0] # post-processing __A : List[Any] = self.movq.decode(_A , force_not_quantize=_A )['sample'] if output_type not in ["pt", "np", "pil"]: raise ValueError(F"""Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}""" ) if output_type in ["np", "pil"]: __A : List[str] = image * 0.5 + 0.5 __A : List[str] = image.clamp(0 , 1 ) __A : Optional[Any] = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": __A : Any = self.numpy_to_pil(_A ) if not return_dict: return (image,) return ImagePipelineOutput(images=_A )
280
1
import os 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 logging UpperCAmelCase : List[Any] = logging.get_logger(__name__) UpperCAmelCase : Optional[Any] = {'''vocab_file''': '''sentencepiece.bpe.model'''} UpperCAmelCase : Any = { '''vocab_file''': { '''camembert-base''': '''https://huggingface.co/camembert-base/resolve/main/sentencepiece.bpe.model''', } } UpperCAmelCase : Any = { '''camembert-base''': 5_12, } UpperCAmelCase : Any = '''▁''' class _A( snake_case__ ): """simple docstring""" UpperCamelCase : List[str] = VOCAB_FILES_NAMES UpperCamelCase : int = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase : List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase : int = ['''input_ids''', '''attention_mask'''] def __init__( self , _A , _A="<s>" , _A="</s>" , _A="</s>" , _A="<s>" , _A="<unk>" , _A="<pad>" , _A="<mask>" , _A=["<s>NOTUSED", "</s>NOTUSED"] , _A = None , **_A , ): # Mask token behave like a normal word, i.e. include the space before it __A : Tuple = AddedToken(_A , lstrip=_A , rstrip=_A ) if isinstance(_A , _A ) else mask_token __A : List[Any] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=_A , eos_token=_A , unk_token=_A , sep_token=_A , cls_token=_A , pad_token=_A , mask_token=_A , additional_special_tokens=_A , sp_model_kwargs=self.sp_model_kwargs , **_A , ) __A : Dict = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(_A ) ) __A : Any = vocab_file # HACK: These tokens were added by fairseq but don't seem to be actually used when duplicated in the actual # sentencepiece vocabulary (this is the case for <s> and </s> __A : Dict = {'<s>NOTUSED': 0, '<pad>': 1, '</s>NOTUSED': 2, '<unk>': 3} __A : Union[str, Any] = len(self.fairseq_tokens_to_ids ) __A : str = len(self.sp_model ) + len(self.fairseq_tokens_to_ids ) __A : Optional[Any] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def UpperCAmelCase_ ( self , _A , _A = None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __A : Union[str, Any] = [self.cls_token_id] __A : Union[str, Any] = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def UpperCAmelCase_ ( self , _A , _A = None , _A = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_A , token_ids_a=_A , already_has_special_tokens=_A ) if token_ids_a is None: return [1] + ([0] * len(_A )) + [1] return [1] + ([0] * len(_A )) + [1, 1] + ([0] * len(_A )) + [1] def UpperCAmelCase_ ( self , _A , _A = None ): __A : Optional[int] = [self.sep_token_id] __A : List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def UpperCAmelCase_ ( self ): return len(self.fairseq_tokens_to_ids ) + len(self.sp_model ) def UpperCAmelCase_ ( self ): __A : Union[str, Any] = {self.convert_ids_to_tokens(_A ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def UpperCAmelCase_ ( self , _A ): return self.sp_model.encode(_A , out_type=_A ) def UpperCAmelCase_ ( self , _A ): if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] elif self.sp_model.PieceToId(_A ) == 0: # Convert sentence piece unk token to fairseq unk token index return self.unk_token_id return self.fairseq_offset + self.sp_model.PieceToId(_A ) def UpperCAmelCase_ ( self , _A ): 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 UpperCAmelCase_ ( self , _A ): __A : Union[str, Any] = [] __A : Union[str, Any] = '' __A : Optional[int] = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(_A ) + token __A : List[Any] = True __A : Optional[int] = [] else: current_sub_tokens.append(_A ) __A : Optional[Any] = False out_string += self.sp_model.decode(_A ) return out_string.strip() def __getstate__( self ): __A : Optional[Any] = self.__dict__.copy() __A : Optional[int] = None return state def __setstate__( self , _A ): __A : Union[str, Any] = d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): __A : str = {} __A : Any = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def UpperCAmelCase_ ( self , _A , _A = None ): if not os.path.isdir(_A ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return __A : Optional[Any] = os.path.join( _A , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_A ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _A ) elif not os.path.isfile(self.vocab_file ): with open(_A , 'wb' ) as fi: __A : Optional[Any] = self.sp_model.serialized_model_proto() fi.write(_A ) return (out_vocab_file,)
280
import argparse import os import gluonnlp as nlp import mxnet as mx import numpy as np import torch from gluonnlp.base import get_home_dir from gluonnlp.model.bert import BERTEncoder from gluonnlp.model.utils import _load_vocab from gluonnlp.vocab import Vocab from packaging import version from torch import nn from transformers import BertConfig, BertForMaskedLM, BertModel, RobertaTokenizer from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertSelfAttention, BertSelfOutput, ) from transformers.utils import logging if version.parse(nlp.__version__) != version.parse('''0.8.3'''): raise Exception('''requires gluonnlp == 0.8.3''') if version.parse(mx.__version__) != version.parse('''1.5.0'''): raise Exception('''requires mxnet == 1.5.0''') logging.set_verbosity_info() UpperCAmelCase : List[Any] = logging.get_logger(__name__) UpperCAmelCase : Optional[Any] = '''The Nymphenburg Palace is a beautiful palace in Munich!''' def _SCREAMING_SNAKE_CASE ( a , a ) -> Optional[Any]: __A : Any = { 'attention_cell': 'multi_head', 'num_layers': 4, 'units': 10_24, 'hidden_size': 7_68, 'max_length': 5_12, 'num_heads': 8, 'scaled': True, 'dropout': 0.1, 'use_residual': True, 'embed_size': 10_24, 'embed_dropout': 0.1, 'word_embed': None, 'layer_norm_eps': 1e-5, 'token_type_vocab_size': 2, } __A : str = bort_4_8_768_1024_hparams # Let's construct the original Bort model here # Taken from official BERT implementation, see: # https://github.com/alexa/bort/blob/master/bort/bort.py __A : Optional[int] = BERTEncoder( attention_cell=predefined_args['attention_cell'] , num_layers=predefined_args['num_layers'] , units=predefined_args['units'] , hidden_size=predefined_args['hidden_size'] , max_length=predefined_args['max_length'] , num_heads=predefined_args['num_heads'] , scaled=predefined_args['scaled'] , dropout=predefined_args['dropout'] , output_attention=a , output_all_encodings=a , use_residual=predefined_args['use_residual'] , activation=predefined_args.get('activation' , 'gelu' ) , layer_norm_eps=predefined_args.get('layer_norm_eps' , a ) , ) # Vocab information needs to be fetched first # It's the same as RoBERTa, so RobertaTokenizer can be used later __A : Union[str, Any] = 'openwebtext_ccnews_stories_books_cased' # Specify download folder to Gluonnlp's vocab __A : Any = os.path.join(get_home_dir() , 'models' ) __A : List[Any] = _load_vocab(a , a , a , cls=a ) __A : Dict = nlp.model.BERTModel( a , len(a ) , units=predefined_args['units'] , embed_size=predefined_args['embed_size'] , embed_dropout=predefined_args['embed_dropout'] , word_embed=predefined_args['word_embed'] , use_pooler=a , use_token_type_embed=a , token_type_vocab_size=predefined_args['token_type_vocab_size'] , use_classifier=a , use_decoder=a , ) original_bort.load_parameters(a , cast_dtype=a , ignore_extra=a ) __A : Union[str, Any] = original_bort._collect_params_with_prefix() # Build our config 🤗 __A : Any = { 'architectures': ['BertForMaskedLM'], 'attention_probs_dropout_prob': predefined_args['dropout'], 'hidden_act': 'gelu', 'hidden_dropout_prob': predefined_args['dropout'], 'hidden_size': predefined_args['embed_size'], 'initializer_range': 0.02, 'intermediate_size': predefined_args['hidden_size'], 'layer_norm_eps': predefined_args['layer_norm_eps'], 'max_position_embeddings': predefined_args['max_length'], 'model_type': 'bort', 'num_attention_heads': predefined_args['num_heads'], 'num_hidden_layers': predefined_args['num_layers'], 'pad_token_id': 1, # 2 = BERT, 1 = RoBERTa 'type_vocab_size': 1, # 2 = BERT, 1 = RoBERTa 'vocab_size': len(a ), } __A : int = BertConfig.from_dict(a ) __A : Union[str, Any] = BertForMaskedLM(a ) hf_bort_model.eval() # Parameter mapping table (Gluonnlp to Transformers) # * denotes layer index # # | Gluon Parameter | Transformers Parameter # | -------------------------------------------------------------- | ---------------------- # | `encoder.layer_norm.beta` | `bert.embeddings.LayerNorm.bias` # | `encoder.layer_norm.gamma` | `bert.embeddings.LayerNorm.weight` # | `encoder.position_weight` | `bert.embeddings.position_embeddings.weight` # | `word_embed.0.weight` | `bert.embeddings.word_embeddings.weight` # | `encoder.transformer_cells.*.attention_cell.proj_key.bias` | `bert.encoder.layer.*.attention.self.key.bias` # | `encoder.transformer_cells.*.attention_cell.proj_key.weight` | `bert.encoder.layer.*.attention.self.key.weight` # | `encoder.transformer_cells.*.attention_cell.proj_query.bias` | `bert.encoder.layer.*.attention.self.query.bias` # | `encoder.transformer_cells.*.attention_cell.proj_query.weight` | `bert.encoder.layer.*.attention.self.query.weight` # | `encoder.transformer_cells.*.attention_cell.proj_value.bias` | `bert.encoder.layer.*.attention.self.value.bias` # | `encoder.transformer_cells.*.attention_cell.proj_value.weight` | `bert.encoder.layer.*.attention.self.value.weight` # | `encoder.transformer_cells.*.ffn.ffn_2.bias` | `bert.encoder.layer.*.attention.output.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_2.weight` | `bert.encoder.layer.*.attention.output.dense.weight` # | `encoder.transformer_cells.*.layer_norm.beta` | `bert.encoder.layer.*.attention.output.LayerNorm.bias` # | `encoder.transformer_cells.*.layer_norm.gamma` | `bert.encoder.layer.*.attention.output.LayerNorm.weight` # | `encoder.transformer_cells.*.ffn.ffn_1.bias` | `bert.encoder.layer.*.intermediate.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_1.weight` | `bert.encoder.layer.*.intermediate.dense.weight` # | `encoder.transformer_cells.*.ffn.layer_norm.beta` | `bert.encoder.layer.*.output.LayerNorm.bias` # | `encoder.transformer_cells.*.ffn.layer_norm.gamma` | `bert.encoder.layer.*.output.LayerNorm.weight` # | `encoder.transformer_cells.*.proj.bias` | `bert.encoder.layer.*.output.dense.bias` # | `encoder.transformer_cells.*.proj.weight` | `bert.encoder.layer.*.output.dense.weight` # Helper function to convert MXNET Arrays to PyTorch def to_torch(a ) -> nn.Parameter: return nn.Parameter(torch.FloatTensor(mx_array.data().asnumpy() ) ) # Check param shapes and map new HF param back def check_and_map_params(a , a ): __A : Tuple = hf_param.shape __A : str = to_torch(params[gluon_param] ) __A : Union[str, Any] = gluon_param.shape assert ( shape_hf == shape_gluon ), F"""The gluon parameter {gluon_param} has shape {shape_gluon}, but expects shape {shape_hf} for Transformers""" return gluon_param __A : str = check_and_map_params( hf_bort_model.bert.embeddings.word_embeddings.weight , 'word_embed.0.weight' ) __A : Tuple = check_and_map_params( hf_bort_model.bert.embeddings.position_embeddings.weight , 'encoder.position_weight' ) __A : List[str] = check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.bias , 'encoder.layer_norm.beta' ) __A : Tuple = check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.weight , 'encoder.layer_norm.gamma' ) # Inspired by RoBERTa conversion script, we just zero them out (Bort does not use them) __A : Tuple = torch.zeros_like( hf_bort_model.bert.embeddings.token_type_embeddings.weight.data ) for i in range(hf_bort_config.num_hidden_layers ): __A : BertLayer = hf_bort_model.bert.encoder.layer[i] # self attention __A : BertSelfAttention = layer.attention.self __A : Optional[Any] = check_and_map_params( self_attn.key.bias.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_key.bias""" ) __A : Optional[int] = check_and_map_params( self_attn.key.weight.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_key.weight""" ) __A : Union[str, Any] = check_and_map_params( self_attn.query.bias.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_query.bias""" ) __A : Optional[Any] = check_and_map_params( self_attn.query.weight.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_query.weight""" ) __A : Union[str, Any] = check_and_map_params( self_attn.value.bias.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_value.bias""" ) __A : Optional[int] = check_and_map_params( self_attn.value.weight.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_value.weight""" ) # self attention output __A : BertSelfOutput = layer.attention.output __A : Tuple = check_and_map_params( self_output.dense.bias , F"""encoder.transformer_cells.{i}.proj.bias""" ) __A : int = check_and_map_params( self_output.dense.weight , F"""encoder.transformer_cells.{i}.proj.weight""" ) __A : List[Any] = check_and_map_params( self_output.LayerNorm.bias , F"""encoder.transformer_cells.{i}.layer_norm.beta""" ) __A : str = check_and_map_params( self_output.LayerNorm.weight , F"""encoder.transformer_cells.{i}.layer_norm.gamma""" ) # intermediate __A : BertIntermediate = layer.intermediate __A : int = check_and_map_params( intermediate.dense.bias , F"""encoder.transformer_cells.{i}.ffn.ffn_1.bias""" ) __A : List[Any] = check_and_map_params( intermediate.dense.weight , F"""encoder.transformer_cells.{i}.ffn.ffn_1.weight""" ) # output __A : BertOutput = layer.output __A : List[Any] = check_and_map_params( bert_output.dense.bias , F"""encoder.transformer_cells.{i}.ffn.ffn_2.bias""" ) __A : Dict = check_and_map_params( bert_output.dense.weight , F"""encoder.transformer_cells.{i}.ffn.ffn_2.weight""" ) __A : Optional[int] = check_and_map_params( bert_output.LayerNorm.bias , F"""encoder.transformer_cells.{i}.ffn.layer_norm.beta""" ) __A : Dict = check_and_map_params( bert_output.LayerNorm.weight , F"""encoder.transformer_cells.{i}.ffn.layer_norm.gamma""" ) # Save space and energy 🎄 hf_bort_model.half() # Compare output of both models __A : Any = RobertaTokenizer.from_pretrained('roberta-base' ) __A : List[str] = tokenizer.encode_plus(a )['input_ids'] # Get gluon output __A : List[str] = mx.nd.array([input_ids] ) __A : Union[str, Any] = original_bort(inputs=a , token_types=[] ) # Get Transformer output (save and reload model again) hf_bort_model.save_pretrained(a ) __A : Optional[Any] = BertModel.from_pretrained(a ) hf_bort_model.eval() __A : Tuple = tokenizer.encode_plus(a , return_tensors='pt' ) __A : Any = hf_bort_model(**a )[0] __A : Union[str, Any] = output_gluon[0].asnumpy() __A : Tuple = output_hf[0].detach().numpy() __A : int = np.max(np.abs(hf_layer - gluon_layer ) ).item() __A : int = np.allclose(a , a , atol=1e-3 ) if success: print('✔️ Both model do output the same tensors' ) else: print('❌ Both model do **NOT** output the same tensors' ) print('Absolute difference is:' , a ) if __name__ == "__main__": UpperCAmelCase : int = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--bort_checkpoint_path''', default=None, type=str, required=True, help='''Path the official Bort params file.''' ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) UpperCAmelCase : Dict = parser.parse_args() convert_bort_checkpoint_to_pytorch(args.bort_checkpoint_path, args.pytorch_dump_folder_path)
280
1
import math from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase : Union[str, Any] = logging.get_logger(__name__) UpperCAmelCase : Optional[int] = { '''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 _A( snake_case__ ): """simple docstring""" UpperCamelCase : Any = '''data2vec-audio''' def __init__( self , _A=32 , _A=768 , _A=12 , _A=12 , _A=3072 , _A="gelu" , _A=0.1 , _A=0.1 , _A=0.1 , _A=0.0 , _A=0.1 , _A=0.1 , _A=0.0_2 , _A=1e-5 , _A="gelu" , _A=(512, 512, 512, 512, 512, 512, 512) , _A=(5, 2, 2, 2, 2, 2, 2) , _A=(10, 3, 3, 3, 3, 2, 2) , _A=False , _A=16 , _A=19 , _A=5 , _A=0.0_5 , _A=10 , _A=2 , _A=0.0 , _A=10 , _A=0 , _A="sum" , _A=False , _A=False , _A=256 , _A=(512, 512, 512, 512, 1500) , _A=(5, 3, 3, 1, 1) , _A=(1, 2, 3, 1, 1) , _A=512 , _A=0 , _A=1 , _A=2 , _A=False , _A=3 , _A=2 , _A=3 , _A=None , **_A , ): super().__init__(**_A , pad_token_id=_A , bos_token_id=_A , eos_token_id=_A ) __A : str = hidden_size __A : Optional[Any] = feat_extract_activation __A : Optional[Any] = list(_A ) __A : Any = list(_A ) __A : Optional[Any] = list(_A ) __A : Dict = conv_bias __A : Optional[int] = num_conv_pos_embeddings __A : int = num_conv_pos_embedding_groups __A : int = conv_pos_kernel_size __A : List[Any] = len(self.conv_dim ) __A : Any = num_hidden_layers __A : List[str] = intermediate_size __A : List[Any] = hidden_act __A : Tuple = num_attention_heads __A : Tuple = hidden_dropout __A : List[Any] = attention_dropout __A : Tuple = activation_dropout __A : Union[str, Any] = feat_proj_dropout __A : List[Any] = final_dropout __A : Optional[Any] = layerdrop __A : Tuple = layer_norm_eps __A : str = initializer_range __A : Optional[int] = vocab_size __A : Any = 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 __A : Optional[int] = mask_time_prob __A : Optional[int] = mask_time_length __A : Union[str, Any] = mask_time_min_masks __A : Optional[int] = mask_feature_prob __A : List[str] = mask_feature_length __A : Tuple = mask_feature_min_masks # ctc loss __A : Dict = ctc_loss_reduction __A : List[Any] = ctc_zero_infinity # adapter __A : Tuple = add_adapter __A : Union[str, Any] = adapter_kernel_size __A : str = adapter_stride __A : List[Any] = num_adapter_layers __A : List[str] = output_hidden_size or hidden_size # SequenceClassification-specific parameter. Feel free to ignore for other classes. __A : Union[str, Any] = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. __A : Optional[int] = list(_A ) __A : Optional[int] = list(_A ) __A : Union[str, Any] = list(_A ) __A : Union[str, Any] = xvector_output_dim @property def UpperCAmelCase_ ( self ): return math.prod(self.conv_stride )
280
import colorsys from PIL import Image # type: ignore def _SCREAMING_SNAKE_CASE ( a , a , a ) -> float: __A : List[str] = x __A : str = y for step in range(a ): # noqa: B007 __A : Union[str, Any] = a * a - b * b + x __A : Optional[int] = 2 * a * b + y __A : List[str] = a_new # divergence happens for all complex number with an absolute value # greater than 4 if a * a + b * b > 4: break return step / (max_step - 1) def _SCREAMING_SNAKE_CASE ( a ) -> tuple: if distance == 1: return (0, 0, 0) else: return (2_55, 2_55, 2_55) def _SCREAMING_SNAKE_CASE ( a ) -> tuple: if distance == 1: return (0, 0, 0) else: return tuple(round(i * 2_55 ) for i in colorsys.hsv_to_rgb(a , 1 , 1 ) ) def _SCREAMING_SNAKE_CASE ( a = 8_00 , a = 6_00 , a = -0.6 , a = 0 , a = 3.2 , a = 50 , a = True , ) -> Image.Image: __A : str = Image.new('RGB' , (image_width, image_height) ) __A : Dict = img.load() # loop through the image-coordinates for image_x in range(a ): for image_y in range(a ): # determine the figure-coordinates based on the image-coordinates __A : Dict = figure_width / image_width * image_height __A : Union[str, Any] = figure_center_x + (image_x / image_width - 0.5) * figure_width __A : Optional[Any] = figure_center_y + (image_y / image_height - 0.5) * figure_height __A : Union[str, Any] = get_distance(a , a , a ) # color the corresponding pixel based on the selected coloring-function if use_distance_color_coding: __A : Optional[Any] = get_color_coded_rgb(a ) else: __A : Dict = get_black_and_white_rgb(a ) return img if __name__ == "__main__": import doctest doctest.testmod() # colored version, full figure UpperCAmelCase : str = get_image() # uncomment for colored version, different section, zoomed in # img = get_image(figure_center_x = -0.6, figure_center_y = -0.4, # figure_width = 0.8) # uncomment for black and white version, full figure # img = get_image(use_distance_color_coding = False) # uncomment to save the image # img.save("mandelbrot.png") img.show()
280
1
import unittest import numpy as np from diffusers import OnnxStableDiffusionInpaintPipelineLegacy from diffusers.utils.testing_utils import ( is_onnx_available, load_image, load_numpy, nightly, require_onnxruntime, require_torch_gpu, ) if is_onnx_available(): import onnxruntime as ort @nightly @require_onnxruntime @require_torch_gpu class _A( unittest.TestCase ): """simple docstring""" @property def UpperCAmelCase_ ( self ): return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def UpperCAmelCase_ ( self ): __A : List[str] = ort.SessionOptions() __A : Optional[int] = False return options def UpperCAmelCase_ ( self ): __A : Tuple = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/in_paint/overture-creations-5sI6fQgYIuo.png' ) __A : Any = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/in_paint/overture-creations-5sI6fQgYIuo_mask.png' ) __A : Tuple = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/in_paint/red_cat_sitting_on_a_park_bench_onnx.npy' ) # using the PNDM scheduler by default __A : List[str] = OnnxStableDiffusionInpaintPipelineLegacy.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='onnx' , safety_checker=_A , feature_extractor=_A , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=_A ) __A : Dict = 'A red cat sitting on a park bench' __A : Union[str, Any] = np.random.RandomState(0 ) __A : List[str] = pipe( prompt=_A , image=_A , mask_image=_A , strength=0.7_5 , guidance_scale=7.5 , num_inference_steps=15 , generator=_A , output_type='np' , ) __A : int = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 1e-2
280
from __future__ import annotations def _SCREAMING_SNAKE_CASE ( a , a , a ) -> float: if days_between_payments <= 0: raise ValueError('days_between_payments must be > 0' ) if daily_interest_rate < 0: raise ValueError('daily_interest_rate must be >= 0' ) if principal <= 0: raise ValueError('principal must be > 0' ) return principal * daily_interest_rate * days_between_payments def _SCREAMING_SNAKE_CASE ( a , a , a , ) -> float: if number_of_compounding_periods <= 0: raise ValueError('number_of_compounding_periods must be > 0' ) if nominal_annual_interest_rate_percentage < 0: raise ValueError('nominal_annual_interest_rate_percentage must be >= 0' ) if principal <= 0: raise ValueError('principal must be > 0' ) return principal * ( (1 + nominal_annual_interest_rate_percentage) ** number_of_compounding_periods - 1 ) def _SCREAMING_SNAKE_CASE ( a , a , a , ) -> float: if number_of_years <= 0: raise ValueError('number_of_years must be > 0' ) if nominal_annual_percentage_rate < 0: raise ValueError('nominal_annual_percentage_rate must be >= 0' ) if principal <= 0: raise ValueError('principal must be > 0' ) return compound_interest( a , nominal_annual_percentage_rate / 3_65 , number_of_years * 3_65 ) if __name__ == "__main__": import doctest doctest.testmod()
280
1
import unittest import numpy as np def _SCREAMING_SNAKE_CASE ( a , a , a , a = None , ) -> np.ndarray: __A : List[str] = np.shape(a ) __A : Union[str, Any] = np.shape(a ) __A : str = np.shape(a ) if shape_a[0] != shape_b[0]: __A : Dict = ( 'Expected the same number of rows for A and B. ' F"""Instead found A of size {shape_a} and B of size {shape_b}""" ) raise ValueError(a ) if shape_b[1] != shape_c[1]: __A : Any = ( 'Expected the same number of columns for B and C. ' F"""Instead found B of size {shape_b} and C of size {shape_c}""" ) raise ValueError(a ) __A : str = pseudo_inv if a_inv is None: try: __A : Any = np.linalg.inv(a ) except np.linalg.LinAlgError: raise ValueError( 'Input matrix A is not invertible. Cannot compute Schur complement.' ) return mat_c - mat_b.T @ a_inv @ mat_b class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): __A : int = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) __A : Dict = np.array([[0, 3], [3, 0], [2, 3]] ) __A : str = np.array([[2, 1], [6, 3]] ) __A : Any = schur_complement(_A , _A , _A ) __A : int = np.block([[a, b], [b.T, c]] ) __A : List[Any] = np.linalg.det(_A ) __A : Optional[Any] = np.linalg.det(_A ) __A : List[str] = np.linalg.det(_A ) self.assertAlmostEqual(_A , det_a * det_s ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) __A : Any = np.array([[0, 3], [3, 0], [2, 3]] ) __A : Tuple = np.array([[2, 1], [6, 3]] ) with self.assertRaises(_A ): schur_complement(_A , _A , _A ) def UpperCAmelCase_ ( self ): __A : List[Any] = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) __A : int = np.array([[0, 3], [3, 0], [2, 3]] ) __A : List[Any] = np.array([[2, 1, 3], [6, 3, 5]] ) with self.assertRaises(_A ): schur_complement(_A , _A , _A ) if __name__ == "__main__": import doctest doctest.testmod() unittest.main()
280
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) UpperCAmelCase : Any = { '''configuration_falcon''': ['''FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''FalconConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Any = [ '''FALCON_PRETRAINED_MODEL_ARCHIVE_LIST''', '''FalconForCausalLM''', '''FalconModel''', '''FalconPreTrainedModel''', '''FalconForSequenceClassification''', '''FalconForTokenClassification''', '''FalconForQuestionAnswering''', ] if TYPE_CHECKING: from .configuration_falcon import FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP, FalconConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_falcon import ( FALCON_PRETRAINED_MODEL_ARCHIVE_LIST, FalconForCausalLM, FalconForQuestionAnswering, FalconForSequenceClassification, FalconForTokenClassification, FalconModel, FalconPreTrainedModel, ) else: import sys UpperCAmelCase : List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
280
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) UpperCAmelCase : List[Any] = { '''configuration_roberta_prelayernorm''': [ '''ROBERTA_PRELAYERNORM_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''RobertaPreLayerNormConfig''', '''RobertaPreLayerNormOnnxConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : List[Any] = [ '''ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''RobertaPreLayerNormForCausalLM''', '''RobertaPreLayerNormForMaskedLM''', '''RobertaPreLayerNormForMultipleChoice''', '''RobertaPreLayerNormForQuestionAnswering''', '''RobertaPreLayerNormForSequenceClassification''', '''RobertaPreLayerNormForTokenClassification''', '''RobertaPreLayerNormModel''', '''RobertaPreLayerNormPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Dict = [ '''TF_ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFRobertaPreLayerNormForCausalLM''', '''TFRobertaPreLayerNormForMaskedLM''', '''TFRobertaPreLayerNormForMultipleChoice''', '''TFRobertaPreLayerNormForQuestionAnswering''', '''TFRobertaPreLayerNormForSequenceClassification''', '''TFRobertaPreLayerNormForTokenClassification''', '''TFRobertaPreLayerNormMainLayer''', '''TFRobertaPreLayerNormModel''', '''TFRobertaPreLayerNormPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Dict = [ '''FlaxRobertaPreLayerNormForCausalLM''', '''FlaxRobertaPreLayerNormForMaskedLM''', '''FlaxRobertaPreLayerNormForMultipleChoice''', '''FlaxRobertaPreLayerNormForQuestionAnswering''', '''FlaxRobertaPreLayerNormForSequenceClassification''', '''FlaxRobertaPreLayerNormForTokenClassification''', '''FlaxRobertaPreLayerNormModel''', '''FlaxRobertaPreLayerNormPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_roberta_prelayernorm import ( ROBERTA_PRELAYERNORM_PRETRAINED_CONFIG_ARCHIVE_MAP, RobertaPreLayerNormConfig, RobertaPreLayerNormOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roberta_prelayernorm import ( ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST, RobertaPreLayerNormForCausalLM, RobertaPreLayerNormForMaskedLM, RobertaPreLayerNormForMultipleChoice, RobertaPreLayerNormForQuestionAnswering, RobertaPreLayerNormForSequenceClassification, RobertaPreLayerNormForTokenClassification, RobertaPreLayerNormModel, RobertaPreLayerNormPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roberta_prelayernorm import ( TF_ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST, TFRobertaPreLayerNormForCausalLM, TFRobertaPreLayerNormForMaskedLM, TFRobertaPreLayerNormForMultipleChoice, TFRobertaPreLayerNormForQuestionAnswering, TFRobertaPreLayerNormForSequenceClassification, TFRobertaPreLayerNormForTokenClassification, TFRobertaPreLayerNormMainLayer, TFRobertaPreLayerNormModel, TFRobertaPreLayerNormPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roberta_prelayernorm import ( FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormModel, FlaxRobertaPreLayerNormPreTrainedModel, ) else: import sys UpperCAmelCase : Optional[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
280
def _SCREAMING_SNAKE_CASE ( a ) -> bool: return str(a ) == str(a )[::-1] def _SCREAMING_SNAKE_CASE ( a ) -> int: return int(a ) + int(str(a )[::-1] ) def _SCREAMING_SNAKE_CASE ( a = 1_00_00 ) -> int: __A : int = [] for num in range(1 , a ): __A : List[str] = 0 __A : List[Any] = num while iterations < 50: __A : str = sum_reverse(a ) iterations += 1 if is_palindrome(a ): break else: lychrel_nums.append(a ) return len(a ) if __name__ == "__main__": print(F"""{solution() = }""")
280
1
def _SCREAMING_SNAKE_CASE ( a , a ) -> str: __A : int = len(a ) __A : int = len(a ) __A : int = ( first_str_length if first_str_length > second_str_length else second_str_length ) __A : list = [] for char_count in range(a ): if char_count < first_str_length: output_list.append(first_str[char_count] ) if char_count < second_str_length: output_list.append(second_str[char_count] ) return "".join(a ) if __name__ == "__main__": print(alternative_string_arrange('''AB''', '''XYZ'''), end=''' ''')
280
from __future__ import annotations import math import random from collections.abc import Collection from typing import overload class _A: """simple docstring""" def __init__( self , _A = None ): if components is None: __A : int = [] __A : Tuple = list(_A ) def __len__( self ): return len(self.__components ) def __str__( self ): return "(" + ",".join(map(_A , self.__components ) ) + ")" def __add__( self , _A ): __A : Optional[int] = len(self ) if size == len(_A ): __A : Any = [self.__components[i] + other.component(_A ) for i in range(_A )] return Vector(_A ) else: raise Exception('must have the same size' ) def __sub__( self , _A ): __A : Tuple = len(self ) if size == len(_A ): __A : Union[str, Any] = [self.__components[i] - other.component(_A ) for i in range(_A )] return Vector(_A ) else: # error case raise Exception('must have the same size' ) @overload def __mul__( self , _A ): ... @overload def __mul__( self , _A ): ... def __mul__( self , _A ): if isinstance(_A , (float, int) ): __A : str = [c * other for c in self.__components] return Vector(_A ) elif isinstance(_A , _A ) and len(self ) == len(_A ): __A : Union[str, Any] = len(self ) __A : Dict = [self.__components[i] * other.component(_A ) for i in range(_A )] return sum(_A ) else: # error case raise Exception('invalid operand!' ) def UpperCAmelCase_ ( self ): return Vector(self.__components ) def UpperCAmelCase_ ( self , _A ): if isinstance(_A , _A ) and -len(self.__components ) <= i < len(self.__components ): return self.__components[i] else: raise Exception('index out of range' ) def UpperCAmelCase_ ( self , _A , _A ): assert -len(self.__components ) <= pos < len(self.__components ) __A : Optional[int] = value def UpperCAmelCase_ ( self ): if len(self.__components ) == 0: raise Exception('Vector is empty' ) __A : Optional[Any] = [c**2 for c in self.__components] return math.sqrt(sum(_A ) ) def UpperCAmelCase_ ( self , _A , _A = False ): __A : Optional[Any] = self * other __A : Optional[Any] = self.euclidean_length() * other.euclidean_length() if deg: return math.degrees(math.acos(num / den ) ) else: return math.acos(num / den ) def _SCREAMING_SNAKE_CASE ( a ) -> Vector: assert isinstance(a , a ) return Vector([0] * dimension ) def _SCREAMING_SNAKE_CASE ( a , a ) -> Vector: assert isinstance(a , a ) and (isinstance(a , a )) __A : Optional[Any] = [0] * dimension __A : Tuple = 1 return Vector(a ) def _SCREAMING_SNAKE_CASE ( a , a , a ) -> Vector: assert ( isinstance(a , a ) and isinstance(a , a ) and (isinstance(a , (int, float) )) ) return x * scalar + y def _SCREAMING_SNAKE_CASE ( a , a , a ) -> Vector: random.seed(a ) __A : str = [random.randint(a , a ) for _ in range(a )] return Vector(a ) class _A: """simple docstring""" def __init__( self , _A , _A , _A ): __A : Optional[Any] = matrix __A : Dict = w __A : Optional[int] = h def __str__( self ): __A : Tuple = '' for i in range(self.__height ): ans += "|" for j in range(self.__width ): if j < self.__width - 1: ans += str(self.__matrix[i][j] ) + "," else: ans += str(self.__matrix[i][j] ) + "|\n" return ans def __add__( self , _A ): if self.__width == other.width() and self.__height == other.height(): __A : Optional[Any] = [] for i in range(self.__height ): __A : Optional[Any] = [ self.__matrix[i][j] + other.component(_A , _A ) for j in range(self.__width ) ] matrix.append(_A ) return Matrix(_A , self.__width , self.__height ) else: raise Exception('matrix must have the same dimension!' ) def __sub__( self , _A ): if self.__width == other.width() and self.__height == other.height(): __A : Tuple = [] for i in range(self.__height ): __A : str = [ self.__matrix[i][j] - other.component(_A , _A ) for j in range(self.__width ) ] matrix.append(_A ) return Matrix(_A , self.__width , self.__height ) else: raise Exception('matrices must have the same dimension!' ) @overload def __mul__( self , _A ): ... @overload def __mul__( self , _A ): ... def __mul__( self , _A ): if isinstance(_A , _A ): # matrix-vector if len(_A ) == self.__width: __A : List[Any] = zero_vector(self.__height ) for i in range(self.__height ): __A : List[str] = [ self.__matrix[i][j] * other.component(_A ) for j in range(self.__width ) ] ans.change_component(_A , sum(_A ) ) return ans else: raise Exception( 'vector must have the same size as the ' 'number of columns of the matrix!' ) elif isinstance(_A , (int, float) ): # matrix-scalar __A : List[str] = [ [self.__matrix[i][j] * other for j in range(self.__width )] for i in range(self.__height ) ] return Matrix(_A , self.__width , self.__height ) return None def UpperCAmelCase_ ( self ): return self.__height def UpperCAmelCase_ ( self ): return self.__width def UpperCAmelCase_ ( self , _A , _A ): if 0 <= x < self.__height and 0 <= y < self.__width: return self.__matrix[x][y] else: raise Exception('change_component: indices out of bounds' ) def UpperCAmelCase_ ( self , _A , _A , _A ): if 0 <= x < self.__height and 0 <= y < self.__width: __A : int = value else: raise Exception('change_component: indices out of bounds' ) def UpperCAmelCase_ ( self , _A , _A ): if self.__height != self.__width: raise Exception('Matrix is not square' ) __A : List[str] = self.__matrix[:x] + self.__matrix[x + 1 :] for i in range(len(_A ) ): __A : Optional[int] = minor[i][:y] + minor[i][y + 1 :] return Matrix(_A , self.__width - 1 , self.__height - 1 ).determinant() def UpperCAmelCase_ ( self , _A , _A ): if self.__height != self.__width: raise Exception('Matrix is not square' ) if 0 <= x < self.__height and 0 <= y < self.__width: return (-1) ** (x + y) * self.minor(_A , _A ) else: raise Exception('Indices out of bounds' ) def UpperCAmelCase_ ( self ): if self.__height != self.__width: raise Exception('Matrix is not square' ) if self.__height < 1: raise Exception('Matrix has no element' ) elif self.__height == 1: return self.__matrix[0][0] elif self.__height == 2: return ( self.__matrix[0][0] * self.__matrix[1][1] - self.__matrix[0][1] * self.__matrix[1][0] ) else: __A : List[str] = [ self.__matrix[0][y] * self.cofactor(0 , _A ) for y in range(self.__width ) ] return sum(_A ) def _SCREAMING_SNAKE_CASE ( a ) -> Matrix: __A : list[list[float]] = [[0] * n for _ in range(a )] return Matrix(a , a , a ) def _SCREAMING_SNAKE_CASE ( a , a , a , a ) -> Matrix: random.seed(a ) __A : list[list[float]] = [ [random.randint(a , a ) for _ in range(a )] for _ in range(a ) ] return Matrix(a , a , a )
280
1
from __future__ import annotations import math import random from typing import Any class _A: """simple docstring""" def __init__( self ): __A : list[Any] = [] __A : int = 0 __A : int = 0 def UpperCAmelCase_ ( self ): return self.head == self.tail def UpperCAmelCase_ ( self , _A ): self.data.append(_A ) __A : List[str] = self.tail + 1 def UpperCAmelCase_ ( self ): __A : List[str] = self.data[self.head] __A : Tuple = self.head + 1 return ret def UpperCAmelCase_ ( self ): return self.tail - self.head def UpperCAmelCase_ ( self ): print(self.data ) print('**************' ) print(self.data[self.head : self.tail] ) class _A: """simple docstring""" def __init__( self , _A ): __A : Any = data __A : MyNode | None = None __A : MyNode | None = None __A : int = 1 def UpperCAmelCase_ ( self ): return self.data def UpperCAmelCase_ ( self ): return self.left def UpperCAmelCase_ ( self ): return self.right def UpperCAmelCase_ ( self ): return self.height def UpperCAmelCase_ ( self , _A ): __A : Dict = data def UpperCAmelCase_ ( self , _A ): __A : Optional[int] = node def UpperCAmelCase_ ( self , _A ): __A : List[str] = node def UpperCAmelCase_ ( self , _A ): __A : int = height def _SCREAMING_SNAKE_CASE ( a ) -> int: if node is None: return 0 return node.get_height() def _SCREAMING_SNAKE_CASE ( a , a ) -> int: if a > b: return a return b def _SCREAMING_SNAKE_CASE ( a ) -> MyNode: print('left rotation node:' , node.get_data() ) __A : int = node.get_left() assert ret is not None node.set_left(ret.get_right() ) ret.set_right(a ) __A : List[Any] = my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(a ) __A : int = my_max(get_height(ret.get_right() ) , get_height(ret.get_left() ) ) + 1 ret.set_height(a ) return ret def _SCREAMING_SNAKE_CASE ( a ) -> MyNode: print('right rotation node:' , node.get_data() ) __A : Optional[int] = node.get_right() assert ret is not None node.set_right(ret.get_left() ) ret.set_left(a ) __A : Dict = my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(a ) __A : Tuple = my_max(get_height(ret.get_right() ) , get_height(ret.get_left() ) ) + 1 ret.set_height(a ) return ret def _SCREAMING_SNAKE_CASE ( a ) -> MyNode: __A : List[Any] = node.get_left() assert left_child is not None node.set_left(left_rotation(a ) ) return right_rotation(a ) def _SCREAMING_SNAKE_CASE ( a ) -> MyNode: __A : Tuple = node.get_right() assert right_child is not None node.set_right(right_rotation(a ) ) return left_rotation(a ) def _SCREAMING_SNAKE_CASE ( a , a ) -> MyNode | None: if node is None: return MyNode(a ) if data < node.get_data(): node.set_left(insert_node(node.get_left() , a ) ) if ( get_height(node.get_left() ) - get_height(node.get_right() ) == 2 ): # an unbalance detected __A : Optional[Any] = node.get_left() assert left_child is not None if ( data < left_child.get_data() ): # new node is the left child of the left child __A : Optional[Any] = right_rotation(a ) else: __A : Optional[Any] = lr_rotation(a ) else: node.set_right(insert_node(node.get_right() , a ) ) if get_height(node.get_right() ) - get_height(node.get_left() ) == 2: __A : Tuple = node.get_right() assert right_child is not None if data < right_child.get_data(): __A : int = rl_rotation(a ) else: __A : int = left_rotation(a ) __A : Any = my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(a ) return node def _SCREAMING_SNAKE_CASE ( a ) -> Any: while True: __A : int = root.get_right() if right_child is None: break __A : Any = right_child return root.get_data() def _SCREAMING_SNAKE_CASE ( a ) -> Any: while True: __A : Tuple = root.get_left() if left_child is None: break __A : str = left_child return root.get_data() def _SCREAMING_SNAKE_CASE ( a , a ) -> MyNode | None: __A : str = root.get_left() __A : List[str] = root.get_right() if root.get_data() == data: if left_child is not None and right_child is not None: __A : str = get_left_most(a ) root.set_data(a ) root.set_right(del_node(a , a ) ) elif left_child is not None: __A : Any = left_child elif right_child is not None: __A : Tuple = right_child else: return None elif root.get_data() > data: if left_child is None: print('No such data' ) return root else: root.set_left(del_node(a , a ) ) else: # root.get_data() < data if right_child is None: return root else: root.set_right(del_node(a , a ) ) if get_height(a ) - get_height(a ) == 2: assert right_child is not None if get_height(right_child.get_right() ) > get_height(right_child.get_left() ): __A : Any = left_rotation(a ) else: __A : str = rl_rotation(a ) elif get_height(a ) - get_height(a ) == -2: assert left_child is not None if get_height(left_child.get_left() ) > get_height(left_child.get_right() ): __A : Union[str, Any] = right_rotation(a ) else: __A : Any = lr_rotation(a ) __A : Dict = my_max(get_height(root.get_right() ) , get_height(root.get_left() ) ) + 1 root.set_height(a ) return root class _A: """simple docstring""" def __init__( self ): __A : MyNode | None = None def UpperCAmelCase_ ( self ): return get_height(self.root ) def UpperCAmelCase_ ( self , _A ): print('insert:' + str(_A ) ) __A : int = insert_node(self.root , _A ) def UpperCAmelCase_ ( self , _A ): print('delete:' + str(_A ) ) if self.root is None: print('Tree is empty!' ) return __A : Optional[int] = del_node(self.root , _A ) def __str__( self , ): # a level traversale, gives a more intuitive look on the tree __A : Dict = '' __A : Optional[Any] = MyQueue() q.push(self.root ) __A : Dict = self.get_height() if layer == 0: return output __A : List[Any] = 0 while not q.is_empty(): __A : Optional[Any] = q.pop() __A : Optional[Any] = ' ' * int(math.pow(2 , layer - 1 ) ) output += space if node is None: output += "*" q.push(_A ) q.push(_A ) else: output += str(node.get_data() ) q.push(node.get_left() ) q.push(node.get_right() ) output += space __A : str = cnt + 1 for i in range(100 ): if cnt == math.pow(2 , _A ) - 1: __A : Any = layer - 1 if layer == 0: output += "\n*************************************" return output output += "\n" break output += "\n*************************************" return output def _SCREAMING_SNAKE_CASE ( ) -> None: import doctest doctest.testmod() if __name__ == "__main__": _test() UpperCAmelCase : Optional[int] = AVLtree() UpperCAmelCase : Any = list(range(10)) random.shuffle(lst) for i in lst: t.insert(i) print(str(t)) random.shuffle(lst) for i in lst: t.del_node(i) print(str(t))
280
import unittest from transformers import BertGenerationTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin UpperCAmelCase : List[str] = '''▁''' UpperCAmelCase : Optional[Any] = get_tests_dir('''fixtures/test_sentencepiece.model''') @require_sentencepiece class _A( snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Optional[int] = BertGenerationTokenizer UpperCamelCase : str = False UpperCamelCase : Tuple = True def UpperCAmelCase_ ( self ): super().setUp() __A : Tuple = BertGenerationTokenizer(_A , keep_accents=_A ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCAmelCase_ ( self ): __A : str = '<s>' __A : str = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_A ) , _A ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_A ) , _A ) def UpperCAmelCase_ ( self ): __A : int = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<unk>' ) self.assertEqual(vocab_keys[1] , '<s>' ) self.assertEqual(vocab_keys[-1] , '<pad>' ) self.assertEqual(len(_A ) , 1002 ) def UpperCAmelCase_ ( self ): self.assertEqual(self.get_tokenizer().vocab_size , 1000 ) def UpperCAmelCase_ ( self ): __A : str = BertGenerationTokenizer(_A , keep_accents=_A ) __A : Dict = tokenizer.tokenize('This is a test' ) self.assertListEqual(_A , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(_A ) , [285, 46, 10, 170, 382] , ) __A : int = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( _A , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.', ] , ) __A : Dict = tokenizer.convert_tokens_to_ids(_A ) self.assertListEqual( _A , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] , ) __A : Optional[int] = tokenizer.convert_ids_to_tokens(_A ) self.assertListEqual( _A , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.', ] , ) @cached_property def UpperCAmelCase_ ( self ): return BertGenerationTokenizer.from_pretrained('google/bert_for_seq_generation_L-24_bbc_encoder' ) @slow def UpperCAmelCase_ ( self ): __A : List[Any] = 'Hello World!' __A : Optional[Any] = [18536, 2260, 101] self.assertListEqual(_A , self.big_tokenizer.encode(_A ) ) @slow def UpperCAmelCase_ ( self ): __A : Dict = ( 'This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will' ' add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth' ) __A : int = [ 871, 419, 358, 946, 991, 2521, 452, 358, 1357, 387, 7751, 3536, 112, 985, 456, 126, 865, 938, 5400, 5734, 458, 1368, 467, 786, 2462, 5246, 1159, 633, 865, 4519, 457, 582, 852, 2557, 427, 916, 508, 405, 34324, 497, 391, 408, 11342, 1244, 385, 100, 938, 985, 456, 574, 362, 12597, 3200, 3129, 1172, ] self.assertListEqual(_A , self.big_tokenizer.encode(_A ) ) @require_torch @slow def UpperCAmelCase_ ( self ): import torch from transformers import BertGenerationConfig, BertGenerationEncoder # Build sequence __A : Tuple = list(self.big_tokenizer.get_vocab().keys() )[:10] __A : List[Any] = ' '.join(_A ) __A : Union[str, Any] = self.big_tokenizer.encode_plus(_A , return_tensors='pt' , return_token_type_ids=_A ) __A : Optional[Any] = self.big_tokenizer.batch_encode_plus( [sequence + ' ' + sequence] , return_tensors='pt' , return_token_type_ids=_A ) __A : int = BertGenerationConfig() __A : List[str] = BertGenerationEncoder(_A ) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**_A ) model(**_A ) @slow def UpperCAmelCase_ ( self ): # fmt: off __A : str = {'input_ids': [[39286, 458, 36335, 2001, 456, 13073, 13266, 455, 113, 7746, 1741, 11157, 391, 13073, 13266, 455, 113, 3967, 35412, 113, 4936, 109, 3870, 2377, 113, 30084, 45720, 458, 134, 17496, 112, 503, 11672, 113, 118, 112, 5665, 13347, 38687, 112, 1496, 31389, 112, 3268, 47264, 134, 962, 112, 16377, 8035, 23130, 430, 12169, 15518, 28592, 458, 146, 41697, 109, 391, 12169, 15518, 16689, 458, 146, 41358, 109, 452, 726, 4034, 111, 763, 35412, 5082, 388, 1903, 111, 9051, 391, 2870, 48918, 1900, 1123, 550, 998, 112, 9586, 15985, 455, 391, 410, 22955, 37636, 114], [448, 17496, 419, 3663, 385, 763, 113, 27533, 2870, 3283, 13043, 1639, 24713, 523, 656, 24013, 18550, 2521, 517, 27014, 21244, 420, 1212, 1465, 391, 927, 4833, 388, 578, 11786, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [484, 2169, 7687, 21932, 18146, 726, 363, 17032, 3391, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=_A , model_name='google/bert_for_seq_generation_L-24_bbc_encoder' , revision='c817d1fd1be2ffa69431227a1fe320544943d4db' , )
280
1
import hashlib import unittest from typing import Dict import numpy as np from transformers import ( MODEL_FOR_MASK_GENERATION_MAPPING, TF_MODEL_FOR_MASK_GENERATION_MAPPING, is_vision_available, pipeline, ) from transformers.pipelines import MaskGenerationPipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) if is_vision_available(): from PIL import Image else: class _A: """simple docstring""" @staticmethod def UpperCAmelCase_ ( *_A , **_A ): pass def _SCREAMING_SNAKE_CASE ( a ) -> str: __A : str = hashlib.mda(image.tobytes() ) return m.hexdigest()[:10] def _SCREAMING_SNAKE_CASE ( a ) -> Dict: __A : Dict = np.array(a ) __A : List[Any] = npimg.shape return {"hash": hashimage(a ), "shape": shape} @is_pipeline_test @require_vision @require_torch class _A( unittest.TestCase ): """simple docstring""" UpperCamelCase : str = dict( (list(MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if MODEL_FOR_MASK_GENERATION_MAPPING else []) ) UpperCamelCase : int = dict( (list(TF_MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if TF_MODEL_FOR_MASK_GENERATION_MAPPING else []) ) def UpperCAmelCase_ ( self , _A , _A , _A ): __A : Dict = MaskGenerationPipeline(model=_A , image_processor=_A ) return image_segmenter, [ "./tests/fixtures/tests_samples/COCO/000000039769.png", "./tests/fixtures/tests_samples/COCO/000000039769.png", ] def UpperCAmelCase_ ( self , _A , _A ): pass @require_tf @unittest.skip('Image segmentation not implemented in TF' ) def UpperCAmelCase_ ( self ): pass @slow @require_torch def UpperCAmelCase_ ( self ): __A : Union[str, Any] = pipeline('mask-generation' , model='facebook/sam-vit-huge' ) __A : List[str] = image_segmenter('http://images.cocodataset.org/val2017/000000039769.jpg' , points_per_batch=256 ) # Shortening by hashing __A : List[Any] = [] for i, o in enumerate(outputs['masks'] ): new_outupt += [{"mask": mask_to_test_readable(_A ), "scores": outputs["scores"][i]}] # fmt: off self.assertEqual( nested_simplify(_A , decimals=4 ) , [ {'mask': {'hash': '115ad19f5f', 'shape': (480, 640)}, 'scores': 1.0_4_4_4}, {'mask': {'hash': '6affa964c6', 'shape': (480, 640)}, 'scores': 1.0_2_1}, {'mask': {'hash': 'dfe28a0388', 'shape': (480, 640)}, 'scores': 1.0_1_6_7}, {'mask': {'hash': 'c0a5f4a318', 'shape': (480, 640)}, 'scores': 1.0_1_3_2}, {'mask': {'hash': 'fe8065c197', 'shape': (480, 640)}, 'scores': 1.0_0_5_3}, {'mask': {'hash': 'e2d0b7a0b7', 'shape': (480, 640)}, 'scores': 0.9_9_6_7}, {'mask': {'hash': '453c7844bd', 'shape': (480, 640)}, 'scores': 0.9_9_3}, {'mask': {'hash': '3d44f2926d', 'shape': (480, 640)}, 'scores': 0.9_9_0_9}, {'mask': {'hash': '64033ddc3f', 'shape': (480, 640)}, 'scores': 0.9_8_7_9}, {'mask': {'hash': '801064ff79', 'shape': (480, 640)}, 'scores': 0.9_8_3_4}, {'mask': {'hash': '6172f276ef', 'shape': (480, 640)}, 'scores': 0.9_7_1_6}, {'mask': {'hash': 'b49e60e084', 'shape': (480, 640)}, 'scores': 0.9_6_1_2}, {'mask': {'hash': 'a811e775fd', 'shape': (480, 640)}, 'scores': 0.9_5_9_9}, {'mask': {'hash': 'a6a8ebcf4b', 'shape': (480, 640)}, 'scores': 0.9_5_5_2}, {'mask': {'hash': '9d8257e080', 'shape': (480, 640)}, 'scores': 0.9_5_3_2}, {'mask': {'hash': '32de6454a8', 'shape': (480, 640)}, 'scores': 0.9_5_1_6}, {'mask': {'hash': 'af3d4af2c8', 'shape': (480, 640)}, 'scores': 0.9_4_9_9}, {'mask': {'hash': '3c6db475fb', 'shape': (480, 640)}, 'scores': 0.9_4_8_3}, {'mask': {'hash': 'c290813fb9', 'shape': (480, 640)}, 'scores': 0.9_4_6_4}, {'mask': {'hash': 'b6f0b8f606', 'shape': (480, 640)}, 'scores': 0.9_4_3}, {'mask': {'hash': '92ce16bfdf', 'shape': (480, 640)}, 'scores': 0.9_4_3}, {'mask': {'hash': 'c749b25868', 'shape': (480, 640)}, 'scores': 0.9_4_0_8}, {'mask': {'hash': 'efb6cab859', 'shape': (480, 640)}, 'scores': 0.9_3_3_5}, {'mask': {'hash': '1ff2eafb30', 'shape': (480, 640)}, 'scores': 0.9_3_2_6}, {'mask': {'hash': '788b798e24', 'shape': (480, 640)}, 'scores': 0.9_2_6_2}, {'mask': {'hash': 'abea804f0e', 'shape': (480, 640)}, 'scores': 0.8_9_9_9}, {'mask': {'hash': '7b9e8ddb73', 'shape': (480, 640)}, 'scores': 0.8_9_8_6}, {'mask': {'hash': 'cd24047c8a', 'shape': (480, 640)}, 'scores': 0.8_9_8_4}, {'mask': {'hash': '6943e6bcbd', 'shape': (480, 640)}, 'scores': 0.8_8_7_3}, {'mask': {'hash': 'b5f47c9191', 'shape': (480, 640)}, 'scores': 0.8_8_7_1} ] , ) # fmt: on @require_torch @slow def UpperCAmelCase_ ( self ): __A : Optional[Any] = 'facebook/sam-vit-huge' __A : List[str] = pipeline('mask-generation' , model=_A ) __A : Tuple = image_segmenter( 'http://images.cocodataset.org/val2017/000000039769.jpg' , pred_iou_thresh=1 , points_per_batch=256 ) # Shortening by hashing __A : List[str] = [] for i, o in enumerate(outputs['masks'] ): new_outupt += [{"mask": mask_to_test_readable(_A ), "scores": outputs["scores"][i]}] self.assertEqual( nested_simplify(_A , decimals=4 ) , [ {'mask': {'hash': '115ad19f5f', 'shape': (480, 640)}, 'scores': 1.0_4_4_4}, {'mask': {'hash': '6affa964c6', 'shape': (480, 640)}, 'scores': 1.0_2_1_0}, {'mask': {'hash': 'dfe28a0388', 'shape': (480, 640)}, 'scores': 1.0_1_6_7}, {'mask': {'hash': 'c0a5f4a318', 'shape': (480, 640)}, 'scores': 1.0_1_3_2}, {'mask': {'hash': 'fe8065c197', 'shape': (480, 640)}, 'scores': 1.0_0_5_3}, ] , )
280
import hashlib import unittest from typing import Dict import numpy as np from transformers import ( MODEL_FOR_MASK_GENERATION_MAPPING, TF_MODEL_FOR_MASK_GENERATION_MAPPING, is_vision_available, pipeline, ) from transformers.pipelines import MaskGenerationPipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) if is_vision_available(): from PIL import Image else: class _A: """simple docstring""" @staticmethod def UpperCAmelCase_ ( *_A , **_A ): pass def _SCREAMING_SNAKE_CASE ( a ) -> str: __A : str = hashlib.mda(image.tobytes() ) return m.hexdigest()[:10] def _SCREAMING_SNAKE_CASE ( a ) -> Dict: __A : Dict = np.array(a ) __A : List[Any] = npimg.shape return {"hash": hashimage(a ), "shape": shape} @is_pipeline_test @require_vision @require_torch class _A( unittest.TestCase ): """simple docstring""" UpperCamelCase : str = dict( (list(MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if MODEL_FOR_MASK_GENERATION_MAPPING else []) ) UpperCamelCase : int = dict( (list(TF_MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if TF_MODEL_FOR_MASK_GENERATION_MAPPING else []) ) def UpperCAmelCase_ ( self , _A , _A , _A ): __A : Dict = MaskGenerationPipeline(model=_A , image_processor=_A ) return image_segmenter, [ "./tests/fixtures/tests_samples/COCO/000000039769.png", "./tests/fixtures/tests_samples/COCO/000000039769.png", ] def UpperCAmelCase_ ( self , _A , _A ): pass @require_tf @unittest.skip('Image segmentation not implemented in TF' ) def UpperCAmelCase_ ( self ): pass @slow @require_torch def UpperCAmelCase_ ( self ): __A : Union[str, Any] = pipeline('mask-generation' , model='facebook/sam-vit-huge' ) __A : List[str] = image_segmenter('http://images.cocodataset.org/val2017/000000039769.jpg' , points_per_batch=256 ) # Shortening by hashing __A : List[Any] = [] for i, o in enumerate(outputs['masks'] ): new_outupt += [{"mask": mask_to_test_readable(_A ), "scores": outputs["scores"][i]}] # fmt: off self.assertEqual( nested_simplify(_A , decimals=4 ) , [ {'mask': {'hash': '115ad19f5f', 'shape': (480, 640)}, 'scores': 1.0_4_4_4}, {'mask': {'hash': '6affa964c6', 'shape': (480, 640)}, 'scores': 1.0_2_1}, {'mask': {'hash': 'dfe28a0388', 'shape': (480, 640)}, 'scores': 1.0_1_6_7}, {'mask': {'hash': 'c0a5f4a318', 'shape': (480, 640)}, 'scores': 1.0_1_3_2}, {'mask': {'hash': 'fe8065c197', 'shape': (480, 640)}, 'scores': 1.0_0_5_3}, {'mask': {'hash': 'e2d0b7a0b7', 'shape': (480, 640)}, 'scores': 0.9_9_6_7}, {'mask': {'hash': '453c7844bd', 'shape': (480, 640)}, 'scores': 0.9_9_3}, {'mask': {'hash': '3d44f2926d', 'shape': (480, 640)}, 'scores': 0.9_9_0_9}, {'mask': {'hash': '64033ddc3f', 'shape': (480, 640)}, 'scores': 0.9_8_7_9}, {'mask': {'hash': '801064ff79', 'shape': (480, 640)}, 'scores': 0.9_8_3_4}, {'mask': {'hash': '6172f276ef', 'shape': (480, 640)}, 'scores': 0.9_7_1_6}, {'mask': {'hash': 'b49e60e084', 'shape': (480, 640)}, 'scores': 0.9_6_1_2}, {'mask': {'hash': 'a811e775fd', 'shape': (480, 640)}, 'scores': 0.9_5_9_9}, {'mask': {'hash': 'a6a8ebcf4b', 'shape': (480, 640)}, 'scores': 0.9_5_5_2}, {'mask': {'hash': '9d8257e080', 'shape': (480, 640)}, 'scores': 0.9_5_3_2}, {'mask': {'hash': '32de6454a8', 'shape': (480, 640)}, 'scores': 0.9_5_1_6}, {'mask': {'hash': 'af3d4af2c8', 'shape': (480, 640)}, 'scores': 0.9_4_9_9}, {'mask': {'hash': '3c6db475fb', 'shape': (480, 640)}, 'scores': 0.9_4_8_3}, {'mask': {'hash': 'c290813fb9', 'shape': (480, 640)}, 'scores': 0.9_4_6_4}, {'mask': {'hash': 'b6f0b8f606', 'shape': (480, 640)}, 'scores': 0.9_4_3}, {'mask': {'hash': '92ce16bfdf', 'shape': (480, 640)}, 'scores': 0.9_4_3}, {'mask': {'hash': 'c749b25868', 'shape': (480, 640)}, 'scores': 0.9_4_0_8}, {'mask': {'hash': 'efb6cab859', 'shape': (480, 640)}, 'scores': 0.9_3_3_5}, {'mask': {'hash': '1ff2eafb30', 'shape': (480, 640)}, 'scores': 0.9_3_2_6}, {'mask': {'hash': '788b798e24', 'shape': (480, 640)}, 'scores': 0.9_2_6_2}, {'mask': {'hash': 'abea804f0e', 'shape': (480, 640)}, 'scores': 0.8_9_9_9}, {'mask': {'hash': '7b9e8ddb73', 'shape': (480, 640)}, 'scores': 0.8_9_8_6}, {'mask': {'hash': 'cd24047c8a', 'shape': (480, 640)}, 'scores': 0.8_9_8_4}, {'mask': {'hash': '6943e6bcbd', 'shape': (480, 640)}, 'scores': 0.8_8_7_3}, {'mask': {'hash': 'b5f47c9191', 'shape': (480, 640)}, 'scores': 0.8_8_7_1} ] , ) # fmt: on @require_torch @slow def UpperCAmelCase_ ( self ): __A : Optional[Any] = 'facebook/sam-vit-huge' __A : List[str] = pipeline('mask-generation' , model=_A ) __A : Tuple = image_segmenter( 'http://images.cocodataset.org/val2017/000000039769.jpg' , pred_iou_thresh=1 , points_per_batch=256 ) # Shortening by hashing __A : List[str] = [] for i, o in enumerate(outputs['masks'] ): new_outupt += [{"mask": mask_to_test_readable(_A ), "scores": outputs["scores"][i]}] self.assertEqual( nested_simplify(_A , decimals=4 ) , [ {'mask': {'hash': '115ad19f5f', 'shape': (480, 640)}, 'scores': 1.0_4_4_4}, {'mask': {'hash': '6affa964c6', 'shape': (480, 640)}, 'scores': 1.0_2_1_0}, {'mask': {'hash': 'dfe28a0388', 'shape': (480, 640)}, 'scores': 1.0_1_6_7}, {'mask': {'hash': 'c0a5f4a318', 'shape': (480, 640)}, 'scores': 1.0_1_3_2}, {'mask': {'hash': 'fe8065c197', 'shape': (480, 640)}, 'scores': 1.0_0_5_3}, ] , )
280
1
from __future__ import annotations def _SCREAMING_SNAKE_CASE ( a , a ) -> list[tuple[int, int]]: __A , __A : Optional[Any] = position __A : Union[str, Any] = [ (y + 1, x + 2), (y - 1, x + 2), (y + 1, x - 2), (y - 1, x - 2), (y + 2, x + 1), (y + 2, x - 1), (y - 2, x + 1), (y - 2, x - 1), ] __A : int = [] for position in positions: __A , __A : Tuple = position if 0 <= y_test < n and 0 <= x_test < n: permissible_positions.append(a ) return permissible_positions def _SCREAMING_SNAKE_CASE ( a ) -> bool: return not any(elem == 0 for row in board for elem in row ) def _SCREAMING_SNAKE_CASE ( a , a , a ) -> bool: if is_complete(a ): return True for position in get_valid_pos(a , len(a ) ): __A , __A : Any = position if board[y][x] == 0: __A : List[str] = curr + 1 if open_knight_tour_helper(a , a , curr + 1 ): return True __A : Optional[Any] = 0 return False def _SCREAMING_SNAKE_CASE ( a ) -> list[list[int]]: __A : Optional[int] = [[0 for i in range(a )] for j in range(a )] for i in range(a ): for j in range(a ): __A : Optional[Any] = 1 if open_knight_tour_helper(a , (i, j) , 1 ): return board __A : Any = 0 __A : List[str] = F"""Open Kight Tour cannot be performed on a board of size {n}""" raise ValueError(a ) if __name__ == "__main__": import doctest doctest.testmod()
280
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import OwlViTImageProcessor, OwlViTProcessor @require_vision class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): __A : List[Any] = tempfile.mkdtemp() # fmt: off __A : List[str] = ['', 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'lo', 'l</w>', 'w</w>', 'r</w>', 't</w>', 'low</w>', 'er</w>', 'lowest</w>', 'newer</w>', 'wider', '<unk>', '<|startoftext|>', '<|endoftext|>'] # fmt: on __A : Union[str, Any] = dict(zip(_A , range(len(_A ) ) ) ) __A : Optional[int] = ['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>', ''] __A : int = {'unk_token': '<unk>'} __A : Optional[int] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) __A : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(_A ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(_A ) ) __A : List[Any] = { 'do_resize': True, 'size': 20, 'do_center_crop': True, 'crop_size': 18, 'do_normalize': True, 'image_mean': [0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3], 'image_std': [0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1], } __A : Optional[int] = os.path.join(self.tmpdirname , _A ) with open(self.image_processor_file , 'w' , encoding='utf-8' ) as fp: json.dump(_A , _A ) def UpperCAmelCase_ ( self , **_A ): return CLIPTokenizer.from_pretrained(self.tmpdirname , pad_token='!' , **_A ) def UpperCAmelCase_ ( self , **_A ): return CLIPTokenizerFast.from_pretrained(self.tmpdirname , pad_token='!' , **_A ) def UpperCAmelCase_ ( self , **_A ): return OwlViTImageProcessor.from_pretrained(self.tmpdirname , **_A ) def UpperCAmelCase_ ( self ): shutil.rmtree(self.tmpdirname ) def UpperCAmelCase_ ( self ): __A : int = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __A : Optional[int] = [Image.fromarray(np.moveaxis(_A , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCAmelCase_ ( self ): __A : List[Any] = self.get_tokenizer() __A : str = self.get_rust_tokenizer() __A : List[str] = self.get_image_processor() __A : Optional[int] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) processor_slow.save_pretrained(self.tmpdirname ) __A : int = OwlViTProcessor.from_pretrained(self.tmpdirname , use_fast=_A ) __A : Optional[Any] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) processor_fast.save_pretrained(self.tmpdirname ) __A : Optional[Any] = OwlViTProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , _A ) self.assertIsInstance(processor_fast.tokenizer , _A ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , _A ) self.assertIsInstance(processor_fast.image_processor , _A ) def UpperCAmelCase_ ( self ): __A : List[str] = OwlViTProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __A : Optional[int] = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) __A : Optional[int] = self.get_image_processor(do_normalize=_A ) __A : Any = OwlViTProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=_A ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , _A ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _A ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.get_image_processor() __A : Optional[Any] = self.get_tokenizer() __A : Union[str, Any] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Union[str, Any] = self.prepare_image_inputs() __A : int = image_processor(_A , return_tensors='np' ) __A : str = processor(images=_A , return_tensors='np' ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1e-2 ) def UpperCAmelCase_ ( self ): __A : str = self.get_image_processor() __A : str = self.get_tokenizer() __A : Tuple = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : str = 'lower newer' __A : str = processor(text=_A , return_tensors='np' ) __A : List[str] = tokenizer(_A , return_tensors='np' ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key][0].tolist() , encoded_processor[key][0].tolist() ) def UpperCAmelCase_ ( self ): __A : int = self.get_image_processor() __A : Optional[int] = self.get_tokenizer() __A : List[str] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Any = 'lower newer' __A : Optional[Any] = self.prepare_image_inputs() __A : List[Any] = processor(text=_A , images=_A ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Any = 'google/owlvit-base-patch32' __A : int = OwlViTProcessor.from_pretrained(_A ) __A : Dict = ['cat', 'nasa badge'] __A : Optional[Any] = processor(text=_A ) __A : Optional[int] = 16 self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (2, seq_length) ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Tuple = 'google/owlvit-base-patch32' __A : Any = OwlViTProcessor.from_pretrained(_A ) __A : Dict = [['cat', 'nasa badge'], ['person']] __A : Dict = processor(text=_A ) __A : Optional[int] = 16 __A : Any = len(_A ) __A : Union[str, Any] = max([len(_A ) for texts in input_texts] ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (batch_size * num_max_text_queries, seq_length) ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : List[Any] = 'google/owlvit-base-patch32' __A : str = OwlViTProcessor.from_pretrained(_A ) __A : Union[str, Any] = ['cat', 'nasa badge'] __A : Tuple = processor(text=_A ) __A : str = 16 __A : int = inputs['input_ids'] __A : List[Any] = [ [49406, 2368, 49407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [49406, 6841, 11301, 49407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (2, seq_length) ) self.assertListEqual(list(input_ids[0] ) , predicted_ids[0] ) self.assertListEqual(list(input_ids[1] ) , predicted_ids[1] ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.get_image_processor() __A : List[str] = self.get_tokenizer() __A : Optional[Any] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Optional[int] = self.prepare_image_inputs() __A : Optional[int] = self.prepare_image_inputs() __A : Optional[int] = processor(images=_A , query_images=_A ) self.assertListEqual(list(inputs.keys() ) , ['query_pixel_values', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.get_image_processor() __A : Union[str, Any] = self.get_tokenizer() __A : str = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Optional[Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __A : Any = processor.batch_decode(_A ) __A : Tuple = tokenizer.batch_decode(_A ) self.assertListEqual(_A , _A )
280
1
def _SCREAMING_SNAKE_CASE ( a ) -> str: return " ".join( ''.join(word[::-1] ) if len(a ) > 4 else word for word in sentence.split() ) if __name__ == "__main__": import doctest doctest.testmod() print(reverse_long_words('''Hey wollef sroirraw'''))
280
import math def _SCREAMING_SNAKE_CASE ( a ) -> list[int]: __A : List[str] = [] __A : Any = 2 __A : Union[str, Any] = int(math.sqrt(a ) ) # Size of every segment __A : Any = [True] * (end + 1) __A : List[Any] = [] while start <= end: if temp[start] is True: in_prime.append(a ) for i in range(start * start , end + 1 , a ): __A : Optional[int] = False start += 1 prime += in_prime __A : Any = end + 1 __A : Any = min(2 * end , a ) while low <= n: __A : List[Any] = [True] * (high - low + 1) for each in in_prime: __A : List[str] = math.floor(low / each ) * each if t < low: t += each for j in range(a , high + 1 , a ): __A : Optional[int] = False for j in range(len(a ) ): if temp[j] is True: prime.append(j + low ) __A : Optional[int] = high + 1 __A : Tuple = min(high + end , a ) return prime print(sieve(10**6))
280
1
from __future__ import annotations def _SCREAMING_SNAKE_CASE ( a , a , a ) -> int | float: if len(a ) == 0: raise ValueError('find_max() arg is an empty sequence' ) if ( left >= len(a ) or left < -len(a ) or right >= len(a ) or right < -len(a ) ): raise IndexError('list index out of range' ) if left == right: return nums[left] __A : str = (left + right) >> 1 # the middle __A : str = find_max(a , a , a ) # find max in range[left, mid] __A : Union[str, Any] = find_max(a , mid + 1 , a ) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
280
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available UpperCAmelCase : Any = { '''configuration_mvp''': ['''MVP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MvpConfig''', '''MvpOnnxConfig'''], '''tokenization_mvp''': ['''MvpTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : int = ['''MvpTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : str = [ '''MVP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MvpForCausalLM''', '''MvpForConditionalGeneration''', '''MvpForQuestionAnswering''', '''MvpForSequenceClassification''', '''MvpModel''', '''MvpPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_mvp import MVP_PRETRAINED_CONFIG_ARCHIVE_MAP, MvpConfig, MvpOnnxConfig from .tokenization_mvp import MvpTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mvp_fast import MvpTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mvp import ( MVP_PRETRAINED_MODEL_ARCHIVE_LIST, MvpForCausalLM, MvpForConditionalGeneration, MvpForQuestionAnswering, MvpForSequenceClassification, MvpModel, MvpPreTrainedModel, ) else: import sys UpperCAmelCase : List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
280
1
def _SCREAMING_SNAKE_CASE ( a , a , a , a , a , a ) -> Dict: if index == r: for j in range(a ): print(data[j] , end=' ' ) print(' ' ) return # When no more elements are there to put in data[] if i >= n: return # current is included, put next at next location __A : List[Any] = arr[i] combination_util(a , a , a , index + 1 , a , i + 1 ) # current is excluded, replace it with # next (Note that i+1 is passed, but # index is not changed) combination_util(a , a , a , a , a , i + 1 ) # The main function that prints all combinations # of size r in arr[] of size n. This function # mainly uses combinationUtil() def _SCREAMING_SNAKE_CASE ( a , a , a ) -> int: # A temporary array to store all combination one by one __A : str = [0] * r # Print all combination using temporary array 'data[]' combination_util(a , a , a , 0 , a , 0 ) if __name__ == "__main__": # Driver code to check the function above UpperCAmelCase : List[Any] = [10, 20, 30, 40, 50] print_combination(arr, len(arr), 3) # This code is contributed by Ambuj sahu
280
def _SCREAMING_SNAKE_CASE ( a ) -> Tuple: __A , __A : Optional[Any] = [], [] while len(a ) > 1: __A , __A : Any = min(a ), max(a ) start.append(a ) end.append(a ) collection.remove(a ) collection.remove(a ) end.reverse() return start + collection + end if __name__ == "__main__": UpperCAmelCase : int = input('''Enter numbers separated by a comma:\n''').strip() UpperCAmelCase : Dict = [int(item) for item in user_input.split(''',''')] print(*merge_sort(unsorted), sep=''',''')
280
1
def _SCREAMING_SNAKE_CASE ( a , a ) -> Optional[Any]: if b == 0: return 1 if (b % 2) == 0: return actual_power(a , int(b / 2 ) ) * actual_power(a , int(b / 2 ) ) else: return a * actual_power(a , int(b / 2 ) ) * actual_power(a , int(b / 2 ) ) def _SCREAMING_SNAKE_CASE ( a , a ) -> float: if b < 0: return 1 / actual_power(a , a ) return actual_power(a , a ) if __name__ == "__main__": print(power(-2, -3))
280
def _SCREAMING_SNAKE_CASE ( a , a = 0 ) -> list: __A : int = length or len(a ) __A : str = False for i in range(length - 1 ): if list_data[i] > list_data[i + 1]: __A , __A : Optional[int] = list_data[i + 1], list_data[i] __A : Union[str, Any] = True return list_data if not swapped else bubble_sort(a , length - 1 ) if __name__ == "__main__": import doctest doctest.testmod()
280
1
from typing import List, Optional, Union import numpy as np import PIL import torch from PIL import Image from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) UpperCAmelCase : List[Any] = logging.get_logger(__name__) # pylint: disable=invalid-name UpperCAmelCase : Dict = ''' Examples: ```py >>> from diffusers import KandinskyV22Img2ImgPipeline, KandinskyV22PriorPipeline >>> from diffusers.utils import load_image >>> import torch >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained( ... "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16 ... ) >>> pipe_prior.to("cuda") >>> prompt = "A red cartoon frog, 4k" >>> image_emb, zero_image_emb = pipe_prior(prompt, return_dict=False) >>> pipe = KandinskyV22Img2ImgPipeline.from_pretrained( ... "kandinsky-community/kandinsky-2-2-decoder", torch_dtype=torch.float16 ... ) >>> pipe.to("cuda") >>> init_image = load_image( ... "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" ... "/kandinsky/frog.png" ... ) >>> image = pipe( ... image=init_image, ... image_embeds=image_emb, ... negative_image_embeds=zero_image_emb, ... height=768, ... width=768, ... num_inference_steps=100, ... strength=0.2, ... ).images >>> image[0].save("red_frog.png") ``` ''' def _SCREAMING_SNAKE_CASE ( a , a , a=8 ) -> Tuple: __A : List[str] = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 __A : Optional[int] = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor def _SCREAMING_SNAKE_CASE ( a , a=5_12 , a=5_12 ) -> int: __A : Optional[Any] = pil_image.resize((w, h) , resample=Image.BICUBIC , reducing_gap=1 ) __A : Union[str, Any] = np.array(pil_image.convert('RGB' ) ) __A : Optional[int] = arr.astype(np.floataa ) / 127.5 - 1 __A : int = np.transpose(a , [2, 0, 1] ) __A : Tuple = torch.from_numpy(a ).unsqueeze(0 ) return image class _A( snake_case__ ): """simple docstring""" def __init__( self , _A , _A , _A , ): super().__init__() self.register_modules( unet=_A , scheduler=_A , movq=_A , ) __A : Tuple = 2 ** (len(self.movq.config.block_out_channels ) - 1) def UpperCAmelCase_ ( self , _A , _A , _A ): # get the original timestep using init_timestep __A : Optional[int] = min(int(num_inference_steps * strength ) , _A ) __A : Dict = max(num_inference_steps - init_timestep , 0 ) __A : Tuple = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A=None ): if not isinstance(_A , (torch.Tensor, PIL.Image.Image, list) ): raise ValueError( F"""`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(_A )}""" ) __A : Union[str, Any] = image.to(device=_A , dtype=_A ) __A : Optional[Any] = batch_size * num_images_per_prompt if image.shape[1] == 4: __A : int = image else: if isinstance(_A , _A ) and len(_A ) != batch_size: raise ValueError( F"""You have passed a list of generators of length {len(_A )}, but requested an effective batch""" F""" size of {batch_size}. Make sure the batch size matches the length of the generators.""" ) elif isinstance(_A , _A ): __A : str = [ self.movq.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(_A ) ] __A : str = torch.cat(_A , dim=0 ) else: __A : List[str] = self.movq.encode(_A ).latent_dist.sample(_A ) __A : Tuple = self.movq.config.scaling_factor * init_latents __A : Optional[int] = torch.cat([init_latents] , dim=0 ) __A : Union[str, Any] = init_latents.shape __A : List[str] = randn_tensor(_A , generator=_A , device=_A , dtype=_A ) # get latents __A : Optional[Any] = self.scheduler.add_noise(_A , _A , _A ) __A : Optional[int] = init_latents return latents def UpperCAmelCase_ ( self , _A=0 ): if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('Please install accelerate via `pip install accelerate`' ) __A : Optional[int] = torch.device(F"""cuda:{gpu_id}""" ) __A : Union[str, Any] = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(_A , _A ) def UpperCAmelCase_ ( self , _A=0 ): if is_accelerate_available() and is_accelerate_version('>=' , '0.17.0.dev0' ): from accelerate import cpu_offload_with_hook else: raise ImportError('`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.' ) __A : List[Any] = torch.device(F"""cuda:{gpu_id}""" ) if self.device.type != "cpu": self.to('cpu' , silence_dtype_warnings=_A ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) __A : int = None for cpu_offloaded_model in [self.unet, self.movq]: __A , __A : Optional[int] = cpu_offload_with_hook(_A , _A , prev_module_hook=_A ) # We'll offload the last model manually. __A : List[str] = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def UpperCAmelCase_ ( self ): if not hasattr(self.unet , '_hf_hook' ): return self.device for module in self.unet.modules(): if ( hasattr(_A , '_hf_hook' ) and hasattr(module._hf_hook , 'execution_device' ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(_A ) def __call__( self , _A , _A , _A , _A = 512 , _A = 512 , _A = 100 , _A = 4.0 , _A = 0.3 , _A = 1 , _A = None , _A = "pil" , _A = True , ): __A : List[Any] = self._execution_device __A : Optional[Any] = guidance_scale > 1.0 if isinstance(_A , _A ): __A : Optional[Any] = torch.cat(_A , dim=0 ) __A : Tuple = image_embeds.shape[0] if isinstance(_A , _A ): __A : List[Any] = torch.cat(_A , dim=0 ) if do_classifier_free_guidance: __A : Union[str, Any] = image_embeds.repeat_interleave(_A , dim=0 ) __A : Optional[int] = negative_image_embeds.repeat_interleave(_A , dim=0 ) __A : List[str] = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=_A ) if not isinstance(_A , _A ): __A : List[Any] = [image] if not all(isinstance(_A , (PIL.Image.Image, torch.Tensor) ) for i in image ): raise ValueError( F"""Input is in incorrect format: {[type(_A ) for i in image]}. Currently, we only support PIL image and pytorch tensor""" ) __A : Dict = torch.cat([prepare_image(_A , _A , _A ) for i in image] , dim=0 ) __A : Any = image.to(dtype=image_embeds.dtype , device=_A ) __A : Tuple = self.movq.encode(_A )['latents'] __A : int = latents.repeat_interleave(_A , dim=0 ) self.scheduler.set_timesteps(_A , device=_A ) __A , __A : int = self.get_timesteps(_A , _A , _A ) __A : Union[str, Any] = timesteps[:1].repeat(batch_size * num_images_per_prompt ) __A , __A : Any = downscale_height_and_width(_A , _A , self.movq_scale_factor ) __A : Tuple = self.prepare_latents( _A , _A , _A , _A , image_embeds.dtype , _A , _A ) for i, t in enumerate(self.progress_bar(_A ) ): # expand the latents if we are doing classifier free guidance __A : Optional[int] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents __A : Dict = {'image_embeds': image_embeds} __A : List[str] = self.unet( sample=_A , timestep=_A , encoder_hidden_states=_A , added_cond_kwargs=_A , return_dict=_A , )[0] if do_classifier_free_guidance: __A , __A : Dict = noise_pred.split(latents.shape[1] , dim=1 ) __A , __A : Optional[Any] = noise_pred.chunk(2 ) __A , __A : List[str] = variance_pred.chunk(2 ) __A : str = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) __A : List[str] = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , 'variance_type' ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): __A , __A : Optional[Any] = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 __A : List[str] = self.scheduler.step( _A , _A , _A , generator=_A , )[0] # post-processing __A : List[Any] = self.movq.decode(_A , force_not_quantize=_A )['sample'] if output_type not in ["pt", "np", "pil"]: raise ValueError(F"""Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}""" ) if output_type in ["np", "pil"]: __A : List[str] = image * 0.5 + 0.5 __A : List[str] = image.clamp(0 , 1 ) __A : Optional[Any] = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": __A : Any = self.numpy_to_pil(_A ) if not return_dict: return (image,) return ImagePipelineOutput(images=_A )
280
from __future__ import annotations def _SCREAMING_SNAKE_CASE ( a ) -> int: if not nums: return 0 __A : Optional[int] = nums[0] __A : str = 0 for num in nums[1:]: __A , __A : Tuple = ( max_excluding + num, max(a , a ), ) return max(a , a ) if __name__ == "__main__": import doctest doctest.testmod()
280
1
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase : Tuple = logging.get_logger(__name__) UpperCAmelCase : List[str] = { '''microsoft/swinv2-tiny-patch4-window8-256''': ( '''https://huggingface.co/microsoft/swinv2-tiny-patch4-window8-256/resolve/main/config.json''' ), } class _A( snake_case__ ): """simple docstring""" UpperCamelCase : List[str] = '''swinv2''' UpperCamelCase : Any = { '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self , _A=224 , _A=4 , _A=3 , _A=96 , _A=[2, 2, 6, 2] , _A=[3, 6, 12, 24] , _A=7 , _A=4.0 , _A=True , _A=0.0 , _A=0.0 , _A=0.1 , _A="gelu" , _A=False , _A=0.0_2 , _A=1e-5 , _A=32 , **_A , ): super().__init__(**_A ) __A : Dict = image_size __A : Dict = patch_size __A : List[Any] = num_channels __A : List[str] = embed_dim __A : Tuple = depths __A : List[Any] = len(_A ) __A : Union[str, Any] = num_heads __A : Union[str, Any] = window_size __A : Optional[int] = mlp_ratio __A : str = qkv_bias __A : Optional[int] = hidden_dropout_prob __A : Optional[Any] = attention_probs_dropout_prob __A : Union[str, Any] = drop_path_rate __A : List[str] = hidden_act __A : Union[str, Any] = use_absolute_embeddings __A : Union[str, Any] = layer_norm_eps __A : str = initializer_range __A : Tuple = encoder_stride # we set the hidden_size attribute in order to make Swinv2 work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model __A : Optional[int] = int(embed_dim * 2 ** (len(_A ) - 1) ) __A : List[Any] = (0, 0, 0, 0)
280
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available UpperCAmelCase : Optional[int] = { '''configuration_xlm''': ['''XLM_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XLMConfig''', '''XLMOnnxConfig'''], '''tokenization_xlm''': ['''XLMTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Union[str, Any] = [ '''XLM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XLMForMultipleChoice''', '''XLMForQuestionAnswering''', '''XLMForQuestionAnsweringSimple''', '''XLMForSequenceClassification''', '''XLMForTokenClassification''', '''XLMModel''', '''XLMPreTrainedModel''', '''XLMWithLMHeadModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Optional[Any] = [ '''TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFXLMForMultipleChoice''', '''TFXLMForQuestionAnsweringSimple''', '''TFXLMForSequenceClassification''', '''TFXLMForTokenClassification''', '''TFXLMMainLayer''', '''TFXLMModel''', '''TFXLMPreTrainedModel''', '''TFXLMWithLMHeadModel''', ] if TYPE_CHECKING: from .configuration_xlm import XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMConfig, XLMOnnxConfig from .tokenization_xlm import XLMTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm import ( XLM_PRETRAINED_MODEL_ARCHIVE_LIST, XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMPreTrainedModel, XLMWithLMHeadModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlm import ( TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLMForMultipleChoice, TFXLMForQuestionAnsweringSimple, TFXLMForSequenceClassification, TFXLMForTokenClassification, TFXLMMainLayer, TFXLMModel, TFXLMPreTrainedModel, TFXLMWithLMHeadModel, ) else: import sys UpperCAmelCase : str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
280
1
import os import unittest from transformers import LxmertTokenizer, LxmertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class _A( snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : List[str] = LxmertTokenizer UpperCamelCase : List[str] = LxmertTokenizerFast UpperCamelCase : Union[str, Any] = True UpperCamelCase : Optional[int] = True def UpperCAmelCase_ ( self ): super().setUp() __A : str = [ '[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] __A : List[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] ) ) def UpperCAmelCase_ ( self , _A ): __A : List[str] = 'UNwant\u00E9d,running' __A : Any = 'unwanted, running' return input_text, output_text def UpperCAmelCase_ ( self ): __A : Dict = self.tokenizer_class(self.vocab_file ) __A : Union[str, Any] = tokenizer.tokenize('UNwant\u00E9d,running' ) self.assertListEqual(_A , ['un', '##want', '##ed', ',', 'runn', '##ing'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_A ) , [7, 4, 5, 10, 8, 9] ) def UpperCAmelCase_ ( self ): if not self.test_rust_tokenizer: return __A : int = self.get_tokenizer() __A : List[str] = self.get_rust_tokenizer() __A : Any = 'I was born in 92000, and this is falsé.' __A : List[str] = tokenizer.tokenize(_A ) __A : Tuple = rust_tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) __A : str = tokenizer.encode(_A , add_special_tokens=_A ) __A : Optional[int] = rust_tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __A : str = self.get_rust_tokenizer() __A : Union[str, Any] = tokenizer.encode(_A ) __A : Union[str, Any] = rust_tokenizer.encode(_A ) self.assertListEqual(_A , _A )
280
def _SCREAMING_SNAKE_CASE ( a ) -> str: if number > 0: raise ValueError('input must be a negative integer' ) __A : Optional[int] = len(bin(a )[3:] ) __A : Dict = bin(abs(a ) - (1 << binary_number_length) )[3:] __A : int = ( ( '1' + '0' * (binary_number_length - len(a )) + twos_complement_number ) if number < 0 else '0' ) return "0b" + twos_complement_number if __name__ == "__main__": import doctest doctest.testmod()
280
1
import logging import os from dataclasses import dataclass, field from typing import Dict, Optional import numpy as np from utils_multiple_choice import MultipleChoiceDataset, Split, processors import transformers from transformers import ( AutoConfig, AutoModelForMultipleChoice, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process UpperCAmelCase : Dict = logging.getLogger(__name__) def _SCREAMING_SNAKE_CASE ( a , a ) -> Union[str, Any]: return (preds == labels).mean() @dataclass class _A: """simple docstring""" UpperCamelCase : str = field( metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''} ) UpperCamelCase : Optional[str] = field( default=snake_case__ , metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} ) UpperCamelCase : Optional[str] = field( default=snake_case__ , metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''} ) UpperCamelCase : Optional[str] = field( default=snake_case__ , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''} , ) @dataclass class _A: """simple docstring""" UpperCamelCase : str = field(metadata={'''help''': '''The name of the task to train on: ''' + ''', '''.join(processors.keys() )} ) UpperCamelCase : str = field(metadata={'''help''': '''Should contain the data files for the task.'''} ) UpperCamelCase : int = field( default=128 , metadata={ '''help''': ( '''The maximum total input sequence length after tokenization. Sequences longer ''' '''than this will be truncated, sequences shorter will be padded.''' ) } , ) UpperCamelCase : bool = field( default=snake_case__ , metadata={'''help''': '''Overwrite the cached training and evaluation sets'''} ) def _SCREAMING_SNAKE_CASE ( ) -> Optional[Any]: # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. __A : Optional[int] = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) __A , __A , __A : Optional[Any] = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( F"""Output directory ({training_args.output_dir}) already exists and is not empty. Use""" ' --overwrite_output_dir to overcome.' ) # Setup logging logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( 'Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s' , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info('Training/evaluation parameters %s' , a ) # Set seed set_seed(training_args.seed ) try: __A : Any = processors[data_args.task_name]() __A : List[str] = processor.get_labels() __A : Union[str, Any] = len(a ) except KeyError: raise ValueError('Task not found: %s' % (data_args.task_name) ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. __A : Dict = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=a , finetuning_task=data_args.task_name , cache_dir=model_args.cache_dir , ) __A : Dict = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) __A : Any = AutoModelForMultipleChoice.from_pretrained( model_args.model_name_or_path , from_tf=bool('.ckpt' in model_args.model_name_or_path ) , config=a , cache_dir=model_args.cache_dir , ) # Get datasets __A : str = ( MultipleChoiceDataset( data_dir=data_args.data_dir , tokenizer=a , task=data_args.task_name , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.train , ) if training_args.do_train else None ) __A : Union[str, Any] = ( MultipleChoiceDataset( data_dir=data_args.data_dir , tokenizer=a , task=data_args.task_name , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.dev , ) if training_args.do_eval else None ) def compute_metrics(a ) -> Dict: __A : Optional[Any] = np.argmax(p.predictions , axis=1 ) return {"acc": simple_accuracy(a , p.label_ids )} # Data collator __A : Any = DataCollatorWithPadding(a , pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer __A : str = Trainer( model=a , args=a , train_dataset=a , eval_dataset=a , compute_metrics=a , data_collator=a , ) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_master(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation __A : Dict = {} if training_args.do_eval: logger.info('*** Evaluate ***' ) __A : Union[str, Any] = trainer.evaluate() __A : Any = os.path.join(training_args.output_dir , 'eval_results.txt' ) if trainer.is_world_master(): with open(a , 'w' ) as writer: logger.info('***** Eval results *****' ) for key, value in result.items(): logger.info(' %s = %s' , a , a ) writer.write('%s = %s\n' % (key, value) ) results.update(a ) return results def _SCREAMING_SNAKE_CASE ( a ) -> List[str]: # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
280
import warnings from pathlib import Path from typing import List, Tuple, Union import fire from torch import nn from transformers import AutoModelForSeqaSeqLM, AutoTokenizer, PreTrainedModel from transformers.utils import logging UpperCAmelCase : Any = logging.get_logger(__name__) def _SCREAMING_SNAKE_CASE ( a , a , a ) -> None: __A : int = nn.ModuleList([src_layers[i] for i in layers_to_copy] ) assert len(a ) == len(a ), F"""{len(a )} != {len(a )}""" dest_layers.load_state_dict(layers_to_copy.state_dict() ) UpperCAmelCase : List[Any] = { # maps num layers in teacher -> num_layers in student -> which teacher layers to copy. # 12: bart, 16: pegasus, 6: marian/Helsinki-NLP 12: { 1: [0], # This says that if the teacher has 12 layers and the student has 1, copy layer 0 of the teacher 2: [0, 6], 3: [0, 6, 11], 4: [0, 4, 8, 11], 6: [0, 2, 4, 7, 9, 11], 9: [0, 1, 2, 4, 5, 7, 9, 10, 11], 12: list(range(12)), }, 16: { # maps num layers in student -> which teacher layers to copy 1: [0], 2: [0, 15], 3: [0, 8, 15], 4: [0, 5, 10, 15], 6: [0, 3, 6, 9, 12, 15], 8: [0, 2, 4, 6, 8, 10, 12, 15], 9: [0, 1, 3, 5, 7, 9, 11, 13, 15], 12: [0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 15], 16: list(range(16)), }, 6: {1: [0], 2: [0, 5], 3: [0, 2, 5], 4: [0, 1, 3, 5], 6: list(range(6))}, } UpperCAmelCase : Optional[int] = { # maps num layers in student -> which teacher layers to copy. 6: {1: [5], 2: [3, 5], 3: [1, 4, 5], 4: [1, 2, 4, 5]}, 12: {1: [11], 2: [5, 11], 3: [3, 7, 11], 6: [1, 3, 5, 8, 10, 11]}, 16: {1: [15], 4: [4, 9, 12, 15], 8: [1, 3, 5, 7, 9, 11, 13, 15]}, } def _SCREAMING_SNAKE_CASE ( a , a ) -> Dict: try: __A : int = LAYERS_TO_COPY[n_teacher][n_student] return val except KeyError: if n_student != n_teacher: warnings.warn( F"""no hardcoded layers to copy for teacher {n_teacher} -> student {n_student}, defaulting to first""" F""" {n_student}""" ) return list(range(a ) ) def _SCREAMING_SNAKE_CASE ( a , a ) -> List[int]: if n_student > n_teacher: raise ValueError(F"""Cannot perform intermediate supervision for student {n_student} > teacher {n_teacher}""" ) elif n_teacher == n_student: return list(range(a ) ) elif n_student == 1: return [n_teacher - 1] else: return LAYERS_TO_SUPERVISE[n_teacher][n_student] def _SCREAMING_SNAKE_CASE ( a , a = "student" , a = None , a = None , a=False , a=None , a=None , **a , ) -> Tuple[PreTrainedModel, List[int], List[int]]: __A : List[str] = 'encoder_layers and decoder_layers cannot be both None-- you would just have an identical teacher.' assert (e is not None) or (d is not None), _msg if isinstance(a , a ): AutoTokenizer.from_pretrained(a ).save_pretrained(a ) # purely for convenience __A : Optional[int] = AutoModelForSeqaSeqLM.from_pretrained(a ).eval() else: assert isinstance(a , a ), F"""teacher must be a model or string got type {type(a )}""" __A : int = teacher.config.to_diff_dict() try: __A , __A : List[Any] = teacher.config.encoder_layers, teacher.config.decoder_layers if e is None: __A : str = teacher_e if d is None: __A : List[Any] = teacher_d init_kwargs.update({'encoder_layers': e, 'decoder_layers': d} ) except AttributeError: # T5 if hasattr(teacher.config , 'num_encoder_layers' ): __A , __A : List[Any] = teacher.config.num_encoder_layers, teacher.config.num_decoder_layers else: __A , __A : Optional[int] = teacher.config.num_layers, teacher.config.num_decoder_layers if e is None: __A : int = teacher_e if d is None: __A : Optional[Any] = teacher_d if hasattr(teacher.config , 'num_encoder_layers' ): init_kwargs.update({'num_encoder_layers': e, 'num_decoder_layers': d} ) else: init_kwargs.update({'num_layers': e, 'num_decoder_layers': d} ) # Kwargs to instantiate student: teacher kwargs with updated layer numbers + **extra_config_kwargs init_kwargs.update(a ) # Copy weights __A : Dict = teacher.config_class(**a ) __A : int = AutoModelForSeqaSeqLM.from_config(a ) # Start by copying the full teacher state dict this will copy the first N teacher layers to the student. __A : Any = student.load_state_dict(teacher.state_dict() , strict=a ) assert info.missing_keys == [], info.missing_keys # every student key should have a teacher keys. if copy_first_teacher_layers: # Our copying is done. We just log and save __A , __A : Optional[int] = list(range(a ) ), list(range(a ) ) logger.info( F"""Copied encoder layers {e_layers_to_copy} and decoder layers {d_layers_to_copy}. Saving them to""" F""" {save_path}""" ) student.save_pretrained(a ) return student, e_layers_to_copy, d_layers_to_copy # Decide which layers of the teacher to copy. Not exactly alternating -- we try to keep first and last layer. if e_layers_to_copy is None: __A : List[int] = pick_layers_to_copy(a , a ) if d_layers_to_copy is None: __A : List[int] = pick_layers_to_copy(a , a ) try: if hasattr( a , 'prophetnet' ): # For ProphetNet, student.model.encoder.layers is called student.prophetnet.encoder.layers copy_layers(teacher.prophetnet.encoder.layers , student.prophetnet.encoder.layers , a ) copy_layers(teacher.prophetnet.decoder.layers , student.prophetnet.decoder.layers , a ) else: copy_layers(teacher.model.encoder.layers , student.model.encoder.layers , a ) copy_layers(teacher.model.decoder.layers , student.model.decoder.layers , a ) except AttributeError: # For t5, student.model.encoder.layers is called student.encoder.block copy_layers(teacher.encoder.block , student.encoder.block , a ) copy_layers(teacher.decoder.block , student.decoder.block , a ) logger.info( F"""Copied encoder layers {e_layers_to_copy} and decoder layers {d_layers_to_copy}. Saving them to {save_path}""" ) __A : Optional[int] = { 'teacher_type': teacher.config.model_type, 'copied_encoder_layers': e_layers_to_copy, 'copied_decoder_layers': d_layers_to_copy, } student.save_pretrained(a ) # Save information about copying for easier reproducibility return student, e_layers_to_copy, d_layers_to_copy if __name__ == "__main__": fire.Fire(create_student_by_copying_alternating_layers)
280
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) UpperCAmelCase : Optional[int] = {'''configuration_vit_mae''': ['''VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ViTMAEConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Optional[int] = [ '''VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ViTMAEForPreTraining''', '''ViTMAELayer''', '''ViTMAEModel''', '''ViTMAEPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Union[str, Any] = [ '''TFViTMAEForPreTraining''', '''TFViTMAEModel''', '''TFViTMAEPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_vit_mae import VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTMAEConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vit_mae import ( VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST, ViTMAEForPreTraining, ViTMAELayer, ViTMAEModel, ViTMAEPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vit_mae import TFViTMAEForPreTraining, TFViTMAEModel, TFViTMAEPreTrainedModel else: import sys UpperCAmelCase : str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
280
def _SCREAMING_SNAKE_CASE ( a , a ) -> list[int]: __A : Optional[int] = int(a ) # Initialize Result __A : Optional[int] = [] # Traverse through all denomination for denomination in reversed(a ): # Find denominations while int(a ) >= int(a ): total_value -= int(a ) answer.append(a ) # Append the "answers" array return answer # Driver Code if __name__ == "__main__": UpperCAmelCase : List[str] = [] UpperCAmelCase : Optional[int] = '''0''' if ( input('''Do you want to enter your denominations ? (yY/n): ''').strip().lower() == "y" ): UpperCAmelCase : List[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 : Optional[int] = [1, 2, 5, 10, 20, 50, 1_00, 5_00, 20_00] UpperCAmelCase : Tuple = 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 : Optional[int] = find_minimum_change(denominations, value) # Print result for i in range(len(answer)): print(answer[i], end=''' ''')
280
1
import re from flax.core.frozen_dict import freeze from flax.traverse_util import flatten_dict, unflatten_dict from jax.experimental import PartitionSpec as P # Sentinels UpperCAmelCase : Optional[Any] = object() # For specifying empty leaf dict `{}` UpperCAmelCase : Optional[int] = object() def _SCREAMING_SNAKE_CASE ( a , a ) -> Optional[int]: __A : List[Any] = tuple((re.compile(x + '$' ) for x in qs) ) for i in range(len(a ) - len(a ) + 1 ): __A : List[str] = [x.match(a ) for x, y in zip(a , ks[i:] )] if matches and all(a ): return True return False def _SCREAMING_SNAKE_CASE ( a ) -> Dict: def replace(a , a ): for rule, replacement in rules: if _match(a , a ): return replacement return val return replace def _SCREAMING_SNAKE_CASE ( ) -> Any: return [ # embeddings (("transformer", "wpe", "embedding"), P('mp' , a )), (("transformer", "wte", "embedding"), P('mp' , a )), # atention (("attention", "(q_proj|k_proj|v_proj)", "kernel"), P(a , 'mp' )), (("attention", "out_proj", "kernel"), P('mp' , a )), (("attention", "out_proj", "bias"), None), # mlp (("mlp", "c_fc", "kernel"), P(a , 'mp' )), (("mlp", "c_fc", "bias"), P('mp' )), (("mlp", "c_proj", "kernel"), P('mp' , a )), (("mlp", "c_proj", "bias"), None), # layer norms ((r"ln_\d+", "bias"), None), ((r"\d+", r"ln_\d+", "scale"), None), (("ln_f", "bias"), None), (("ln_f", "scale"), None), ] def _SCREAMING_SNAKE_CASE ( a ) -> Dict: __A : Any = _get_partition_rules() __A : Any = _replacement_rules(a ) __A : str = {k: _unmatched for k in flatten_dict(a )} __A : Tuple = {k: replace(a , a ) for k, v in initd.items()} assert _unmatched not in result.values(), "Incomplete partition spec." return freeze(unflatten_dict(a ) )
280
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 YolosImageProcessor class _A( unittest.TestCase ): """simple docstring""" def __init__( self , _A , _A=7 , _A=3 , _A=30 , _A=400 , _A=True , _A=None , _A=True , _A=[0.5, 0.5, 0.5] , _A=[0.5, 0.5, 0.5] , _A=True , _A=1 / 255 , _A=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __A : List[Any] = size if size is not None else {'shortest_edge': 18, 'longest_edge': 1333} __A : Union[str, Any] = parent __A : Optional[int] = batch_size __A : int = num_channels __A : int = min_resolution __A : Any = max_resolution __A : List[Any] = do_resize __A : List[Any] = size __A : Union[str, Any] = do_normalize __A : Optional[int] = image_mean __A : Optional[int] = image_std __A : int = do_rescale __A : str = rescale_factor __A : Tuple = do_pad def UpperCAmelCase_ ( self ): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def UpperCAmelCase_ ( self , _A , _A=False ): if not batched: __A : List[str] = image_inputs[0] if isinstance(_A , Image.Image ): __A , __A : int = image.size else: __A , __A : Any = image.shape[1], image.shape[2] if w < h: __A : List[Any] = int(self.size['shortest_edge'] * h / w ) __A : List[Any] = self.size['shortest_edge'] elif w > h: __A : Union[str, Any] = self.size['shortest_edge'] __A : str = int(self.size['shortest_edge'] * w / h ) else: __A : Dict = self.size['shortest_edge'] __A : str = self.size['shortest_edge'] else: __A : int = [] for image in image_inputs: __A , __A : Optional[Any] = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __A : List[str] = max(_A , key=lambda _A : item[0] )[0] __A : str = max(_A , key=lambda _A : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class _A( snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : List[str] = YolosImageProcessor if is_vision_available() else None def UpperCAmelCase_ ( self ): __A : Dict = YolosImageProcessingTester(self ) @property def UpperCAmelCase_ ( self ): return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase_ ( self ): __A : str = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_A , 'image_mean' ) ) self.assertTrue(hasattr(_A , 'image_std' ) ) self.assertTrue(hasattr(_A , 'do_normalize' ) ) self.assertTrue(hasattr(_A , 'do_resize' ) ) self.assertTrue(hasattr(_A , 'size' ) ) def UpperCAmelCase_ ( self ): __A : Tuple = 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 , _A ) __A : Dict = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=_A ) self.assertEqual(image_processor.size , {'shortest_edge': 42, 'longest_edge': 84} ) self.assertEqual(image_processor.do_pad , _A ) def UpperCAmelCase_ ( self ): pass def UpperCAmelCase_ ( self ): # Initialize image_processing __A : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __A : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A ) for image in image_inputs: self.assertIsInstance(_A , Image.Image ) # Test not batched input __A : Any = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values __A , __A : Optional[int] = self.image_processor_tester.get_expected_values(_A ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __A , __A : Optional[Any] = self.image_processor_tester.get_expected_values(_A , batched=_A ) __A : str = image_processing(_A , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def UpperCAmelCase_ ( self ): # Initialize image_processing __A : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __A : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A , numpify=_A ) for image in image_inputs: self.assertIsInstance(_A , np.ndarray ) # Test not batched input __A : str = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values __A , __A : List[Any] = self.image_processor_tester.get_expected_values(_A ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __A : Tuple = image_processing(_A , return_tensors='pt' ).pixel_values __A , __A : Optional[int] = self.image_processor_tester.get_expected_values(_A , batched=_A ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def UpperCAmelCase_ ( self ): # Initialize image_processing __A : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __A : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A , torchify=_A ) for image in image_inputs: self.assertIsInstance(_A , torch.Tensor ) # Test not batched input __A : Union[str, Any] = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values __A , __A : Union[str, Any] = self.image_processor_tester.get_expected_values(_A ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __A : Optional[int] = image_processing(_A , return_tensors='pt' ).pixel_values __A , __A : Optional[int] = self.image_processor_tester.get_expected_values(_A , batched=_A ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def UpperCAmelCase_ ( self ): # Initialize image_processings __A : Tuple = self.image_processing_class(**self.image_processor_dict ) __A : Any = self.image_processing_class(do_resize=_A , do_normalize=_A , do_rescale=_A ) # create random PyTorch tensors __A : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A , torchify=_A ) for image in image_inputs: self.assertIsInstance(_A , torch.Tensor ) # Test whether the method "pad" and calling the image processor return the same tensors __A : Optional[int] = image_processing_a.pad(_A , return_tensors='pt' ) __A : Optional[int] = image_processing_a(_A , return_tensors='pt' ) self.assertTrue( torch.allclose(encoded_images_with_method['pixel_values'] , encoded_images['pixel_values'] , atol=1e-4 ) ) @slow def UpperCAmelCase_ ( self ): # prepare image and target __A : List[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' , 'r' ) as f: __A : Optional[Any] = json.loads(f.read() ) __A : Optional[Any] = {'image_id': 39769, 'annotations': target} # encode them __A : str = YolosImageProcessor.from_pretrained('hustvl/yolos-small' ) __A : List[Any] = image_processing(images=_A , annotations=_A , return_tensors='pt' ) # verify pixel values __A : List[Any] = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding['pixel_values'].shape , _A ) __A : Union[str, Any] = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , _A , atol=1e-4 ) ) # verify area __A : List[Any] = torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , _A ) ) # verify boxes __A : Any = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , _A ) __A : Optional[Any] = torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , _A , atol=1e-3 ) ) # verify image_id __A : Optional[int] = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , _A ) ) # verify is_crowd __A : str = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , _A ) ) # verify class_labels __A : Any = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , _A ) ) # verify orig_size __A : int = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , _A ) ) # verify size __A : str = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , _A ) ) @slow def UpperCAmelCase_ ( self ): # prepare image, target and masks_path __A : Dict = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' , 'r' ) as f: __A : Tuple = json.loads(f.read() ) __A : Any = {'file_name': '000000039769.png', 'image_id': 39769, 'segments_info': target} __A : List[Any] = pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic' ) # encode them __A : Any = YolosImageProcessor(format='coco_panoptic' ) __A : List[Any] = image_processing(images=_A , annotations=_A , masks_path=_A , return_tensors='pt' ) # verify pixel values __A : Any = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding['pixel_values'].shape , _A ) __A : Union[str, Any] = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , _A , atol=1e-4 ) ) # verify area __A : int = torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , _A ) ) # verify boxes __A : Optional[int] = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , _A ) __A : Optional[Any] = torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , _A , atol=1e-3 ) ) # verify image_id __A : Union[str, Any] = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , _A ) ) # verify is_crowd __A : Tuple = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , _A ) ) # verify class_labels __A : List[str] = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , _A ) ) # verify masks __A : Tuple = 822873 self.assertEqual(encoding['labels'][0]['masks'].sum().item() , _A ) # verify orig_size __A : str = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , _A ) ) # verify size __A : int = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , _A ) )
280
1
class _A: """simple docstring""" def __init__( self , _A , _A , _A ): __A : Optional[int] = None __A : List[Any] = None __A : Tuple = graph self._normalize_graph(_A , _A ) __A : str = len(_A ) __A : str = None def UpperCAmelCase_ ( self , _A , _A ): if sources is int: __A : int = [sources] if sinks is int: __A : Any = [sinks] if len(_A ) == 0 or len(_A ) == 0: return __A : List[Any] = sources[0] __A : Tuple = sinks[0] # make fake vertex if there are more # than one source or sink if len(_A ) > 1 or len(_A ) > 1: __A : Optional[int] = 0 for i in sources: max_input_flow += sum(self.graph[i] ) __A : List[str] = len(self.graph ) + 1 for room in self.graph: room.insert(0 , 0 ) self.graph.insert(0 , [0] * size ) for i in sources: __A : Any = max_input_flow __A : Union[str, Any] = 0 __A : Optional[int] = len(self.graph ) + 1 for room in self.graph: room.append(0 ) self.graph.append([0] * size ) for i in sinks: __A : Dict = max_input_flow __A : Optional[Any] = size - 1 def UpperCAmelCase_ ( self ): if self.maximum_flow_algorithm is None: raise Exception('You need to set maximum flow algorithm before.' ) if self.source_index is None or self.sink_index is None: return 0 self.maximum_flow_algorithm.execute() return self.maximum_flow_algorithm.getMaximumFlow() def UpperCAmelCase_ ( self , _A ): __A : Any = algorithm(self ) class _A: """simple docstring""" def __init__( self , _A ): __A : str = flow_network __A : int = flow_network.verticesCount __A : Any = flow_network.sourceIndex __A : Tuple = flow_network.sinkIndex # it's just a reference, so you shouldn't change # it in your algorithms, use deep copy before doing that __A : Tuple = flow_network.graph __A : List[str] = False def UpperCAmelCase_ ( self ): if not self.executed: self._algorithm() __A : Any = True def UpperCAmelCase_ ( self ): pass class _A( snake_case__ ): """simple docstring""" def __init__( self , _A ): super().__init__(_A ) # use this to save your result __A : List[Any] = -1 def UpperCAmelCase_ ( self ): if not self.executed: raise Exception('You should execute algorithm before using its result!' ) return self.maximum_flow class _A( snake_case__ ): """simple docstring""" def __init__( self , _A ): super().__init__(_A ) __A : Any = [[0] * self.verticies_count for i in range(self.verticies_count )] __A : str = [0] * self.verticies_count __A : List[str] = [0] * self.verticies_count def UpperCAmelCase_ ( self ): __A : Any = self.verticies_count # push some substance to graph for nextvertex_index, bandwidth in enumerate(self.graph[self.source_index] ): self.preflow[self.source_index][nextvertex_index] += bandwidth self.preflow[nextvertex_index][self.source_index] -= bandwidth self.excesses[nextvertex_index] += bandwidth # Relabel-to-front selection rule __A : Optional[Any] = [ i for i in range(self.verticies_count ) if i != self.source_index and i != self.sink_index ] # move through list __A : Union[str, Any] = 0 while i < len(_A ): __A : int = vertices_list[i] __A : Dict = self.heights[vertex_index] self.process_vertex(_A ) if self.heights[vertex_index] > previous_height: # if it was relabeled, swap elements # and start from 0 index vertices_list.insert(0 , vertices_list.pop(_A ) ) __A : int = 0 else: i += 1 __A : Optional[Any] = sum(self.preflow[self.source_index] ) def UpperCAmelCase_ ( self , _A ): while self.excesses[vertex_index] > 0: for neighbour_index in range(self.verticies_count ): # if it's neighbour and current vertex is higher if ( self.graph[vertex_index][neighbour_index] - self.preflow[vertex_index][neighbour_index] > 0 and self.heights[vertex_index] > self.heights[neighbour_index] ): self.push(_A , _A ) self.relabel(_A ) def UpperCAmelCase_ ( self , _A , _A ): __A : Union[str, Any] = min( self.excesses[from_index] , self.graph[from_index][to_index] - self.preflow[from_index][to_index] , ) self.preflow[from_index][to_index] += preflow_delta self.preflow[to_index][from_index] -= preflow_delta self.excesses[from_index] -= preflow_delta self.excesses[to_index] += preflow_delta def UpperCAmelCase_ ( self , _A ): __A : List[Any] = None for to_index in range(self.verticies_count ): if ( self.graph[vertex_index][to_index] - self.preflow[vertex_index][to_index] > 0 ) and (min_height is None or self.heights[to_index] < min_height): __A : Union[str, Any] = self.heights[to_index] if min_height is not None: __A : List[str] = min_height + 1 if __name__ == "__main__": UpperCAmelCase : int = [0] UpperCAmelCase : Any = [3] # graph = [ # [0, 0, 4, 6, 0, 0], # [0, 0, 5, 2, 0, 0], # [0, 0, 0, 0, 4, 4], # [0, 0, 0, 0, 6, 6], # [0, 0, 0, 0, 0, 0], # [0, 0, 0, 0, 0, 0], # ] UpperCAmelCase : List[str] = [[0, 7, 0, 0], [0, 0, 6, 0], [0, 0, 0, 8], [9, 0, 0, 0]] # prepare our network UpperCAmelCase : int = FlowNetwork(graph, entrances, exits) # set algorithm flow_network.set_maximum_flow_algorithm(PushRelabelExecutor) # and calculate UpperCAmelCase : Optional[Any] = flow_network.find_maximum_flow() print(F"""maximum flow is {maximum_flow}""")
280
import argparse import json from tqdm import tqdm def _SCREAMING_SNAKE_CASE ( ) -> List[Any]: __A : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( '--src_path' , type=a , default='biencoder-nq-dev.json' , help='Path to raw DPR training data' , ) parser.add_argument( '--evaluation_set' , type=a , help='where to store parsed evaluation_set file' , ) parser.add_argument( '--gold_data_path' , type=a , help='where to store parsed gold_data_path file' , ) __A : Optional[int] = parser.parse_args() with open(args.src_path , 'r' ) as src_file, open(args.evaluation_set , 'w' ) as eval_file, open( args.gold_data_path , 'w' ) as gold_file: __A : List[Any] = json.load(a ) for dpr_record in tqdm(a ): __A : Dict = dpr_record['question'] __A : Any = [context['title'] for context in dpr_record['positive_ctxs']] eval_file.write(question + '\n' ) gold_file.write('\t'.join(a ) + '\n' ) if __name__ == "__main__": main()
280
1
import inspect from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel, VQModel from ...schedulers import DDIMScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class _A( snake_case__ ): """simple docstring""" def __init__( self , _A , _A , _A ): super().__init__() self.register_modules(vqvae=_A , unet=_A , scheduler=_A ) @torch.no_grad() def __call__( self , _A = 1 , _A = None , _A = 0.0 , _A = 50 , _A = "pil" , _A = True , **_A , ): __A : Optional[int] = randn_tensor( (batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , generator=_A , ) __A : Any = latents.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler __A : int = latents * self.scheduler.init_noise_sigma self.scheduler.set_timesteps(_A ) # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature __A : Optional[int] = 'eta' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) __A : Any = {} if accepts_eta: __A : List[str] = eta for t in self.progress_bar(self.scheduler.timesteps ): __A : Dict = self.scheduler.scale_model_input(_A , _A ) # predict the noise residual __A : int = self.unet(_A , _A ).sample # compute the previous noisy sample x_t -> x_t-1 __A : int = self.scheduler.step(_A , _A , _A , **_A ).prev_sample # decode the image latents with the VAE __A : Tuple = self.vqvae.decode(_A ).sample __A : Dict = (image / 2 + 0.5).clamp(0 , 1 ) __A : Any = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": __A : List[str] = self.numpy_to_pil(_A ) if not return_dict: return (image,) return ImagePipelineOutput(images=_A )
280
from heapq import heappop, heappush import numpy as np def _SCREAMING_SNAKE_CASE ( a , a , a , a , ) -> tuple[float | int, list[tuple[int, int]]]: __A , __A : int = grid.shape __A : Any = [-1, 1, 0, 0] __A : Optional[Any] = [0, 0, -1, 1] if allow_diagonal: dx += [-1, -1, 1, 1] dy += [-1, 1, -1, 1] __A , __A : Optional[int] = [(0, source)], set() __A : Any = np.full((rows, cols) , np.inf ) __A : Any = 0 __A : Any = np.empty((rows, cols) , dtype=a ) __A : Optional[Any] = None while queue: ((__A) , (__A)) : List[str] = heappop(a ) if (x, y) in visited: continue visited.add((x, y) ) if (x, y) == destination: __A : int = [] while (x, y) != source: path.append((x, y) ) __A , __A : Optional[int] = predecessors[x, y] path.append(a ) # add the source manually path.reverse() return matrix[destination], path for i in range(len(a ) ): __A , __A : Union[str, Any] = x + dx[i], y + dy[i] if 0 <= nx < rows and 0 <= ny < cols: __A : Optional[int] = grid[nx][ny] if next_node == 1 and matrix[nx, ny] > dist + 1: heappush(a , (dist + 1, (nx, ny)) ) __A : List[Any] = dist + 1 __A : Union[str, Any] = (x, y) return np.inf, [] if __name__ == "__main__": import doctest doctest.testmod()
280
1
def _SCREAMING_SNAKE_CASE ( a ) -> list: # bit count represents no. of bits in the gray code if bit_count < 0: raise ValueError('The given input must be positive' ) # get the generated string sequence __A : int = gray_code_sequence_string(a ) # # convert them to integers for i in range(len(a ) ): __A : Any = int(sequence[i] , 2 ) return sequence def _SCREAMING_SNAKE_CASE ( a ) -> list: # The approach is a recursive one # Base case achieved when either n = 0 or n=1 if bit_count == 0: return ["0"] if bit_count == 1: return ["0", "1"] __A : Tuple = 1 << bit_count # defines the length of the sequence # 1<< n is equivalent to 2^n # recursive answer will generate answer for n-1 bits __A : str = gray_code_sequence_string(bit_count - 1 ) __A : Tuple = [] # append 0 to first half of the smaller sequence generated for i in range(seq_len // 2 ): __A : int = '0' + smaller_sequence[i] sequence.append(a ) # append 1 to second half ... start from the end of the list for i in reversed(range(seq_len // 2 ) ): __A : List[Any] = '1' + smaller_sequence[i] sequence.append(a ) return sequence if __name__ == "__main__": import doctest doctest.testmod()
280
from typing import List, Optional, Union import numpy as np import PIL import torch from PIL import Image from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) UpperCAmelCase : List[Any] = logging.get_logger(__name__) # pylint: disable=invalid-name UpperCAmelCase : Dict = ''' Examples: ```py >>> from diffusers import KandinskyV22Img2ImgPipeline, KandinskyV22PriorPipeline >>> from diffusers.utils import load_image >>> import torch >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained( ... "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16 ... ) >>> pipe_prior.to("cuda") >>> prompt = "A red cartoon frog, 4k" >>> image_emb, zero_image_emb = pipe_prior(prompt, return_dict=False) >>> pipe = KandinskyV22Img2ImgPipeline.from_pretrained( ... "kandinsky-community/kandinsky-2-2-decoder", torch_dtype=torch.float16 ... ) >>> pipe.to("cuda") >>> init_image = load_image( ... "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" ... "/kandinsky/frog.png" ... ) >>> image = pipe( ... image=init_image, ... image_embeds=image_emb, ... negative_image_embeds=zero_image_emb, ... height=768, ... width=768, ... num_inference_steps=100, ... strength=0.2, ... ).images >>> image[0].save("red_frog.png") ``` ''' def _SCREAMING_SNAKE_CASE ( a , a , a=8 ) -> Tuple: __A : List[str] = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 __A : Optional[int] = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor def _SCREAMING_SNAKE_CASE ( a , a=5_12 , a=5_12 ) -> int: __A : Optional[Any] = pil_image.resize((w, h) , resample=Image.BICUBIC , reducing_gap=1 ) __A : Union[str, Any] = np.array(pil_image.convert('RGB' ) ) __A : Optional[int] = arr.astype(np.floataa ) / 127.5 - 1 __A : int = np.transpose(a , [2, 0, 1] ) __A : Tuple = torch.from_numpy(a ).unsqueeze(0 ) return image class _A( snake_case__ ): """simple docstring""" def __init__( self , _A , _A , _A , ): super().__init__() self.register_modules( unet=_A , scheduler=_A , movq=_A , ) __A : Tuple = 2 ** (len(self.movq.config.block_out_channels ) - 1) def UpperCAmelCase_ ( self , _A , _A , _A ): # get the original timestep using init_timestep __A : Optional[int] = min(int(num_inference_steps * strength ) , _A ) __A : Dict = max(num_inference_steps - init_timestep , 0 ) __A : Tuple = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A=None ): if not isinstance(_A , (torch.Tensor, PIL.Image.Image, list) ): raise ValueError( F"""`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(_A )}""" ) __A : Union[str, Any] = image.to(device=_A , dtype=_A ) __A : Optional[Any] = batch_size * num_images_per_prompt if image.shape[1] == 4: __A : int = image else: if isinstance(_A , _A ) and len(_A ) != batch_size: raise ValueError( F"""You have passed a list of generators of length {len(_A )}, but requested an effective batch""" F""" size of {batch_size}. Make sure the batch size matches the length of the generators.""" ) elif isinstance(_A , _A ): __A : str = [ self.movq.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(_A ) ] __A : str = torch.cat(_A , dim=0 ) else: __A : List[str] = self.movq.encode(_A ).latent_dist.sample(_A ) __A : Tuple = self.movq.config.scaling_factor * init_latents __A : Optional[int] = torch.cat([init_latents] , dim=0 ) __A : Union[str, Any] = init_latents.shape __A : List[str] = randn_tensor(_A , generator=_A , device=_A , dtype=_A ) # get latents __A : Optional[Any] = self.scheduler.add_noise(_A , _A , _A ) __A : Optional[int] = init_latents return latents def UpperCAmelCase_ ( self , _A=0 ): if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('Please install accelerate via `pip install accelerate`' ) __A : Optional[int] = torch.device(F"""cuda:{gpu_id}""" ) __A : Union[str, Any] = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(_A , _A ) def UpperCAmelCase_ ( self , _A=0 ): if is_accelerate_available() and is_accelerate_version('>=' , '0.17.0.dev0' ): from accelerate import cpu_offload_with_hook else: raise ImportError('`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.' ) __A : List[Any] = torch.device(F"""cuda:{gpu_id}""" ) if self.device.type != "cpu": self.to('cpu' , silence_dtype_warnings=_A ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) __A : int = None for cpu_offloaded_model in [self.unet, self.movq]: __A , __A : Optional[int] = cpu_offload_with_hook(_A , _A , prev_module_hook=_A ) # We'll offload the last model manually. __A : List[str] = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def UpperCAmelCase_ ( self ): if not hasattr(self.unet , '_hf_hook' ): return self.device for module in self.unet.modules(): if ( hasattr(_A , '_hf_hook' ) and hasattr(module._hf_hook , 'execution_device' ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(_A ) def __call__( self , _A , _A , _A , _A = 512 , _A = 512 , _A = 100 , _A = 4.0 , _A = 0.3 , _A = 1 , _A = None , _A = "pil" , _A = True , ): __A : List[Any] = self._execution_device __A : Optional[Any] = guidance_scale > 1.0 if isinstance(_A , _A ): __A : Optional[Any] = torch.cat(_A , dim=0 ) __A : Tuple = image_embeds.shape[0] if isinstance(_A , _A ): __A : List[Any] = torch.cat(_A , dim=0 ) if do_classifier_free_guidance: __A : Union[str, Any] = image_embeds.repeat_interleave(_A , dim=0 ) __A : Optional[int] = negative_image_embeds.repeat_interleave(_A , dim=0 ) __A : List[str] = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=_A ) if not isinstance(_A , _A ): __A : List[Any] = [image] if not all(isinstance(_A , (PIL.Image.Image, torch.Tensor) ) for i in image ): raise ValueError( F"""Input is in incorrect format: {[type(_A ) for i in image]}. Currently, we only support PIL image and pytorch tensor""" ) __A : Dict = torch.cat([prepare_image(_A , _A , _A ) for i in image] , dim=0 ) __A : Any = image.to(dtype=image_embeds.dtype , device=_A ) __A : Tuple = self.movq.encode(_A )['latents'] __A : int = latents.repeat_interleave(_A , dim=0 ) self.scheduler.set_timesteps(_A , device=_A ) __A , __A : int = self.get_timesteps(_A , _A , _A ) __A : Union[str, Any] = timesteps[:1].repeat(batch_size * num_images_per_prompt ) __A , __A : Any = downscale_height_and_width(_A , _A , self.movq_scale_factor ) __A : Tuple = self.prepare_latents( _A , _A , _A , _A , image_embeds.dtype , _A , _A ) for i, t in enumerate(self.progress_bar(_A ) ): # expand the latents if we are doing classifier free guidance __A : Optional[int] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents __A : Dict = {'image_embeds': image_embeds} __A : List[str] = self.unet( sample=_A , timestep=_A , encoder_hidden_states=_A , added_cond_kwargs=_A , return_dict=_A , )[0] if do_classifier_free_guidance: __A , __A : Dict = noise_pred.split(latents.shape[1] , dim=1 ) __A , __A : Optional[Any] = noise_pred.chunk(2 ) __A , __A : List[str] = variance_pred.chunk(2 ) __A : str = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) __A : List[str] = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , 'variance_type' ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): __A , __A : Optional[Any] = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 __A : List[str] = self.scheduler.step( _A , _A , _A , generator=_A , )[0] # post-processing __A : List[Any] = self.movq.decode(_A , force_not_quantize=_A )['sample'] if output_type not in ["pt", "np", "pil"]: raise ValueError(F"""Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}""" ) if output_type in ["np", "pil"]: __A : List[str] = image * 0.5 + 0.5 __A : List[str] = image.clamp(0 , 1 ) __A : Optional[Any] = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": __A : Any = self.numpy_to_pil(_A ) if not return_dict: return (image,) return ImagePipelineOutput(images=_A )
280
1
def _SCREAMING_SNAKE_CASE ( a ) -> int: if not isinstance(a , a ): raise ValueError('Input must be an integer' ) if input_num <= 0: raise ValueError('Input must be positive' ) return sum( divisor for divisor in range(1 , input_num // 2 + 1 ) if input_num % divisor == 0 ) if __name__ == "__main__": import doctest doctest.testmod()
280
import argparse import os import gluonnlp as nlp import mxnet as mx import numpy as np import torch from gluonnlp.base import get_home_dir from gluonnlp.model.bert import BERTEncoder from gluonnlp.model.utils import _load_vocab from gluonnlp.vocab import Vocab from packaging import version from torch import nn from transformers import BertConfig, BertForMaskedLM, BertModel, RobertaTokenizer from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertSelfAttention, BertSelfOutput, ) from transformers.utils import logging if version.parse(nlp.__version__) != version.parse('''0.8.3'''): raise Exception('''requires gluonnlp == 0.8.3''') if version.parse(mx.__version__) != version.parse('''1.5.0'''): raise Exception('''requires mxnet == 1.5.0''') logging.set_verbosity_info() UpperCAmelCase : List[Any] = logging.get_logger(__name__) UpperCAmelCase : Optional[Any] = '''The Nymphenburg Palace is a beautiful palace in Munich!''' def _SCREAMING_SNAKE_CASE ( a , a ) -> Optional[Any]: __A : Any = { 'attention_cell': 'multi_head', 'num_layers': 4, 'units': 10_24, 'hidden_size': 7_68, 'max_length': 5_12, 'num_heads': 8, 'scaled': True, 'dropout': 0.1, 'use_residual': True, 'embed_size': 10_24, 'embed_dropout': 0.1, 'word_embed': None, 'layer_norm_eps': 1e-5, 'token_type_vocab_size': 2, } __A : str = bort_4_8_768_1024_hparams # Let's construct the original Bort model here # Taken from official BERT implementation, see: # https://github.com/alexa/bort/blob/master/bort/bort.py __A : Optional[int] = BERTEncoder( attention_cell=predefined_args['attention_cell'] , num_layers=predefined_args['num_layers'] , units=predefined_args['units'] , hidden_size=predefined_args['hidden_size'] , max_length=predefined_args['max_length'] , num_heads=predefined_args['num_heads'] , scaled=predefined_args['scaled'] , dropout=predefined_args['dropout'] , output_attention=a , output_all_encodings=a , use_residual=predefined_args['use_residual'] , activation=predefined_args.get('activation' , 'gelu' ) , layer_norm_eps=predefined_args.get('layer_norm_eps' , a ) , ) # Vocab information needs to be fetched first # It's the same as RoBERTa, so RobertaTokenizer can be used later __A : Union[str, Any] = 'openwebtext_ccnews_stories_books_cased' # Specify download folder to Gluonnlp's vocab __A : Any = os.path.join(get_home_dir() , 'models' ) __A : List[Any] = _load_vocab(a , a , a , cls=a ) __A : Dict = nlp.model.BERTModel( a , len(a ) , units=predefined_args['units'] , embed_size=predefined_args['embed_size'] , embed_dropout=predefined_args['embed_dropout'] , word_embed=predefined_args['word_embed'] , use_pooler=a , use_token_type_embed=a , token_type_vocab_size=predefined_args['token_type_vocab_size'] , use_classifier=a , use_decoder=a , ) original_bort.load_parameters(a , cast_dtype=a , ignore_extra=a ) __A : Union[str, Any] = original_bort._collect_params_with_prefix() # Build our config 🤗 __A : Any = { 'architectures': ['BertForMaskedLM'], 'attention_probs_dropout_prob': predefined_args['dropout'], 'hidden_act': 'gelu', 'hidden_dropout_prob': predefined_args['dropout'], 'hidden_size': predefined_args['embed_size'], 'initializer_range': 0.02, 'intermediate_size': predefined_args['hidden_size'], 'layer_norm_eps': predefined_args['layer_norm_eps'], 'max_position_embeddings': predefined_args['max_length'], 'model_type': 'bort', 'num_attention_heads': predefined_args['num_heads'], 'num_hidden_layers': predefined_args['num_layers'], 'pad_token_id': 1, # 2 = BERT, 1 = RoBERTa 'type_vocab_size': 1, # 2 = BERT, 1 = RoBERTa 'vocab_size': len(a ), } __A : int = BertConfig.from_dict(a ) __A : Union[str, Any] = BertForMaskedLM(a ) hf_bort_model.eval() # Parameter mapping table (Gluonnlp to Transformers) # * denotes layer index # # | Gluon Parameter | Transformers Parameter # | -------------------------------------------------------------- | ---------------------- # | `encoder.layer_norm.beta` | `bert.embeddings.LayerNorm.bias` # | `encoder.layer_norm.gamma` | `bert.embeddings.LayerNorm.weight` # | `encoder.position_weight` | `bert.embeddings.position_embeddings.weight` # | `word_embed.0.weight` | `bert.embeddings.word_embeddings.weight` # | `encoder.transformer_cells.*.attention_cell.proj_key.bias` | `bert.encoder.layer.*.attention.self.key.bias` # | `encoder.transformer_cells.*.attention_cell.proj_key.weight` | `bert.encoder.layer.*.attention.self.key.weight` # | `encoder.transformer_cells.*.attention_cell.proj_query.bias` | `bert.encoder.layer.*.attention.self.query.bias` # | `encoder.transformer_cells.*.attention_cell.proj_query.weight` | `bert.encoder.layer.*.attention.self.query.weight` # | `encoder.transformer_cells.*.attention_cell.proj_value.bias` | `bert.encoder.layer.*.attention.self.value.bias` # | `encoder.transformer_cells.*.attention_cell.proj_value.weight` | `bert.encoder.layer.*.attention.self.value.weight` # | `encoder.transformer_cells.*.ffn.ffn_2.bias` | `bert.encoder.layer.*.attention.output.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_2.weight` | `bert.encoder.layer.*.attention.output.dense.weight` # | `encoder.transformer_cells.*.layer_norm.beta` | `bert.encoder.layer.*.attention.output.LayerNorm.bias` # | `encoder.transformer_cells.*.layer_norm.gamma` | `bert.encoder.layer.*.attention.output.LayerNorm.weight` # | `encoder.transformer_cells.*.ffn.ffn_1.bias` | `bert.encoder.layer.*.intermediate.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_1.weight` | `bert.encoder.layer.*.intermediate.dense.weight` # | `encoder.transformer_cells.*.ffn.layer_norm.beta` | `bert.encoder.layer.*.output.LayerNorm.bias` # | `encoder.transformer_cells.*.ffn.layer_norm.gamma` | `bert.encoder.layer.*.output.LayerNorm.weight` # | `encoder.transformer_cells.*.proj.bias` | `bert.encoder.layer.*.output.dense.bias` # | `encoder.transformer_cells.*.proj.weight` | `bert.encoder.layer.*.output.dense.weight` # Helper function to convert MXNET Arrays to PyTorch def to_torch(a ) -> nn.Parameter: return nn.Parameter(torch.FloatTensor(mx_array.data().asnumpy() ) ) # Check param shapes and map new HF param back def check_and_map_params(a , a ): __A : Tuple = hf_param.shape __A : str = to_torch(params[gluon_param] ) __A : Union[str, Any] = gluon_param.shape assert ( shape_hf == shape_gluon ), F"""The gluon parameter {gluon_param} has shape {shape_gluon}, but expects shape {shape_hf} for Transformers""" return gluon_param __A : str = check_and_map_params( hf_bort_model.bert.embeddings.word_embeddings.weight , 'word_embed.0.weight' ) __A : Tuple = check_and_map_params( hf_bort_model.bert.embeddings.position_embeddings.weight , 'encoder.position_weight' ) __A : List[str] = check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.bias , 'encoder.layer_norm.beta' ) __A : Tuple = check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.weight , 'encoder.layer_norm.gamma' ) # Inspired by RoBERTa conversion script, we just zero them out (Bort does not use them) __A : Tuple = torch.zeros_like( hf_bort_model.bert.embeddings.token_type_embeddings.weight.data ) for i in range(hf_bort_config.num_hidden_layers ): __A : BertLayer = hf_bort_model.bert.encoder.layer[i] # self attention __A : BertSelfAttention = layer.attention.self __A : Optional[Any] = check_and_map_params( self_attn.key.bias.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_key.bias""" ) __A : Optional[int] = check_and_map_params( self_attn.key.weight.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_key.weight""" ) __A : Union[str, Any] = check_and_map_params( self_attn.query.bias.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_query.bias""" ) __A : Optional[Any] = check_and_map_params( self_attn.query.weight.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_query.weight""" ) __A : Union[str, Any] = check_and_map_params( self_attn.value.bias.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_value.bias""" ) __A : Optional[int] = check_and_map_params( self_attn.value.weight.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_value.weight""" ) # self attention output __A : BertSelfOutput = layer.attention.output __A : Tuple = check_and_map_params( self_output.dense.bias , F"""encoder.transformer_cells.{i}.proj.bias""" ) __A : int = check_and_map_params( self_output.dense.weight , F"""encoder.transformer_cells.{i}.proj.weight""" ) __A : List[Any] = check_and_map_params( self_output.LayerNorm.bias , F"""encoder.transformer_cells.{i}.layer_norm.beta""" ) __A : str = check_and_map_params( self_output.LayerNorm.weight , F"""encoder.transformer_cells.{i}.layer_norm.gamma""" ) # intermediate __A : BertIntermediate = layer.intermediate __A : int = check_and_map_params( intermediate.dense.bias , F"""encoder.transformer_cells.{i}.ffn.ffn_1.bias""" ) __A : List[Any] = check_and_map_params( intermediate.dense.weight , F"""encoder.transformer_cells.{i}.ffn.ffn_1.weight""" ) # output __A : BertOutput = layer.output __A : List[Any] = check_and_map_params( bert_output.dense.bias , F"""encoder.transformer_cells.{i}.ffn.ffn_2.bias""" ) __A : Dict = check_and_map_params( bert_output.dense.weight , F"""encoder.transformer_cells.{i}.ffn.ffn_2.weight""" ) __A : Optional[int] = check_and_map_params( bert_output.LayerNorm.bias , F"""encoder.transformer_cells.{i}.ffn.layer_norm.beta""" ) __A : Dict = check_and_map_params( bert_output.LayerNorm.weight , F"""encoder.transformer_cells.{i}.ffn.layer_norm.gamma""" ) # Save space and energy 🎄 hf_bort_model.half() # Compare output of both models __A : Any = RobertaTokenizer.from_pretrained('roberta-base' ) __A : List[str] = tokenizer.encode_plus(a )['input_ids'] # Get gluon output __A : List[str] = mx.nd.array([input_ids] ) __A : Union[str, Any] = original_bort(inputs=a , token_types=[] ) # Get Transformer output (save and reload model again) hf_bort_model.save_pretrained(a ) __A : Optional[Any] = BertModel.from_pretrained(a ) hf_bort_model.eval() __A : Tuple = tokenizer.encode_plus(a , return_tensors='pt' ) __A : Any = hf_bort_model(**a )[0] __A : Union[str, Any] = output_gluon[0].asnumpy() __A : Tuple = output_hf[0].detach().numpy() __A : int = np.max(np.abs(hf_layer - gluon_layer ) ).item() __A : int = np.allclose(a , a , atol=1e-3 ) if success: print('✔️ Both model do output the same tensors' ) else: print('❌ Both model do **NOT** output the same tensors' ) print('Absolute difference is:' , a ) if __name__ == "__main__": UpperCAmelCase : int = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--bort_checkpoint_path''', default=None, type=str, required=True, help='''Path the official Bort params file.''' ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) UpperCAmelCase : Dict = parser.parse_args() convert_bort_checkpoint_to_pytorch(args.bort_checkpoint_path, args.pytorch_dump_folder_path)
280
1
import os import posixpath import uuid from dataclasses import dataclass from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union import numpy as np import pyarrow as pa import datasets from datasets.arrow_writer import ArrowWriter, ParquetWriter from datasets.config import MAX_SHARD_SIZE from datasets.filesystems import ( is_remote_filesystem, rename, ) from datasets.iterable_dataset import _BaseExamplesIterable from datasets.utils.py_utils import convert_file_size_to_int UpperCAmelCase : Tuple = datasets.utils.logging.get_logger(__name__) if TYPE_CHECKING: import pyspark @dataclass class _A( datasets.BuilderConfig ): """simple docstring""" UpperCamelCase : Optional[datasets.Features] = None def _SCREAMING_SNAKE_CASE ( a , a , ) -> Union[str, Any]: import pyspark def generate_fn(): __A : str = df.select('*' , pyspark.sql.functions.spark_partition_id().alias('part_id' ) ) for partition_id in partition_order: __A : int = df_with_partition_id.select('*' ).where(F"""part_id = {partition_id}""" ).drop('part_id' ) __A : Optional[Any] = partition_df.collect() __A : Optional[Any] = 0 for row in rows: yield F"""{partition_id}_{row_id}""", row.asDict() row_id += 1 return generate_fn class _A( _BaseExamplesIterable ): """simple docstring""" def __init__( self , _A , _A=None , ): __A : Union[str, Any] = df __A : Any = partition_order or range(self.df.rdd.getNumPartitions() ) __A : Union[str, Any] = _generate_iterable_examples(self.df , self.partition_order ) def __iter__( self ): yield from self.generate_examples_fn() def UpperCAmelCase_ ( self , _A ): __A : Optional[int] = list(range(self.df.rdd.getNumPartitions() ) ) generator.shuffle(_A ) return SparkExamplesIterable(self.df , partition_order=_A ) def UpperCAmelCase_ ( self , _A , _A ): __A : Optional[int] = self.split_shard_indices_by_worker(_A , _A ) return SparkExamplesIterable(self.df , partition_order=_A ) @property def UpperCAmelCase_ ( self ): return len(self.partition_order ) class _A( datasets.DatasetBuilder ): """simple docstring""" UpperCamelCase : List[Any] = SparkConfig def __init__( self , _A , _A = None , _A = None , **_A , ): import pyspark __A : Any = pyspark.sql.SparkSession.builder.getOrCreate() __A : List[Any] = df __A : Optional[int] = working_dir super().__init__( cache_dir=_A , config_name=str(self.df.semanticHash() ) , **_A , ) def UpperCAmelCase_ ( self ): # Returns the path of the created file. def create_cache_and_write_probe(_A ): # makedirs with exist_ok will recursively create the directory. It will not throw an error if directories # already exist. os.makedirs(self._cache_dir , exist_ok=_A ) __A : Any = os.path.join(self._cache_dir , 'fs_test' + uuid.uuida().hex ) # Opening the file in append mode will create a new file unless it already exists, in which case it will not # change the file contents. open(_A , 'a' ) return [probe_file] if self._spark.conf.get('spark.master' , '' ).startswith('local' ): return # If the cluster is multi-node, make sure that the user provided a cache_dir and that it is on an NFS # accessible to the driver. # TODO: Stream batches to the driver using ArrowCollectSerializer instead of throwing an error. if self._cache_dir: __A : List[str] = ( self._spark.sparkContext.parallelize(range(1 ) , 1 ).mapPartitions(_A ).collect() ) if os.path.isfile(probe[0] ): return raise ValueError( 'When using Dataset.from_spark on a multi-node cluster, the driver and all workers should be able to access cache_dir' ) def UpperCAmelCase_ ( self ): return datasets.DatasetInfo(features=self.config.features ) def UpperCAmelCase_ ( self , _A ): return [datasets.SplitGenerator(name=datasets.Split.TRAIN )] def UpperCAmelCase_ ( self , _A ): import pyspark def get_arrow_batch_size(_A ): for batch in it: yield pa.RecordBatch.from_pydict({'batch_bytes': [batch.nbytes]} ) __A : Any = self.df.count() __A : List[str] = df_num_rows if df_num_rows <= 100 else 100 # Approximate the size of each row (in Arrow format) by averaging over a max-100-row sample. __A : str = ( self.df.limit(_A ) .repartition(1 ) .mapInArrow(_A , 'batch_bytes: long' ) .agg(pyspark.sql.functions.sum('batch_bytes' ).alias('sample_bytes' ) ) .collect()[0] .sample_bytes / sample_num_rows ) __A : List[Any] = approx_bytes_per_row * df_num_rows if approx_total_size > max_shard_size: # Make sure there is at least one row per partition. __A : Optional[Any] = min(_A , int(approx_total_size / max_shard_size ) ) __A : str = self.df.repartition(_A ) def UpperCAmelCase_ ( self , _A , _A , _A , ): import pyspark __A : Tuple = ParquetWriter if file_format == 'parquet' else ArrowWriter __A : Optional[Any] = os.path.join(self._working_dir , os.path.basename(_A ) ) if self._working_dir else fpath __A : Dict = file_format == 'parquet' # Define these so that we don't reference self in write_arrow, which will result in a pickling error due to # pickling the SparkContext. __A : int = self.config.features __A : List[Any] = self._writer_batch_size __A : int = self._fs.storage_options def write_arrow(_A ): # Within the same SparkContext, no two task attempts will share the same attempt ID. __A : List[Any] = pyspark.TaskContext().taskAttemptId() __A : List[str] = next(_A , _A ) if first_batch is None: # Some partitions might not receive any data. return pa.RecordBatch.from_arrays( [[task_id], [0], [0]] , names=['task_id', 'num_examples', 'num_bytes'] , ) __A : Dict = 0 __A : List[str] = writer_class( features=_A , path=working_fpath.replace('SSSSS' , F"""{shard_id:05d}""" ).replace('TTTTT' , F"""{task_id:05d}""" ) , writer_batch_size=_A , storage_options=_A , embed_local_files=_A , ) __A : Tuple = pa.Table.from_batches([first_batch] ) writer.write_table(_A ) for batch in it: if max_shard_size is not None and writer._num_bytes >= max_shard_size: __A , __A : Optional[Any] = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=['task_id', 'num_examples', 'num_bytes'] , ) shard_id += 1 __A : List[Any] = writer_class( features=writer._features , path=working_fpath.replace('SSSSS' , F"""{shard_id:05d}""" ).replace('TTTTT' , F"""{task_id:05d}""" ) , writer_batch_size=_A , storage_options=_A , embed_local_files=_A , ) __A : List[Any] = pa.Table.from_batches([batch] ) writer.write_table(_A ) if writer._num_bytes > 0: __A , __A : Union[str, Any] = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=['task_id', 'num_examples', 'num_bytes'] , ) if working_fpath != fpath: for file in os.listdir(os.path.dirname(_A ) ): __A : List[Any] = os.path.join(os.path.dirname(_A ) , os.path.basename(_A ) ) shutil.move(_A , _A ) __A : List[str] = ( self.df.mapInArrow(_A , 'task_id: long, num_examples: long, num_bytes: long' ) .groupBy('task_id' ) .agg( pyspark.sql.functions.sum('num_examples' ).alias('total_num_examples' ) , pyspark.sql.functions.sum('num_bytes' ).alias('total_num_bytes' ) , pyspark.sql.functions.count('num_bytes' ).alias('num_shards' ) , pyspark.sql.functions.collect_list('num_examples' ).alias('shard_lengths' ) , ) .collect() ) for row in stats: yield row.task_id, (row.total_num_examples, row.total_num_bytes, row.num_shards, row.shard_lengths) def UpperCAmelCase_ ( self , _A , _A = "arrow" , _A = None , _A = None , **_A , ): self._validate_cache_dir() __A : Dict = convert_file_size_to_int(max_shard_size or MAX_SHARD_SIZE ) self._repartition_df_if_needed(_A ) __A : List[Any] = not is_remote_filesystem(self._fs ) __A : Union[str, Any] = os.path.join if is_local else posixpath.join __A : List[str] = '-TTTTT-SSSSS-of-NNNNN' __A : Any = F"""{self.name}-{split_generator.name}{SUFFIX}.{file_format}""" __A : str = path_join(self._output_dir , _A ) __A : Any = 0 __A : List[str] = 0 __A : Optional[Any] = 0 __A : Tuple = [] __A : Optional[Any] = [] for task_id, content in self._prepare_split_single(_A , _A , _A ): ( ( __A ) , ( __A ) , ( __A ) , ( __A ) , ) : List[str] = content if num_bytes > 0: total_num_examples += num_examples total_num_bytes += num_bytes total_shards += num_shards task_id_and_num_shards.append((task_id, num_shards) ) all_shard_lengths.extend(_A ) __A : Optional[int] = total_num_examples __A : Tuple = total_num_bytes # should rename everything at the end logger.debug(F"""Renaming {total_shards} shards.""" ) if total_shards > 1: __A : Any = all_shard_lengths # Define fs outside of _rename_shard so that we don't reference self in the function, which will result in a # pickling error due to pickling the SparkContext. __A : Union[str, Any] = self._fs # use the -SSSSS-of-NNNNN pattern def _rename_shard( _A , _A , _A , ): rename( _A , fpath.replace('SSSSS' , F"""{shard_id:05d}""" ).replace('TTTTT' , F"""{task_id:05d}""" ) , fpath.replace('TTTTT-SSSSS' , F"""{global_shard_id:05d}""" ).replace('NNNNN' , F"""{total_shards:05d}""" ) , ) __A : List[Any] = [] __A : List[Any] = 0 for i in range(len(_A ) ): __A , __A : Tuple = task_id_and_num_shards[i] for shard_id in range(_A ): args.append([task_id, shard_id, global_shard_id] ) global_shard_id += 1 self._spark.sparkContext.parallelize(_A , len(_A ) ).map(lambda _A : _rename_shard(*_A ) ).collect() else: # don't use any pattern __A : Union[str, Any] = 0 __A : Dict = task_id_and_num_shards[0][0] self._rename( fpath.replace('SSSSS' , F"""{shard_id:05d}""" ).replace('TTTTT' , F"""{task_id:05d}""" ) , fpath.replace(_A , '' ) , ) def UpperCAmelCase_ ( self , _A , ): return SparkExamplesIterable(self.df )
280
import colorsys from PIL import Image # type: ignore def _SCREAMING_SNAKE_CASE ( a , a , a ) -> float: __A : List[str] = x __A : str = y for step in range(a ): # noqa: B007 __A : Union[str, Any] = a * a - b * b + x __A : Optional[int] = 2 * a * b + y __A : List[str] = a_new # divergence happens for all complex number with an absolute value # greater than 4 if a * a + b * b > 4: break return step / (max_step - 1) def _SCREAMING_SNAKE_CASE ( a ) -> tuple: if distance == 1: return (0, 0, 0) else: return (2_55, 2_55, 2_55) def _SCREAMING_SNAKE_CASE ( a ) -> tuple: if distance == 1: return (0, 0, 0) else: return tuple(round(i * 2_55 ) for i in colorsys.hsv_to_rgb(a , 1 , 1 ) ) def _SCREAMING_SNAKE_CASE ( a = 8_00 , a = 6_00 , a = -0.6 , a = 0 , a = 3.2 , a = 50 , a = True , ) -> Image.Image: __A : str = Image.new('RGB' , (image_width, image_height) ) __A : Dict = img.load() # loop through the image-coordinates for image_x in range(a ): for image_y in range(a ): # determine the figure-coordinates based on the image-coordinates __A : Dict = figure_width / image_width * image_height __A : Union[str, Any] = figure_center_x + (image_x / image_width - 0.5) * figure_width __A : Optional[Any] = figure_center_y + (image_y / image_height - 0.5) * figure_height __A : Union[str, Any] = get_distance(a , a , a ) # color the corresponding pixel based on the selected coloring-function if use_distance_color_coding: __A : Optional[Any] = get_color_coded_rgb(a ) else: __A : Dict = get_black_and_white_rgb(a ) return img if __name__ == "__main__": import doctest doctest.testmod() # colored version, full figure UpperCAmelCase : str = get_image() # uncomment for colored version, different section, zoomed in # img = get_image(figure_center_x = -0.6, figure_center_y = -0.4, # figure_width = 0.8) # uncomment for black and white version, full figure # img = get_image(use_distance_color_coding = False) # uncomment to save the image # img.save("mandelbrot.png") img.show()
280
1
from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def _SCREAMING_SNAKE_CASE ( a , a , a , a , ) -> list[float]: __A , __A : Optional[Any] = coefficient_matrix.shape __A , __A : str = constant_matrix.shape if rowsa != colsa: __A : Optional[Any] = F"""Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}""" raise ValueError(a ) if colsa != 1: __A : int = F"""Constant matrix must be nx1 but received {rowsa}x{colsa}""" raise ValueError(a ) if rowsa != rowsa: __A : Any = ( 'Coefficient and constant matrices dimensions must be nxn and nx1 but ' F"""received {rowsa}x{colsa} and {rowsa}x{colsa}""" ) raise ValueError(a ) if len(a ) != rowsa: __A : str = ( 'Number of initial values must be equal to number of rows in coefficient ' F"""matrix but received {len(a )} and {rowsa}""" ) raise ValueError(a ) if iterations <= 0: raise ValueError('Iterations must be at least 1' ) __A : NDArray[floataa] = np.concatenate( (coefficient_matrix, constant_matrix) , axis=1 ) __A , __A : Any = table.shape strictly_diagonally_dominant(a ) # Iterates the whole matrix for given number of times for _ in range(a ): __A : Dict = [] for row in range(a ): __A : Dict = 0 for col in range(a ): if col == row: __A : List[str] = table[row][col] elif col == cols - 1: __A : Optional[Any] = table[row][col] else: temp += (-1) * table[row][col] * init_val[col] __A : str = (temp + val) / denom new_val.append(a ) __A : int = new_val return [float(a ) for i in new_val] def _SCREAMING_SNAKE_CASE ( a ) -> bool: __A , __A : Union[str, Any] = table.shape __A : Any = True for i in range(0 , a ): __A : str = 0 for j in range(0 , cols - 1 ): if i == j: continue else: total += table[i][j] if table[i][i] <= total: raise ValueError('Coefficient matrix is not strictly diagonally dominant' ) return is_diagonally_dominant # Test Cases if __name__ == "__main__": import doctest doctest.testmod()
280
from __future__ import annotations def _SCREAMING_SNAKE_CASE ( a , a , a ) -> float: if days_between_payments <= 0: raise ValueError('days_between_payments must be > 0' ) if daily_interest_rate < 0: raise ValueError('daily_interest_rate must be >= 0' ) if principal <= 0: raise ValueError('principal must be > 0' ) return principal * daily_interest_rate * days_between_payments def _SCREAMING_SNAKE_CASE ( a , a , a , ) -> float: if number_of_compounding_periods <= 0: raise ValueError('number_of_compounding_periods must be > 0' ) if nominal_annual_interest_rate_percentage < 0: raise ValueError('nominal_annual_interest_rate_percentage must be >= 0' ) if principal <= 0: raise ValueError('principal must be > 0' ) return principal * ( (1 + nominal_annual_interest_rate_percentage) ** number_of_compounding_periods - 1 ) def _SCREAMING_SNAKE_CASE ( a , a , a , ) -> float: if number_of_years <= 0: raise ValueError('number_of_years must be > 0' ) if nominal_annual_percentage_rate < 0: raise ValueError('nominal_annual_percentage_rate must be >= 0' ) if principal <= 0: raise ValueError('principal must be > 0' ) return compound_interest( a , nominal_annual_percentage_rate / 3_65 , number_of_years * 3_65 ) if __name__ == "__main__": import doctest doctest.testmod()
280
1
def _SCREAMING_SNAKE_CASE ( a = 1_00 ) -> int: __A : List[str] = n * (n + 1) * (2 * n + 1) / 6 __A : List[str] = (n * (n + 1) / 2) ** 2 return int(square_of_sum - sum_of_squares ) if __name__ == "__main__": print(F"""{solution() = }""")
280
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) UpperCAmelCase : Any = { '''configuration_falcon''': ['''FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''FalconConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Any = [ '''FALCON_PRETRAINED_MODEL_ARCHIVE_LIST''', '''FalconForCausalLM''', '''FalconModel''', '''FalconPreTrainedModel''', '''FalconForSequenceClassification''', '''FalconForTokenClassification''', '''FalconForQuestionAnswering''', ] if TYPE_CHECKING: from .configuration_falcon import FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP, FalconConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_falcon import ( FALCON_PRETRAINED_MODEL_ARCHIVE_LIST, FalconForCausalLM, FalconForQuestionAnswering, FalconForSequenceClassification, FalconForTokenClassification, FalconModel, FalconPreTrainedModel, ) else: import sys UpperCAmelCase : List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
280
1
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase : Dict = logging.get_logger(__name__) UpperCAmelCase : List[Any] = { '''google/fnet-base''': '''https://huggingface.co/google/fnet-base/resolve/main/config.json''', '''google/fnet-large''': '''https://huggingface.co/google/fnet-large/resolve/main/config.json''' # See all FNet models at https://huggingface.co/models?filter=fnet } class _A( snake_case__ ): """simple docstring""" UpperCamelCase : Dict = '''fnet''' def __init__( self , _A=32000 , _A=768 , _A=12 , _A=3072 , _A="gelu_new" , _A=0.1 , _A=512 , _A=4 , _A=0.0_2 , _A=1e-1_2 , _A=False , _A=512 , _A=3 , _A=1 , _A=2 , **_A , ): super().__init__(pad_token_id=_A , bos_token_id=_A , eos_token_id=_A , **_A ) __A : Dict = vocab_size __A : Optional[Any] = max_position_embeddings __A : Dict = hidden_size __A : Any = num_hidden_layers __A : Optional[int] = intermediate_size __A : Optional[int] = hidden_act __A : List[Any] = hidden_dropout_prob __A : Optional[Any] = initializer_range __A : Optional[int] = type_vocab_size __A : Tuple = layer_norm_eps __A : Tuple = use_tpu_fourier_optimizations __A : str = tpu_short_seq_length
280
def _SCREAMING_SNAKE_CASE ( a ) -> bool: return str(a ) == str(a )[::-1] def _SCREAMING_SNAKE_CASE ( a ) -> int: return int(a ) + int(str(a )[::-1] ) def _SCREAMING_SNAKE_CASE ( a = 1_00_00 ) -> int: __A : int = [] for num in range(1 , a ): __A : List[str] = 0 __A : List[Any] = num while iterations < 50: __A : str = sum_reverse(a ) iterations += 1 if is_palindrome(a ): break else: lychrel_nums.append(a ) return len(a ) if __name__ == "__main__": print(F"""{solution() = }""")
280
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available UpperCAmelCase : Dict = {'''configuration_speech_encoder_decoder''': ['''SpeechEncoderDecoderConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Any = ['''SpeechEncoderDecoderModel'''] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : List[str] = ['''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 : str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
280
from __future__ import annotations import math import random from collections.abc import Collection from typing import overload class _A: """simple docstring""" def __init__( self , _A = None ): if components is None: __A : int = [] __A : Tuple = list(_A ) def __len__( self ): return len(self.__components ) def __str__( self ): return "(" + ",".join(map(_A , self.__components ) ) + ")" def __add__( self , _A ): __A : Optional[int] = len(self ) if size == len(_A ): __A : Any = [self.__components[i] + other.component(_A ) for i in range(_A )] return Vector(_A ) else: raise Exception('must have the same size' ) def __sub__( self , _A ): __A : Tuple = len(self ) if size == len(_A ): __A : Union[str, Any] = [self.__components[i] - other.component(_A ) for i in range(_A )] return Vector(_A ) else: # error case raise Exception('must have the same size' ) @overload def __mul__( self , _A ): ... @overload def __mul__( self , _A ): ... def __mul__( self , _A ): if isinstance(_A , (float, int) ): __A : str = [c * other for c in self.__components] return Vector(_A ) elif isinstance(_A , _A ) and len(self ) == len(_A ): __A : Union[str, Any] = len(self ) __A : Dict = [self.__components[i] * other.component(_A ) for i in range(_A )] return sum(_A ) else: # error case raise Exception('invalid operand!' ) def UpperCAmelCase_ ( self ): return Vector(self.__components ) def UpperCAmelCase_ ( self , _A ): if isinstance(_A , _A ) and -len(self.__components ) <= i < len(self.__components ): return self.__components[i] else: raise Exception('index out of range' ) def UpperCAmelCase_ ( self , _A , _A ): assert -len(self.__components ) <= pos < len(self.__components ) __A : Optional[int] = value def UpperCAmelCase_ ( self ): if len(self.__components ) == 0: raise Exception('Vector is empty' ) __A : Optional[Any] = [c**2 for c in self.__components] return math.sqrt(sum(_A ) ) def UpperCAmelCase_ ( self , _A , _A = False ): __A : Optional[Any] = self * other __A : Optional[Any] = self.euclidean_length() * other.euclidean_length() if deg: return math.degrees(math.acos(num / den ) ) else: return math.acos(num / den ) def _SCREAMING_SNAKE_CASE ( a ) -> Vector: assert isinstance(a , a ) return Vector([0] * dimension ) def _SCREAMING_SNAKE_CASE ( a , a ) -> Vector: assert isinstance(a , a ) and (isinstance(a , a )) __A : Optional[Any] = [0] * dimension __A : Tuple = 1 return Vector(a ) def _SCREAMING_SNAKE_CASE ( a , a , a ) -> Vector: assert ( isinstance(a , a ) and isinstance(a , a ) and (isinstance(a , (int, float) )) ) return x * scalar + y def _SCREAMING_SNAKE_CASE ( a , a , a ) -> Vector: random.seed(a ) __A : str = [random.randint(a , a ) for _ in range(a )] return Vector(a ) class _A: """simple docstring""" def __init__( self , _A , _A , _A ): __A : Optional[Any] = matrix __A : Dict = w __A : Optional[int] = h def __str__( self ): __A : Tuple = '' for i in range(self.__height ): ans += "|" for j in range(self.__width ): if j < self.__width - 1: ans += str(self.__matrix[i][j] ) + "," else: ans += str(self.__matrix[i][j] ) + "|\n" return ans def __add__( self , _A ): if self.__width == other.width() and self.__height == other.height(): __A : Optional[Any] = [] for i in range(self.__height ): __A : Optional[Any] = [ self.__matrix[i][j] + other.component(_A , _A ) for j in range(self.__width ) ] matrix.append(_A ) return Matrix(_A , self.__width , self.__height ) else: raise Exception('matrix must have the same dimension!' ) def __sub__( self , _A ): if self.__width == other.width() and self.__height == other.height(): __A : Tuple = [] for i in range(self.__height ): __A : str = [ self.__matrix[i][j] - other.component(_A , _A ) for j in range(self.__width ) ] matrix.append(_A ) return Matrix(_A , self.__width , self.__height ) else: raise Exception('matrices must have the same dimension!' ) @overload def __mul__( self , _A ): ... @overload def __mul__( self , _A ): ... def __mul__( self , _A ): if isinstance(_A , _A ): # matrix-vector if len(_A ) == self.__width: __A : List[Any] = zero_vector(self.__height ) for i in range(self.__height ): __A : List[str] = [ self.__matrix[i][j] * other.component(_A ) for j in range(self.__width ) ] ans.change_component(_A , sum(_A ) ) return ans else: raise Exception( 'vector must have the same size as the ' 'number of columns of the matrix!' ) elif isinstance(_A , (int, float) ): # matrix-scalar __A : List[str] = [ [self.__matrix[i][j] * other for j in range(self.__width )] for i in range(self.__height ) ] return Matrix(_A , self.__width , self.__height ) return None def UpperCAmelCase_ ( self ): return self.__height def UpperCAmelCase_ ( self ): return self.__width def UpperCAmelCase_ ( self , _A , _A ): if 0 <= x < self.__height and 0 <= y < self.__width: return self.__matrix[x][y] else: raise Exception('change_component: indices out of bounds' ) def UpperCAmelCase_ ( self , _A , _A , _A ): if 0 <= x < self.__height and 0 <= y < self.__width: __A : int = value else: raise Exception('change_component: indices out of bounds' ) def UpperCAmelCase_ ( self , _A , _A ): if self.__height != self.__width: raise Exception('Matrix is not square' ) __A : List[str] = self.__matrix[:x] + self.__matrix[x + 1 :] for i in range(len(_A ) ): __A : Optional[int] = minor[i][:y] + minor[i][y + 1 :] return Matrix(_A , self.__width - 1 , self.__height - 1 ).determinant() def UpperCAmelCase_ ( self , _A , _A ): if self.__height != self.__width: raise Exception('Matrix is not square' ) if 0 <= x < self.__height and 0 <= y < self.__width: return (-1) ** (x + y) * self.minor(_A , _A ) else: raise Exception('Indices out of bounds' ) def UpperCAmelCase_ ( self ): if self.__height != self.__width: raise Exception('Matrix is not square' ) if self.__height < 1: raise Exception('Matrix has no element' ) elif self.__height == 1: return self.__matrix[0][0] elif self.__height == 2: return ( self.__matrix[0][0] * self.__matrix[1][1] - self.__matrix[0][1] * self.__matrix[1][0] ) else: __A : List[str] = [ self.__matrix[0][y] * self.cofactor(0 , _A ) for y in range(self.__width ) ] return sum(_A ) def _SCREAMING_SNAKE_CASE ( a ) -> Matrix: __A : list[list[float]] = [[0] * n for _ in range(a )] return Matrix(a , a , a ) def _SCREAMING_SNAKE_CASE ( a , a , a , a ) -> Matrix: random.seed(a ) __A : list[list[float]] = [ [random.randint(a , a ) for _ in range(a )] for _ in range(a ) ] return Matrix(a , a , a )
280
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available UpperCAmelCase : Any = { '''configuration_mvp''': ['''MVP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MvpConfig''', '''MvpOnnxConfig'''], '''tokenization_mvp''': ['''MvpTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : int = ['''MvpTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : str = [ '''MVP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MvpForCausalLM''', '''MvpForConditionalGeneration''', '''MvpForQuestionAnswering''', '''MvpForSequenceClassification''', '''MvpModel''', '''MvpPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_mvp import MVP_PRETRAINED_CONFIG_ARCHIVE_MAP, MvpConfig, MvpOnnxConfig from .tokenization_mvp import MvpTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mvp_fast import MvpTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mvp import ( MVP_PRETRAINED_MODEL_ARCHIVE_LIST, MvpForCausalLM, MvpForConditionalGeneration, MvpForQuestionAnswering, MvpForSequenceClassification, MvpModel, MvpPreTrainedModel, ) else: import sys UpperCAmelCase : List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
280
import unittest from transformers import BertGenerationTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin UpperCAmelCase : List[str] = '''▁''' UpperCAmelCase : Optional[Any] = get_tests_dir('''fixtures/test_sentencepiece.model''') @require_sentencepiece class _A( snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Optional[int] = BertGenerationTokenizer UpperCamelCase : str = False UpperCamelCase : Tuple = True def UpperCAmelCase_ ( self ): super().setUp() __A : Tuple = BertGenerationTokenizer(_A , keep_accents=_A ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCAmelCase_ ( self ): __A : str = '<s>' __A : str = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_A ) , _A ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_A ) , _A ) def UpperCAmelCase_ ( self ): __A : int = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<unk>' ) self.assertEqual(vocab_keys[1] , '<s>' ) self.assertEqual(vocab_keys[-1] , '<pad>' ) self.assertEqual(len(_A ) , 1002 ) def UpperCAmelCase_ ( self ): self.assertEqual(self.get_tokenizer().vocab_size , 1000 ) def UpperCAmelCase_ ( self ): __A : str = BertGenerationTokenizer(_A , keep_accents=_A ) __A : Dict = tokenizer.tokenize('This is a test' ) self.assertListEqual(_A , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(_A ) , [285, 46, 10, 170, 382] , ) __A : int = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( _A , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.', ] , ) __A : Dict = tokenizer.convert_tokens_to_ids(_A ) self.assertListEqual( _A , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] , ) __A : Optional[int] = tokenizer.convert_ids_to_tokens(_A ) self.assertListEqual( _A , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.', ] , ) @cached_property def UpperCAmelCase_ ( self ): return BertGenerationTokenizer.from_pretrained('google/bert_for_seq_generation_L-24_bbc_encoder' ) @slow def UpperCAmelCase_ ( self ): __A : List[Any] = 'Hello World!' __A : Optional[Any] = [18536, 2260, 101] self.assertListEqual(_A , self.big_tokenizer.encode(_A ) ) @slow def UpperCAmelCase_ ( self ): __A : Dict = ( 'This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will' ' add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth' ) __A : int = [ 871, 419, 358, 946, 991, 2521, 452, 358, 1357, 387, 7751, 3536, 112, 985, 456, 126, 865, 938, 5400, 5734, 458, 1368, 467, 786, 2462, 5246, 1159, 633, 865, 4519, 457, 582, 852, 2557, 427, 916, 508, 405, 34324, 497, 391, 408, 11342, 1244, 385, 100, 938, 985, 456, 574, 362, 12597, 3200, 3129, 1172, ] self.assertListEqual(_A , self.big_tokenizer.encode(_A ) ) @require_torch @slow def UpperCAmelCase_ ( self ): import torch from transformers import BertGenerationConfig, BertGenerationEncoder # Build sequence __A : Tuple = list(self.big_tokenizer.get_vocab().keys() )[:10] __A : List[Any] = ' '.join(_A ) __A : Union[str, Any] = self.big_tokenizer.encode_plus(_A , return_tensors='pt' , return_token_type_ids=_A ) __A : Optional[Any] = self.big_tokenizer.batch_encode_plus( [sequence + ' ' + sequence] , return_tensors='pt' , return_token_type_ids=_A ) __A : int = BertGenerationConfig() __A : List[str] = BertGenerationEncoder(_A ) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**_A ) model(**_A ) @slow def UpperCAmelCase_ ( self ): # fmt: off __A : str = {'input_ids': [[39286, 458, 36335, 2001, 456, 13073, 13266, 455, 113, 7746, 1741, 11157, 391, 13073, 13266, 455, 113, 3967, 35412, 113, 4936, 109, 3870, 2377, 113, 30084, 45720, 458, 134, 17496, 112, 503, 11672, 113, 118, 112, 5665, 13347, 38687, 112, 1496, 31389, 112, 3268, 47264, 134, 962, 112, 16377, 8035, 23130, 430, 12169, 15518, 28592, 458, 146, 41697, 109, 391, 12169, 15518, 16689, 458, 146, 41358, 109, 452, 726, 4034, 111, 763, 35412, 5082, 388, 1903, 111, 9051, 391, 2870, 48918, 1900, 1123, 550, 998, 112, 9586, 15985, 455, 391, 410, 22955, 37636, 114], [448, 17496, 419, 3663, 385, 763, 113, 27533, 2870, 3283, 13043, 1639, 24713, 523, 656, 24013, 18550, 2521, 517, 27014, 21244, 420, 1212, 1465, 391, 927, 4833, 388, 578, 11786, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [484, 2169, 7687, 21932, 18146, 726, 363, 17032, 3391, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=_A , model_name='google/bert_for_seq_generation_L-24_bbc_encoder' , revision='c817d1fd1be2ffa69431227a1fe320544943d4db' , )
280
1
import unittest from transformers import BertGenerationTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin UpperCAmelCase : List[str] = '''▁''' UpperCAmelCase : Optional[Any] = get_tests_dir('''fixtures/test_sentencepiece.model''') @require_sentencepiece class _A( snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Optional[int] = BertGenerationTokenizer UpperCamelCase : str = False UpperCamelCase : Tuple = True def UpperCAmelCase_ ( self ): super().setUp() __A : Tuple = BertGenerationTokenizer(_A , keep_accents=_A ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCAmelCase_ ( self ): __A : str = '<s>' __A : str = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_A ) , _A ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_A ) , _A ) def UpperCAmelCase_ ( self ): __A : int = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<unk>' ) self.assertEqual(vocab_keys[1] , '<s>' ) self.assertEqual(vocab_keys[-1] , '<pad>' ) self.assertEqual(len(_A ) , 1002 ) def UpperCAmelCase_ ( self ): self.assertEqual(self.get_tokenizer().vocab_size , 1000 ) def UpperCAmelCase_ ( self ): __A : str = BertGenerationTokenizer(_A , keep_accents=_A ) __A : Dict = tokenizer.tokenize('This is a test' ) self.assertListEqual(_A , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(_A ) , [285, 46, 10, 170, 382] , ) __A : int = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( _A , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.', ] , ) __A : Dict = tokenizer.convert_tokens_to_ids(_A ) self.assertListEqual( _A , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] , ) __A : Optional[int] = tokenizer.convert_ids_to_tokens(_A ) self.assertListEqual( _A , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.', ] , ) @cached_property def UpperCAmelCase_ ( self ): return BertGenerationTokenizer.from_pretrained('google/bert_for_seq_generation_L-24_bbc_encoder' ) @slow def UpperCAmelCase_ ( self ): __A : List[Any] = 'Hello World!' __A : Optional[Any] = [18536, 2260, 101] self.assertListEqual(_A , self.big_tokenizer.encode(_A ) ) @slow def UpperCAmelCase_ ( self ): __A : Dict = ( 'This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will' ' add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth' ) __A : int = [ 871, 419, 358, 946, 991, 2521, 452, 358, 1357, 387, 7751, 3536, 112, 985, 456, 126, 865, 938, 5400, 5734, 458, 1368, 467, 786, 2462, 5246, 1159, 633, 865, 4519, 457, 582, 852, 2557, 427, 916, 508, 405, 34324, 497, 391, 408, 11342, 1244, 385, 100, 938, 985, 456, 574, 362, 12597, 3200, 3129, 1172, ] self.assertListEqual(_A , self.big_tokenizer.encode(_A ) ) @require_torch @slow def UpperCAmelCase_ ( self ): import torch from transformers import BertGenerationConfig, BertGenerationEncoder # Build sequence __A : Tuple = list(self.big_tokenizer.get_vocab().keys() )[:10] __A : List[Any] = ' '.join(_A ) __A : Union[str, Any] = self.big_tokenizer.encode_plus(_A , return_tensors='pt' , return_token_type_ids=_A ) __A : Optional[Any] = self.big_tokenizer.batch_encode_plus( [sequence + ' ' + sequence] , return_tensors='pt' , return_token_type_ids=_A ) __A : int = BertGenerationConfig() __A : List[str] = BertGenerationEncoder(_A ) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**_A ) model(**_A ) @slow def UpperCAmelCase_ ( self ): # fmt: off __A : str = {'input_ids': [[39286, 458, 36335, 2001, 456, 13073, 13266, 455, 113, 7746, 1741, 11157, 391, 13073, 13266, 455, 113, 3967, 35412, 113, 4936, 109, 3870, 2377, 113, 30084, 45720, 458, 134, 17496, 112, 503, 11672, 113, 118, 112, 5665, 13347, 38687, 112, 1496, 31389, 112, 3268, 47264, 134, 962, 112, 16377, 8035, 23130, 430, 12169, 15518, 28592, 458, 146, 41697, 109, 391, 12169, 15518, 16689, 458, 146, 41358, 109, 452, 726, 4034, 111, 763, 35412, 5082, 388, 1903, 111, 9051, 391, 2870, 48918, 1900, 1123, 550, 998, 112, 9586, 15985, 455, 391, 410, 22955, 37636, 114], [448, 17496, 419, 3663, 385, 763, 113, 27533, 2870, 3283, 13043, 1639, 24713, 523, 656, 24013, 18550, 2521, 517, 27014, 21244, 420, 1212, 1465, 391, 927, 4833, 388, 578, 11786, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [484, 2169, 7687, 21932, 18146, 726, 363, 17032, 3391, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=_A , model_name='google/bert_for_seq_generation_L-24_bbc_encoder' , revision='c817d1fd1be2ffa69431227a1fe320544943d4db' , )
280
import hashlib import unittest from typing import Dict import numpy as np from transformers import ( MODEL_FOR_MASK_GENERATION_MAPPING, TF_MODEL_FOR_MASK_GENERATION_MAPPING, is_vision_available, pipeline, ) from transformers.pipelines import MaskGenerationPipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) if is_vision_available(): from PIL import Image else: class _A: """simple docstring""" @staticmethod def UpperCAmelCase_ ( *_A , **_A ): pass def _SCREAMING_SNAKE_CASE ( a ) -> str: __A : str = hashlib.mda(image.tobytes() ) return m.hexdigest()[:10] def _SCREAMING_SNAKE_CASE ( a ) -> Dict: __A : Dict = np.array(a ) __A : List[Any] = npimg.shape return {"hash": hashimage(a ), "shape": shape} @is_pipeline_test @require_vision @require_torch class _A( unittest.TestCase ): """simple docstring""" UpperCamelCase : str = dict( (list(MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if MODEL_FOR_MASK_GENERATION_MAPPING else []) ) UpperCamelCase : int = dict( (list(TF_MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if TF_MODEL_FOR_MASK_GENERATION_MAPPING else []) ) def UpperCAmelCase_ ( self , _A , _A , _A ): __A : Dict = MaskGenerationPipeline(model=_A , image_processor=_A ) return image_segmenter, [ "./tests/fixtures/tests_samples/COCO/000000039769.png", "./tests/fixtures/tests_samples/COCO/000000039769.png", ] def UpperCAmelCase_ ( self , _A , _A ): pass @require_tf @unittest.skip('Image segmentation not implemented in TF' ) def UpperCAmelCase_ ( self ): pass @slow @require_torch def UpperCAmelCase_ ( self ): __A : Union[str, Any] = pipeline('mask-generation' , model='facebook/sam-vit-huge' ) __A : List[str] = image_segmenter('http://images.cocodataset.org/val2017/000000039769.jpg' , points_per_batch=256 ) # Shortening by hashing __A : List[Any] = [] for i, o in enumerate(outputs['masks'] ): new_outupt += [{"mask": mask_to_test_readable(_A ), "scores": outputs["scores"][i]}] # fmt: off self.assertEqual( nested_simplify(_A , decimals=4 ) , [ {'mask': {'hash': '115ad19f5f', 'shape': (480, 640)}, 'scores': 1.0_4_4_4}, {'mask': {'hash': '6affa964c6', 'shape': (480, 640)}, 'scores': 1.0_2_1}, {'mask': {'hash': 'dfe28a0388', 'shape': (480, 640)}, 'scores': 1.0_1_6_7}, {'mask': {'hash': 'c0a5f4a318', 'shape': (480, 640)}, 'scores': 1.0_1_3_2}, {'mask': {'hash': 'fe8065c197', 'shape': (480, 640)}, 'scores': 1.0_0_5_3}, {'mask': {'hash': 'e2d0b7a0b7', 'shape': (480, 640)}, 'scores': 0.9_9_6_7}, {'mask': {'hash': '453c7844bd', 'shape': (480, 640)}, 'scores': 0.9_9_3}, {'mask': {'hash': '3d44f2926d', 'shape': (480, 640)}, 'scores': 0.9_9_0_9}, {'mask': {'hash': '64033ddc3f', 'shape': (480, 640)}, 'scores': 0.9_8_7_9}, {'mask': {'hash': '801064ff79', 'shape': (480, 640)}, 'scores': 0.9_8_3_4}, {'mask': {'hash': '6172f276ef', 'shape': (480, 640)}, 'scores': 0.9_7_1_6}, {'mask': {'hash': 'b49e60e084', 'shape': (480, 640)}, 'scores': 0.9_6_1_2}, {'mask': {'hash': 'a811e775fd', 'shape': (480, 640)}, 'scores': 0.9_5_9_9}, {'mask': {'hash': 'a6a8ebcf4b', 'shape': (480, 640)}, 'scores': 0.9_5_5_2}, {'mask': {'hash': '9d8257e080', 'shape': (480, 640)}, 'scores': 0.9_5_3_2}, {'mask': {'hash': '32de6454a8', 'shape': (480, 640)}, 'scores': 0.9_5_1_6}, {'mask': {'hash': 'af3d4af2c8', 'shape': (480, 640)}, 'scores': 0.9_4_9_9}, {'mask': {'hash': '3c6db475fb', 'shape': (480, 640)}, 'scores': 0.9_4_8_3}, {'mask': {'hash': 'c290813fb9', 'shape': (480, 640)}, 'scores': 0.9_4_6_4}, {'mask': {'hash': 'b6f0b8f606', 'shape': (480, 640)}, 'scores': 0.9_4_3}, {'mask': {'hash': '92ce16bfdf', 'shape': (480, 640)}, 'scores': 0.9_4_3}, {'mask': {'hash': 'c749b25868', 'shape': (480, 640)}, 'scores': 0.9_4_0_8}, {'mask': {'hash': 'efb6cab859', 'shape': (480, 640)}, 'scores': 0.9_3_3_5}, {'mask': {'hash': '1ff2eafb30', 'shape': (480, 640)}, 'scores': 0.9_3_2_6}, {'mask': {'hash': '788b798e24', 'shape': (480, 640)}, 'scores': 0.9_2_6_2}, {'mask': {'hash': 'abea804f0e', 'shape': (480, 640)}, 'scores': 0.8_9_9_9}, {'mask': {'hash': '7b9e8ddb73', 'shape': (480, 640)}, 'scores': 0.8_9_8_6}, {'mask': {'hash': 'cd24047c8a', 'shape': (480, 640)}, 'scores': 0.8_9_8_4}, {'mask': {'hash': '6943e6bcbd', 'shape': (480, 640)}, 'scores': 0.8_8_7_3}, {'mask': {'hash': 'b5f47c9191', 'shape': (480, 640)}, 'scores': 0.8_8_7_1} ] , ) # fmt: on @require_torch @slow def UpperCAmelCase_ ( self ): __A : Optional[Any] = 'facebook/sam-vit-huge' __A : List[str] = pipeline('mask-generation' , model=_A ) __A : Tuple = image_segmenter( 'http://images.cocodataset.org/val2017/000000039769.jpg' , pred_iou_thresh=1 , points_per_batch=256 ) # Shortening by hashing __A : List[str] = [] for i, o in enumerate(outputs['masks'] ): new_outupt += [{"mask": mask_to_test_readable(_A ), "scores": outputs["scores"][i]}] self.assertEqual( nested_simplify(_A , decimals=4 ) , [ {'mask': {'hash': '115ad19f5f', 'shape': (480, 640)}, 'scores': 1.0_4_4_4}, {'mask': {'hash': '6affa964c6', 'shape': (480, 640)}, 'scores': 1.0_2_1_0}, {'mask': {'hash': 'dfe28a0388', 'shape': (480, 640)}, 'scores': 1.0_1_6_7}, {'mask': {'hash': 'c0a5f4a318', 'shape': (480, 640)}, 'scores': 1.0_1_3_2}, {'mask': {'hash': 'fe8065c197', 'shape': (480, 640)}, 'scores': 1.0_0_5_3}, ] , )
280
1
# 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 UpperCAmelCase : str = {'''configuration_timm_backbone''': ['''TimmBackboneConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Optional[Any] = ['''TimmBackbone'''] if TYPE_CHECKING: from .configuration_timm_backbone import TimmBackboneConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_timm_backbone import TimmBackbone else: import sys UpperCAmelCase : str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
280
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import OwlViTImageProcessor, OwlViTProcessor @require_vision class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): __A : List[Any] = tempfile.mkdtemp() # fmt: off __A : List[str] = ['', 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'lo', 'l</w>', 'w</w>', 'r</w>', 't</w>', 'low</w>', 'er</w>', 'lowest</w>', 'newer</w>', 'wider', '<unk>', '<|startoftext|>', '<|endoftext|>'] # fmt: on __A : Union[str, Any] = dict(zip(_A , range(len(_A ) ) ) ) __A : Optional[int] = ['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>', ''] __A : int = {'unk_token': '<unk>'} __A : Optional[int] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) __A : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(_A ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(_A ) ) __A : List[Any] = { 'do_resize': True, 'size': 20, 'do_center_crop': True, 'crop_size': 18, 'do_normalize': True, 'image_mean': [0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3], 'image_std': [0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1], } __A : Optional[int] = os.path.join(self.tmpdirname , _A ) with open(self.image_processor_file , 'w' , encoding='utf-8' ) as fp: json.dump(_A , _A ) def UpperCAmelCase_ ( self , **_A ): return CLIPTokenizer.from_pretrained(self.tmpdirname , pad_token='!' , **_A ) def UpperCAmelCase_ ( self , **_A ): return CLIPTokenizerFast.from_pretrained(self.tmpdirname , pad_token='!' , **_A ) def UpperCAmelCase_ ( self , **_A ): return OwlViTImageProcessor.from_pretrained(self.tmpdirname , **_A ) def UpperCAmelCase_ ( self ): shutil.rmtree(self.tmpdirname ) def UpperCAmelCase_ ( self ): __A : int = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __A : Optional[int] = [Image.fromarray(np.moveaxis(_A , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCAmelCase_ ( self ): __A : List[Any] = self.get_tokenizer() __A : str = self.get_rust_tokenizer() __A : List[str] = self.get_image_processor() __A : Optional[int] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) processor_slow.save_pretrained(self.tmpdirname ) __A : int = OwlViTProcessor.from_pretrained(self.tmpdirname , use_fast=_A ) __A : Optional[Any] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) processor_fast.save_pretrained(self.tmpdirname ) __A : Optional[Any] = OwlViTProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , _A ) self.assertIsInstance(processor_fast.tokenizer , _A ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , _A ) self.assertIsInstance(processor_fast.image_processor , _A ) def UpperCAmelCase_ ( self ): __A : List[str] = OwlViTProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __A : Optional[int] = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) __A : Optional[int] = self.get_image_processor(do_normalize=_A ) __A : Any = OwlViTProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=_A ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , _A ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _A ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.get_image_processor() __A : Optional[Any] = self.get_tokenizer() __A : Union[str, Any] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Union[str, Any] = self.prepare_image_inputs() __A : int = image_processor(_A , return_tensors='np' ) __A : str = processor(images=_A , return_tensors='np' ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1e-2 ) def UpperCAmelCase_ ( self ): __A : str = self.get_image_processor() __A : str = self.get_tokenizer() __A : Tuple = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : str = 'lower newer' __A : str = processor(text=_A , return_tensors='np' ) __A : List[str] = tokenizer(_A , return_tensors='np' ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key][0].tolist() , encoded_processor[key][0].tolist() ) def UpperCAmelCase_ ( self ): __A : int = self.get_image_processor() __A : Optional[int] = self.get_tokenizer() __A : List[str] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Any = 'lower newer' __A : Optional[Any] = self.prepare_image_inputs() __A : List[Any] = processor(text=_A , images=_A ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Any = 'google/owlvit-base-patch32' __A : int = OwlViTProcessor.from_pretrained(_A ) __A : Dict = ['cat', 'nasa badge'] __A : Optional[Any] = processor(text=_A ) __A : Optional[int] = 16 self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (2, seq_length) ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Tuple = 'google/owlvit-base-patch32' __A : Any = OwlViTProcessor.from_pretrained(_A ) __A : Dict = [['cat', 'nasa badge'], ['person']] __A : Dict = processor(text=_A ) __A : Optional[int] = 16 __A : Any = len(_A ) __A : Union[str, Any] = max([len(_A ) for texts in input_texts] ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (batch_size * num_max_text_queries, seq_length) ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : List[Any] = 'google/owlvit-base-patch32' __A : str = OwlViTProcessor.from_pretrained(_A ) __A : Union[str, Any] = ['cat', 'nasa badge'] __A : Tuple = processor(text=_A ) __A : str = 16 __A : int = inputs['input_ids'] __A : List[Any] = [ [49406, 2368, 49407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [49406, 6841, 11301, 49407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (2, seq_length) ) self.assertListEqual(list(input_ids[0] ) , predicted_ids[0] ) self.assertListEqual(list(input_ids[1] ) , predicted_ids[1] ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.get_image_processor() __A : List[str] = self.get_tokenizer() __A : Optional[Any] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Optional[int] = self.prepare_image_inputs() __A : Optional[int] = self.prepare_image_inputs() __A : Optional[int] = processor(images=_A , query_images=_A ) self.assertListEqual(list(inputs.keys() ) , ['query_pixel_values', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.get_image_processor() __A : Union[str, Any] = self.get_tokenizer() __A : str = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Optional[Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __A : Any = processor.batch_decode(_A ) __A : Tuple = tokenizer.batch_decode(_A ) self.assertListEqual(_A , _A )
280
1
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 YolosImageProcessor class _A( unittest.TestCase ): """simple docstring""" def __init__( self , _A , _A=7 , _A=3 , _A=30 , _A=400 , _A=True , _A=None , _A=True , _A=[0.5, 0.5, 0.5] , _A=[0.5, 0.5, 0.5] , _A=True , _A=1 / 255 , _A=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __A : List[Any] = size if size is not None else {'shortest_edge': 18, 'longest_edge': 1333} __A : Union[str, Any] = parent __A : Optional[int] = batch_size __A : int = num_channels __A : int = min_resolution __A : Any = max_resolution __A : List[Any] = do_resize __A : List[Any] = size __A : Union[str, Any] = do_normalize __A : Optional[int] = image_mean __A : Optional[int] = image_std __A : int = do_rescale __A : str = rescale_factor __A : Tuple = do_pad def UpperCAmelCase_ ( self ): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def UpperCAmelCase_ ( self , _A , _A=False ): if not batched: __A : List[str] = image_inputs[0] if isinstance(_A , Image.Image ): __A , __A : int = image.size else: __A , __A : Any = image.shape[1], image.shape[2] if w < h: __A : List[Any] = int(self.size['shortest_edge'] * h / w ) __A : List[Any] = self.size['shortest_edge'] elif w > h: __A : Union[str, Any] = self.size['shortest_edge'] __A : str = int(self.size['shortest_edge'] * w / h ) else: __A : Dict = self.size['shortest_edge'] __A : str = self.size['shortest_edge'] else: __A : int = [] for image in image_inputs: __A , __A : Optional[Any] = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __A : List[str] = max(_A , key=lambda _A : item[0] )[0] __A : str = max(_A , key=lambda _A : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class _A( snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : List[str] = YolosImageProcessor if is_vision_available() else None def UpperCAmelCase_ ( self ): __A : Dict = YolosImageProcessingTester(self ) @property def UpperCAmelCase_ ( self ): return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase_ ( self ): __A : str = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_A , 'image_mean' ) ) self.assertTrue(hasattr(_A , 'image_std' ) ) self.assertTrue(hasattr(_A , 'do_normalize' ) ) self.assertTrue(hasattr(_A , 'do_resize' ) ) self.assertTrue(hasattr(_A , 'size' ) ) def UpperCAmelCase_ ( self ): __A : Tuple = 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 , _A ) __A : Dict = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=_A ) self.assertEqual(image_processor.size , {'shortest_edge': 42, 'longest_edge': 84} ) self.assertEqual(image_processor.do_pad , _A ) def UpperCAmelCase_ ( self ): pass def UpperCAmelCase_ ( self ): # Initialize image_processing __A : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __A : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A ) for image in image_inputs: self.assertIsInstance(_A , Image.Image ) # Test not batched input __A : Any = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values __A , __A : Optional[int] = self.image_processor_tester.get_expected_values(_A ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __A , __A : Optional[Any] = self.image_processor_tester.get_expected_values(_A , batched=_A ) __A : str = image_processing(_A , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def UpperCAmelCase_ ( self ): # Initialize image_processing __A : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __A : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A , numpify=_A ) for image in image_inputs: self.assertIsInstance(_A , np.ndarray ) # Test not batched input __A : str = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values __A , __A : List[Any] = self.image_processor_tester.get_expected_values(_A ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __A : Tuple = image_processing(_A , return_tensors='pt' ).pixel_values __A , __A : Optional[int] = self.image_processor_tester.get_expected_values(_A , batched=_A ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def UpperCAmelCase_ ( self ): # Initialize image_processing __A : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __A : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A , torchify=_A ) for image in image_inputs: self.assertIsInstance(_A , torch.Tensor ) # Test not batched input __A : Union[str, Any] = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values __A , __A : Union[str, Any] = self.image_processor_tester.get_expected_values(_A ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __A : Optional[int] = image_processing(_A , return_tensors='pt' ).pixel_values __A , __A : Optional[int] = self.image_processor_tester.get_expected_values(_A , batched=_A ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def UpperCAmelCase_ ( self ): # Initialize image_processings __A : Tuple = self.image_processing_class(**self.image_processor_dict ) __A : Any = self.image_processing_class(do_resize=_A , do_normalize=_A , do_rescale=_A ) # create random PyTorch tensors __A : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A , torchify=_A ) for image in image_inputs: self.assertIsInstance(_A , torch.Tensor ) # Test whether the method "pad" and calling the image processor return the same tensors __A : Optional[int] = image_processing_a.pad(_A , return_tensors='pt' ) __A : Optional[int] = image_processing_a(_A , return_tensors='pt' ) self.assertTrue( torch.allclose(encoded_images_with_method['pixel_values'] , encoded_images['pixel_values'] , atol=1e-4 ) ) @slow def UpperCAmelCase_ ( self ): # prepare image and target __A : List[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' , 'r' ) as f: __A : Optional[Any] = json.loads(f.read() ) __A : Optional[Any] = {'image_id': 39769, 'annotations': target} # encode them __A : str = YolosImageProcessor.from_pretrained('hustvl/yolos-small' ) __A : List[Any] = image_processing(images=_A , annotations=_A , return_tensors='pt' ) # verify pixel values __A : List[Any] = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding['pixel_values'].shape , _A ) __A : Union[str, Any] = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , _A , atol=1e-4 ) ) # verify area __A : List[Any] = torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , _A ) ) # verify boxes __A : Any = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , _A ) __A : Optional[Any] = torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , _A , atol=1e-3 ) ) # verify image_id __A : Optional[int] = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , _A ) ) # verify is_crowd __A : str = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , _A ) ) # verify class_labels __A : Any = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , _A ) ) # verify orig_size __A : int = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , _A ) ) # verify size __A : str = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , _A ) ) @slow def UpperCAmelCase_ ( self ): # prepare image, target and masks_path __A : Dict = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' , 'r' ) as f: __A : Tuple = json.loads(f.read() ) __A : Any = {'file_name': '000000039769.png', 'image_id': 39769, 'segments_info': target} __A : List[Any] = pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic' ) # encode them __A : Any = YolosImageProcessor(format='coco_panoptic' ) __A : List[Any] = image_processing(images=_A , annotations=_A , masks_path=_A , return_tensors='pt' ) # verify pixel values __A : Any = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding['pixel_values'].shape , _A ) __A : Union[str, Any] = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , _A , atol=1e-4 ) ) # verify area __A : int = torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , _A ) ) # verify boxes __A : Optional[int] = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , _A ) __A : Optional[Any] = torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , _A , atol=1e-3 ) ) # verify image_id __A : Union[str, Any] = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , _A ) ) # verify is_crowd __A : Tuple = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , _A ) ) # verify class_labels __A : List[str] = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , _A ) ) # verify masks __A : Tuple = 822873 self.assertEqual(encoding['labels'][0]['masks'].sum().item() , _A ) # verify orig_size __A : str = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , _A ) ) # verify size __A : int = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , _A ) )
280
import math def _SCREAMING_SNAKE_CASE ( a ) -> list[int]: __A : List[str] = [] __A : Any = 2 __A : Union[str, Any] = int(math.sqrt(a ) ) # Size of every segment __A : Any = [True] * (end + 1) __A : List[Any] = [] while start <= end: if temp[start] is True: in_prime.append(a ) for i in range(start * start , end + 1 , a ): __A : Optional[int] = False start += 1 prime += in_prime __A : Any = end + 1 __A : Any = min(2 * end , a ) while low <= n: __A : List[Any] = [True] * (high - low + 1) for each in in_prime: __A : List[str] = math.floor(low / each ) * each if t < low: t += each for j in range(a , high + 1 , a ): __A : Optional[int] = False for j in range(len(a ) ): if temp[j] is True: prime.append(j + low ) __A : Optional[int] = high + 1 __A : Tuple = min(high + end , a ) return prime print(sieve(10**6))
280
1
from __future__ import annotations from math import ceil, floor, sqrt def _SCREAMING_SNAKE_CASE ( a = 2_00_00_00 ) -> int: __A : list[int] = [0] __A : int for idx in range(1 , ceil(sqrt(target * 2 ) * 1.1 ) ): triangle_numbers.append(triangle_numbers[-1] + idx ) # we want this to be as close as possible to target __A : int = 0 # the area corresponding to the grid that gives the product closest to target __A : int = 0 # an estimate of b, using the quadratic formula __A : float # the largest integer less than b_estimate __A : int # the largest integer less than b_estimate __A : int # the triangle number corresponding to b_floor __A : int # the triangle number corresponding to b_ceil __A : int for idx_a, triangle_a in enumerate(triangle_numbers[1:] , 1 ): __A : Optional[Any] = (-1 + sqrt(1 + 8 * target / triangle_a )) / 2 __A : Optional[Any] = floor(a ) __A : int = ceil(a ) __A : int = triangle_numbers[b_floor] __A : int = triangle_numbers[b_ceil] if abs(target - triangle_b_first_guess * triangle_a ) < abs( target - best_product ): __A : Optional[int] = triangle_b_first_guess * triangle_a __A : Any = idx_a * b_floor if abs(target - triangle_b_second_guess * triangle_a ) < abs( target - best_product ): __A : Optional[Any] = triangle_b_second_guess * triangle_a __A : Union[str, Any] = idx_a * b_ceil return area if __name__ == "__main__": print(F"""{solution() = }""")
280
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available UpperCAmelCase : Any = { '''configuration_mvp''': ['''MVP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MvpConfig''', '''MvpOnnxConfig'''], '''tokenization_mvp''': ['''MvpTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : int = ['''MvpTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : str = [ '''MVP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MvpForCausalLM''', '''MvpForConditionalGeneration''', '''MvpForQuestionAnswering''', '''MvpForSequenceClassification''', '''MvpModel''', '''MvpPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_mvp import MVP_PRETRAINED_CONFIG_ARCHIVE_MAP, MvpConfig, MvpOnnxConfig from .tokenization_mvp import MvpTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mvp_fast import MvpTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mvp import ( MVP_PRETRAINED_MODEL_ARCHIVE_LIST, MvpForCausalLM, MvpForConditionalGeneration, MvpForQuestionAnswering, MvpForSequenceClassification, MvpModel, MvpPreTrainedModel, ) else: import sys UpperCAmelCase : List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
280
1
from __future__ import annotations from dataclasses import dataclass @dataclass class _A: """simple docstring""" UpperCamelCase : float UpperCamelCase : TreeNode | None = None UpperCamelCase : TreeNode | None = None def _SCREAMING_SNAKE_CASE ( a ) -> bool: # Validation def is_valid_tree(a ) -> bool: if node is None: return True if not isinstance(a , a ): return False try: float(node.data ) except (TypeError, ValueError): return False return is_valid_tree(node.left ) and is_valid_tree(node.right ) if not is_valid_tree(a ): raise ValueError( 'Each node should be type of TreeNode and data should be float.' ) def is_binary_search_tree_recursive_check( a , a , a ) -> bool: if node is None: return True return ( left_bound < node.data < right_bound and is_binary_search_tree_recursive_check(node.left , a , node.data ) and is_binary_search_tree_recursive_check( node.right , node.data , a ) ) return is_binary_search_tree_recursive_check(a , -float('inf' ) , float('inf' ) ) if __name__ == "__main__": import doctest doctest.testmod()
280
def _SCREAMING_SNAKE_CASE ( a ) -> Tuple: __A , __A : Optional[Any] = [], [] while len(a ) > 1: __A , __A : Any = min(a ), max(a ) start.append(a ) end.append(a ) collection.remove(a ) collection.remove(a ) end.reverse() return start + collection + end if __name__ == "__main__": UpperCAmelCase : int = input('''Enter numbers separated by a comma:\n''').strip() UpperCAmelCase : Dict = [int(item) for item in user_input.split(''',''')] print(*merge_sort(unsorted), sep=''',''')
280
1
import copy import unittest from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_MULTIPLE_CHOICE_MAPPING, MODEL_FOR_QUESTION_ANSWERING_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaModel, ) from transformers.models.layoutlmva.modeling_layoutlmva import LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class _A: """simple docstring""" def __init__( self , _A , _A=2 , _A=3 , _A=4 , _A=2 , _A=7 , _A=True , _A=True , _A=True , _A=True , _A=99 , _A=36 , _A=3 , _A=4 , _A=37 , _A="gelu" , _A=0.1 , _A=0.1 , _A=512 , _A=16 , _A=2 , _A=0.0_2 , _A=6 , _A=6 , _A=3 , _A=4 , _A=None , _A=1000 , ): __A : Tuple = parent __A : Tuple = batch_size __A : Dict = num_channels __A : Tuple = image_size __A : str = patch_size __A : Dict = text_seq_length __A : int = is_training __A : int = use_input_mask __A : Union[str, Any] = use_token_type_ids __A : List[str] = use_labels __A : Union[str, Any] = vocab_size __A : Dict = hidden_size __A : Union[str, Any] = num_hidden_layers __A : Optional[int] = num_attention_heads __A : Any = intermediate_size __A : Optional[Any] = hidden_act __A : Optional[Any] = hidden_dropout_prob __A : Union[str, Any] = attention_probs_dropout_prob __A : int = max_position_embeddings __A : Tuple = type_vocab_size __A : List[str] = type_sequence_label_size __A : List[str] = initializer_range __A : Any = coordinate_size __A : Optional[int] = shape_size __A : Tuple = num_labels __A : Union[str, Any] = num_choices __A : List[str] = scope __A : Union[str, Any] = range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) __A : Union[str, Any] = text_seq_length __A : Tuple = (image_size // patch_size) ** 2 + 1 __A : Optional[int] = self.text_seq_length + self.image_seq_length def UpperCAmelCase_ ( self ): __A : Any = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size ) __A : int = ids_tensor([self.batch_size, self.text_seq_length, 4] , self.range_bbox ) # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: __A : Union[str, Any] = bbox[i, j, 3] __A : Optional[int] = bbox[i, j, 1] __A : int = t if bbox[i, j, 2] < bbox[i, j, 0]: __A : Optional[int] = bbox[i, j, 2] __A : List[Any] = bbox[i, j, 0] __A : Tuple = t __A : Dict = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __A : Dict = None if self.use_input_mask: __A : int = random_attention_mask([self.batch_size, self.text_seq_length] ) __A : Optional[Any] = None if self.use_token_type_ids: __A : List[str] = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size ) __A : Union[str, Any] = None __A : int = None if self.use_labels: __A : Union[str, Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __A : Optional[int] = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels ) __A : Optional[int] = LayoutLMvaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , coordinate_size=self.coordinate_size , shape_size=self.shape_size , input_size=self.image_size , patch_size=self.patch_size , ) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A , _A ): __A : Optional[Any] = LayoutLMvaModel(config=_A ) model.to(_A ) model.eval() # text + image __A : Union[str, Any] = model(_A , pixel_values=_A ) __A : Dict = model( _A , bbox=_A , pixel_values=_A , attention_mask=_A , token_type_ids=_A ) __A : Union[str, Any] = model(_A , bbox=_A , pixel_values=_A , token_type_ids=_A ) __A : List[str] = model(_A , bbox=_A , pixel_values=_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # text only __A : Any = model(_A ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only __A : str = model(pixel_values=_A ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A , _A ): __A : Any = self.num_labels __A : str = LayoutLMvaForSequenceClassification(_A ) model.to(_A ) model.eval() __A : List[Any] = model( _A , bbox=_A , pixel_values=_A , attention_mask=_A , token_type_ids=_A , labels=_A , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A , _A ): __A : Optional[int] = self.num_labels __A : int = LayoutLMvaForTokenClassification(config=_A ) model.to(_A ) model.eval() __A : Tuple = model( _A , bbox=_A , pixel_values=_A , attention_mask=_A , token_type_ids=_A , labels=_A , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A , _A ): __A : Union[str, Any] = LayoutLMvaForQuestionAnswering(config=_A ) model.to(_A ) model.eval() __A : Union[str, Any] = model( _A , bbox=_A , pixel_values=_A , attention_mask=_A , token_type_ids=_A , start_positions=_A , end_positions=_A , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def UpperCAmelCase_ ( self ): __A : Tuple = self.prepare_config_and_inputs() ( ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ) : Any = config_and_inputs __A : Any = { 'input_ids': input_ids, 'bbox': bbox, 'pixel_values': pixel_values, 'token_type_ids': token_type_ids, 'attention_mask': input_mask, } return config, inputs_dict @require_torch class _A( snake_case__ , snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : str = False UpperCamelCase : Optional[int] = False UpperCamelCase : List[Any] = False UpperCamelCase : Optional[Any] = ( ( LayoutLMvaModel, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaForQuestionAnswering, ) if is_torch_available() else () ) UpperCamelCase : Dict = ( {'''document-question-answering''': LayoutLMvaForQuestionAnswering, '''feature-extraction''': LayoutLMvaModel} if is_torch_available() else {} ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A ): # `DocumentQuestionAnsweringPipeline` is expected to work with this model, but it combines the text and visual # embedding along the sequence dimension (dim 1), which causes an error during post-processing as `p_mask` has # the sequence dimension of the text embedding only. # (see the line `embedding_output = torch.cat([embedding_output, visual_embeddings], dim=1)`) return True def UpperCAmelCase_ ( self ): __A : Dict = LayoutLMvaModelTester(self ) __A : List[Any] = ConfigTester(self , config_class=_A , hidden_size=37 ) def UpperCAmelCase_ ( self , _A , _A , _A=False ): __A : int = copy.deepcopy(_A ) if model_class in get_values(_A ): __A : Union[str, Any] = { k: v.unsqueeze(1 ).expand(-1 , self.model_tester.num_choices , -1 ).contiguous() if isinstance(_A , torch.Tensor ) and v.ndim > 1 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(_A ): __A : int = torch.ones(self.model_tester.batch_size , dtype=torch.long , device=_A ) elif model_class in get_values(_A ): __A : List[str] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=_A ) __A : str = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=_A ) elif model_class in [ *get_values(_A ), ]: __A : Optional[int] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=_A ) elif model_class in [ *get_values(_A ), ]: __A : List[Any] = torch.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=torch.long , device=_A , ) return inputs_dict def UpperCAmelCase_ ( self ): self.config_tester.run_common_tests() def UpperCAmelCase_ ( self ): __A : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_A ) def UpperCAmelCase_ ( self ): __A : Tuple = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __A : List[Any] = type self.model_tester.create_and_check_model(*_A ) def UpperCAmelCase_ ( self ): __A : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*_A ) def UpperCAmelCase_ ( self ): __A : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_A ) def UpperCAmelCase_ ( self ): __A : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*_A ) @slow def UpperCAmelCase_ ( self ): for model_name in LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __A : str = LayoutLMvaModel.from_pretrained(_A ) self.assertIsNotNone(_A ) def _SCREAMING_SNAKE_CASE ( ) -> Any: __A : Optional[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch class _A( unittest.TestCase ): """simple docstring""" @cached_property def UpperCAmelCase_ ( self ): return LayoutLMvaImageProcessor(apply_ocr=_A ) if is_vision_available() else None @slow def UpperCAmelCase_ ( self ): __A : List[str] = LayoutLMvaModel.from_pretrained('microsoft/layoutlmv3-base' ).to(_A ) __A : Any = self.default_image_processor __A : List[str] = prepare_img() __A : int = image_processor(images=_A , return_tensors='pt' ).pixel_values.to(_A ) __A : Optional[Any] = torch.tensor([[1, 2]] ) __A : int = torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]] ).unsqueeze(0 ) # forward pass __A : Tuple = model( input_ids=input_ids.to(_A ) , bbox=bbox.to(_A ) , pixel_values=pixel_values.to(_A ) , ) # verify the logits __A : Union[str, Any] = torch.Size((1, 199, 768) ) self.assertEqual(outputs.last_hidden_state.shape , _A ) __A : Optional[Any] = torch.tensor( [[-0.0_5_2_9, 0.3_6_1_8, 0.1_6_3_2], [-0.1_5_8_7, -0.1_6_6_7, -0.0_4_0_0], [-0.1_5_5_7, -0.1_6_7_1, -0.0_5_0_5]] ).to(_A ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3] , _A , atol=1e-4 ) )
280
def _SCREAMING_SNAKE_CASE ( a , a = 0 ) -> list: __A : int = length or len(a ) __A : str = False for i in range(length - 1 ): if list_data[i] > list_data[i + 1]: __A , __A : Optional[int] = list_data[i + 1], list_data[i] __A : Union[str, Any] = True return list_data if not swapped else bubble_sort(a , length - 1 ) if __name__ == "__main__": import doctest doctest.testmod()
280
1
import operator as op def _SCREAMING_SNAKE_CASE ( a ) -> List[str]: __A : Optional[int] = [] __A : List[Any] = lambda a , a : int(x / y ) # noqa: E731 integer division operation __A : Any = { '^': op.pow, '*': op.mul, '/': div, '+': op.add, '-': op.sub, } # operators & their respective operation # print table header print('Symbol'.center(8 ) , 'Action'.center(12 ) , 'Stack' , sep=' | ' ) print('-' * (30 + len(a )) ) for x in post_fix: if x.isdigit(): # if x in digit stack.append(a ) # append x to stack # output in tabular format print(x.rjust(8 ) , ('push(' + x + ')').ljust(12 ) , ','.join(a ) , sep=' | ' ) else: __A : str = stack.pop() # pop stack # output in tabular format print(''.rjust(8 ) , ('pop(' + b + ')').ljust(12 ) , ','.join(a ) , sep=' | ' ) __A : List[Any] = stack.pop() # pop stack # output in tabular format print(''.rjust(8 ) , ('pop(' + a + ')').ljust(12 ) , ','.join(a ) , sep=' | ' ) stack.append( str(opr[x](int(a ) , int(a ) ) ) ) # evaluate the 2 values popped from stack & push result to stack # output in tabular format print( x.rjust(8 ) , ('push(' + a + x + b + ')').ljust(12 ) , ','.join(a ) , sep=' | ' , ) return int(stack[0] ) if __name__ == "__main__": UpperCAmelCase : Union[str, Any] = input('''\n\nEnter a Postfix Equation (space separated) = ''').split(''' ''') print('''\n\tResult = ''', solve(Postfix))
280
from __future__ import annotations def _SCREAMING_SNAKE_CASE ( a ) -> int: if not nums: return 0 __A : Optional[int] = nums[0] __A : str = 0 for num in nums[1:]: __A , __A : Tuple = ( max_excluding + num, max(a , a ), ) return max(a , a ) if __name__ == "__main__": import doctest doctest.testmod()
280
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) UpperCAmelCase : Any = { '''configuration_falcon''': ['''FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''FalconConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Any = [ '''FALCON_PRETRAINED_MODEL_ARCHIVE_LIST''', '''FalconForCausalLM''', '''FalconModel''', '''FalconPreTrainedModel''', '''FalconForSequenceClassification''', '''FalconForTokenClassification''', '''FalconForQuestionAnswering''', ] if TYPE_CHECKING: from .configuration_falcon import FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP, FalconConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_falcon import ( FALCON_PRETRAINED_MODEL_ARCHIVE_LIST, FalconForCausalLM, FalconForQuestionAnswering, FalconForSequenceClassification, FalconForTokenClassification, FalconModel, FalconPreTrainedModel, ) else: import sys UpperCAmelCase : List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
280
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available UpperCAmelCase : Optional[int] = { '''configuration_xlm''': ['''XLM_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XLMConfig''', '''XLMOnnxConfig'''], '''tokenization_xlm''': ['''XLMTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Union[str, Any] = [ '''XLM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XLMForMultipleChoice''', '''XLMForQuestionAnswering''', '''XLMForQuestionAnsweringSimple''', '''XLMForSequenceClassification''', '''XLMForTokenClassification''', '''XLMModel''', '''XLMPreTrainedModel''', '''XLMWithLMHeadModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Optional[Any] = [ '''TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFXLMForMultipleChoice''', '''TFXLMForQuestionAnsweringSimple''', '''TFXLMForSequenceClassification''', '''TFXLMForTokenClassification''', '''TFXLMMainLayer''', '''TFXLMModel''', '''TFXLMPreTrainedModel''', '''TFXLMWithLMHeadModel''', ] if TYPE_CHECKING: from .configuration_xlm import XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMConfig, XLMOnnxConfig from .tokenization_xlm import XLMTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm import ( XLM_PRETRAINED_MODEL_ARCHIVE_LIST, XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMPreTrainedModel, XLMWithLMHeadModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlm import ( TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLMForMultipleChoice, TFXLMForQuestionAnsweringSimple, TFXLMForSequenceClassification, TFXLMForTokenClassification, TFXLMMainLayer, TFXLMModel, TFXLMPreTrainedModel, TFXLMWithLMHeadModel, ) else: import sys UpperCAmelCase : str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
280
1
from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _A( snake_case__ ): """simple docstring""" UpperCamelCase : Union[str, Any] = ['''image_processor''', '''tokenizer'''] UpperCamelCase : int = '''AutoImageProcessor''' UpperCamelCase : Any = '''AutoTokenizer''' def __init__( self , _A , _A ): super().__init__(_A , _A ) __A : int = self.image_processor def __call__( self , _A=None , _A=None , _A=None , **_A ): 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: __A : Tuple = self.tokenizer(_A , return_tensors=_A , **_A ) if images is not None: __A : Optional[int] = self.image_processor(_A , return_tensors=_A , **_A ) if text is not None and images is not None: __A : List[Any] = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**_A ) , tensor_type=_A ) def UpperCAmelCase_ ( self , *_A , **_A ): return self.tokenizer.batch_decode(*_A , **_A ) def UpperCAmelCase_ ( self , *_A , **_A ): return self.tokenizer.decode(*_A , **_A ) @property def UpperCAmelCase_ ( self ): return ["input_ids", "attention_mask", "pixel_values"]
280
def _SCREAMING_SNAKE_CASE ( a ) -> str: if number > 0: raise ValueError('input must be a negative integer' ) __A : Optional[int] = len(bin(a )[3:] ) __A : Dict = bin(abs(a ) - (1 << binary_number_length) )[3:] __A : int = ( ( '1' + '0' * (binary_number_length - len(a )) + twos_complement_number ) if number < 0 else '0' ) return "0b" + twos_complement_number if __name__ == "__main__": import doctest doctest.testmod()
280
1
import inspect import re 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/check_config_docstrings.py UpperCAmelCase : Optional[Any] = '''src/transformers''' # This is to make sure the transformers module imported is the one in the repo. UpperCAmelCase : int = direct_transformers_import(PATH_TO_TRANSFORMERS) UpperCAmelCase : Tuple = transformers.models.auto.configuration_auto.CONFIG_MAPPING # Regex pattern used to find the checkpoint mentioned in the docstring of `config_class`. # For example, `[bert-base-uncased](https://huggingface.co/bert-base-uncased)` UpperCAmelCase : Union[str, Any] = re.compile(r'''\[(.+?)\]\((https://huggingface\.co/.+?)\)''') UpperCAmelCase : int = { '''DecisionTransformerConfig''', '''EncoderDecoderConfig''', '''MusicgenConfig''', '''RagConfig''', '''SpeechEncoderDecoderConfig''', '''TimmBackboneConfig''', '''VisionEncoderDecoderConfig''', '''VisionTextDualEncoderConfig''', '''LlamaConfig''', } def _SCREAMING_SNAKE_CASE ( a ) -> Any: __A : int = None # source code of `config_class` __A : Tuple = inspect.getsource(a ) __A : int = _re_checkpoint.findall(a ) # Each `checkpoint` is a tuple of a checkpoint name and a checkpoint link. # For example, `('bert-base-uncased', 'https://huggingface.co/bert-base-uncased')` for ckpt_name, ckpt_link in checkpoints: # allow the link to end with `/` if ckpt_link.endswith('/' ): __A : str = ckpt_link[:-1] # verify the checkpoint name corresponds to the checkpoint link __A : List[str] = F"""https://huggingface.co/{ckpt_name}""" if ckpt_link == ckpt_link_from_name: __A : str = ckpt_name break return checkpoint def _SCREAMING_SNAKE_CASE ( ) -> Tuple: __A : Tuple = [] for config_class in list(CONFIG_MAPPING.values() ): # Skip deprecated models if "models.deprecated" in config_class.__module__: continue __A : Optional[Any] = get_checkpoint_from_config_class(a ) __A : Any = config_class.__name__ if checkpoint is None and name not in CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK: configs_without_checkpoint.append(a ) if len(a ) > 0: __A : Dict = '\n'.join(sorted(a ) ) raise ValueError(F"""The following configurations don't contain any valid checkpoint:\n{message}""" ) if __name__ == "__main__": check_config_docstrings_have_checkpoints()
280
import warnings from pathlib import Path from typing import List, Tuple, Union import fire from torch import nn from transformers import AutoModelForSeqaSeqLM, AutoTokenizer, PreTrainedModel from transformers.utils import logging UpperCAmelCase : Any = logging.get_logger(__name__) def _SCREAMING_SNAKE_CASE ( a , a , a ) -> None: __A : int = nn.ModuleList([src_layers[i] for i in layers_to_copy] ) assert len(a ) == len(a ), F"""{len(a )} != {len(a )}""" dest_layers.load_state_dict(layers_to_copy.state_dict() ) UpperCAmelCase : List[Any] = { # maps num layers in teacher -> num_layers in student -> which teacher layers to copy. # 12: bart, 16: pegasus, 6: marian/Helsinki-NLP 12: { 1: [0], # This says that if the teacher has 12 layers and the student has 1, copy layer 0 of the teacher 2: [0, 6], 3: [0, 6, 11], 4: [0, 4, 8, 11], 6: [0, 2, 4, 7, 9, 11], 9: [0, 1, 2, 4, 5, 7, 9, 10, 11], 12: list(range(12)), }, 16: { # maps num layers in student -> which teacher layers to copy 1: [0], 2: [0, 15], 3: [0, 8, 15], 4: [0, 5, 10, 15], 6: [0, 3, 6, 9, 12, 15], 8: [0, 2, 4, 6, 8, 10, 12, 15], 9: [0, 1, 3, 5, 7, 9, 11, 13, 15], 12: [0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 15], 16: list(range(16)), }, 6: {1: [0], 2: [0, 5], 3: [0, 2, 5], 4: [0, 1, 3, 5], 6: list(range(6))}, } UpperCAmelCase : Optional[int] = { # maps num layers in student -> which teacher layers to copy. 6: {1: [5], 2: [3, 5], 3: [1, 4, 5], 4: [1, 2, 4, 5]}, 12: {1: [11], 2: [5, 11], 3: [3, 7, 11], 6: [1, 3, 5, 8, 10, 11]}, 16: {1: [15], 4: [4, 9, 12, 15], 8: [1, 3, 5, 7, 9, 11, 13, 15]}, } def _SCREAMING_SNAKE_CASE ( a , a ) -> Dict: try: __A : int = LAYERS_TO_COPY[n_teacher][n_student] return val except KeyError: if n_student != n_teacher: warnings.warn( F"""no hardcoded layers to copy for teacher {n_teacher} -> student {n_student}, defaulting to first""" F""" {n_student}""" ) return list(range(a ) ) def _SCREAMING_SNAKE_CASE ( a , a ) -> List[int]: if n_student > n_teacher: raise ValueError(F"""Cannot perform intermediate supervision for student {n_student} > teacher {n_teacher}""" ) elif n_teacher == n_student: return list(range(a ) ) elif n_student == 1: return [n_teacher - 1] else: return LAYERS_TO_SUPERVISE[n_teacher][n_student] def _SCREAMING_SNAKE_CASE ( a , a = "student" , a = None , a = None , a=False , a=None , a=None , **a , ) -> Tuple[PreTrainedModel, List[int], List[int]]: __A : List[str] = 'encoder_layers and decoder_layers cannot be both None-- you would just have an identical teacher.' assert (e is not None) or (d is not None), _msg if isinstance(a , a ): AutoTokenizer.from_pretrained(a ).save_pretrained(a ) # purely for convenience __A : Optional[int] = AutoModelForSeqaSeqLM.from_pretrained(a ).eval() else: assert isinstance(a , a ), F"""teacher must be a model or string got type {type(a )}""" __A : int = teacher.config.to_diff_dict() try: __A , __A : List[Any] = teacher.config.encoder_layers, teacher.config.decoder_layers if e is None: __A : str = teacher_e if d is None: __A : List[Any] = teacher_d init_kwargs.update({'encoder_layers': e, 'decoder_layers': d} ) except AttributeError: # T5 if hasattr(teacher.config , 'num_encoder_layers' ): __A , __A : List[Any] = teacher.config.num_encoder_layers, teacher.config.num_decoder_layers else: __A , __A : Optional[int] = teacher.config.num_layers, teacher.config.num_decoder_layers if e is None: __A : int = teacher_e if d is None: __A : Optional[Any] = teacher_d if hasattr(teacher.config , 'num_encoder_layers' ): init_kwargs.update({'num_encoder_layers': e, 'num_decoder_layers': d} ) else: init_kwargs.update({'num_layers': e, 'num_decoder_layers': d} ) # Kwargs to instantiate student: teacher kwargs with updated layer numbers + **extra_config_kwargs init_kwargs.update(a ) # Copy weights __A : Dict = teacher.config_class(**a ) __A : int = AutoModelForSeqaSeqLM.from_config(a ) # Start by copying the full teacher state dict this will copy the first N teacher layers to the student. __A : Any = student.load_state_dict(teacher.state_dict() , strict=a ) assert info.missing_keys == [], info.missing_keys # every student key should have a teacher keys. if copy_first_teacher_layers: # Our copying is done. We just log and save __A , __A : Optional[int] = list(range(a ) ), list(range(a ) ) logger.info( F"""Copied encoder layers {e_layers_to_copy} and decoder layers {d_layers_to_copy}. Saving them to""" F""" {save_path}""" ) student.save_pretrained(a ) return student, e_layers_to_copy, d_layers_to_copy # Decide which layers of the teacher to copy. Not exactly alternating -- we try to keep first and last layer. if e_layers_to_copy is None: __A : List[int] = pick_layers_to_copy(a , a ) if d_layers_to_copy is None: __A : List[int] = pick_layers_to_copy(a , a ) try: if hasattr( a , 'prophetnet' ): # For ProphetNet, student.model.encoder.layers is called student.prophetnet.encoder.layers copy_layers(teacher.prophetnet.encoder.layers , student.prophetnet.encoder.layers , a ) copy_layers(teacher.prophetnet.decoder.layers , student.prophetnet.decoder.layers , a ) else: copy_layers(teacher.model.encoder.layers , student.model.encoder.layers , a ) copy_layers(teacher.model.decoder.layers , student.model.decoder.layers , a ) except AttributeError: # For t5, student.model.encoder.layers is called student.encoder.block copy_layers(teacher.encoder.block , student.encoder.block , a ) copy_layers(teacher.decoder.block , student.decoder.block , a ) logger.info( F"""Copied encoder layers {e_layers_to_copy} and decoder layers {d_layers_to_copy}. Saving them to {save_path}""" ) __A : Optional[int] = { 'teacher_type': teacher.config.model_type, 'copied_encoder_layers': e_layers_to_copy, 'copied_decoder_layers': d_layers_to_copy, } student.save_pretrained(a ) # Save information about copying for easier reproducibility return student, e_layers_to_copy, d_layers_to_copy if __name__ == "__main__": fire.Fire(create_student_by_copying_alternating_layers)
280
1
from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available UpperCAmelCase : Union[str, Any] = {'''configuration_van''': ['''VAN_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''VanConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Optional[Any] = [ '''VAN_PRETRAINED_MODEL_ARCHIVE_LIST''', '''VanForImageClassification''', '''VanModel''', '''VanPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_van import VAN_PRETRAINED_CONFIG_ARCHIVE_MAP, VanConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_van import ( VAN_PRETRAINED_MODEL_ARCHIVE_LIST, VanForImageClassification, VanModel, VanPreTrainedModel, ) else: import sys UpperCAmelCase : str = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
280
def _SCREAMING_SNAKE_CASE ( a , a ) -> list[int]: __A : Optional[int] = int(a ) # Initialize Result __A : Optional[int] = [] # Traverse through all denomination for denomination in reversed(a ): # Find denominations while int(a ) >= int(a ): total_value -= int(a ) answer.append(a ) # Append the "answers" array return answer # Driver Code if __name__ == "__main__": UpperCAmelCase : List[str] = [] UpperCAmelCase : Optional[int] = '''0''' if ( input('''Do you want to enter your denominations ? (yY/n): ''').strip().lower() == "y" ): UpperCAmelCase : List[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 : Optional[int] = [1, 2, 5, 10, 20, 50, 1_00, 5_00, 20_00] UpperCAmelCase : Tuple = 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 : Optional[int] = find_minimum_change(denominations, value) # Print result for i in range(len(answer)): print(answer[i], end=''' ''')
280
1
from __future__ import annotations def _SCREAMING_SNAKE_CASE ( a , a , a , ) -> tuple[str, float]: if (stress, tangential_force, area).count(0 ) != 1: raise ValueError('You cannot supply more or less than 2 values' ) elif stress < 0: raise ValueError('Stress cannot be negative' ) elif tangential_force < 0: raise ValueError('Tangential Force cannot be negative' ) elif area < 0: raise ValueError('Area cannot be negative' ) elif stress == 0: return ( "stress", tangential_force / area, ) elif tangential_force == 0: return ( "tangential_force", stress * area, ) else: return ( "area", tangential_force / stress, ) if __name__ == "__main__": import doctest doctest.testmod()
280
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 YolosImageProcessor class _A( unittest.TestCase ): """simple docstring""" def __init__( self , _A , _A=7 , _A=3 , _A=30 , _A=400 , _A=True , _A=None , _A=True , _A=[0.5, 0.5, 0.5] , _A=[0.5, 0.5, 0.5] , _A=True , _A=1 / 255 , _A=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __A : List[Any] = size if size is not None else {'shortest_edge': 18, 'longest_edge': 1333} __A : Union[str, Any] = parent __A : Optional[int] = batch_size __A : int = num_channels __A : int = min_resolution __A : Any = max_resolution __A : List[Any] = do_resize __A : List[Any] = size __A : Union[str, Any] = do_normalize __A : Optional[int] = image_mean __A : Optional[int] = image_std __A : int = do_rescale __A : str = rescale_factor __A : Tuple = do_pad def UpperCAmelCase_ ( self ): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def UpperCAmelCase_ ( self , _A , _A=False ): if not batched: __A : List[str] = image_inputs[0] if isinstance(_A , Image.Image ): __A , __A : int = image.size else: __A , __A : Any = image.shape[1], image.shape[2] if w < h: __A : List[Any] = int(self.size['shortest_edge'] * h / w ) __A : List[Any] = self.size['shortest_edge'] elif w > h: __A : Union[str, Any] = self.size['shortest_edge'] __A : str = int(self.size['shortest_edge'] * w / h ) else: __A : Dict = self.size['shortest_edge'] __A : str = self.size['shortest_edge'] else: __A : int = [] for image in image_inputs: __A , __A : Optional[Any] = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __A : List[str] = max(_A , key=lambda _A : item[0] )[0] __A : str = max(_A , key=lambda _A : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class _A( snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : List[str] = YolosImageProcessor if is_vision_available() else None def UpperCAmelCase_ ( self ): __A : Dict = YolosImageProcessingTester(self ) @property def UpperCAmelCase_ ( self ): return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase_ ( self ): __A : str = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_A , 'image_mean' ) ) self.assertTrue(hasattr(_A , 'image_std' ) ) self.assertTrue(hasattr(_A , 'do_normalize' ) ) self.assertTrue(hasattr(_A , 'do_resize' ) ) self.assertTrue(hasattr(_A , 'size' ) ) def UpperCAmelCase_ ( self ): __A : Tuple = 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 , _A ) __A : Dict = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=_A ) self.assertEqual(image_processor.size , {'shortest_edge': 42, 'longest_edge': 84} ) self.assertEqual(image_processor.do_pad , _A ) def UpperCAmelCase_ ( self ): pass def UpperCAmelCase_ ( self ): # Initialize image_processing __A : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __A : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A ) for image in image_inputs: self.assertIsInstance(_A , Image.Image ) # Test not batched input __A : Any = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values __A , __A : Optional[int] = self.image_processor_tester.get_expected_values(_A ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __A , __A : Optional[Any] = self.image_processor_tester.get_expected_values(_A , batched=_A ) __A : str = image_processing(_A , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def UpperCAmelCase_ ( self ): # Initialize image_processing __A : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __A : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A , numpify=_A ) for image in image_inputs: self.assertIsInstance(_A , np.ndarray ) # Test not batched input __A : str = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values __A , __A : List[Any] = self.image_processor_tester.get_expected_values(_A ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __A : Tuple = image_processing(_A , return_tensors='pt' ).pixel_values __A , __A : Optional[int] = self.image_processor_tester.get_expected_values(_A , batched=_A ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def UpperCAmelCase_ ( self ): # Initialize image_processing __A : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __A : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A , torchify=_A ) for image in image_inputs: self.assertIsInstance(_A , torch.Tensor ) # Test not batched input __A : Union[str, Any] = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values __A , __A : Union[str, Any] = self.image_processor_tester.get_expected_values(_A ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __A : Optional[int] = image_processing(_A , return_tensors='pt' ).pixel_values __A , __A : Optional[int] = self.image_processor_tester.get_expected_values(_A , batched=_A ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def UpperCAmelCase_ ( self ): # Initialize image_processings __A : Tuple = self.image_processing_class(**self.image_processor_dict ) __A : Any = self.image_processing_class(do_resize=_A , do_normalize=_A , do_rescale=_A ) # create random PyTorch tensors __A : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A , torchify=_A ) for image in image_inputs: self.assertIsInstance(_A , torch.Tensor ) # Test whether the method "pad" and calling the image processor return the same tensors __A : Optional[int] = image_processing_a.pad(_A , return_tensors='pt' ) __A : Optional[int] = image_processing_a(_A , return_tensors='pt' ) self.assertTrue( torch.allclose(encoded_images_with_method['pixel_values'] , encoded_images['pixel_values'] , atol=1e-4 ) ) @slow def UpperCAmelCase_ ( self ): # prepare image and target __A : List[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' , 'r' ) as f: __A : Optional[Any] = json.loads(f.read() ) __A : Optional[Any] = {'image_id': 39769, 'annotations': target} # encode them __A : str = YolosImageProcessor.from_pretrained('hustvl/yolos-small' ) __A : List[Any] = image_processing(images=_A , annotations=_A , return_tensors='pt' ) # verify pixel values __A : List[Any] = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding['pixel_values'].shape , _A ) __A : Union[str, Any] = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , _A , atol=1e-4 ) ) # verify area __A : List[Any] = torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , _A ) ) # verify boxes __A : Any = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , _A ) __A : Optional[Any] = torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , _A , atol=1e-3 ) ) # verify image_id __A : Optional[int] = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , _A ) ) # verify is_crowd __A : str = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , _A ) ) # verify class_labels __A : Any = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , _A ) ) # verify orig_size __A : int = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , _A ) ) # verify size __A : str = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , _A ) ) @slow def UpperCAmelCase_ ( self ): # prepare image, target and masks_path __A : Dict = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' , 'r' ) as f: __A : Tuple = json.loads(f.read() ) __A : Any = {'file_name': '000000039769.png', 'image_id': 39769, 'segments_info': target} __A : List[Any] = pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic' ) # encode them __A : Any = YolosImageProcessor(format='coco_panoptic' ) __A : List[Any] = image_processing(images=_A , annotations=_A , masks_path=_A , return_tensors='pt' ) # verify pixel values __A : Any = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding['pixel_values'].shape , _A ) __A : Union[str, Any] = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , _A , atol=1e-4 ) ) # verify area __A : int = torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , _A ) ) # verify boxes __A : Optional[int] = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , _A ) __A : Optional[Any] = torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , _A , atol=1e-3 ) ) # verify image_id __A : Union[str, Any] = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , _A ) ) # verify is_crowd __A : Tuple = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , _A ) ) # verify class_labels __A : List[str] = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , _A ) ) # verify masks __A : Tuple = 822873 self.assertEqual(encoding['labels'][0]['masks'].sum().item() , _A ) # verify orig_size __A : str = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , _A ) ) # verify size __A : int = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , _A ) )
280
1
class _A: """simple docstring""" def __init__( self , _A , _A ): __A : Optional[int] = name __A : List[str] = val def __str__( self ): return F"""{self.__class__.__name__}({self.name}, {self.val})""" def __lt__( self , _A ): return self.val < other.val class _A: """simple docstring""" def __init__( self , _A ): __A : List[Any] = {} __A : List[Any] = {} __A : str = self.build_heap(_A ) def __getitem__( self , _A ): return self.get_value(_A ) def UpperCAmelCase_ ( self , _A ): return (idx - 1) // 2 def UpperCAmelCase_ ( self , _A ): return idx * 2 + 1 def UpperCAmelCase_ ( self , _A ): return idx * 2 + 2 def UpperCAmelCase_ ( self , _A ): return self.heap_dict[key] def UpperCAmelCase_ ( self , _A ): __A : List[str] = len(_A ) - 1 __A : Optional[Any] = self.get_parent_idx(_A ) for idx, i in enumerate(_A ): __A : Union[str, Any] = idx __A : Any = i.val for i in range(_A , -1 , -1 ): self.sift_down(_A , _A ) return array def UpperCAmelCase_ ( self , _A , _A ): while True: __A : Any = self.get_left_child_idx(_A ) # noqa: E741 __A : Any = self.get_right_child_idx(_A ) __A : Dict = idx if l < len(_A ) and array[l] < array[idx]: __A : Any = l if r < len(_A ) and array[r] < array[smallest]: __A : Tuple = r if smallest != idx: __A , __A : Optional[int] = array[smallest], array[idx] ( ( __A ) , ( __A ) , ) : Tuple = ( self.idx_of_element[array[smallest]], self.idx_of_element[array[idx]], ) __A : str = smallest else: break def UpperCAmelCase_ ( self , _A ): __A : List[Any] = self.get_parent_idx(_A ) while p >= 0 and self.heap[p] > self.heap[idx]: __A , __A : List[Any] = self.heap[idx], self.heap[p] __A , __A : Tuple = ( self.idx_of_element[self.heap[idx]], self.idx_of_element[self.heap[p]], ) __A : List[Any] = p __A : int = self.get_parent_idx(_A ) def UpperCAmelCase_ ( self ): return self.heap[0] def UpperCAmelCase_ ( self ): __A , __A : Any = self.heap[-1], self.heap[0] __A , __A : Any = ( self.idx_of_element[self.heap[-1]], self.idx_of_element[self.heap[0]], ) __A : Tuple = self.heap.pop() del self.idx_of_element[x] self.sift_down(0 , self.heap ) return x def UpperCAmelCase_ ( self , _A ): self.heap.append(_A ) __A : Any = len(self.heap ) - 1 __A : str = node.val self.sift_up(len(self.heap ) - 1 ) def UpperCAmelCase_ ( self ): return len(self.heap ) == 0 def UpperCAmelCase_ ( self , _A , _A ): assert ( self.heap[self.idx_of_element[node]].val > new_value ), "newValue must be less that current value" __A : Dict = new_value __A : int = new_value self.sift_up(self.idx_of_element[node] ) UpperCAmelCase : Union[str, Any] = Node('''R''', -1) UpperCAmelCase : Optional[int] = Node('''B''', 6) UpperCAmelCase : Optional[Any] = Node('''A''', 3) UpperCAmelCase : int = Node('''X''', 1) UpperCAmelCase : List[Any] = Node('''E''', 4) # Use one of these two ways to generate Min-Heap # Generating Min-Heap from array UpperCAmelCase : Optional[int] = MinHeap([r, b, a, x, e]) # Generating Min-Heap by Insert method # myMinHeap.insert(a) # myMinHeap.insert(b) # myMinHeap.insert(x) # myMinHeap.insert(r) # myMinHeap.insert(e) # Before print('''Min Heap - before decrease key''') for i in my_min_heap.heap: print(i) print('''Min Heap - After decrease key of node [B -> -17]''') my_min_heap.decrease_key(b, -17) # After for i in my_min_heap.heap: print(i) if __name__ == "__main__": import doctest doctest.testmod()
280
import argparse import json from tqdm import tqdm def _SCREAMING_SNAKE_CASE ( ) -> List[Any]: __A : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( '--src_path' , type=a , default='biencoder-nq-dev.json' , help='Path to raw DPR training data' , ) parser.add_argument( '--evaluation_set' , type=a , help='where to store parsed evaluation_set file' , ) parser.add_argument( '--gold_data_path' , type=a , help='where to store parsed gold_data_path file' , ) __A : Optional[int] = parser.parse_args() with open(args.src_path , 'r' ) as src_file, open(args.evaluation_set , 'w' ) as eval_file, open( args.gold_data_path , 'w' ) as gold_file: __A : List[Any] = json.load(a ) for dpr_record in tqdm(a ): __A : Dict = dpr_record['question'] __A : Any = [context['title'] for context in dpr_record['positive_ctxs']] eval_file.write(question + '\n' ) gold_file.write('\t'.join(a ) + '\n' ) if __name__ == "__main__": main()
280
1
import copy from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING UpperCAmelCase : str = logging.get_logger(__name__) UpperCAmelCase : str = { '''microsoft/conditional-detr-resnet-50''': ( '''https://huggingface.co/microsoft/conditional-detr-resnet-50/resolve/main/config.json''' ), } class _A( snake_case__ ): """simple docstring""" UpperCamelCase : Any = '''conditional_detr''' UpperCamelCase : int = ['''past_key_values'''] UpperCamelCase : str = { '''hidden_size''': '''d_model''', '''num_attention_heads''': '''encoder_attention_heads''', } def __init__( self , _A=True , _A=None , _A=3 , _A=300 , _A=6 , _A=2048 , _A=8 , _A=6 , _A=2048 , _A=8 , _A=0.0 , _A=0.0 , _A=True , _A="relu" , _A=256 , _A=0.1 , _A=0.0 , _A=0.0 , _A=0.0_2 , _A=1.0 , _A=False , _A="sine" , _A="resnet50" , _A=True , _A=False , _A=2 , _A=5 , _A=2 , _A=1 , _A=1 , _A=2 , _A=5 , _A=2 , _A=0.2_5 , **_A , ): if backbone_config is not None and use_timm_backbone: raise ValueError('You can\'t specify both `backbone_config` and `use_timm_backbone`.' ) if not use_timm_backbone: if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.' ) __A : Union[str, Any] = CONFIG_MAPPING['resnet'](out_features=['stage4'] ) elif isinstance(_A , _A ): __A : List[str] = backbone_config.get('model_type' ) __A : Tuple = CONFIG_MAPPING[backbone_model_type] __A : Dict = config_class.from_dict(_A ) __A : Optional[Any] = use_timm_backbone __A : Optional[int] = backbone_config __A : Optional[Any] = num_channels __A : Optional[int] = num_queries __A : str = d_model __A : Optional[Any] = encoder_ffn_dim __A : str = encoder_layers __A : List[Any] = encoder_attention_heads __A : int = decoder_ffn_dim __A : Optional[int] = decoder_layers __A : Optional[int] = decoder_attention_heads __A : Optional[int] = dropout __A : Dict = attention_dropout __A : Optional[int] = activation_dropout __A : List[str] = activation_function __A : Dict = init_std __A : List[Any] = init_xavier_std __A : Dict = encoder_layerdrop __A : List[str] = decoder_layerdrop __A : Union[str, Any] = encoder_layers __A : Any = auxiliary_loss __A : List[Any] = position_embedding_type __A : Union[str, Any] = backbone __A : int = use_pretrained_backbone __A : Optional[Any] = dilation # Hungarian matcher __A : List[Any] = class_cost __A : str = bbox_cost __A : List[Any] = giou_cost # Loss coefficients __A : Any = mask_loss_coefficient __A : List[str] = dice_loss_coefficient __A : List[str] = cls_loss_coefficient __A : Optional[int] = bbox_loss_coefficient __A : Optional[int] = giou_loss_coefficient __A : List[str] = focal_alpha super().__init__(is_encoder_decoder=_A , **_A ) @property def UpperCAmelCase_ ( self ): return self.encoder_attention_heads @property def UpperCAmelCase_ ( self ): return self.d_model def UpperCAmelCase_ ( self ): __A : Dict = copy.deepcopy(self.__dict__ ) if self.backbone_config is not None: __A : Union[str, Any] = self.backbone_config.to_dict() __A : List[Any] = self.__class__.model_type return output class _A( snake_case__ ): """simple docstring""" UpperCamelCase : Dict = version.parse('''1.11''' ) @property def UpperCAmelCase_ ( self ): return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ('pixel_mask', {0: 'batch'}), ] ) @property def UpperCAmelCase_ ( self ): return 1e-5 @property def UpperCAmelCase_ ( self ): return 12
280
from heapq import heappop, heappush import numpy as np def _SCREAMING_SNAKE_CASE ( a , a , a , a , ) -> tuple[float | int, list[tuple[int, int]]]: __A , __A : int = grid.shape __A : Any = [-1, 1, 0, 0] __A : Optional[Any] = [0, 0, -1, 1] if allow_diagonal: dx += [-1, -1, 1, 1] dy += [-1, 1, -1, 1] __A , __A : Optional[int] = [(0, source)], set() __A : Any = np.full((rows, cols) , np.inf ) __A : Any = 0 __A : Any = np.empty((rows, cols) , dtype=a ) __A : Optional[Any] = None while queue: ((__A) , (__A)) : List[str] = heappop(a ) if (x, y) in visited: continue visited.add((x, y) ) if (x, y) == destination: __A : int = [] while (x, y) != source: path.append((x, y) ) __A , __A : Optional[int] = predecessors[x, y] path.append(a ) # add the source manually path.reverse() return matrix[destination], path for i in range(len(a ) ): __A , __A : Union[str, Any] = x + dx[i], y + dy[i] if 0 <= nx < rows and 0 <= ny < cols: __A : Optional[int] = grid[nx][ny] if next_node == 1 and matrix[nx, ny] > dist + 1: heappush(a , (dist + 1, (nx, ny)) ) __A : List[Any] = dist + 1 __A : Union[str, Any] = (x, y) return np.inf, [] if __name__ == "__main__": import doctest doctest.testmod()
280
1
import warnings from ...utils import is_sklearn_available, requires_backends if is_sklearn_available(): from scipy.stats import pearsonr, spearmanr from sklearn.metrics import fa_score, matthews_corrcoef UpperCAmelCase : Optional[Any] = ( '''This metric will be removed from the library soon, metrics should be handled with the 🤗 Evaluate ''' '''library. You can have a look at this example script for pointers: ''' '''https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py''' ) def _SCREAMING_SNAKE_CASE ( a , a ) -> Union[str, Any]: warnings.warn(a , a ) requires_backends(a , 'sklearn' ) return (preds == labels).mean() def _SCREAMING_SNAKE_CASE ( a , a ) -> int: warnings.warn(a , a ) requires_backends(a , 'sklearn' ) __A : Any = simple_accuracy(a , a ) __A : Dict = fa_score(y_true=a , y_pred=a ) return { "acc": acc, "f1": fa, "acc_and_f1": (acc + fa) / 2, } def _SCREAMING_SNAKE_CASE ( a , a ) -> str: warnings.warn(a , a ) requires_backends(a , 'sklearn' ) __A : int = pearsonr(a , a )[0] __A : List[str] = spearmanr(a , a )[0] return { "pearson": pearson_corr, "spearmanr": spearman_corr, "corr": (pearson_corr + spearman_corr) / 2, } def _SCREAMING_SNAKE_CASE ( a , a , a ) -> int: warnings.warn(a , a ) requires_backends(a , 'sklearn' ) assert len(a ) == len(a ), F"""Predictions and labels have mismatched lengths {len(a )} and {len(a )}""" if task_name == "cola": return {"mcc": matthews_corrcoef(a , a )} elif task_name == "sst-2": return {"acc": simple_accuracy(a , a )} elif task_name == "mrpc": return acc_and_fa(a , a ) elif task_name == "sts-b": return pearson_and_spearman(a , a ) elif task_name == "qqp": return acc_and_fa(a , a ) elif task_name == "mnli": return {"mnli/acc": simple_accuracy(a , a )} elif task_name == "mnli-mm": return {"mnli-mm/acc": simple_accuracy(a , a )} elif task_name == "qnli": return {"acc": simple_accuracy(a , a )} elif task_name == "rte": return {"acc": simple_accuracy(a , a )} elif task_name == "wnli": return {"acc": simple_accuracy(a , a )} elif task_name == "hans": return {"acc": simple_accuracy(a , a )} else: raise KeyError(a ) def _SCREAMING_SNAKE_CASE ( a , a , a ) -> List[Any]: warnings.warn(a , a ) requires_backends(a , 'sklearn' ) if len(a ) != len(a ): raise ValueError(F"""Predictions and labels have mismatched lengths {len(a )} and {len(a )}""" ) if task_name == "xnli": return {"acc": simple_accuracy(a , a )} else: raise KeyError(a )
280
from typing import List, Optional, Union import numpy as np import PIL import torch from PIL import Image from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) UpperCAmelCase : List[Any] = logging.get_logger(__name__) # pylint: disable=invalid-name UpperCAmelCase : Dict = ''' Examples: ```py >>> from diffusers import KandinskyV22Img2ImgPipeline, KandinskyV22PriorPipeline >>> from diffusers.utils import load_image >>> import torch >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained( ... "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16 ... ) >>> pipe_prior.to("cuda") >>> prompt = "A red cartoon frog, 4k" >>> image_emb, zero_image_emb = pipe_prior(prompt, return_dict=False) >>> pipe = KandinskyV22Img2ImgPipeline.from_pretrained( ... "kandinsky-community/kandinsky-2-2-decoder", torch_dtype=torch.float16 ... ) >>> pipe.to("cuda") >>> init_image = load_image( ... "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" ... "/kandinsky/frog.png" ... ) >>> image = pipe( ... image=init_image, ... image_embeds=image_emb, ... negative_image_embeds=zero_image_emb, ... height=768, ... width=768, ... num_inference_steps=100, ... strength=0.2, ... ).images >>> image[0].save("red_frog.png") ``` ''' def _SCREAMING_SNAKE_CASE ( a , a , a=8 ) -> Tuple: __A : List[str] = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 __A : Optional[int] = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor def _SCREAMING_SNAKE_CASE ( a , a=5_12 , a=5_12 ) -> int: __A : Optional[Any] = pil_image.resize((w, h) , resample=Image.BICUBIC , reducing_gap=1 ) __A : Union[str, Any] = np.array(pil_image.convert('RGB' ) ) __A : Optional[int] = arr.astype(np.floataa ) / 127.5 - 1 __A : int = np.transpose(a , [2, 0, 1] ) __A : Tuple = torch.from_numpy(a ).unsqueeze(0 ) return image class _A( snake_case__ ): """simple docstring""" def __init__( self , _A , _A , _A , ): super().__init__() self.register_modules( unet=_A , scheduler=_A , movq=_A , ) __A : Tuple = 2 ** (len(self.movq.config.block_out_channels ) - 1) def UpperCAmelCase_ ( self , _A , _A , _A ): # get the original timestep using init_timestep __A : Optional[int] = min(int(num_inference_steps * strength ) , _A ) __A : Dict = max(num_inference_steps - init_timestep , 0 ) __A : Tuple = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A=None ): if not isinstance(_A , (torch.Tensor, PIL.Image.Image, list) ): raise ValueError( F"""`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(_A )}""" ) __A : Union[str, Any] = image.to(device=_A , dtype=_A ) __A : Optional[Any] = batch_size * num_images_per_prompt if image.shape[1] == 4: __A : int = image else: if isinstance(_A , _A ) and len(_A ) != batch_size: raise ValueError( F"""You have passed a list of generators of length {len(_A )}, but requested an effective batch""" F""" size of {batch_size}. Make sure the batch size matches the length of the generators.""" ) elif isinstance(_A , _A ): __A : str = [ self.movq.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(_A ) ] __A : str = torch.cat(_A , dim=0 ) else: __A : List[str] = self.movq.encode(_A ).latent_dist.sample(_A ) __A : Tuple = self.movq.config.scaling_factor * init_latents __A : Optional[int] = torch.cat([init_latents] , dim=0 ) __A : Union[str, Any] = init_latents.shape __A : List[str] = randn_tensor(_A , generator=_A , device=_A , dtype=_A ) # get latents __A : Optional[Any] = self.scheduler.add_noise(_A , _A , _A ) __A : Optional[int] = init_latents return latents def UpperCAmelCase_ ( self , _A=0 ): if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('Please install accelerate via `pip install accelerate`' ) __A : Optional[int] = torch.device(F"""cuda:{gpu_id}""" ) __A : Union[str, Any] = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(_A , _A ) def UpperCAmelCase_ ( self , _A=0 ): if is_accelerate_available() and is_accelerate_version('>=' , '0.17.0.dev0' ): from accelerate import cpu_offload_with_hook else: raise ImportError('`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.' ) __A : List[Any] = torch.device(F"""cuda:{gpu_id}""" ) if self.device.type != "cpu": self.to('cpu' , silence_dtype_warnings=_A ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) __A : int = None for cpu_offloaded_model in [self.unet, self.movq]: __A , __A : Optional[int] = cpu_offload_with_hook(_A , _A , prev_module_hook=_A ) # We'll offload the last model manually. __A : List[str] = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def UpperCAmelCase_ ( self ): if not hasattr(self.unet , '_hf_hook' ): return self.device for module in self.unet.modules(): if ( hasattr(_A , '_hf_hook' ) and hasattr(module._hf_hook , 'execution_device' ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(_A ) def __call__( self , _A , _A , _A , _A = 512 , _A = 512 , _A = 100 , _A = 4.0 , _A = 0.3 , _A = 1 , _A = None , _A = "pil" , _A = True , ): __A : List[Any] = self._execution_device __A : Optional[Any] = guidance_scale > 1.0 if isinstance(_A , _A ): __A : Optional[Any] = torch.cat(_A , dim=0 ) __A : Tuple = image_embeds.shape[0] if isinstance(_A , _A ): __A : List[Any] = torch.cat(_A , dim=0 ) if do_classifier_free_guidance: __A : Union[str, Any] = image_embeds.repeat_interleave(_A , dim=0 ) __A : Optional[int] = negative_image_embeds.repeat_interleave(_A , dim=0 ) __A : List[str] = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=_A ) if not isinstance(_A , _A ): __A : List[Any] = [image] if not all(isinstance(_A , (PIL.Image.Image, torch.Tensor) ) for i in image ): raise ValueError( F"""Input is in incorrect format: {[type(_A ) for i in image]}. Currently, we only support PIL image and pytorch tensor""" ) __A : Dict = torch.cat([prepare_image(_A , _A , _A ) for i in image] , dim=0 ) __A : Any = image.to(dtype=image_embeds.dtype , device=_A ) __A : Tuple = self.movq.encode(_A )['latents'] __A : int = latents.repeat_interleave(_A , dim=0 ) self.scheduler.set_timesteps(_A , device=_A ) __A , __A : int = self.get_timesteps(_A , _A , _A ) __A : Union[str, Any] = timesteps[:1].repeat(batch_size * num_images_per_prompt ) __A , __A : Any = downscale_height_and_width(_A , _A , self.movq_scale_factor ) __A : Tuple = self.prepare_latents( _A , _A , _A , _A , image_embeds.dtype , _A , _A ) for i, t in enumerate(self.progress_bar(_A ) ): # expand the latents if we are doing classifier free guidance __A : Optional[int] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents __A : Dict = {'image_embeds': image_embeds} __A : List[str] = self.unet( sample=_A , timestep=_A , encoder_hidden_states=_A , added_cond_kwargs=_A , return_dict=_A , )[0] if do_classifier_free_guidance: __A , __A : Dict = noise_pred.split(latents.shape[1] , dim=1 ) __A , __A : Optional[Any] = noise_pred.chunk(2 ) __A , __A : List[str] = variance_pred.chunk(2 ) __A : str = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) __A : List[str] = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , 'variance_type' ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): __A , __A : Optional[Any] = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 __A : List[str] = self.scheduler.step( _A , _A , _A , generator=_A , )[0] # post-processing __A : List[Any] = self.movq.decode(_A , force_not_quantize=_A )['sample'] if output_type not in ["pt", "np", "pil"]: raise ValueError(F"""Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}""" ) if output_type in ["np", "pil"]: __A : List[str] = image * 0.5 + 0.5 __A : List[str] = image.clamp(0 , 1 ) __A : Optional[Any] = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": __A : Any = self.numpy_to_pil(_A ) if not return_dict: return (image,) return ImagePipelineOutput(images=_A )
280
1
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import PoolFormerImageProcessor class _A( unittest.TestCase ): """simple docstring""" def __init__( self , _A , _A=7 , _A=3 , _A=30 , _A=400 , _A=True , _A=None , _A=0.9 , _A=None , _A=True , _A=[0.5, 0.5, 0.5] , _A=[0.5, 0.5, 0.5] , ): __A : Any = size if size is not None else {'shortest_edge': 30} __A : Optional[Any] = crop_size if crop_size is not None else {'height': 30, 'width': 30} __A : str = parent __A : Optional[int] = batch_size __A : Tuple = num_channels __A : List[Any] = min_resolution __A : Union[str, Any] = max_resolution __A : Tuple = do_resize_and_center_crop __A : List[Any] = size __A : str = crop_pct __A : Dict = crop_size __A : Optional[int] = do_normalize __A : Any = image_mean __A : Union[str, Any] = image_std def UpperCAmelCase_ ( self ): return { "size": self.size, "do_resize_and_center_crop": self.do_resize_and_center_crop, "crop_pct": self.crop_pct, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, } @require_torch @require_vision class _A( snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Union[str, Any] = PoolFormerImageProcessor if is_vision_available() else None def UpperCAmelCase_ ( self ): __A : Optional[int] = PoolFormerImageProcessingTester(self ) @property def UpperCAmelCase_ ( self ): return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase_ ( self ): __A : List[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_A , 'do_resize_and_center_crop' ) ) self.assertTrue(hasattr(_A , 'size' ) ) self.assertTrue(hasattr(_A , 'crop_pct' ) ) self.assertTrue(hasattr(_A , 'do_normalize' ) ) self.assertTrue(hasattr(_A , 'image_mean' ) ) self.assertTrue(hasattr(_A , 'image_std' ) ) def UpperCAmelCase_ ( self ): __A : Tuple = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'shortest_edge': 30} ) self.assertEqual(image_processor.crop_size , {'height': 30, 'width': 30} ) __A : Optional[Any] = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {'shortest_edge': 42} ) self.assertEqual(image_processor.crop_size , {'height': 84, 'width': 84} ) def UpperCAmelCase_ ( self ): pass def UpperCAmelCase_ ( self ): # Initialize image_processing __A : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __A : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A ) for image in image_inputs: self.assertIsInstance(_A , Image.Image ) # Test not batched input __A : int = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched __A : Optional[int] = image_processing(_A , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def UpperCAmelCase_ ( self ): # Initialize image_processing __A : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __A : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A , numpify=_A ) for image in image_inputs: self.assertIsInstance(_A , np.ndarray ) # Test not batched input __A : int = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched __A : Union[str, Any] = image_processing(_A , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def UpperCAmelCase_ ( self ): # Initialize image_processing __A : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __A : Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A , torchify=_A ) for image in image_inputs: self.assertIsInstance(_A , torch.Tensor ) # Test not batched input __A : Any = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched __A : int = image_processing(_A , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , )
280
import argparse import os import gluonnlp as nlp import mxnet as mx import numpy as np import torch from gluonnlp.base import get_home_dir from gluonnlp.model.bert import BERTEncoder from gluonnlp.model.utils import _load_vocab from gluonnlp.vocab import Vocab from packaging import version from torch import nn from transformers import BertConfig, BertForMaskedLM, BertModel, RobertaTokenizer from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertSelfAttention, BertSelfOutput, ) from transformers.utils import logging if version.parse(nlp.__version__) != version.parse('''0.8.3'''): raise Exception('''requires gluonnlp == 0.8.3''') if version.parse(mx.__version__) != version.parse('''1.5.0'''): raise Exception('''requires mxnet == 1.5.0''') logging.set_verbosity_info() UpperCAmelCase : List[Any] = logging.get_logger(__name__) UpperCAmelCase : Optional[Any] = '''The Nymphenburg Palace is a beautiful palace in Munich!''' def _SCREAMING_SNAKE_CASE ( a , a ) -> Optional[Any]: __A : Any = { 'attention_cell': 'multi_head', 'num_layers': 4, 'units': 10_24, 'hidden_size': 7_68, 'max_length': 5_12, 'num_heads': 8, 'scaled': True, 'dropout': 0.1, 'use_residual': True, 'embed_size': 10_24, 'embed_dropout': 0.1, 'word_embed': None, 'layer_norm_eps': 1e-5, 'token_type_vocab_size': 2, } __A : str = bort_4_8_768_1024_hparams # Let's construct the original Bort model here # Taken from official BERT implementation, see: # https://github.com/alexa/bort/blob/master/bort/bort.py __A : Optional[int] = BERTEncoder( attention_cell=predefined_args['attention_cell'] , num_layers=predefined_args['num_layers'] , units=predefined_args['units'] , hidden_size=predefined_args['hidden_size'] , max_length=predefined_args['max_length'] , num_heads=predefined_args['num_heads'] , scaled=predefined_args['scaled'] , dropout=predefined_args['dropout'] , output_attention=a , output_all_encodings=a , use_residual=predefined_args['use_residual'] , activation=predefined_args.get('activation' , 'gelu' ) , layer_norm_eps=predefined_args.get('layer_norm_eps' , a ) , ) # Vocab information needs to be fetched first # It's the same as RoBERTa, so RobertaTokenizer can be used later __A : Union[str, Any] = 'openwebtext_ccnews_stories_books_cased' # Specify download folder to Gluonnlp's vocab __A : Any = os.path.join(get_home_dir() , 'models' ) __A : List[Any] = _load_vocab(a , a , a , cls=a ) __A : Dict = nlp.model.BERTModel( a , len(a ) , units=predefined_args['units'] , embed_size=predefined_args['embed_size'] , embed_dropout=predefined_args['embed_dropout'] , word_embed=predefined_args['word_embed'] , use_pooler=a , use_token_type_embed=a , token_type_vocab_size=predefined_args['token_type_vocab_size'] , use_classifier=a , use_decoder=a , ) original_bort.load_parameters(a , cast_dtype=a , ignore_extra=a ) __A : Union[str, Any] = original_bort._collect_params_with_prefix() # Build our config 🤗 __A : Any = { 'architectures': ['BertForMaskedLM'], 'attention_probs_dropout_prob': predefined_args['dropout'], 'hidden_act': 'gelu', 'hidden_dropout_prob': predefined_args['dropout'], 'hidden_size': predefined_args['embed_size'], 'initializer_range': 0.02, 'intermediate_size': predefined_args['hidden_size'], 'layer_norm_eps': predefined_args['layer_norm_eps'], 'max_position_embeddings': predefined_args['max_length'], 'model_type': 'bort', 'num_attention_heads': predefined_args['num_heads'], 'num_hidden_layers': predefined_args['num_layers'], 'pad_token_id': 1, # 2 = BERT, 1 = RoBERTa 'type_vocab_size': 1, # 2 = BERT, 1 = RoBERTa 'vocab_size': len(a ), } __A : int = BertConfig.from_dict(a ) __A : Union[str, Any] = BertForMaskedLM(a ) hf_bort_model.eval() # Parameter mapping table (Gluonnlp to Transformers) # * denotes layer index # # | Gluon Parameter | Transformers Parameter # | -------------------------------------------------------------- | ---------------------- # | `encoder.layer_norm.beta` | `bert.embeddings.LayerNorm.bias` # | `encoder.layer_norm.gamma` | `bert.embeddings.LayerNorm.weight` # | `encoder.position_weight` | `bert.embeddings.position_embeddings.weight` # | `word_embed.0.weight` | `bert.embeddings.word_embeddings.weight` # | `encoder.transformer_cells.*.attention_cell.proj_key.bias` | `bert.encoder.layer.*.attention.self.key.bias` # | `encoder.transformer_cells.*.attention_cell.proj_key.weight` | `bert.encoder.layer.*.attention.self.key.weight` # | `encoder.transformer_cells.*.attention_cell.proj_query.bias` | `bert.encoder.layer.*.attention.self.query.bias` # | `encoder.transformer_cells.*.attention_cell.proj_query.weight` | `bert.encoder.layer.*.attention.self.query.weight` # | `encoder.transformer_cells.*.attention_cell.proj_value.bias` | `bert.encoder.layer.*.attention.self.value.bias` # | `encoder.transformer_cells.*.attention_cell.proj_value.weight` | `bert.encoder.layer.*.attention.self.value.weight` # | `encoder.transformer_cells.*.ffn.ffn_2.bias` | `bert.encoder.layer.*.attention.output.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_2.weight` | `bert.encoder.layer.*.attention.output.dense.weight` # | `encoder.transformer_cells.*.layer_norm.beta` | `bert.encoder.layer.*.attention.output.LayerNorm.bias` # | `encoder.transformer_cells.*.layer_norm.gamma` | `bert.encoder.layer.*.attention.output.LayerNorm.weight` # | `encoder.transformer_cells.*.ffn.ffn_1.bias` | `bert.encoder.layer.*.intermediate.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_1.weight` | `bert.encoder.layer.*.intermediate.dense.weight` # | `encoder.transformer_cells.*.ffn.layer_norm.beta` | `bert.encoder.layer.*.output.LayerNorm.bias` # | `encoder.transformer_cells.*.ffn.layer_norm.gamma` | `bert.encoder.layer.*.output.LayerNorm.weight` # | `encoder.transformer_cells.*.proj.bias` | `bert.encoder.layer.*.output.dense.bias` # | `encoder.transformer_cells.*.proj.weight` | `bert.encoder.layer.*.output.dense.weight` # Helper function to convert MXNET Arrays to PyTorch def to_torch(a ) -> nn.Parameter: return nn.Parameter(torch.FloatTensor(mx_array.data().asnumpy() ) ) # Check param shapes and map new HF param back def check_and_map_params(a , a ): __A : Tuple = hf_param.shape __A : str = to_torch(params[gluon_param] ) __A : Union[str, Any] = gluon_param.shape assert ( shape_hf == shape_gluon ), F"""The gluon parameter {gluon_param} has shape {shape_gluon}, but expects shape {shape_hf} for Transformers""" return gluon_param __A : str = check_and_map_params( hf_bort_model.bert.embeddings.word_embeddings.weight , 'word_embed.0.weight' ) __A : Tuple = check_and_map_params( hf_bort_model.bert.embeddings.position_embeddings.weight , 'encoder.position_weight' ) __A : List[str] = check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.bias , 'encoder.layer_norm.beta' ) __A : Tuple = check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.weight , 'encoder.layer_norm.gamma' ) # Inspired by RoBERTa conversion script, we just zero them out (Bort does not use them) __A : Tuple = torch.zeros_like( hf_bort_model.bert.embeddings.token_type_embeddings.weight.data ) for i in range(hf_bort_config.num_hidden_layers ): __A : BertLayer = hf_bort_model.bert.encoder.layer[i] # self attention __A : BertSelfAttention = layer.attention.self __A : Optional[Any] = check_and_map_params( self_attn.key.bias.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_key.bias""" ) __A : Optional[int] = check_and_map_params( self_attn.key.weight.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_key.weight""" ) __A : Union[str, Any] = check_and_map_params( self_attn.query.bias.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_query.bias""" ) __A : Optional[Any] = check_and_map_params( self_attn.query.weight.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_query.weight""" ) __A : Union[str, Any] = check_and_map_params( self_attn.value.bias.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_value.bias""" ) __A : Optional[int] = check_and_map_params( self_attn.value.weight.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_value.weight""" ) # self attention output __A : BertSelfOutput = layer.attention.output __A : Tuple = check_and_map_params( self_output.dense.bias , F"""encoder.transformer_cells.{i}.proj.bias""" ) __A : int = check_and_map_params( self_output.dense.weight , F"""encoder.transformer_cells.{i}.proj.weight""" ) __A : List[Any] = check_and_map_params( self_output.LayerNorm.bias , F"""encoder.transformer_cells.{i}.layer_norm.beta""" ) __A : str = check_and_map_params( self_output.LayerNorm.weight , F"""encoder.transformer_cells.{i}.layer_norm.gamma""" ) # intermediate __A : BertIntermediate = layer.intermediate __A : int = check_and_map_params( intermediate.dense.bias , F"""encoder.transformer_cells.{i}.ffn.ffn_1.bias""" ) __A : List[Any] = check_and_map_params( intermediate.dense.weight , F"""encoder.transformer_cells.{i}.ffn.ffn_1.weight""" ) # output __A : BertOutput = layer.output __A : List[Any] = check_and_map_params( bert_output.dense.bias , F"""encoder.transformer_cells.{i}.ffn.ffn_2.bias""" ) __A : Dict = check_and_map_params( bert_output.dense.weight , F"""encoder.transformer_cells.{i}.ffn.ffn_2.weight""" ) __A : Optional[int] = check_and_map_params( bert_output.LayerNorm.bias , F"""encoder.transformer_cells.{i}.ffn.layer_norm.beta""" ) __A : Dict = check_and_map_params( bert_output.LayerNorm.weight , F"""encoder.transformer_cells.{i}.ffn.layer_norm.gamma""" ) # Save space and energy 🎄 hf_bort_model.half() # Compare output of both models __A : Any = RobertaTokenizer.from_pretrained('roberta-base' ) __A : List[str] = tokenizer.encode_plus(a )['input_ids'] # Get gluon output __A : List[str] = mx.nd.array([input_ids] ) __A : Union[str, Any] = original_bort(inputs=a , token_types=[] ) # Get Transformer output (save and reload model again) hf_bort_model.save_pretrained(a ) __A : Optional[Any] = BertModel.from_pretrained(a ) hf_bort_model.eval() __A : Tuple = tokenizer.encode_plus(a , return_tensors='pt' ) __A : Any = hf_bort_model(**a )[0] __A : Union[str, Any] = output_gluon[0].asnumpy() __A : Tuple = output_hf[0].detach().numpy() __A : int = np.max(np.abs(hf_layer - gluon_layer ) ).item() __A : int = np.allclose(a , a , atol=1e-3 ) if success: print('✔️ Both model do output the same tensors' ) else: print('❌ Both model do **NOT** output the same tensors' ) print('Absolute difference is:' , a ) if __name__ == "__main__": UpperCAmelCase : int = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--bort_checkpoint_path''', default=None, type=str, required=True, help='''Path the official Bort params file.''' ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) UpperCAmelCase : Dict = parser.parse_args() convert_bort_checkpoint_to_pytorch(args.bort_checkpoint_path, args.pytorch_dump_folder_path)
280
1
import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def _SCREAMING_SNAKE_CASE ( a ) -> List[Any]: monkeypatch.setattr('datasets.utils.deprecation_utils._emitted_deprecation_warnings' , set() ) @pytest.fixture def _SCREAMING_SNAKE_CASE ( a ) -> List[str]: class _A: """simple docstring""" def __init__( self , _A ): __A : Optional[Any] = metric_id class _A: """simple docstring""" UpperCamelCase : Dict = [MetricMock(snake_case__ ) for metric_id in ['''accuracy''', '''mse''', '''precision''', '''codeparrot/apps_metric''']] def UpperCAmelCase_ ( self ): return self._metrics monkeypatch.setattr('datasets.inspect.huggingface_hub' , HfhMock() ) @pytest.mark.parametrize( 'func, args' , [(load_metric, ('metrics/mse',)), (list_metrics, ()), (inspect_metric, ('metrics/mse', 'tmp_path'))] ) def _SCREAMING_SNAKE_CASE ( a , a , a , a , a ) -> int: if "tmp_path" in args: __A : Optional[int] = tuple(arg if arg != 'tmp_path' else tmp_path for arg in args ) with pytest.warns(a , match='https://huggingface.co/docs/evaluate' ): func(*a )
280
import colorsys from PIL import Image # type: ignore def _SCREAMING_SNAKE_CASE ( a , a , a ) -> float: __A : List[str] = x __A : str = y for step in range(a ): # noqa: B007 __A : Union[str, Any] = a * a - b * b + x __A : Optional[int] = 2 * a * b + y __A : List[str] = a_new # divergence happens for all complex number with an absolute value # greater than 4 if a * a + b * b > 4: break return step / (max_step - 1) def _SCREAMING_SNAKE_CASE ( a ) -> tuple: if distance == 1: return (0, 0, 0) else: return (2_55, 2_55, 2_55) def _SCREAMING_SNAKE_CASE ( a ) -> tuple: if distance == 1: return (0, 0, 0) else: return tuple(round(i * 2_55 ) for i in colorsys.hsv_to_rgb(a , 1 , 1 ) ) def _SCREAMING_SNAKE_CASE ( a = 8_00 , a = 6_00 , a = -0.6 , a = 0 , a = 3.2 , a = 50 , a = True , ) -> Image.Image: __A : str = Image.new('RGB' , (image_width, image_height) ) __A : Dict = img.load() # loop through the image-coordinates for image_x in range(a ): for image_y in range(a ): # determine the figure-coordinates based on the image-coordinates __A : Dict = figure_width / image_width * image_height __A : Union[str, Any] = figure_center_x + (image_x / image_width - 0.5) * figure_width __A : Optional[Any] = figure_center_y + (image_y / image_height - 0.5) * figure_height __A : Union[str, Any] = get_distance(a , a , a ) # color the corresponding pixel based on the selected coloring-function if use_distance_color_coding: __A : Optional[Any] = get_color_coded_rgb(a ) else: __A : Dict = get_black_and_white_rgb(a ) return img if __name__ == "__main__": import doctest doctest.testmod() # colored version, full figure UpperCAmelCase : str = get_image() # uncomment for colored version, different section, zoomed in # img = get_image(figure_center_x = -0.6, figure_center_y = -0.4, # figure_width = 0.8) # uncomment for black and white version, full figure # img = get_image(use_distance_color_coding = False) # uncomment to save the image # img.save("mandelbrot.png") img.show()
280
1
def _SCREAMING_SNAKE_CASE ( a ) -> int: __A : list[list[int]] = [[0 for _ in range(a )] for _ in range(m + 1 )] for i in range(m + 1 ): __A : Dict = 1 for n in range(m + 1 ): for k in range(1 , a ): memo[n][k] += memo[n][k - 1] if n - k > 0: memo[n][k] += memo[n - k - 1][k] return memo[m][m - 1] if __name__ == "__main__": import sys if len(sys.argv) == 1: try: UpperCAmelCase : Tuple = int(input('''Enter a number: ''').strip()) print(partition(n)) except ValueError: print('''Please enter a number.''') else: try: UpperCAmelCase : str = int(sys.argv[1]) print(partition(n)) except ValueError: print('''Please pass a number.''')
280
from __future__ import annotations def _SCREAMING_SNAKE_CASE ( a , a , a ) -> float: if days_between_payments <= 0: raise ValueError('days_between_payments must be > 0' ) if daily_interest_rate < 0: raise ValueError('daily_interest_rate must be >= 0' ) if principal <= 0: raise ValueError('principal must be > 0' ) return principal * daily_interest_rate * days_between_payments def _SCREAMING_SNAKE_CASE ( a , a , a , ) -> float: if number_of_compounding_periods <= 0: raise ValueError('number_of_compounding_periods must be > 0' ) if nominal_annual_interest_rate_percentage < 0: raise ValueError('nominal_annual_interest_rate_percentage must be >= 0' ) if principal <= 0: raise ValueError('principal must be > 0' ) return principal * ( (1 + nominal_annual_interest_rate_percentage) ** number_of_compounding_periods - 1 ) def _SCREAMING_SNAKE_CASE ( a , a , a , ) -> float: if number_of_years <= 0: raise ValueError('number_of_years must be > 0' ) if nominal_annual_percentage_rate < 0: raise ValueError('nominal_annual_percentage_rate must be >= 0' ) if principal <= 0: raise ValueError('principal must be > 0' ) return compound_interest( a , nominal_annual_percentage_rate / 3_65 , number_of_years * 3_65 ) if __name__ == "__main__": import doctest doctest.testmod()
280
1
from math import sqrt import numpy as np from sympy import symbols # Coefficient # Speed of light (m/s) UpperCAmelCase : List[str] = 2_99_79_24_58 # Symbols UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase : Optional[int] = symbols('''ct x y z''') def _SCREAMING_SNAKE_CASE ( a ) -> float: 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 _SCREAMING_SNAKE_CASE ( a ) -> float: return 1 / sqrt(1 - beta(a ) ** 2 ) def _SCREAMING_SNAKE_CASE ( a ) -> np.ndarray: return np.array( [ [gamma(a ), -gamma(a ) * beta(a ), 0, 0], [-gamma(a ) * beta(a ), gamma(a ), 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], ] ) def _SCREAMING_SNAKE_CASE ( a , a = None ) -> np.ndarray: # Ensure event is not empty if event is None: __A : str = np.array([ct, x, y, z] ) # Symbolic four vector else: event[0] *= c # x0 is ct (speed of light * time) return transformation_matrix(a ) @ event if __name__ == "__main__": import doctest doctest.testmod() # Example of symbolic vector: UpperCAmelCase : str = transform(29_97_92_45) 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 : Union[str, Any] = {ct: c, x: 1, y: 1, z: 1} UpperCAmelCase : Any = [four_vector[i].subs(sub_dict) for i in range(4)] print(F"""\n{numerical_vector}""")
280
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) UpperCAmelCase : Any = { '''configuration_falcon''': ['''FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''FalconConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Any = [ '''FALCON_PRETRAINED_MODEL_ARCHIVE_LIST''', '''FalconForCausalLM''', '''FalconModel''', '''FalconPreTrainedModel''', '''FalconForSequenceClassification''', '''FalconForTokenClassification''', '''FalconForQuestionAnswering''', ] if TYPE_CHECKING: from .configuration_falcon import FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP, FalconConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_falcon import ( FALCON_PRETRAINED_MODEL_ARCHIVE_LIST, FalconForCausalLM, FalconForQuestionAnswering, FalconForSequenceClassification, FalconForTokenClassification, FalconModel, FalconPreTrainedModel, ) else: import sys UpperCAmelCase : List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
280
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 UpperCAmelCase : int = logging.get_logger(__name__) @add_end_docstrings(snake_case__ ) class _A( snake_case__ ): """simple docstring""" def __init__( self , **_A ): super().__init__(**_A ) if self.framework != "pt": raise ValueError(F"""The {self.__class__} is only available in PyTorch.""" ) # No specific FOR_XXX available yet def __call__( self , _A , **_A ): return super().__call__(_A , **_A ) def UpperCAmelCase_ ( self , **_A ): __A : Tuple = {} if "candidate_labels" in kwargs: __A : int = kwargs['candidate_labels'] if "hypothesis_template" in kwargs: __A : Any = kwargs['hypothesis_template'] return preprocess_params, {}, {} def UpperCAmelCase_ ( self , _A , _A=None , _A="This is a sound of {}." ): if isinstance(_A , _A ): 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 : int = requests.get(_A ).content else: with open(_A , 'rb' ) as f: __A : Optional[Any] = f.read() if isinstance(_A , _A ): __A : Optional[int] = ffmpeg_read(_A , self.feature_extractor.sampling_rate ) if not isinstance(_A , 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 : Any = self.feature_extractor( [audio] , sampling_rate=self.feature_extractor.sampling_rate , return_tensors='pt' ) __A : Optional[Any] = candidate_labels __A : Tuple = [hypothesis_template.format(_A ) for x in candidate_labels] __A : Optional[Any] = self.tokenizer(_A , return_tensors=self.framework , padding=_A ) __A : Tuple = [text_inputs] return inputs def UpperCAmelCase_ ( self , _A ): __A : Optional[Any] = model_inputs.pop('candidate_labels' ) __A : int = model_inputs.pop('text_inputs' ) if isinstance(text_inputs[0] , _A ): __A : Union[str, Any] = text_inputs[0] else: # Batching case. __A : str = text_inputs[0][0] __A : Optional[int] = self.model(**_A , **_A ) __A : Tuple = { 'candidate_labels': candidate_labels, 'logits': outputs.logits_per_audio, } return model_outputs def UpperCAmelCase_ ( self , _A ): __A : str = model_outputs.pop('candidate_labels' ) __A : Any = model_outputs['logits'][0] if self.framework == "pt": __A : Union[str, Any] = logits.softmax(dim=0 ) __A : List[Any] = probs.tolist() else: raise ValueError('`tf` framework not supported.' ) __A : Union[str, Any] = [ {'score': score, 'label': candidate_label} for score, candidate_label in sorted(zip(_A , _A ) , key=lambda _A : -x[0] ) ] return result
280
def _SCREAMING_SNAKE_CASE ( a ) -> bool: return str(a ) == str(a )[::-1] def _SCREAMING_SNAKE_CASE ( a ) -> int: return int(a ) + int(str(a )[::-1] ) def _SCREAMING_SNAKE_CASE ( a = 1_00_00 ) -> int: __A : int = [] for num in range(1 , a ): __A : List[str] = 0 __A : List[Any] = num while iterations < 50: __A : str = sum_reverse(a ) iterations += 1 if is_palindrome(a ): break else: lychrel_nums.append(a ) return len(a ) if __name__ == "__main__": print(F"""{solution() = }""")
280
1
import argparse import os from pathlib import Path import torch from bark.generation import _load_model as _bark_load_model from huggingface_hub import hf_hub_download from transformers import EncodecConfig, EncodecModel, set_seed from transformers.models.bark.configuration_bark import ( BarkCoarseConfig, BarkConfig, BarkFineConfig, BarkSemanticConfig, ) from transformers.models.bark.generation_configuration_bark import ( BarkCoarseGenerationConfig, BarkFineGenerationConfig, BarkGenerationConfig, BarkSemanticGenerationConfig, ) from transformers.models.bark.modeling_bark import BarkCoarseModel, BarkFineModel, BarkModel, BarkSemanticModel from transformers.utils import logging logging.set_verbosity_info() UpperCAmelCase : int = logging.get_logger(__name__) set_seed(7_70) UpperCAmelCase : Optional[Any] = { '''c_attn''': '''att_proj''', '''c_proj''': '''out_proj''', '''c_fc''': '''in_proj''', '''transformer.''': '''''', '''h.''': '''layers.''', '''ln_1''': '''layernorm_1''', '''ln_2''': '''layernorm_2''', '''ln_f''': '''layernorm_final''', '''wpe''': '''position_embeds_layer''', '''wte''': '''input_embeds_layer''', } UpperCAmelCase : List[Any] = { '''text_small''': { '''repo_id''': '''suno/bark''', '''file_name''': '''text.pt''', }, '''coarse_small''': { '''repo_id''': '''suno/bark''', '''file_name''': '''coarse.pt''', }, '''fine_small''': { '''repo_id''': '''suno/bark''', '''file_name''': '''fine.pt''', }, '''text''': { '''repo_id''': '''suno/bark''', '''file_name''': '''text_2.pt''', }, '''coarse''': { '''repo_id''': '''suno/bark''', '''file_name''': '''coarse_2.pt''', }, '''fine''': { '''repo_id''': '''suno/bark''', '''file_name''': '''fine_2.pt''', }, } UpperCAmelCase : Tuple = os.path.dirname(os.path.abspath(__file__)) UpperCAmelCase : str = os.path.join(os.path.expanduser('''~'''), '''.cache''') UpperCAmelCase : Dict = os.path.join(os.getenv('''XDG_CACHE_HOME''', default_cache_dir), '''suno''', '''bark_v0''') def _SCREAMING_SNAKE_CASE ( a , a=False ) -> Any: __A : Dict = model_type if use_small: key += "_small" return os.path.join(a , REMOTE_MODEL_PATHS[key]['file_name'] ) def _SCREAMING_SNAKE_CASE ( a , a ) -> List[str]: os.makedirs(a , exist_ok=a ) hf_hub_download(repo_id=a , filename=a , local_dir=a ) def _SCREAMING_SNAKE_CASE ( a , a , a=False , a="text" ) -> Any: if model_type == "text": __A : Optional[Any] = BarkSemanticModel __A : Dict = BarkSemanticConfig __A : Any = BarkSemanticGenerationConfig elif model_type == "coarse": __A : Optional[int] = BarkCoarseModel __A : List[Any] = BarkCoarseConfig __A : Optional[Any] = BarkCoarseGenerationConfig elif model_type == "fine": __A : List[str] = BarkFineModel __A : Union[str, Any] = BarkFineConfig __A : Dict = BarkFineGenerationConfig else: raise NotImplementedError() __A : int = F"""{model_type}_small""" if use_small else model_type __A : Dict = REMOTE_MODEL_PATHS[model_key] if not os.path.exists(a ): logger.info(F"""{model_type} model not found, downloading into `{CACHE_DIR}`.""" ) _download(model_info['repo_id'] , model_info['file_name'] ) __A : Any = torch.load(a , map_location=a ) # this is a hack __A : Optional[Any] = checkpoint['model_args'] if "input_vocab_size" not in model_args: __A : Dict = model_args['vocab_size'] __A : Union[str, Any] = model_args['vocab_size'] del model_args["vocab_size"] # convert Bark model arguments to HF Bark model arguments __A : List[Any] = model_args.pop('n_head' ) __A : Union[str, Any] = model_args.pop('n_embd' ) __A : Union[str, Any] = model_args.pop('n_layer' ) __A : str = ConfigClass(**checkpoint['model_args'] ) __A : Optional[int] = ModelClass(config=a ) __A : int = GenerationConfigClass() __A : Optional[int] = model_generation_config __A : Optional[int] = checkpoint['model'] # fixup checkpoint __A : Union[str, Any] = '_orig_mod.' for k, v in list(state_dict.items() ): if k.startswith(a ): # replace part of the key with corresponding layer name in HF implementation __A : Union[str, Any] = k[len(a ) :] for old_layer_name in new_layer_name_dict: __A : Tuple = new_k.replace(a , new_layer_name_dict[old_layer_name] ) __A : List[Any] = state_dict.pop(a ) __A : Any = set(state_dict.keys() ) - set(model.state_dict().keys() ) __A : Any = {k for k in extra_keys if not k.endswith('.attn.bias' )} __A : Optional[int] = set(model.state_dict().keys() ) - set(state_dict.keys() ) __A : Union[str, Any] = {k for k in missing_keys if not k.endswith('.attn.bias' )} if len(a ) != 0: raise ValueError(F"""extra keys found: {extra_keys}""" ) if len(a ) != 0: raise ValueError(F"""missing keys: {missing_keys}""" ) model.load_state_dict(a , strict=a ) __A : str = model.num_parameters(exclude_embeddings=a ) __A : Union[str, Any] = checkpoint['best_val_loss'].item() logger.info(F"""model loaded: {round(n_params/1e6 , 1 )}M params, {round(a , 3 )} loss""" ) model.eval() model.to(a ) del checkpoint, state_dict return model def _SCREAMING_SNAKE_CASE ( a , a=False , a="text" ) -> Tuple: if model_type not in ("text", "coarse", "fine"): raise NotImplementedError() __A : List[str] = 'cpu' # do conversion on cpu __A : Optional[int] = _get_ckpt_path(a , use_small=a ) __A : List[str] = _load_model(a , a , model_type=a , use_small=a ) # load bark initial model __A : str = _bark_load_model(a , 'cpu' , model_type=a , use_small=a ) if model_type == "text": __A : Union[str, Any] = bark_model['model'] if model.num_parameters(exclude_embeddings=a ) != bark_model.get_num_params(): raise ValueError('initial and new models don\'t have the same number of parameters' ) # check if same output as the bark model __A : Tuple = 5 __A : Optional[Any] = 10 if model_type in ["text", "coarse"]: __A : Optional[int] = torch.randint(2_56 , (batch_size, sequence_length) , dtype=torch.int ) __A : List[str] = bark_model(a )[0] __A : List[str] = model(a ) # take last logits __A : List[str] = output_new_model_total.logits[:, [-1], :] else: __A : Tuple = 3 __A : str = 8 __A : str = torch.randint(2_56 , (batch_size, sequence_length, n_codes_total) , dtype=torch.int ) __A : int = model(a , a ) __A : Union[str, Any] = bark_model(a , a ) __A : List[str] = output_new_model_total.logits # output difference should come from the difference of self-attention implementation design if output_new_model.shape != output_old_model.shape: raise ValueError('initial and new outputs don\'t have the same shape' ) if (output_new_model - output_old_model).abs().max().item() > 1e-3: raise ValueError('initial and new outputs are not equal' ) Path(a ).mkdir(exist_ok=a ) model.save_pretrained(a ) def _SCREAMING_SNAKE_CASE ( a , a , a , a , a , a , ) -> Optional[int]: __A : int = os.path.join(a , a ) __A : Optional[int] = BarkSemanticConfig.from_pretrained(os.path.join(a , 'config.json' ) ) __A : Optional[int] = BarkCoarseConfig.from_pretrained(os.path.join(a , 'config.json' ) ) __A : Optional[int] = BarkFineConfig.from_pretrained(os.path.join(a , 'config.json' ) ) __A : List[Any] = EncodecConfig.from_pretrained('facebook/encodec_24khz' ) __A : Any = BarkSemanticModel.from_pretrained(a ) __A : List[Any] = BarkCoarseModel.from_pretrained(a ) __A : Dict = BarkFineModel.from_pretrained(a ) __A : Optional[Any] = EncodecModel.from_pretrained('facebook/encodec_24khz' ) __A : int = BarkConfig.from_sub_model_configs( a , a , a , a ) __A : int = BarkGenerationConfig.from_sub_model_configs( semantic.generation_config , coarseAcoustic.generation_config , fineAcoustic.generation_config ) __A : Union[str, Any] = BarkModel(a ) __A : Optional[Any] = semantic __A : Tuple = coarseAcoustic __A : List[Any] = fineAcoustic __A : Tuple = codec __A : List[Any] = bark_generation_config Path(a ).mkdir(exist_ok=a ) bark.save_pretrained(a , repo_id=a , push_to_hub=a ) if __name__ == "__main__": UpperCAmelCase : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument('''model_type''', type=str, help='''text, coarse or fine.''') parser.add_argument('''pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--is_small''', action='''store_true''', help='''convert the small version instead of the large.''') UpperCAmelCase : str = parser.parse_args() load_model(args.pytorch_dump_folder_path, model_type=args.model_type, use_small=args.is_small)
280
from __future__ import annotations import math import random from collections.abc import Collection from typing import overload class _A: """simple docstring""" def __init__( self , _A = None ): if components is None: __A : int = [] __A : Tuple = list(_A ) def __len__( self ): return len(self.__components ) def __str__( self ): return "(" + ",".join(map(_A , self.__components ) ) + ")" def __add__( self , _A ): __A : Optional[int] = len(self ) if size == len(_A ): __A : Any = [self.__components[i] + other.component(_A ) for i in range(_A )] return Vector(_A ) else: raise Exception('must have the same size' ) def __sub__( self , _A ): __A : Tuple = len(self ) if size == len(_A ): __A : Union[str, Any] = [self.__components[i] - other.component(_A ) for i in range(_A )] return Vector(_A ) else: # error case raise Exception('must have the same size' ) @overload def __mul__( self , _A ): ... @overload def __mul__( self , _A ): ... def __mul__( self , _A ): if isinstance(_A , (float, int) ): __A : str = [c * other for c in self.__components] return Vector(_A ) elif isinstance(_A , _A ) and len(self ) == len(_A ): __A : Union[str, Any] = len(self ) __A : Dict = [self.__components[i] * other.component(_A ) for i in range(_A )] return sum(_A ) else: # error case raise Exception('invalid operand!' ) def UpperCAmelCase_ ( self ): return Vector(self.__components ) def UpperCAmelCase_ ( self , _A ): if isinstance(_A , _A ) and -len(self.__components ) <= i < len(self.__components ): return self.__components[i] else: raise Exception('index out of range' ) def UpperCAmelCase_ ( self , _A , _A ): assert -len(self.__components ) <= pos < len(self.__components ) __A : Optional[int] = value def UpperCAmelCase_ ( self ): if len(self.__components ) == 0: raise Exception('Vector is empty' ) __A : Optional[Any] = [c**2 for c in self.__components] return math.sqrt(sum(_A ) ) def UpperCAmelCase_ ( self , _A , _A = False ): __A : Optional[Any] = self * other __A : Optional[Any] = self.euclidean_length() * other.euclidean_length() if deg: return math.degrees(math.acos(num / den ) ) else: return math.acos(num / den ) def _SCREAMING_SNAKE_CASE ( a ) -> Vector: assert isinstance(a , a ) return Vector([0] * dimension ) def _SCREAMING_SNAKE_CASE ( a , a ) -> Vector: assert isinstance(a , a ) and (isinstance(a , a )) __A : Optional[Any] = [0] * dimension __A : Tuple = 1 return Vector(a ) def _SCREAMING_SNAKE_CASE ( a , a , a ) -> Vector: assert ( isinstance(a , a ) and isinstance(a , a ) and (isinstance(a , (int, float) )) ) return x * scalar + y def _SCREAMING_SNAKE_CASE ( a , a , a ) -> Vector: random.seed(a ) __A : str = [random.randint(a , a ) for _ in range(a )] return Vector(a ) class _A: """simple docstring""" def __init__( self , _A , _A , _A ): __A : Optional[Any] = matrix __A : Dict = w __A : Optional[int] = h def __str__( self ): __A : Tuple = '' for i in range(self.__height ): ans += "|" for j in range(self.__width ): if j < self.__width - 1: ans += str(self.__matrix[i][j] ) + "," else: ans += str(self.__matrix[i][j] ) + "|\n" return ans def __add__( self , _A ): if self.__width == other.width() and self.__height == other.height(): __A : Optional[Any] = [] for i in range(self.__height ): __A : Optional[Any] = [ self.__matrix[i][j] + other.component(_A , _A ) for j in range(self.__width ) ] matrix.append(_A ) return Matrix(_A , self.__width , self.__height ) else: raise Exception('matrix must have the same dimension!' ) def __sub__( self , _A ): if self.__width == other.width() and self.__height == other.height(): __A : Tuple = [] for i in range(self.__height ): __A : str = [ self.__matrix[i][j] - other.component(_A , _A ) for j in range(self.__width ) ] matrix.append(_A ) return Matrix(_A , self.__width , self.__height ) else: raise Exception('matrices must have the same dimension!' ) @overload def __mul__( self , _A ): ... @overload def __mul__( self , _A ): ... def __mul__( self , _A ): if isinstance(_A , _A ): # matrix-vector if len(_A ) == self.__width: __A : List[Any] = zero_vector(self.__height ) for i in range(self.__height ): __A : List[str] = [ self.__matrix[i][j] * other.component(_A ) for j in range(self.__width ) ] ans.change_component(_A , sum(_A ) ) return ans else: raise Exception( 'vector must have the same size as the ' 'number of columns of the matrix!' ) elif isinstance(_A , (int, float) ): # matrix-scalar __A : List[str] = [ [self.__matrix[i][j] * other for j in range(self.__width )] for i in range(self.__height ) ] return Matrix(_A , self.__width , self.__height ) return None def UpperCAmelCase_ ( self ): return self.__height def UpperCAmelCase_ ( self ): return self.__width def UpperCAmelCase_ ( self , _A , _A ): if 0 <= x < self.__height and 0 <= y < self.__width: return self.__matrix[x][y] else: raise Exception('change_component: indices out of bounds' ) def UpperCAmelCase_ ( self , _A , _A , _A ): if 0 <= x < self.__height and 0 <= y < self.__width: __A : int = value else: raise Exception('change_component: indices out of bounds' ) def UpperCAmelCase_ ( self , _A , _A ): if self.__height != self.__width: raise Exception('Matrix is not square' ) __A : List[str] = self.__matrix[:x] + self.__matrix[x + 1 :] for i in range(len(_A ) ): __A : Optional[int] = minor[i][:y] + minor[i][y + 1 :] return Matrix(_A , self.__width - 1 , self.__height - 1 ).determinant() def UpperCAmelCase_ ( self , _A , _A ): if self.__height != self.__width: raise Exception('Matrix is not square' ) if 0 <= x < self.__height and 0 <= y < self.__width: return (-1) ** (x + y) * self.minor(_A , _A ) else: raise Exception('Indices out of bounds' ) def UpperCAmelCase_ ( self ): if self.__height != self.__width: raise Exception('Matrix is not square' ) if self.__height < 1: raise Exception('Matrix has no element' ) elif self.__height == 1: return self.__matrix[0][0] elif self.__height == 2: return ( self.__matrix[0][0] * self.__matrix[1][1] - self.__matrix[0][1] * self.__matrix[1][0] ) else: __A : List[str] = [ self.__matrix[0][y] * self.cofactor(0 , _A ) for y in range(self.__width ) ] return sum(_A ) def _SCREAMING_SNAKE_CASE ( a ) -> Matrix: __A : list[list[float]] = [[0] * n for _ in range(a )] return Matrix(a , a , a ) def _SCREAMING_SNAKE_CASE ( a , a , a , a ) -> Matrix: random.seed(a ) __A : list[list[float]] = [ [random.randint(a , a ) for _ in range(a )] for _ in range(a ) ] return Matrix(a , a , a )
280
1
import math def _SCREAMING_SNAKE_CASE ( a ) -> list[int]: __A : List[str] = [] __A : Any = 2 __A : Union[str, Any] = int(math.sqrt(a ) ) # Size of every segment __A : Any = [True] * (end + 1) __A : List[Any] = [] while start <= end: if temp[start] is True: in_prime.append(a ) for i in range(start * start , end + 1 , a ): __A : Optional[int] = False start += 1 prime += in_prime __A : Any = end + 1 __A : Any = min(2 * end , a ) while low <= n: __A : List[Any] = [True] * (high - low + 1) for each in in_prime: __A : List[str] = math.floor(low / each ) * each if t < low: t += each for j in range(a , high + 1 , a ): __A : Optional[int] = False for j in range(len(a ) ): if temp[j] is True: prime.append(j + low ) __A : Optional[int] = high + 1 __A : Tuple = min(high + end , a ) return prime print(sieve(10**6))
280
import unittest from transformers import BertGenerationTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin UpperCAmelCase : List[str] = '''▁''' UpperCAmelCase : Optional[Any] = get_tests_dir('''fixtures/test_sentencepiece.model''') @require_sentencepiece class _A( snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Optional[int] = BertGenerationTokenizer UpperCamelCase : str = False UpperCamelCase : Tuple = True def UpperCAmelCase_ ( self ): super().setUp() __A : Tuple = BertGenerationTokenizer(_A , keep_accents=_A ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCAmelCase_ ( self ): __A : str = '<s>' __A : str = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_A ) , _A ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_A ) , _A ) def UpperCAmelCase_ ( self ): __A : int = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<unk>' ) self.assertEqual(vocab_keys[1] , '<s>' ) self.assertEqual(vocab_keys[-1] , '<pad>' ) self.assertEqual(len(_A ) , 1002 ) def UpperCAmelCase_ ( self ): self.assertEqual(self.get_tokenizer().vocab_size , 1000 ) def UpperCAmelCase_ ( self ): __A : str = BertGenerationTokenizer(_A , keep_accents=_A ) __A : Dict = tokenizer.tokenize('This is a test' ) self.assertListEqual(_A , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(_A ) , [285, 46, 10, 170, 382] , ) __A : int = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( _A , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.', ] , ) __A : Dict = tokenizer.convert_tokens_to_ids(_A ) self.assertListEqual( _A , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] , ) __A : Optional[int] = tokenizer.convert_ids_to_tokens(_A ) self.assertListEqual( _A , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.', ] , ) @cached_property def UpperCAmelCase_ ( self ): return BertGenerationTokenizer.from_pretrained('google/bert_for_seq_generation_L-24_bbc_encoder' ) @slow def UpperCAmelCase_ ( self ): __A : List[Any] = 'Hello World!' __A : Optional[Any] = [18536, 2260, 101] self.assertListEqual(_A , self.big_tokenizer.encode(_A ) ) @slow def UpperCAmelCase_ ( self ): __A : Dict = ( 'This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will' ' add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth' ) __A : int = [ 871, 419, 358, 946, 991, 2521, 452, 358, 1357, 387, 7751, 3536, 112, 985, 456, 126, 865, 938, 5400, 5734, 458, 1368, 467, 786, 2462, 5246, 1159, 633, 865, 4519, 457, 582, 852, 2557, 427, 916, 508, 405, 34324, 497, 391, 408, 11342, 1244, 385, 100, 938, 985, 456, 574, 362, 12597, 3200, 3129, 1172, ] self.assertListEqual(_A , self.big_tokenizer.encode(_A ) ) @require_torch @slow def UpperCAmelCase_ ( self ): import torch from transformers import BertGenerationConfig, BertGenerationEncoder # Build sequence __A : Tuple = list(self.big_tokenizer.get_vocab().keys() )[:10] __A : List[Any] = ' '.join(_A ) __A : Union[str, Any] = self.big_tokenizer.encode_plus(_A , return_tensors='pt' , return_token_type_ids=_A ) __A : Optional[Any] = self.big_tokenizer.batch_encode_plus( [sequence + ' ' + sequence] , return_tensors='pt' , return_token_type_ids=_A ) __A : int = BertGenerationConfig() __A : List[str] = BertGenerationEncoder(_A ) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**_A ) model(**_A ) @slow def UpperCAmelCase_ ( self ): # fmt: off __A : str = {'input_ids': [[39286, 458, 36335, 2001, 456, 13073, 13266, 455, 113, 7746, 1741, 11157, 391, 13073, 13266, 455, 113, 3967, 35412, 113, 4936, 109, 3870, 2377, 113, 30084, 45720, 458, 134, 17496, 112, 503, 11672, 113, 118, 112, 5665, 13347, 38687, 112, 1496, 31389, 112, 3268, 47264, 134, 962, 112, 16377, 8035, 23130, 430, 12169, 15518, 28592, 458, 146, 41697, 109, 391, 12169, 15518, 16689, 458, 146, 41358, 109, 452, 726, 4034, 111, 763, 35412, 5082, 388, 1903, 111, 9051, 391, 2870, 48918, 1900, 1123, 550, 998, 112, 9586, 15985, 455, 391, 410, 22955, 37636, 114], [448, 17496, 419, 3663, 385, 763, 113, 27533, 2870, 3283, 13043, 1639, 24713, 523, 656, 24013, 18550, 2521, 517, 27014, 21244, 420, 1212, 1465, 391, 927, 4833, 388, 578, 11786, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [484, 2169, 7687, 21932, 18146, 726, 363, 17032, 3391, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=_A , model_name='google/bert_for_seq_generation_L-24_bbc_encoder' , revision='c817d1fd1be2ffa69431227a1fe320544943d4db' , )
280
1
import gc import random import unittest import numpy as np import torch from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import ( DiffusionPipeline, UnCLIPImageVariationPipeline, UnCLIPScheduler, UNetaDConditionModel, UNetaDModel, ) from diffusers.pipelines.unclip.text_proj import UnCLIPTextProjModel from diffusers.utils import floats_tensor, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, load_image, require_torch_gpu, skip_mps from ..pipeline_params import IMAGE_VARIATION_BATCH_PARAMS, IMAGE_VARIATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class _A( snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Optional[Any] = UnCLIPImageVariationPipeline UpperCamelCase : Optional[Any] = IMAGE_VARIATION_PARAMS - {'''height''', '''width''', '''guidance_scale'''} UpperCamelCase : Optional[int] = IMAGE_VARIATION_BATCH_PARAMS UpperCamelCase : List[Any] = [ '''generator''', '''return_dict''', '''decoder_num_inference_steps''', '''super_res_num_inference_steps''', ] UpperCamelCase : Optional[int] = False @property def UpperCAmelCase_ ( self ): return 32 @property def UpperCAmelCase_ ( self ): return 32 @property def UpperCAmelCase_ ( self ): return self.time_input_dim @property def UpperCAmelCase_ ( self ): return self.time_input_dim * 4 @property def UpperCAmelCase_ ( self ): return 100 @property def UpperCAmelCase_ ( self ): __A : List[str] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) return tokenizer @property def UpperCAmelCase_ ( self ): torch.manual_seed(0 ) __A : str = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(_A ) @property def UpperCAmelCase_ ( self ): torch.manual_seed(0 ) __A : Tuple = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , num_hidden_layers=5 , num_attention_heads=4 , image_size=32 , intermediate_size=37 , patch_size=1 , ) return CLIPVisionModelWithProjection(_A ) @property def UpperCAmelCase_ ( self ): torch.manual_seed(0 ) __A : Optional[int] = { 'clip_embeddings_dim': self.text_embedder_hidden_size, 'time_embed_dim': self.time_embed_dim, 'cross_attention_dim': self.cross_attention_dim, } __A : Tuple = UnCLIPTextProjModel(**_A ) return model @property def UpperCAmelCase_ ( self ): torch.manual_seed(0 ) __A : Optional[int] = { 'sample_size': 32, # RGB in channels 'in_channels': 3, # Out channels is double in channels because predicts mean and variance 'out_channels': 6, 'down_block_types': ('ResnetDownsampleBlock2D', 'SimpleCrossAttnDownBlock2D'), 'up_block_types': ('SimpleCrossAttnUpBlock2D', 'ResnetUpsampleBlock2D'), 'mid_block_type': 'UNetMidBlock2DSimpleCrossAttn', 'block_out_channels': (self.block_out_channels_a, self.block_out_channels_a * 2), 'layers_per_block': 1, 'cross_attention_dim': self.cross_attention_dim, 'attention_head_dim': 4, 'resnet_time_scale_shift': 'scale_shift', 'class_embed_type': 'identity', } __A : Optional[Any] = UNetaDConditionModel(**_A ) return model @property def UpperCAmelCase_ ( self ): return { "sample_size": 64, "layers_per_block": 1, "down_block_types": ("ResnetDownsampleBlock2D", "ResnetDownsampleBlock2D"), "up_block_types": ("ResnetUpsampleBlock2D", "ResnetUpsampleBlock2D"), "block_out_channels": (self.block_out_channels_a, self.block_out_channels_a * 2), "in_channels": 6, "out_channels": 3, } @property def UpperCAmelCase_ ( self ): torch.manual_seed(0 ) __A : Any = UNetaDModel(**self.dummy_super_res_kwargs ) return model @property def UpperCAmelCase_ ( self ): # seeded differently to get different unet than `self.dummy_super_res_first` torch.manual_seed(1 ) __A : Optional[Any] = UNetaDModel(**self.dummy_super_res_kwargs ) return model def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.dummy_decoder __A : int = self.dummy_text_proj __A : Dict = self.dummy_text_encoder __A : Optional[int] = self.dummy_tokenizer __A : Tuple = self.dummy_super_res_first __A : Union[str, Any] = self.dummy_super_res_last __A : Any = UnCLIPScheduler( variance_type='learned_range' , prediction_type='epsilon' , num_train_timesteps=1000 , ) __A : Any = UnCLIPScheduler( variance_type='fixed_small_log' , prediction_type='epsilon' , num_train_timesteps=1000 , ) __A : Union[str, Any] = CLIPImageProcessor(crop_size=32 , size=32 ) __A : int = self.dummy_image_encoder return { "decoder": decoder, "text_encoder": text_encoder, "tokenizer": tokenizer, "text_proj": text_proj, "feature_extractor": feature_extractor, "image_encoder": image_encoder, "super_res_first": super_res_first, "super_res_last": super_res_last, "decoder_scheduler": decoder_scheduler, "super_res_scheduler": super_res_scheduler, } def UpperCAmelCase_ ( self , _A , _A=0 , _A=True ): __A : Tuple = floats_tensor((1, 3, 32, 32) , rng=random.Random(_A ) ).to(_A ) if str(_A ).startswith('mps' ): __A : Dict = torch.manual_seed(_A ) else: __A : List[Any] = torch.Generator(device=_A ).manual_seed(_A ) if pil_image: __A : Tuple = input_image * 0.5 + 0.5 __A : Union[str, Any] = input_image.clamp(0 , 1 ) __A : Any = input_image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() __A : List[Any] = DiffusionPipeline.numpy_to_pil(_A )[0] return { "image": input_image, "generator": generator, "decoder_num_inference_steps": 2, "super_res_num_inference_steps": 2, "output_type": "np", } def UpperCAmelCase_ ( self ): __A : Any = 'cpu' __A : Tuple = self.get_dummy_components() __A : Tuple = self.pipeline_class(**_A ) __A : Tuple = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) __A : Optional[int] = self.get_dummy_inputs(_A , pil_image=_A ) __A : Dict = pipe(**_A ) __A : Tuple = output.images __A : Union[str, Any] = self.get_dummy_inputs(_A , pil_image=_A ) __A : int = pipe( **_A , return_dict=_A , )[0] __A : Optional[Any] = image[0, -3:, -3:, -1] __A : Dict = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __A : Dict = np.array( [ 0.9_9_9_7, 0.0_0_0_2, 0.9_9_9_7, 0.9_9_9_7, 0.9_9_6_9, 0.0_0_2_3, 0.9_9_9_7, 0.9_9_6_9, 0.9_9_7_0, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 def UpperCAmelCase_ ( self ): __A : Optional[int] = 'cpu' __A : List[Any] = self.get_dummy_components() __A : Optional[Any] = self.pipeline_class(**_A ) __A : List[str] = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) __A : List[str] = self.get_dummy_inputs(_A , pil_image=_A ) __A : List[str] = pipe(**_A ) __A : Optional[Any] = output.images __A : Optional[int] = self.get_dummy_inputs(_A , pil_image=_A ) __A : Dict = pipe( **_A , return_dict=_A , )[0] __A : Optional[Any] = image[0, -3:, -3:, -1] __A : str = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __A : Tuple = np.array([0.9_9_9_7, 0.0_0_0_3, 0.9_9_9_7, 0.9_9_9_7, 0.9_9_7_0, 0.0_0_2_4, 0.9_9_9_7, 0.9_9_7_1, 0.9_9_7_1] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 def UpperCAmelCase_ ( self ): __A : Optional[int] = 'cpu' __A : str = self.get_dummy_components() __A : List[str] = self.pipeline_class(**_A ) __A : Dict = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) __A : List[str] = self.get_dummy_inputs(_A , pil_image=_A ) __A : Union[str, Any] = [ pipeline_inputs['image'], pipeline_inputs['image'], ] __A : Optional[int] = pipe(**_A ) __A : Tuple = output.images __A : Dict = self.get_dummy_inputs(_A , pil_image=_A ) __A : Any = [ tuple_pipeline_inputs['image'], tuple_pipeline_inputs['image'], ] __A : Union[str, Any] = pipe( **_A , return_dict=_A , )[0] __A : List[Any] = image[0, -3:, -3:, -1] __A : str = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (2, 64, 64, 3) __A : Any = np.array( [ 0.9_9_9_7, 0.9_9_8_9, 0.0_0_0_8, 0.0_0_2_1, 0.9_9_6_0, 0.0_0_1_8, 0.0_0_1_4, 0.0_0_0_2, 0.9_9_3_3, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 def UpperCAmelCase_ ( self ): __A : Tuple = torch.device('cpu' ) class _A: """simple docstring""" UpperCamelCase : List[Any] = 1 __A : str = self.get_dummy_components() __A : Optional[int] = self.pipeline_class(**_A ) __A : Tuple = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) __A : Optional[int] = torch.Generator(device=_A ).manual_seed(0 ) __A : List[str] = pipe.decoder.dtype __A : List[Any] = 1 __A : Optional[int] = ( batch_size, pipe.decoder.config.in_channels, pipe.decoder.config.sample_size, pipe.decoder.config.sample_size, ) __A : Any = pipe.prepare_latents( _A , dtype=_A , device=_A , generator=_A , latents=_A , scheduler=DummyScheduler() ) __A : Tuple = ( batch_size, pipe.super_res_first.config.in_channels // 2, pipe.super_res_first.config.sample_size, pipe.super_res_first.config.sample_size, ) __A : Tuple = pipe.prepare_latents( _A , dtype=_A , device=_A , generator=_A , latents=_A , scheduler=DummyScheduler() ) __A : Optional[int] = self.get_dummy_inputs(_A , pil_image=_A ) __A : Dict = pipe( **_A , decoder_latents=_A , super_res_latents=_A ).images __A : int = self.get_dummy_inputs(_A , pil_image=_A ) # Don't pass image, instead pass embedding __A : Any = pipeline_inputs.pop('image' ) __A : List[str] = pipe.image_encoder(_A ).image_embeds __A : List[str] = pipe( **_A , decoder_latents=_A , super_res_latents=_A , image_embeddings=_A , ).images # make sure passing text embeddings manually is identical assert np.abs(img_out_a - img_out_a ).max() < 1e-4 @skip_mps def UpperCAmelCase_ ( self ): __A : str = torch_device == 'cpu' # Check is relaxed because there is not a torch 2.0 sliced attention added kv processor __A : Tuple = 1e-2 self._test_attention_slicing_forward_pass( test_max_difference=_A , expected_max_diff=_A ) @skip_mps def UpperCAmelCase_ ( self ): __A : Union[str, Any] = torch_device == 'cpu' __A : List[Any] = True __A : Dict = [ 'decoder_num_inference_steps', 'super_res_num_inference_steps', ] self._test_inference_batch_single_identical( test_max_difference=_A , relax_max_difference=_A , additional_params_copy_to_batched_inputs=_A , ) def UpperCAmelCase_ ( self ): __A : Union[str, Any] = [ 'decoder_num_inference_steps', 'super_res_num_inference_steps', ] if torch_device == "mps": # TODO: MPS errors with larger batch sizes __A : Any = [2, 3] self._test_inference_batch_consistent( batch_sizes=_A , additional_params_copy_to_batched_inputs=_A , ) else: self._test_inference_batch_consistent( additional_params_copy_to_batched_inputs=_A ) @skip_mps def UpperCAmelCase_ ( self ): return super().test_dict_tuple_outputs_equivalent() @skip_mps def UpperCAmelCase_ ( self ): return super().test_save_load_local() @skip_mps def UpperCAmelCase_ ( self ): return super().test_save_load_optional_components() @slow @require_torch_gpu class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase_ ( self ): __A : Tuple = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/unclip/cat.png' ) __A : Dict = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/unclip/karlo_v1_alpha_cat_variation_fp16.npy' ) __A : Optional[Any] = UnCLIPImageVariationPipeline.from_pretrained( 'kakaobrain/karlo-v1-alpha-image-variations' , torch_dtype=torch.floataa ) __A : Tuple = pipeline.to(_A ) pipeline.set_progress_bar_config(disable=_A ) __A : Optional[Any] = torch.Generator(device='cpu' ).manual_seed(0 ) __A : List[Any] = pipeline( _A , generator=_A , output_type='np' , ) __A : Optional[Any] = output.images[0] assert image.shape == (256, 256, 3) assert_mean_pixel_difference(_A , _A , 15 )
280
import hashlib import unittest from typing import Dict import numpy as np from transformers import ( MODEL_FOR_MASK_GENERATION_MAPPING, TF_MODEL_FOR_MASK_GENERATION_MAPPING, is_vision_available, pipeline, ) from transformers.pipelines import MaskGenerationPipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) if is_vision_available(): from PIL import Image else: class _A: """simple docstring""" @staticmethod def UpperCAmelCase_ ( *_A , **_A ): pass def _SCREAMING_SNAKE_CASE ( a ) -> str: __A : str = hashlib.mda(image.tobytes() ) return m.hexdigest()[:10] def _SCREAMING_SNAKE_CASE ( a ) -> Dict: __A : Dict = np.array(a ) __A : List[Any] = npimg.shape return {"hash": hashimage(a ), "shape": shape} @is_pipeline_test @require_vision @require_torch class _A( unittest.TestCase ): """simple docstring""" UpperCamelCase : str = dict( (list(MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if MODEL_FOR_MASK_GENERATION_MAPPING else []) ) UpperCamelCase : int = dict( (list(TF_MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if TF_MODEL_FOR_MASK_GENERATION_MAPPING else []) ) def UpperCAmelCase_ ( self , _A , _A , _A ): __A : Dict = MaskGenerationPipeline(model=_A , image_processor=_A ) return image_segmenter, [ "./tests/fixtures/tests_samples/COCO/000000039769.png", "./tests/fixtures/tests_samples/COCO/000000039769.png", ] def UpperCAmelCase_ ( self , _A , _A ): pass @require_tf @unittest.skip('Image segmentation not implemented in TF' ) def UpperCAmelCase_ ( self ): pass @slow @require_torch def UpperCAmelCase_ ( self ): __A : Union[str, Any] = pipeline('mask-generation' , model='facebook/sam-vit-huge' ) __A : List[str] = image_segmenter('http://images.cocodataset.org/val2017/000000039769.jpg' , points_per_batch=256 ) # Shortening by hashing __A : List[Any] = [] for i, o in enumerate(outputs['masks'] ): new_outupt += [{"mask": mask_to_test_readable(_A ), "scores": outputs["scores"][i]}] # fmt: off self.assertEqual( nested_simplify(_A , decimals=4 ) , [ {'mask': {'hash': '115ad19f5f', 'shape': (480, 640)}, 'scores': 1.0_4_4_4}, {'mask': {'hash': '6affa964c6', 'shape': (480, 640)}, 'scores': 1.0_2_1}, {'mask': {'hash': 'dfe28a0388', 'shape': (480, 640)}, 'scores': 1.0_1_6_7}, {'mask': {'hash': 'c0a5f4a318', 'shape': (480, 640)}, 'scores': 1.0_1_3_2}, {'mask': {'hash': 'fe8065c197', 'shape': (480, 640)}, 'scores': 1.0_0_5_3}, {'mask': {'hash': 'e2d0b7a0b7', 'shape': (480, 640)}, 'scores': 0.9_9_6_7}, {'mask': {'hash': '453c7844bd', 'shape': (480, 640)}, 'scores': 0.9_9_3}, {'mask': {'hash': '3d44f2926d', 'shape': (480, 640)}, 'scores': 0.9_9_0_9}, {'mask': {'hash': '64033ddc3f', 'shape': (480, 640)}, 'scores': 0.9_8_7_9}, {'mask': {'hash': '801064ff79', 'shape': (480, 640)}, 'scores': 0.9_8_3_4}, {'mask': {'hash': '6172f276ef', 'shape': (480, 640)}, 'scores': 0.9_7_1_6}, {'mask': {'hash': 'b49e60e084', 'shape': (480, 640)}, 'scores': 0.9_6_1_2}, {'mask': {'hash': 'a811e775fd', 'shape': (480, 640)}, 'scores': 0.9_5_9_9}, {'mask': {'hash': 'a6a8ebcf4b', 'shape': (480, 640)}, 'scores': 0.9_5_5_2}, {'mask': {'hash': '9d8257e080', 'shape': (480, 640)}, 'scores': 0.9_5_3_2}, {'mask': {'hash': '32de6454a8', 'shape': (480, 640)}, 'scores': 0.9_5_1_6}, {'mask': {'hash': 'af3d4af2c8', 'shape': (480, 640)}, 'scores': 0.9_4_9_9}, {'mask': {'hash': '3c6db475fb', 'shape': (480, 640)}, 'scores': 0.9_4_8_3}, {'mask': {'hash': 'c290813fb9', 'shape': (480, 640)}, 'scores': 0.9_4_6_4}, {'mask': {'hash': 'b6f0b8f606', 'shape': (480, 640)}, 'scores': 0.9_4_3}, {'mask': {'hash': '92ce16bfdf', 'shape': (480, 640)}, 'scores': 0.9_4_3}, {'mask': {'hash': 'c749b25868', 'shape': (480, 640)}, 'scores': 0.9_4_0_8}, {'mask': {'hash': 'efb6cab859', 'shape': (480, 640)}, 'scores': 0.9_3_3_5}, {'mask': {'hash': '1ff2eafb30', 'shape': (480, 640)}, 'scores': 0.9_3_2_6}, {'mask': {'hash': '788b798e24', 'shape': (480, 640)}, 'scores': 0.9_2_6_2}, {'mask': {'hash': 'abea804f0e', 'shape': (480, 640)}, 'scores': 0.8_9_9_9}, {'mask': {'hash': '7b9e8ddb73', 'shape': (480, 640)}, 'scores': 0.8_9_8_6}, {'mask': {'hash': 'cd24047c8a', 'shape': (480, 640)}, 'scores': 0.8_9_8_4}, {'mask': {'hash': '6943e6bcbd', 'shape': (480, 640)}, 'scores': 0.8_8_7_3}, {'mask': {'hash': 'b5f47c9191', 'shape': (480, 640)}, 'scores': 0.8_8_7_1} ] , ) # fmt: on @require_torch @slow def UpperCAmelCase_ ( self ): __A : Optional[Any] = 'facebook/sam-vit-huge' __A : List[str] = pipeline('mask-generation' , model=_A ) __A : Tuple = image_segmenter( 'http://images.cocodataset.org/val2017/000000039769.jpg' , pred_iou_thresh=1 , points_per_batch=256 ) # Shortening by hashing __A : List[str] = [] for i, o in enumerate(outputs['masks'] ): new_outupt += [{"mask": mask_to_test_readable(_A ), "scores": outputs["scores"][i]}] self.assertEqual( nested_simplify(_A , decimals=4 ) , [ {'mask': {'hash': '115ad19f5f', 'shape': (480, 640)}, 'scores': 1.0_4_4_4}, {'mask': {'hash': '6affa964c6', 'shape': (480, 640)}, 'scores': 1.0_2_1_0}, {'mask': {'hash': 'dfe28a0388', 'shape': (480, 640)}, 'scores': 1.0_1_6_7}, {'mask': {'hash': 'c0a5f4a318', 'shape': (480, 640)}, 'scores': 1.0_1_3_2}, {'mask': {'hash': 'fe8065c197', 'shape': (480, 640)}, 'scores': 1.0_0_5_3}, ] , )
280
1
import argparse from transformers import BigBirdConfig, BigBirdForPreTraining, BigBirdForQuestionAnswering, load_tf_weights_in_big_bird from transformers.utils import logging logging.set_verbosity_info() def _SCREAMING_SNAKE_CASE ( a , a , a , a ) -> Any: # Initialise PyTorch model __A : Union[str, Any] = BigBirdConfig.from_json_file(a ) print(F"""Building PyTorch model from configuration: {config}""" ) if is_trivia_qa: __A : Dict = BigBirdForQuestionAnswering(a ) else: __A : str = BigBirdForPreTraining(a ) # Load weights from tf checkpoint load_tf_weights_in_big_bird(a , a , is_trivia_qa=a ) # Save pytorch-model print(F"""Save PyTorch model to {pytorch_dump_path}""" ) model.save_pretrained(a ) if __name__ == "__main__": UpperCAmelCase : int = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--tf_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--big_bird_config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained BERT model. \n''' '''This specifies the model architecture.''' ), ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) parser.add_argument( '''--is_trivia_qa''', action='''store_true''', help='''Whether to convert a model with a trivia_qa head.''' ) UpperCAmelCase : List[Any] = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.tf_checkpoint_path, args.big_bird_config_file, args.pytorch_dump_path, args.is_trivia_qa )
280
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import OwlViTImageProcessor, OwlViTProcessor @require_vision class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): __A : List[Any] = tempfile.mkdtemp() # fmt: off __A : List[str] = ['', 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'lo', 'l</w>', 'w</w>', 'r</w>', 't</w>', 'low</w>', 'er</w>', 'lowest</w>', 'newer</w>', 'wider', '<unk>', '<|startoftext|>', '<|endoftext|>'] # fmt: on __A : Union[str, Any] = dict(zip(_A , range(len(_A ) ) ) ) __A : Optional[int] = ['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>', ''] __A : int = {'unk_token': '<unk>'} __A : Optional[int] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) __A : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(_A ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(_A ) ) __A : List[Any] = { 'do_resize': True, 'size': 20, 'do_center_crop': True, 'crop_size': 18, 'do_normalize': True, 'image_mean': [0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3], 'image_std': [0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1], } __A : Optional[int] = os.path.join(self.tmpdirname , _A ) with open(self.image_processor_file , 'w' , encoding='utf-8' ) as fp: json.dump(_A , _A ) def UpperCAmelCase_ ( self , **_A ): return CLIPTokenizer.from_pretrained(self.tmpdirname , pad_token='!' , **_A ) def UpperCAmelCase_ ( self , **_A ): return CLIPTokenizerFast.from_pretrained(self.tmpdirname , pad_token='!' , **_A ) def UpperCAmelCase_ ( self , **_A ): return OwlViTImageProcessor.from_pretrained(self.tmpdirname , **_A ) def UpperCAmelCase_ ( self ): shutil.rmtree(self.tmpdirname ) def UpperCAmelCase_ ( self ): __A : int = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __A : Optional[int] = [Image.fromarray(np.moveaxis(_A , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCAmelCase_ ( self ): __A : List[Any] = self.get_tokenizer() __A : str = self.get_rust_tokenizer() __A : List[str] = self.get_image_processor() __A : Optional[int] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) processor_slow.save_pretrained(self.tmpdirname ) __A : int = OwlViTProcessor.from_pretrained(self.tmpdirname , use_fast=_A ) __A : Optional[Any] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) processor_fast.save_pretrained(self.tmpdirname ) __A : Optional[Any] = OwlViTProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , _A ) self.assertIsInstance(processor_fast.tokenizer , _A ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , _A ) self.assertIsInstance(processor_fast.image_processor , _A ) def UpperCAmelCase_ ( self ): __A : List[str] = OwlViTProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __A : Optional[int] = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) __A : Optional[int] = self.get_image_processor(do_normalize=_A ) __A : Any = OwlViTProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=_A ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , _A ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _A ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.get_image_processor() __A : Optional[Any] = self.get_tokenizer() __A : Union[str, Any] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Union[str, Any] = self.prepare_image_inputs() __A : int = image_processor(_A , return_tensors='np' ) __A : str = processor(images=_A , return_tensors='np' ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1e-2 ) def UpperCAmelCase_ ( self ): __A : str = self.get_image_processor() __A : str = self.get_tokenizer() __A : Tuple = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : str = 'lower newer' __A : str = processor(text=_A , return_tensors='np' ) __A : List[str] = tokenizer(_A , return_tensors='np' ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key][0].tolist() , encoded_processor[key][0].tolist() ) def UpperCAmelCase_ ( self ): __A : int = self.get_image_processor() __A : Optional[int] = self.get_tokenizer() __A : List[str] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Any = 'lower newer' __A : Optional[Any] = self.prepare_image_inputs() __A : List[Any] = processor(text=_A , images=_A ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Any = 'google/owlvit-base-patch32' __A : int = OwlViTProcessor.from_pretrained(_A ) __A : Dict = ['cat', 'nasa badge'] __A : Optional[Any] = processor(text=_A ) __A : Optional[int] = 16 self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (2, seq_length) ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Tuple = 'google/owlvit-base-patch32' __A : Any = OwlViTProcessor.from_pretrained(_A ) __A : Dict = [['cat', 'nasa badge'], ['person']] __A : Dict = processor(text=_A ) __A : Optional[int] = 16 __A : Any = len(_A ) __A : Union[str, Any] = max([len(_A ) for texts in input_texts] ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (batch_size * num_max_text_queries, seq_length) ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : List[Any] = 'google/owlvit-base-patch32' __A : str = OwlViTProcessor.from_pretrained(_A ) __A : Union[str, Any] = ['cat', 'nasa badge'] __A : Tuple = processor(text=_A ) __A : str = 16 __A : int = inputs['input_ids'] __A : List[Any] = [ [49406, 2368, 49407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [49406, 6841, 11301, 49407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (2, seq_length) ) self.assertListEqual(list(input_ids[0] ) , predicted_ids[0] ) self.assertListEqual(list(input_ids[1] ) , predicted_ids[1] ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.get_image_processor() __A : List[str] = self.get_tokenizer() __A : Optional[Any] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Optional[int] = self.prepare_image_inputs() __A : Optional[int] = self.prepare_image_inputs() __A : Optional[int] = processor(images=_A , query_images=_A ) self.assertListEqual(list(inputs.keys() ) , ['query_pixel_values', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.get_image_processor() __A : Union[str, Any] = self.get_tokenizer() __A : str = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Optional[Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __A : Any = processor.batch_decode(_A ) __A : Tuple = tokenizer.batch_decode(_A ) self.assertListEqual(_A , _A )
280
1
def _SCREAMING_SNAKE_CASE ( a , a ) -> str: __A : list[list[str]] = [[] for _ in range(a )] __A : Dict = key - 1 if key <= 0: raise ValueError('Height of grid can\'t be 0 or negative' ) if key == 1 or len(a ) <= key: return input_string for position, character in enumerate(a ): __A : List[str] = position % (lowest * 2) # puts it in bounds __A : Tuple = min(a , lowest * 2 - num ) # creates zigzag pattern temp_grid[num].append(a ) __A : Union[str, Any] = [''.join(a ) for row in temp_grid] __A : Optional[int] = ''.join(a ) return output_string def _SCREAMING_SNAKE_CASE ( a , a ) -> str: __A : Dict = [] __A : Any = key - 1 if key <= 0: raise ValueError('Height of grid can\'t be 0 or negative' ) if key == 1: return input_string __A : list[list[str]] = [[] for _ in range(a )] # generates template for position in range(len(a ) ): __A : Optional[Any] = position % (lowest * 2) # puts it in bounds __A : Dict = min(a , lowest * 2 - num ) # creates zigzag pattern temp_grid[num].append('*' ) __A : Dict = 0 for row in temp_grid: # fills in the characters __A : List[str] = input_string[counter : counter + len(a )] grid.append(list(a ) ) counter += len(a ) __A : Any = '' # reads as zigzag for position in range(len(a ) ): __A : List[Any] = position % (lowest * 2) # puts it in bounds __A : Optional[Any] = min(a , lowest * 2 - num ) # creates zigzag pattern output_string += grid[num][0] grid[num].pop(0 ) return output_string def _SCREAMING_SNAKE_CASE ( a ) -> dict[int, str]: __A : int = {} for key_guess in range(1 , len(a ) ): # tries every key __A : Tuple = decrypt(a , a ) return results if __name__ == "__main__": import doctest doctest.testmod()
280
import math def _SCREAMING_SNAKE_CASE ( a ) -> list[int]: __A : List[str] = [] __A : Any = 2 __A : Union[str, Any] = int(math.sqrt(a ) ) # Size of every segment __A : Any = [True] * (end + 1) __A : List[Any] = [] while start <= end: if temp[start] is True: in_prime.append(a ) for i in range(start * start , end + 1 , a ): __A : Optional[int] = False start += 1 prime += in_prime __A : Any = end + 1 __A : Any = min(2 * end , a ) while low <= n: __A : List[Any] = [True] * (high - low + 1) for each in in_prime: __A : List[str] = math.floor(low / each ) * each if t < low: t += each for j in range(a , high + 1 , a ): __A : Optional[int] = False for j in range(len(a ) ): if temp[j] is True: prime.append(j + low ) __A : Optional[int] = high + 1 __A : Tuple = min(high + end , a ) return prime print(sieve(10**6))
280
1
def _SCREAMING_SNAKE_CASE ( a ) -> list[int]: if length <= 0 or not isinstance(a , a ): raise ValueError('Length must be a positive integer.' ) return [n * (2 * n - 1) for n in range(a )] if __name__ == "__main__": print(hexagonal_numbers(length=5)) print(hexagonal_numbers(length=10))
280
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available UpperCAmelCase : Any = { '''configuration_mvp''': ['''MVP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MvpConfig''', '''MvpOnnxConfig'''], '''tokenization_mvp''': ['''MvpTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : int = ['''MvpTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : str = [ '''MVP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MvpForCausalLM''', '''MvpForConditionalGeneration''', '''MvpForQuestionAnswering''', '''MvpForSequenceClassification''', '''MvpModel''', '''MvpPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_mvp import MVP_PRETRAINED_CONFIG_ARCHIVE_MAP, MvpConfig, MvpOnnxConfig from .tokenization_mvp import MvpTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mvp_fast import MvpTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mvp import ( MVP_PRETRAINED_MODEL_ARCHIVE_LIST, MvpForCausalLM, MvpForConditionalGeneration, MvpForQuestionAnswering, MvpForSequenceClassification, MvpModel, MvpPreTrainedModel, ) else: import sys UpperCAmelCase : List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
280
1
from typing import Any, Dict, List, Optional, Tuple, Union import torch from torch import nn from torch.utils.data import DistributedSampler, RandomSampler from transformers import PreTrainedModel, Trainer, logging from transformers.integrations import is_fairscale_available from transformers.models.fsmt.configuration_fsmt import FSMTConfig from transformers.optimization import ( Adafactor, AdamW, get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) from transformers.trainer_pt_utils import get_tpu_sampler from transformers.training_args import ParallelMode from transformers.utils import is_torch_tpu_available if is_fairscale_available(): from fairscale.optim import OSS UpperCAmelCase : Optional[int] = logging.get_logger(__name__) UpperCAmelCase : List[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, '''constant''': get_constant_schedule, '''constant_w_warmup''': get_constant_schedule_with_warmup, } class _A( snake_case__ ): """simple docstring""" def __init__( self , _A=None , _A=None , *_A , **_A ): super().__init__(*_A , **_A ) if config is None: assert isinstance(self.model , _A ), ( "If no `config` is passed the model to be trained has to be of type `PreTrainedModel`, but is" F""" {self.model.__class__}""" ) __A : Optional[Any] = self.model.config else: __A : Tuple = config __A : Union[str, Any] = data_args __A : List[Any] = self.config.tgt_vocab_size if isinstance(self.config , _A ) else self.config.vocab_size if self.args.label_smoothing != 0 or (self.data_args is not None and self.data_args.ignore_pad_token_for_loss): assert self.config.pad_token_id is not None, ( "Make sure that `config.pad_token_id` is correcly defined when ignoring `pad_token` for loss" " calculation or doing label smoothing." ) if self.config.pad_token_id is None and self.config.eos_token_id is not None: logger.warning( F"""The `config.pad_token_id` is `None`. Using `config.eos_token_id` = {self.config.eos_token_id} for""" ' padding..' ) if self.args.label_smoothing == 0: __A : List[str] = torch.nn.CrossEntropyLoss(ignore_index=self.config.pad_token_id ) else: # dynamically import label_smoothed_nll_loss from utils import label_smoothed_nll_loss __A : Optional[int] = label_smoothed_nll_loss def UpperCAmelCase_ ( self , _A ): if self.optimizer is None: __A : List[str] = ['bias', 'LayerNorm.weight'] __A : List[Any] = [ { 'params': [p for n, p in self.model.named_parameters() if not any(nd in n for nd in no_decay )], 'weight_decay': self.args.weight_decay, }, { 'params': [p for n, p in self.model.named_parameters() if any(nd in n for nd in no_decay )], 'weight_decay': 0.0, }, ] __A : Dict = Adafactor if self.args.adafactor else AdamW if self.args.adafactor: __A : Any = Adafactor __A : List[str] = {'scale_parameter': False, 'relative_step': False} else: __A : Tuple = AdamW __A : List[Any] = { 'betas': (self.args.adam_betaa, self.args.adam_betaa), 'eps': self.args.adam_epsilon, } __A : Optional[Any] = self.args.learning_rate if self.sharded_ddp: __A : Any = OSS( params=_A , optim=_A , **_A , ) else: __A : List[str] = optimizer_cls(_A , **_A ) if self.lr_scheduler is None: __A : Any = self._get_lr_scheduler(_A ) else: # ignoring --lr_scheduler logger.warning('scheduler is passed to `Seq2SeqTrainer`, `--lr_scheduler` arg is ignored.' ) def UpperCAmelCase_ ( self , _A ): __A : Dict = arg_to_scheduler[self.args.lr_scheduler] if self.args.lr_scheduler == "constant": __A : Dict = schedule_func(self.optimizer ) elif self.args.lr_scheduler == "constant_w_warmup": __A : str = schedule_func(self.optimizer , num_warmup_steps=self.args.warmup_steps ) else: __A : int = schedule_func( self.optimizer , num_warmup_steps=self.args.warmup_steps , num_training_steps=_A ) return scheduler def UpperCAmelCase_ ( self ): if isinstance(self.train_dataset , torch.utils.data.IterableDataset ): return None elif is_torch_tpu_available(): return get_tpu_sampler(self.train_dataset ) else: if self.args.sortish_sampler: self.train_dataset.make_sortish_sampler( self.args.per_device_train_batch_size , distributed=(self.args.parallel_mode == ParallelMode.DISTRIBUTED) , ) return ( RandomSampler(self.train_dataset ) if self.args.local_rank == -1 else DistributedSampler(self.train_dataset ) ) def UpperCAmelCase_ ( self , _A , _A , _A ): if self.args.label_smoothing == 0: if self.data_args is not None and self.data_args.ignore_pad_token_for_loss: # force training to ignore pad token __A : List[str] = model(**_A , use_cache=_A )[0] __A : List[str] = self.loss_fn(logits.view(-1 , logits.shape[-1] ) , labels.view(-1 ) ) else: # compute usual loss via models __A , __A : List[str] = model(**_A , labels=_A , use_cache=_A )[:2] else: # compute label smoothed loss __A : Tuple = model(**_A , use_cache=_A )[0] __A : Optional[int] = torch.nn.functional.log_softmax(_A , dim=-1 ) __A , __A : Tuple = self.loss_fn(_A , _A , self.args.label_smoothing , ignore_index=self.config.pad_token_id ) return loss, logits def UpperCAmelCase_ ( self , _A , _A ): __A : int = inputs.pop('labels' ) __A , __A : int = self._compute_loss(_A , _A , _A ) return loss def UpperCAmelCase_ ( self , _A , _A , _A , _A = None , ): __A : str = self._prepare_inputs(_A ) __A : List[str] = { 'max_length': self.data_args.val_max_target_length if self.data_args is not None else self.config.max_length, 'num_beams': self.data_args.eval_beams if self.data_args is not None else self.config.num_beams, } if self.args.predict_with_generate and not self.args.prediction_loss_only: __A : Dict = self.model.generate( inputs['input_ids'] , attention_mask=inputs['attention_mask'] , **_A , ) # in case the batch is shorter than max length, the output should be padded if generated_tokens.shape[-1] < gen_kwargs["max_length"]: __A : int = self._pad_tensors_to_max_len(_A , gen_kwargs['max_length'] ) __A : List[Any] = inputs.pop('labels' ) with torch.no_grad(): # compute loss on predict data __A , __A : int = self._compute_loss(_A , _A , _A ) __A : List[str] = loss.mean().detach() if self.args.prediction_loss_only: return (loss, None, None) __A : Union[str, Any] = generated_tokens if self.args.predict_with_generate else logits if labels.shape[-1] < gen_kwargs["max_length"]: __A : List[Any] = self._pad_tensors_to_max_len(_A , gen_kwargs['max_length'] ) return (loss, logits, labels) def UpperCAmelCase_ ( self , _A , _A ): # If PAD token is not defined at least EOS token has to be defined __A : Dict = self.config.pad_token_id if self.config.pad_token_id is not None else self.config.eos_token_id if pad_token_id is None: raise ValueError( 'Make sure that either `config.pad_token_id` or `config.eos_token_id` is defined if tensor has to be' F""" padded to `max_length`={max_length}""" ) __A : Union[str, Any] = pad_token_id * torch.ones( (tensor.shape[0], max_length) , dtype=tensor.dtype , device=tensor.device ) __A : str = tensor return padded_tensor
280
def _SCREAMING_SNAKE_CASE ( a ) -> Tuple: __A , __A : Optional[Any] = [], [] while len(a ) > 1: __A , __A : Any = min(a ), max(a ) start.append(a ) end.append(a ) collection.remove(a ) collection.remove(a ) end.reverse() return start + collection + end if __name__ == "__main__": UpperCAmelCase : int = input('''Enter numbers separated by a comma:\n''').strip() UpperCAmelCase : Dict = [int(item) for item in user_input.split(''',''')] print(*merge_sort(unsorted), sep=''',''')
280
1
from __future__ import annotations import math def _SCREAMING_SNAKE_CASE ( a , a ) -> float: __A : Tuple = u for i in range(1 , a ): __A : int = temp * (u - i) return temp def _SCREAMING_SNAKE_CASE ( ) -> None: __A : str = int(input('enter the numbers of values: ' ) ) __A : list[list[float]] = [] for _ in range(a ): y.append([] ) for i in range(a ): for j in range(a ): y[i].append(a ) __A : Dict = 0 print('enter the values of parameters in a list: ' ) __A : str = list(map(a , input().split() ) ) print('enter the values of corresponding parameters: ' ) for i in range(a ): __A : Optional[int] = float(input() ) __A : str = int(input('enter the value to interpolate: ' ) ) __A : Union[str, Any] = (value - x[0]) / (x[1] - x[0]) # for calculating forward difference table for i in range(1 , a ): for j in range(n - i ): __A : List[Any] = y[j + 1][i - 1] - y[j][i - 1] __A : List[str] = y[0][0] for i in range(1 , a ): summ += (ucal(a , a ) * y[0][i]) / math.factorial(a ) print(F"""the value at {value} is {summ}""" ) if __name__ == "__main__": main()
280
def _SCREAMING_SNAKE_CASE ( a , a = 0 ) -> list: __A : int = length or len(a ) __A : str = False for i in range(length - 1 ): if list_data[i] > list_data[i + 1]: __A , __A : Optional[int] = list_data[i + 1], list_data[i] __A : Union[str, Any] = True return list_data if not swapped else bubble_sort(a , length - 1 ) if __name__ == "__main__": import doctest doctest.testmod()
280
1
from collections.abc import Callable from math import pi, sqrt from random import uniform from statistics import mean def _SCREAMING_SNAKE_CASE ( a ) -> List[Any]: # A local function to see if a dot lands in the circle. def is_in_circle(a , a ) -> bool: __A : Any = sqrt((x**2) + (y**2) ) # Our circle has a radius of 1, so a distance # greater than 1 would land outside the circle. return distance_from_centre <= 1 # The proportion of guesses that landed in the circle __A : Dict = mean( int(is_in_circle(uniform(-1.0 , 1.0 ) , uniform(-1.0 , 1.0 ) ) ) for _ in range(a ) ) # The ratio of the area for circle to square is pi/4. __A : Optional[int] = proportion * 4 print(F"""The estimated value of pi is {pi_estimate}""" ) print(F"""The numpy value of pi is {pi}""" ) print(F"""The total error is {abs(pi - pi_estimate )}""" ) def _SCREAMING_SNAKE_CASE ( a , a , a = 0.0 , a = 1.0 , ) -> float: return mean( function_to_integrate(uniform(a , a ) ) for _ in range(a ) ) * (max_value - min_value) def _SCREAMING_SNAKE_CASE ( a , a = 0.0 , a = 1.0 ) -> None: def identity_function(a ) -> float: return x __A : int = area_under_curve_estimator( a , a , a , a ) __A : List[str] = (max_value * max_value - min_value * min_value) / 2 print('******************' ) print(F"""Estimating area under y=x where x varies from {min_value} to {max_value}""" ) print(F"""Estimated value is {estimated_value}""" ) print(F"""Expected value is {expected_value}""" ) print(F"""Total error is {abs(estimated_value - expected_value )}""" ) print('******************' ) def _SCREAMING_SNAKE_CASE ( a ) -> None: def function_to_integrate(a ) -> float: return sqrt(4.0 - x * x ) __A : List[Any] = area_under_curve_estimator( a , a , 0.0 , 2.0 ) print('******************' ) print('Estimating pi using area_under_curve_estimator' ) print(F"""Estimated value is {estimated_value}""" ) print(F"""Expected value is {pi}""" ) print(F"""Total error is {abs(estimated_value - pi )}""" ) print('******************' ) if __name__ == "__main__": import doctest doctest.testmod()
280
from __future__ import annotations def _SCREAMING_SNAKE_CASE ( a ) -> int: if not nums: return 0 __A : Optional[int] = nums[0] __A : str = 0 for num in nums[1:]: __A , __A : Tuple = ( max_excluding + num, max(a , a ), ) return max(a , a ) if __name__ == "__main__": import doctest doctest.testmod()
280
1
UpperCAmelCase : List[Any] = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0], ] def _SCREAMING_SNAKE_CASE ( a , a , a , a ) -> List[str]: # Return True if there is node that has not iterated. __A : Optional[int] = [False] * len(a ) __A : List[str] = [s] __A : Dict = True while queue: __A : List[Any] = queue.pop(0 ) for ind in range(len(graph[u] ) ): if visited[ind] is False and graph[u][ind] > 0: queue.append(a ) __A : List[Any] = True __A : Union[str, Any] = u return visited[t] def _SCREAMING_SNAKE_CASE ( a , a , a ) -> List[str]: __A : Union[str, Any] = [-1] * (len(a )) __A : Union[str, Any] = 0 __A : str = [] __A : int = [i[:] for i in graph] # Record original cut, copy. while bfs(a , a , a , a ): __A : Dict = float('Inf' ) __A : str = sink while s != source: # Find the minimum value in select path __A : Optional[Any] = min(a , graph[parent[s]][s] ) __A : int = parent[s] max_flow += path_flow __A : Any = sink while v != source: __A : Dict = parent[v] graph[u][v] -= path_flow graph[v][u] += path_flow __A : List[Any] = parent[v] for i in range(len(a ) ): for j in range(len(graph[0] ) ): if graph[i][j] == 0 and temp[i][j] > 0: res.append((i, j) ) return res if __name__ == "__main__": print(mincut(test_graph, source=0, sink=5))
280
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available UpperCAmelCase : Optional[int] = { '''configuration_xlm''': ['''XLM_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XLMConfig''', '''XLMOnnxConfig'''], '''tokenization_xlm''': ['''XLMTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Union[str, Any] = [ '''XLM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XLMForMultipleChoice''', '''XLMForQuestionAnswering''', '''XLMForQuestionAnsweringSimple''', '''XLMForSequenceClassification''', '''XLMForTokenClassification''', '''XLMModel''', '''XLMPreTrainedModel''', '''XLMWithLMHeadModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Optional[Any] = [ '''TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFXLMForMultipleChoice''', '''TFXLMForQuestionAnsweringSimple''', '''TFXLMForSequenceClassification''', '''TFXLMForTokenClassification''', '''TFXLMMainLayer''', '''TFXLMModel''', '''TFXLMPreTrainedModel''', '''TFXLMWithLMHeadModel''', ] if TYPE_CHECKING: from .configuration_xlm import XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMConfig, XLMOnnxConfig from .tokenization_xlm import XLMTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm import ( XLM_PRETRAINED_MODEL_ARCHIVE_LIST, XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMPreTrainedModel, XLMWithLMHeadModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlm import ( TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLMForMultipleChoice, TFXLMForQuestionAnsweringSimple, TFXLMForSequenceClassification, TFXLMForTokenClassification, TFXLMMainLayer, TFXLMModel, TFXLMPreTrainedModel, TFXLMWithLMHeadModel, ) else: import sys UpperCAmelCase : str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
280
1
# Lint as: python3 import itertools import os import re UpperCAmelCase : Union[str, Any] = re.compile(r'''([A-Z]+)([A-Z][a-z])''') UpperCAmelCase : Union[str, Any] = re.compile(r'''([a-z\d])([A-Z])''') UpperCAmelCase : List[Any] = re.compile(r'''(?<!_)_(?!_)''') UpperCAmelCase : Optional[Any] = re.compile(r'''(_{2,})''') UpperCAmelCase : Dict = r'''^\w+(\.\w+)*$''' UpperCAmelCase : List[Any] = r'''<>:/\|?*''' def _SCREAMING_SNAKE_CASE ( a ) -> str: __A : Dict = _uppercase_uppercase_re.sub(r'\1_\2' , a ) __A : Dict = _lowercase_uppercase_re.sub(r'\1_\2' , a ) return name.lower() def _SCREAMING_SNAKE_CASE ( a ) -> Dict: __A : str = _single_underscore_re.split(a ) __A : Tuple = [_multiple_underscores_re.split(a ) for n in name] return "".join(n.capitalize() for n in itertools.chain.from_iterable(a ) if n != '' ) def _SCREAMING_SNAKE_CASE ( a ) -> Dict: if os.path.basename(a ) != name: raise ValueError(F"""Should be a dataset name, not a path: {name}""" ) return camelcase_to_snakecase(a ) def _SCREAMING_SNAKE_CASE ( a , a ) -> str: if os.path.basename(a ) != name: raise ValueError(F"""Should be a dataset name, not a path: {name}""" ) if not re.match(_split_re , a ): raise ValueError(F"""Split name should match '{_split_re}'' but got '{split}'.""" ) return F"""{filename_prefix_for_name(a )}-{split}""" def _SCREAMING_SNAKE_CASE ( a , a , a , a=None ) -> Tuple: __A : int = filename_prefix_for_split(a , a ) if filetype_suffix: prefix += F""".{filetype_suffix}""" __A : str = os.path.join(a , a ) return F"""{filepath}*""" def _SCREAMING_SNAKE_CASE ( a , a , a , a=None , a=None ) -> Optional[Any]: __A : Tuple = filename_prefix_for_split(a , a ) __A : Any = os.path.join(a , a ) if shard_lengths: __A : Optional[Any] = len(a ) __A : Union[str, Any] = [F"""{prefix}-{shard_id:05d}-of-{num_shards:05d}""" for shard_id in range(a )] if filetype_suffix: __A : Optional[int] = [filename + F""".{filetype_suffix}""" for filename in filenames] return filenames else: __A : Optional[int] = prefix if filetype_suffix: filename += F""".{filetype_suffix}""" return [filename]
280
def _SCREAMING_SNAKE_CASE ( a ) -> str: if number > 0: raise ValueError('input must be a negative integer' ) __A : Optional[int] = len(bin(a )[3:] ) __A : Dict = bin(abs(a ) - (1 << binary_number_length) )[3:] __A : int = ( ( '1' + '0' * (binary_number_length - len(a )) + twos_complement_number ) if number < 0 else '0' ) return "0b" + twos_complement_number if __name__ == "__main__": import doctest doctest.testmod()
280
1
def _SCREAMING_SNAKE_CASE ( a ) -> bool: return credit_card_number.startswith(('34', '35', '37', '4', '5', '6') ) def _SCREAMING_SNAKE_CASE ( a ) -> bool: __A : Dict = credit_card_number __A : Any = 0 __A : List[Any] = len(a ) - 2 for i in range(a , -1 , -2 ): # double the value of every second digit __A : Any = int(cc_number[i] ) digit *= 2 # If doubling of a number results in a two digit number # i.e greater than 9(e.g., 6 × 2 = 12), # then add the digits of the product (e.g., 12: 1 + 2 = 3, 15: 1 + 5 = 6), # to get a single digit number. if digit > 9: digit %= 10 digit += 1 __A : List[str] = cc_number[:i] + str(a ) + cc_number[i + 1 :] total += digit # Sum up the remaining digits for i in range(len(a ) - 1 , -1 , -2 ): total += int(cc_number[i] ) return total % 10 == 0 def _SCREAMING_SNAKE_CASE ( a ) -> bool: __A : Dict = F"""{credit_card_number} is an invalid credit card number because""" if not credit_card_number.isdigit(): print(F"""{error_message} it has nonnumerical characters.""" ) return False if not 13 <= len(a ) <= 16: print(F"""{error_message} of its length.""" ) return False if not validate_initial_digits(a ): print(F"""{error_message} of its first two digits.""" ) return False if not luhn_validation(a ): print(F"""{error_message} it fails the Luhn check.""" ) return False print(F"""{credit_card_number} is a valid credit card number.""" ) return True if __name__ == "__main__": import doctest doctest.testmod() validate_credit_card_number('''4111111111111111''') validate_credit_card_number('''32323''')
280
import warnings from pathlib import Path from typing import List, Tuple, Union import fire from torch import nn from transformers import AutoModelForSeqaSeqLM, AutoTokenizer, PreTrainedModel from transformers.utils import logging UpperCAmelCase : Any = logging.get_logger(__name__) def _SCREAMING_SNAKE_CASE ( a , a , a ) -> None: __A : int = nn.ModuleList([src_layers[i] for i in layers_to_copy] ) assert len(a ) == len(a ), F"""{len(a )} != {len(a )}""" dest_layers.load_state_dict(layers_to_copy.state_dict() ) UpperCAmelCase : List[Any] = { # maps num layers in teacher -> num_layers in student -> which teacher layers to copy. # 12: bart, 16: pegasus, 6: marian/Helsinki-NLP 12: { 1: [0], # This says that if the teacher has 12 layers and the student has 1, copy layer 0 of the teacher 2: [0, 6], 3: [0, 6, 11], 4: [0, 4, 8, 11], 6: [0, 2, 4, 7, 9, 11], 9: [0, 1, 2, 4, 5, 7, 9, 10, 11], 12: list(range(12)), }, 16: { # maps num layers in student -> which teacher layers to copy 1: [0], 2: [0, 15], 3: [0, 8, 15], 4: [0, 5, 10, 15], 6: [0, 3, 6, 9, 12, 15], 8: [0, 2, 4, 6, 8, 10, 12, 15], 9: [0, 1, 3, 5, 7, 9, 11, 13, 15], 12: [0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 15], 16: list(range(16)), }, 6: {1: [0], 2: [0, 5], 3: [0, 2, 5], 4: [0, 1, 3, 5], 6: list(range(6))}, } UpperCAmelCase : Optional[int] = { # maps num layers in student -> which teacher layers to copy. 6: {1: [5], 2: [3, 5], 3: [1, 4, 5], 4: [1, 2, 4, 5]}, 12: {1: [11], 2: [5, 11], 3: [3, 7, 11], 6: [1, 3, 5, 8, 10, 11]}, 16: {1: [15], 4: [4, 9, 12, 15], 8: [1, 3, 5, 7, 9, 11, 13, 15]}, } def _SCREAMING_SNAKE_CASE ( a , a ) -> Dict: try: __A : int = LAYERS_TO_COPY[n_teacher][n_student] return val except KeyError: if n_student != n_teacher: warnings.warn( F"""no hardcoded layers to copy for teacher {n_teacher} -> student {n_student}, defaulting to first""" F""" {n_student}""" ) return list(range(a ) ) def _SCREAMING_SNAKE_CASE ( a , a ) -> List[int]: if n_student > n_teacher: raise ValueError(F"""Cannot perform intermediate supervision for student {n_student} > teacher {n_teacher}""" ) elif n_teacher == n_student: return list(range(a ) ) elif n_student == 1: return [n_teacher - 1] else: return LAYERS_TO_SUPERVISE[n_teacher][n_student] def _SCREAMING_SNAKE_CASE ( a , a = "student" , a = None , a = None , a=False , a=None , a=None , **a , ) -> Tuple[PreTrainedModel, List[int], List[int]]: __A : List[str] = 'encoder_layers and decoder_layers cannot be both None-- you would just have an identical teacher.' assert (e is not None) or (d is not None), _msg if isinstance(a , a ): AutoTokenizer.from_pretrained(a ).save_pretrained(a ) # purely for convenience __A : Optional[int] = AutoModelForSeqaSeqLM.from_pretrained(a ).eval() else: assert isinstance(a , a ), F"""teacher must be a model or string got type {type(a )}""" __A : int = teacher.config.to_diff_dict() try: __A , __A : List[Any] = teacher.config.encoder_layers, teacher.config.decoder_layers if e is None: __A : str = teacher_e if d is None: __A : List[Any] = teacher_d init_kwargs.update({'encoder_layers': e, 'decoder_layers': d} ) except AttributeError: # T5 if hasattr(teacher.config , 'num_encoder_layers' ): __A , __A : List[Any] = teacher.config.num_encoder_layers, teacher.config.num_decoder_layers else: __A , __A : Optional[int] = teacher.config.num_layers, teacher.config.num_decoder_layers if e is None: __A : int = teacher_e if d is None: __A : Optional[Any] = teacher_d if hasattr(teacher.config , 'num_encoder_layers' ): init_kwargs.update({'num_encoder_layers': e, 'num_decoder_layers': d} ) else: init_kwargs.update({'num_layers': e, 'num_decoder_layers': d} ) # Kwargs to instantiate student: teacher kwargs with updated layer numbers + **extra_config_kwargs init_kwargs.update(a ) # Copy weights __A : Dict = teacher.config_class(**a ) __A : int = AutoModelForSeqaSeqLM.from_config(a ) # Start by copying the full teacher state dict this will copy the first N teacher layers to the student. __A : Any = student.load_state_dict(teacher.state_dict() , strict=a ) assert info.missing_keys == [], info.missing_keys # every student key should have a teacher keys. if copy_first_teacher_layers: # Our copying is done. We just log and save __A , __A : Optional[int] = list(range(a ) ), list(range(a ) ) logger.info( F"""Copied encoder layers {e_layers_to_copy} and decoder layers {d_layers_to_copy}. Saving them to""" F""" {save_path}""" ) student.save_pretrained(a ) return student, e_layers_to_copy, d_layers_to_copy # Decide which layers of the teacher to copy. Not exactly alternating -- we try to keep first and last layer. if e_layers_to_copy is None: __A : List[int] = pick_layers_to_copy(a , a ) if d_layers_to_copy is None: __A : List[int] = pick_layers_to_copy(a , a ) try: if hasattr( a , 'prophetnet' ): # For ProphetNet, student.model.encoder.layers is called student.prophetnet.encoder.layers copy_layers(teacher.prophetnet.encoder.layers , student.prophetnet.encoder.layers , a ) copy_layers(teacher.prophetnet.decoder.layers , student.prophetnet.decoder.layers , a ) else: copy_layers(teacher.model.encoder.layers , student.model.encoder.layers , a ) copy_layers(teacher.model.decoder.layers , student.model.decoder.layers , a ) except AttributeError: # For t5, student.model.encoder.layers is called student.encoder.block copy_layers(teacher.encoder.block , student.encoder.block , a ) copy_layers(teacher.decoder.block , student.decoder.block , a ) logger.info( F"""Copied encoder layers {e_layers_to_copy} and decoder layers {d_layers_to_copy}. Saving them to {save_path}""" ) __A : Optional[int] = { 'teacher_type': teacher.config.model_type, 'copied_encoder_layers': e_layers_to_copy, 'copied_decoder_layers': d_layers_to_copy, } student.save_pretrained(a ) # Save information about copying for easier reproducibility return student, e_layers_to_copy, d_layers_to_copy if __name__ == "__main__": fire.Fire(create_student_by_copying_alternating_layers)
280
1
import unittest import numpy as np from datasets import load_dataset from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import BeitImageProcessor class _A( unittest.TestCase ): """simple docstring""" def __init__( self , _A , _A=7 , _A=3 , _A=18 , _A=30 , _A=400 , _A=True , _A=None , _A=True , _A=None , _A=True , _A=[0.5, 0.5, 0.5] , _A=[0.5, 0.5, 0.5] , _A=False , ): __A : List[str] = size if size is not None else {'height': 20, 'width': 20} __A : int = crop_size if crop_size is not None else {'height': 18, 'width': 18} __A : Optional[int] = parent __A : Union[str, Any] = batch_size __A : Tuple = num_channels __A : List[Any] = image_size __A : Tuple = min_resolution __A : str = max_resolution __A : Tuple = do_resize __A : List[Any] = size __A : Dict = do_center_crop __A : Optional[int] = crop_size __A : int = do_normalize __A : Optional[Any] = image_mean __A : List[Any] = image_std __A : List[Any] = do_reduce_labels def UpperCAmelCase_ ( self ): return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_reduce_labels": self.do_reduce_labels, } def _SCREAMING_SNAKE_CASE ( ) -> Dict: __A : str = load_dataset('hf-internal-testing/fixtures_ade20k' , split='test' ) __A : str = Image.open(dataset[0]['file'] ) __A : Any = Image.open(dataset[1]['file'] ) return image, map def _SCREAMING_SNAKE_CASE ( ) -> List[Any]: __A : List[Any] = load_dataset('hf-internal-testing/fixtures_ade20k' , split='test' ) __A : int = Image.open(ds[0]['file'] ) __A : List[str] = Image.open(ds[1]['file'] ) __A : Any = Image.open(ds[2]['file'] ) __A : Dict = Image.open(ds[3]['file'] ) return [imagea, imagea], [mapa, mapa] @require_torch @require_vision class _A( snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : int = BeitImageProcessor if is_vision_available() else None def UpperCAmelCase_ ( self ): __A : Optional[int] = BeitImageProcessingTester(self ) @property def UpperCAmelCase_ ( self ): return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase_ ( self ): __A : Any = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_A , 'do_resize' ) ) self.assertTrue(hasattr(_A , 'size' ) ) self.assertTrue(hasattr(_A , 'do_center_crop' ) ) self.assertTrue(hasattr(_A , 'center_crop' ) ) self.assertTrue(hasattr(_A , 'do_normalize' ) ) self.assertTrue(hasattr(_A , 'image_mean' ) ) self.assertTrue(hasattr(_A , 'image_std' ) ) def UpperCAmelCase_ ( self ): __A : List[Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'height': 20, 'width': 20} ) self.assertEqual(image_processor.crop_size , {'height': 18, 'width': 18} ) self.assertEqual(image_processor.do_reduce_labels , _A ) __A : int = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , crop_size=84 , reduce_labels=_A ) self.assertEqual(image_processor.size , {'height': 42, 'width': 42} ) self.assertEqual(image_processor.crop_size , {'height': 84, 'width': 84} ) self.assertEqual(image_processor.do_reduce_labels , _A ) def UpperCAmelCase_ ( self ): pass def UpperCAmelCase_ ( self ): # Initialize image_processing __A : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __A : Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A ) for image in image_inputs: self.assertIsInstance(_A , Image.Image ) # Test not batched input __A : Union[str, Any] = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched __A : Optional[int] = image_processing(_A , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def UpperCAmelCase_ ( self ): # Initialize image_processing __A : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __A : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A , numpify=_A ) for image in image_inputs: self.assertIsInstance(_A , np.ndarray ) # Test not batched input __A : Union[str, Any] = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched __A : Any = image_processing(_A , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def UpperCAmelCase_ ( self ): # Initialize image_processing __A : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __A : Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A , torchify=_A ) for image in image_inputs: self.assertIsInstance(_A , torch.Tensor ) # Test not batched input __A : Dict = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched __A : Any = image_processing(_A , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def UpperCAmelCase_ ( self ): # Initialize image_processing __A : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __A : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A , torchify=_A ) __A : Optional[int] = [] for image in image_inputs: self.assertIsInstance(_A , torch.Tensor ) maps.append(torch.zeros(image.shape[-2:] ).long() ) # Test not batched input __A : Optional[Any] = image_processing(image_inputs[0] , maps[0] , return_tensors='pt' ) self.assertEqual( encoding['pixel_values'].shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) self.assertEqual( encoding['labels'].shape , ( 1, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) self.assertEqual(encoding['labels'].dtype , torch.long ) self.assertTrue(encoding['labels'].min().item() >= 0 ) self.assertTrue(encoding['labels'].max().item() <= 255 ) # Test batched __A : str = image_processing(_A , _A , return_tensors='pt' ) self.assertEqual( encoding['pixel_values'].shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) self.assertEqual( encoding['labels'].shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) self.assertEqual(encoding['labels'].dtype , torch.long ) self.assertTrue(encoding['labels'].min().item() >= 0 ) self.assertTrue(encoding['labels'].max().item() <= 255 ) # Test not batched input (PIL images) __A , __A : Dict = prepare_semantic_single_inputs() __A : str = image_processing(_A , _A , return_tensors='pt' ) self.assertEqual( encoding['pixel_values'].shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) self.assertEqual( encoding['labels'].shape , ( 1, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) self.assertEqual(encoding['labels'].dtype , torch.long ) self.assertTrue(encoding['labels'].min().item() >= 0 ) self.assertTrue(encoding['labels'].max().item() <= 255 ) # Test batched input (PIL images) __A , __A : int = prepare_semantic_batch_inputs() __A : int = image_processing(_A , _A , return_tensors='pt' ) self.assertEqual( encoding['pixel_values'].shape , ( 2, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) self.assertEqual( encoding['labels'].shape , ( 2, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) self.assertEqual(encoding['labels'].dtype , torch.long ) self.assertTrue(encoding['labels'].min().item() >= 0 ) self.assertTrue(encoding['labels'].max().item() <= 255 ) def UpperCAmelCase_ ( self ): # Initialize image_processing __A : List[Any] = self.image_processing_class(**self.image_processor_dict ) # ADE20k has 150 classes, and the background is included, so labels should be between 0 and 150 __A , __A : Any = prepare_semantic_single_inputs() __A : Optional[int] = image_processing(_A , _A , return_tensors='pt' ) self.assertTrue(encoding['labels'].min().item() >= 0 ) self.assertTrue(encoding['labels'].max().item() <= 150 ) __A : Optional[int] = True __A : Dict = image_processing(_A , _A , return_tensors='pt' ) self.assertTrue(encoding['labels'].min().item() >= 0 ) self.assertTrue(encoding['labels'].max().item() <= 255 )
280
def _SCREAMING_SNAKE_CASE ( a , a ) -> list[int]: __A : Optional[int] = int(a ) # Initialize Result __A : Optional[int] = [] # Traverse through all denomination for denomination in reversed(a ): # Find denominations while int(a ) >= int(a ): total_value -= int(a ) answer.append(a ) # Append the "answers" array return answer # Driver Code if __name__ == "__main__": UpperCAmelCase : List[str] = [] UpperCAmelCase : Optional[int] = '''0''' if ( input('''Do you want to enter your denominations ? (yY/n): ''').strip().lower() == "y" ): UpperCAmelCase : List[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 : Optional[int] = [1, 2, 5, 10, 20, 50, 1_00, 5_00, 20_00] UpperCAmelCase : Tuple = 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 : Optional[int] = find_minimum_change(denominations, value) # Print result for i in range(len(answer)): print(answer[i], end=''' ''')
280
1
def _SCREAMING_SNAKE_CASE ( a ) -> list: if any(not isinstance(a , a ) or x < 0 for x in sequence ): raise TypeError('Sequence must be list of non-negative integers' ) for _ in range(len(a ) ): for i, (rod_upper, rod_lower) in enumerate(zip(a , 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]
280
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 YolosImageProcessor class _A( unittest.TestCase ): """simple docstring""" def __init__( self , _A , _A=7 , _A=3 , _A=30 , _A=400 , _A=True , _A=None , _A=True , _A=[0.5, 0.5, 0.5] , _A=[0.5, 0.5, 0.5] , _A=True , _A=1 / 255 , _A=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __A : List[Any] = size if size is not None else {'shortest_edge': 18, 'longest_edge': 1333} __A : Union[str, Any] = parent __A : Optional[int] = batch_size __A : int = num_channels __A : int = min_resolution __A : Any = max_resolution __A : List[Any] = do_resize __A : List[Any] = size __A : Union[str, Any] = do_normalize __A : Optional[int] = image_mean __A : Optional[int] = image_std __A : int = do_rescale __A : str = rescale_factor __A : Tuple = do_pad def UpperCAmelCase_ ( self ): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def UpperCAmelCase_ ( self , _A , _A=False ): if not batched: __A : List[str] = image_inputs[0] if isinstance(_A , Image.Image ): __A , __A : int = image.size else: __A , __A : Any = image.shape[1], image.shape[2] if w < h: __A : List[Any] = int(self.size['shortest_edge'] * h / w ) __A : List[Any] = self.size['shortest_edge'] elif w > h: __A : Union[str, Any] = self.size['shortest_edge'] __A : str = int(self.size['shortest_edge'] * w / h ) else: __A : Dict = self.size['shortest_edge'] __A : str = self.size['shortest_edge'] else: __A : int = [] for image in image_inputs: __A , __A : Optional[Any] = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __A : List[str] = max(_A , key=lambda _A : item[0] )[0] __A : str = max(_A , key=lambda _A : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class _A( snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : List[str] = YolosImageProcessor if is_vision_available() else None def UpperCAmelCase_ ( self ): __A : Dict = YolosImageProcessingTester(self ) @property def UpperCAmelCase_ ( self ): return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase_ ( self ): __A : str = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_A , 'image_mean' ) ) self.assertTrue(hasattr(_A , 'image_std' ) ) self.assertTrue(hasattr(_A , 'do_normalize' ) ) self.assertTrue(hasattr(_A , 'do_resize' ) ) self.assertTrue(hasattr(_A , 'size' ) ) def UpperCAmelCase_ ( self ): __A : Tuple = 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 , _A ) __A : Dict = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=_A ) self.assertEqual(image_processor.size , {'shortest_edge': 42, 'longest_edge': 84} ) self.assertEqual(image_processor.do_pad , _A ) def UpperCAmelCase_ ( self ): pass def UpperCAmelCase_ ( self ): # Initialize image_processing __A : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __A : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A ) for image in image_inputs: self.assertIsInstance(_A , Image.Image ) # Test not batched input __A : Any = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values __A , __A : Optional[int] = self.image_processor_tester.get_expected_values(_A ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __A , __A : Optional[Any] = self.image_processor_tester.get_expected_values(_A , batched=_A ) __A : str = image_processing(_A , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def UpperCAmelCase_ ( self ): # Initialize image_processing __A : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __A : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A , numpify=_A ) for image in image_inputs: self.assertIsInstance(_A , np.ndarray ) # Test not batched input __A : str = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values __A , __A : List[Any] = self.image_processor_tester.get_expected_values(_A ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __A : Tuple = image_processing(_A , return_tensors='pt' ).pixel_values __A , __A : Optional[int] = self.image_processor_tester.get_expected_values(_A , batched=_A ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def UpperCAmelCase_ ( self ): # Initialize image_processing __A : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __A : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A , torchify=_A ) for image in image_inputs: self.assertIsInstance(_A , torch.Tensor ) # Test not batched input __A : Union[str, Any] = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values __A , __A : Union[str, Any] = self.image_processor_tester.get_expected_values(_A ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __A : Optional[int] = image_processing(_A , return_tensors='pt' ).pixel_values __A , __A : Optional[int] = self.image_processor_tester.get_expected_values(_A , batched=_A ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def UpperCAmelCase_ ( self ): # Initialize image_processings __A : Tuple = self.image_processing_class(**self.image_processor_dict ) __A : Any = self.image_processing_class(do_resize=_A , do_normalize=_A , do_rescale=_A ) # create random PyTorch tensors __A : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A , torchify=_A ) for image in image_inputs: self.assertIsInstance(_A , torch.Tensor ) # Test whether the method "pad" and calling the image processor return the same tensors __A : Optional[int] = image_processing_a.pad(_A , return_tensors='pt' ) __A : Optional[int] = image_processing_a(_A , return_tensors='pt' ) self.assertTrue( torch.allclose(encoded_images_with_method['pixel_values'] , encoded_images['pixel_values'] , atol=1e-4 ) ) @slow def UpperCAmelCase_ ( self ): # prepare image and target __A : List[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' , 'r' ) as f: __A : Optional[Any] = json.loads(f.read() ) __A : Optional[Any] = {'image_id': 39769, 'annotations': target} # encode them __A : str = YolosImageProcessor.from_pretrained('hustvl/yolos-small' ) __A : List[Any] = image_processing(images=_A , annotations=_A , return_tensors='pt' ) # verify pixel values __A : List[Any] = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding['pixel_values'].shape , _A ) __A : Union[str, Any] = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , _A , atol=1e-4 ) ) # verify area __A : List[Any] = torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , _A ) ) # verify boxes __A : Any = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , _A ) __A : Optional[Any] = torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , _A , atol=1e-3 ) ) # verify image_id __A : Optional[int] = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , _A ) ) # verify is_crowd __A : str = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , _A ) ) # verify class_labels __A : Any = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , _A ) ) # verify orig_size __A : int = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , _A ) ) # verify size __A : str = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , _A ) ) @slow def UpperCAmelCase_ ( self ): # prepare image, target and masks_path __A : Dict = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' , 'r' ) as f: __A : Tuple = json.loads(f.read() ) __A : Any = {'file_name': '000000039769.png', 'image_id': 39769, 'segments_info': target} __A : List[Any] = pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic' ) # encode them __A : Any = YolosImageProcessor(format='coco_panoptic' ) __A : List[Any] = image_processing(images=_A , annotations=_A , masks_path=_A , return_tensors='pt' ) # verify pixel values __A : Any = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding['pixel_values'].shape , _A ) __A : Union[str, Any] = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , _A , atol=1e-4 ) ) # verify area __A : int = torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , _A ) ) # verify boxes __A : Optional[int] = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , _A ) __A : Optional[Any] = torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , _A , atol=1e-3 ) ) # verify image_id __A : Union[str, Any] = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , _A ) ) # verify is_crowd __A : Tuple = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , _A ) ) # verify class_labels __A : List[str] = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , _A ) ) # verify masks __A : Tuple = 822873 self.assertEqual(encoding['labels'][0]['masks'].sum().item() , _A ) # verify orig_size __A : str = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , _A ) ) # verify size __A : int = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , _A ) )
280
1
def _SCREAMING_SNAKE_CASE ( a ) -> bool: return sum(i for i in range(1 , number // 2 + 1 ) if number % i == 0 ) == number if __name__ == "__main__": print('''Program to check whether a number is a Perfect number or not...''') UpperCAmelCase : Union[str, Any] = int(input('''Enter number: ''').strip()) print(F"""{number} is {"" if perfect(number) else "not "}a Perfect Number.""")
280
import argparse import json from tqdm import tqdm def _SCREAMING_SNAKE_CASE ( ) -> List[Any]: __A : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( '--src_path' , type=a , default='biencoder-nq-dev.json' , help='Path to raw DPR training data' , ) parser.add_argument( '--evaluation_set' , type=a , help='where to store parsed evaluation_set file' , ) parser.add_argument( '--gold_data_path' , type=a , help='where to store parsed gold_data_path file' , ) __A : Optional[int] = parser.parse_args() with open(args.src_path , 'r' ) as src_file, open(args.evaluation_set , 'w' ) as eval_file, open( args.gold_data_path , 'w' ) as gold_file: __A : List[Any] = json.load(a ) for dpr_record in tqdm(a ): __A : Dict = dpr_record['question'] __A : Any = [context['title'] for context in dpr_record['positive_ctxs']] eval_file.write(question + '\n' ) gold_file.write('\t'.join(a ) + '\n' ) if __name__ == "__main__": main()
280
1
import inspect import re from hashlib import shaaaa from typing import Dict, List from .arrow import arrow from .audiofolder import audiofolder from .csv import csv from .imagefolder import imagefolder from .json import json from .pandas import pandas from .parquet import parquet from .sql import sql # noqa F401 from .text import text def _SCREAMING_SNAKE_CASE ( a ) -> str: __A : List[str] = [] for line in lines: __A : List[str] = re.sub(r'#.*' , '' , a ) # remove comments if line: filtered_lines.append(a ) __A : List[str] = '\n'.join(a ) # Make a hash from all this code __A : str = full_str.encode('utf-8' ) return shaaaa(a ).hexdigest() # get importable module names and hash for caching UpperCAmelCase : Tuple = { '''csv''': (csv.__name__, _hash_python_lines(inspect.getsource(csv).splitlines())), '''json''': (json.__name__, _hash_python_lines(inspect.getsource(json).splitlines())), '''pandas''': (pandas.__name__, _hash_python_lines(inspect.getsource(pandas).splitlines())), '''parquet''': (parquet.__name__, _hash_python_lines(inspect.getsource(parquet).splitlines())), '''arrow''': (arrow.__name__, _hash_python_lines(inspect.getsource(arrow).splitlines())), '''text''': (text.__name__, _hash_python_lines(inspect.getsource(text).splitlines())), '''imagefolder''': (imagefolder.__name__, _hash_python_lines(inspect.getsource(imagefolder).splitlines())), '''audiofolder''': (audiofolder.__name__, _hash_python_lines(inspect.getsource(audiofolder).splitlines())), } # Used to infer the module to use based on the data files extensions UpperCAmelCase : Union[str, Any] = { '''.csv''': ('''csv''', {}), '''.tsv''': ('''csv''', {'''sep''': '''\t'''}), '''.json''': ('''json''', {}), '''.jsonl''': ('''json''', {}), '''.parquet''': ('''parquet''', {}), '''.arrow''': ('''arrow''', {}), '''.txt''': ('''text''', {}), } _EXTENSION_TO_MODULE.update({ext: ('''imagefolder''', {}) for ext in imagefolder.ImageFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext.upper(): ('''imagefolder''', {}) for ext in imagefolder.ImageFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext: ('''audiofolder''', {}) for ext in audiofolder.AudioFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext.upper(): ('''audiofolder''', {}) for ext in audiofolder.AudioFolder.EXTENSIONS}) UpperCAmelCase : List[Any] = {'''imagefolder''', '''audiofolder'''} # Used to filter data files based on extensions given a module name UpperCAmelCase : Dict[str, List[str]] = {} for _ext, (_module, _) in _EXTENSION_TO_MODULE.items(): _MODULE_TO_EXTENSIONS.setdefault(_module, []).append(_ext) _MODULE_TO_EXTENSIONS["imagefolder"].append('''.zip''') _MODULE_TO_EXTENSIONS["audiofolder"].append('''.zip''')
280
from heapq import heappop, heappush import numpy as np def _SCREAMING_SNAKE_CASE ( a , a , a , a , ) -> tuple[float | int, list[tuple[int, int]]]: __A , __A : int = grid.shape __A : Any = [-1, 1, 0, 0] __A : Optional[Any] = [0, 0, -1, 1] if allow_diagonal: dx += [-1, -1, 1, 1] dy += [-1, 1, -1, 1] __A , __A : Optional[int] = [(0, source)], set() __A : Any = np.full((rows, cols) , np.inf ) __A : Any = 0 __A : Any = np.empty((rows, cols) , dtype=a ) __A : Optional[Any] = None while queue: ((__A) , (__A)) : List[str] = heappop(a ) if (x, y) in visited: continue visited.add((x, y) ) if (x, y) == destination: __A : int = [] while (x, y) != source: path.append((x, y) ) __A , __A : Optional[int] = predecessors[x, y] path.append(a ) # add the source manually path.reverse() return matrix[destination], path for i in range(len(a ) ): __A , __A : Union[str, Any] = x + dx[i], y + dy[i] if 0 <= nx < rows and 0 <= ny < cols: __A : Optional[int] = grid[nx][ny] if next_node == 1 and matrix[nx, ny] > dist + 1: heappush(a , (dist + 1, (nx, ny)) ) __A : List[Any] = dist + 1 __A : Union[str, Any] = (x, y) return np.inf, [] if __name__ == "__main__": import doctest doctest.testmod()
280
1
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class _A( unittest.TestCase ): """simple docstring""" def __init__( self , _A , _A=7 , _A=3 , _A=18 , _A=30 , _A=400 , _A=True , _A=None , _A=True , _A=None , _A=True , ): __A : Any = size if size is not None else {'shortest_edge': 20} __A : Any = crop_size if crop_size is not None else {'height': 18, 'width': 18} __A : Optional[int] = parent __A : Optional[int] = batch_size __A : Union[str, Any] = num_channels __A : List[str] = image_size __A : Any = min_resolution __A : List[Any] = max_resolution __A : int = do_resize __A : int = size __A : str = do_center_crop __A : int = crop_size __A : List[Any] = do_flip_channel_order def UpperCAmelCase_ ( self ): return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_flip_channel_order": self.do_flip_channel_order, } @require_torch @require_vision class _A( snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : int = MobileViTImageProcessor if is_vision_available() else None def UpperCAmelCase_ ( self ): __A : str = MobileViTImageProcessingTester(self ) @property def UpperCAmelCase_ ( self ): return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_A , 'do_resize' ) ) self.assertTrue(hasattr(_A , 'size' ) ) self.assertTrue(hasattr(_A , 'do_center_crop' ) ) self.assertTrue(hasattr(_A , 'center_crop' ) ) self.assertTrue(hasattr(_A , 'do_flip_channel_order' ) ) def UpperCAmelCase_ ( self ): __A : List[Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'shortest_edge': 20} ) self.assertEqual(image_processor.crop_size , {'height': 18, 'width': 18} ) __A : int = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {'shortest_edge': 42} ) self.assertEqual(image_processor.crop_size , {'height': 84, 'width': 84} ) def UpperCAmelCase_ ( self ): pass def UpperCAmelCase_ ( self ): # Initialize image_processing __A : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __A : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A ) for image in image_inputs: self.assertIsInstance(_A , Image.Image ) # Test not batched input __A : Union[str, Any] = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched __A : Union[str, Any] = image_processing(_A , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def UpperCAmelCase_ ( self ): # Initialize image_processing __A : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __A : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A , numpify=_A ) for image in image_inputs: self.assertIsInstance(_A , np.ndarray ) # Test not batched input __A : List[str] = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched __A : List[Any] = image_processing(_A , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def UpperCAmelCase_ ( self ): # Initialize image_processing __A : Any = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __A : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A , torchify=_A ) for image in image_inputs: self.assertIsInstance(_A , torch.Tensor ) # Test not batched input __A : Optional[Any] = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched __A : Union[str, Any] = image_processing(_A , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , )
280
from typing import List, Optional, Union import numpy as np import PIL import torch from PIL import Image from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) UpperCAmelCase : List[Any] = logging.get_logger(__name__) # pylint: disable=invalid-name UpperCAmelCase : Dict = ''' Examples: ```py >>> from diffusers import KandinskyV22Img2ImgPipeline, KandinskyV22PriorPipeline >>> from diffusers.utils import load_image >>> import torch >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained( ... "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16 ... ) >>> pipe_prior.to("cuda") >>> prompt = "A red cartoon frog, 4k" >>> image_emb, zero_image_emb = pipe_prior(prompt, return_dict=False) >>> pipe = KandinskyV22Img2ImgPipeline.from_pretrained( ... "kandinsky-community/kandinsky-2-2-decoder", torch_dtype=torch.float16 ... ) >>> pipe.to("cuda") >>> init_image = load_image( ... "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" ... "/kandinsky/frog.png" ... ) >>> image = pipe( ... image=init_image, ... image_embeds=image_emb, ... negative_image_embeds=zero_image_emb, ... height=768, ... width=768, ... num_inference_steps=100, ... strength=0.2, ... ).images >>> image[0].save("red_frog.png") ``` ''' def _SCREAMING_SNAKE_CASE ( a , a , a=8 ) -> Tuple: __A : List[str] = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 __A : Optional[int] = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor def _SCREAMING_SNAKE_CASE ( a , a=5_12 , a=5_12 ) -> int: __A : Optional[Any] = pil_image.resize((w, h) , resample=Image.BICUBIC , reducing_gap=1 ) __A : Union[str, Any] = np.array(pil_image.convert('RGB' ) ) __A : Optional[int] = arr.astype(np.floataa ) / 127.5 - 1 __A : int = np.transpose(a , [2, 0, 1] ) __A : Tuple = torch.from_numpy(a ).unsqueeze(0 ) return image class _A( snake_case__ ): """simple docstring""" def __init__( self , _A , _A , _A , ): super().__init__() self.register_modules( unet=_A , scheduler=_A , movq=_A , ) __A : Tuple = 2 ** (len(self.movq.config.block_out_channels ) - 1) def UpperCAmelCase_ ( self , _A , _A , _A ): # get the original timestep using init_timestep __A : Optional[int] = min(int(num_inference_steps * strength ) , _A ) __A : Dict = max(num_inference_steps - init_timestep , 0 ) __A : Tuple = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A=None ): if not isinstance(_A , (torch.Tensor, PIL.Image.Image, list) ): raise ValueError( F"""`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(_A )}""" ) __A : Union[str, Any] = image.to(device=_A , dtype=_A ) __A : Optional[Any] = batch_size * num_images_per_prompt if image.shape[1] == 4: __A : int = image else: if isinstance(_A , _A ) and len(_A ) != batch_size: raise ValueError( F"""You have passed a list of generators of length {len(_A )}, but requested an effective batch""" F""" size of {batch_size}. Make sure the batch size matches the length of the generators.""" ) elif isinstance(_A , _A ): __A : str = [ self.movq.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(_A ) ] __A : str = torch.cat(_A , dim=0 ) else: __A : List[str] = self.movq.encode(_A ).latent_dist.sample(_A ) __A : Tuple = self.movq.config.scaling_factor * init_latents __A : Optional[int] = torch.cat([init_latents] , dim=0 ) __A : Union[str, Any] = init_latents.shape __A : List[str] = randn_tensor(_A , generator=_A , device=_A , dtype=_A ) # get latents __A : Optional[Any] = self.scheduler.add_noise(_A , _A , _A ) __A : Optional[int] = init_latents return latents def UpperCAmelCase_ ( self , _A=0 ): if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('Please install accelerate via `pip install accelerate`' ) __A : Optional[int] = torch.device(F"""cuda:{gpu_id}""" ) __A : Union[str, Any] = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(_A , _A ) def UpperCAmelCase_ ( self , _A=0 ): if is_accelerate_available() and is_accelerate_version('>=' , '0.17.0.dev0' ): from accelerate import cpu_offload_with_hook else: raise ImportError('`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.' ) __A : List[Any] = torch.device(F"""cuda:{gpu_id}""" ) if self.device.type != "cpu": self.to('cpu' , silence_dtype_warnings=_A ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) __A : int = None for cpu_offloaded_model in [self.unet, self.movq]: __A , __A : Optional[int] = cpu_offload_with_hook(_A , _A , prev_module_hook=_A ) # We'll offload the last model manually. __A : List[str] = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def UpperCAmelCase_ ( self ): if not hasattr(self.unet , '_hf_hook' ): return self.device for module in self.unet.modules(): if ( hasattr(_A , '_hf_hook' ) and hasattr(module._hf_hook , 'execution_device' ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(_A ) def __call__( self , _A , _A , _A , _A = 512 , _A = 512 , _A = 100 , _A = 4.0 , _A = 0.3 , _A = 1 , _A = None , _A = "pil" , _A = True , ): __A : List[Any] = self._execution_device __A : Optional[Any] = guidance_scale > 1.0 if isinstance(_A , _A ): __A : Optional[Any] = torch.cat(_A , dim=0 ) __A : Tuple = image_embeds.shape[0] if isinstance(_A , _A ): __A : List[Any] = torch.cat(_A , dim=0 ) if do_classifier_free_guidance: __A : Union[str, Any] = image_embeds.repeat_interleave(_A , dim=0 ) __A : Optional[int] = negative_image_embeds.repeat_interleave(_A , dim=0 ) __A : List[str] = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=_A ) if not isinstance(_A , _A ): __A : List[Any] = [image] if not all(isinstance(_A , (PIL.Image.Image, torch.Tensor) ) for i in image ): raise ValueError( F"""Input is in incorrect format: {[type(_A ) for i in image]}. Currently, we only support PIL image and pytorch tensor""" ) __A : Dict = torch.cat([prepare_image(_A , _A , _A ) for i in image] , dim=0 ) __A : Any = image.to(dtype=image_embeds.dtype , device=_A ) __A : Tuple = self.movq.encode(_A )['latents'] __A : int = latents.repeat_interleave(_A , dim=0 ) self.scheduler.set_timesteps(_A , device=_A ) __A , __A : int = self.get_timesteps(_A , _A , _A ) __A : Union[str, Any] = timesteps[:1].repeat(batch_size * num_images_per_prompt ) __A , __A : Any = downscale_height_and_width(_A , _A , self.movq_scale_factor ) __A : Tuple = self.prepare_latents( _A , _A , _A , _A , image_embeds.dtype , _A , _A ) for i, t in enumerate(self.progress_bar(_A ) ): # expand the latents if we are doing classifier free guidance __A : Optional[int] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents __A : Dict = {'image_embeds': image_embeds} __A : List[str] = self.unet( sample=_A , timestep=_A , encoder_hidden_states=_A , added_cond_kwargs=_A , return_dict=_A , )[0] if do_classifier_free_guidance: __A , __A : Dict = noise_pred.split(latents.shape[1] , dim=1 ) __A , __A : Optional[Any] = noise_pred.chunk(2 ) __A , __A : List[str] = variance_pred.chunk(2 ) __A : str = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) __A : List[str] = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , 'variance_type' ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): __A , __A : Optional[Any] = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 __A : List[str] = self.scheduler.step( _A , _A , _A , generator=_A , )[0] # post-processing __A : List[Any] = self.movq.decode(_A , force_not_quantize=_A )['sample'] if output_type not in ["pt", "np", "pil"]: raise ValueError(F"""Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}""" ) if output_type in ["np", "pil"]: __A : List[str] = image * 0.5 + 0.5 __A : List[str] = image.clamp(0 , 1 ) __A : Optional[Any] = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": __A : Any = self.numpy_to_pil(_A ) if not return_dict: return (image,) return ImagePipelineOutput(images=_A )
280
1
import random import unittest import numpy as np from diffusers import ( DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionImgaImgPipeline, PNDMScheduler, ) from diffusers.utils import floats_tensor from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class _A( snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Tuple = '''hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline''' def UpperCAmelCase_ ( self , _A=0 ): __A : Dict = floats_tensor((1, 3, 128, 128) , rng=random.Random(_A ) ) __A : List[Any] = np.random.RandomState(_A ) __A : str = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'generator': generator, 'num_inference_steps': 3, 'strength': 0.7_5, 'guidance_scale': 7.5, 'output_type': 'numpy', } return inputs def UpperCAmelCase_ ( self ): __A : Dict = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) pipe.set_progress_bar_config(disable=_A ) __A : int = self.get_dummy_inputs() __A : List[Any] = pipe(**_A ).images __A : Optional[Any] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 128, 128, 3) __A : Dict = np.array([0.6_9_6_4_3, 0.5_8_4_8_4, 0.5_0_3_1_4, 0.5_8_7_6_0, 0.5_5_3_6_8, 0.5_9_6_4_3, 0.5_1_5_2_9, 0.4_1_2_1_7, 0.4_9_0_8_7] ) assert np.abs(image_slice - expected_slice ).max() < 1e-1 def UpperCAmelCase_ ( self ): __A : int = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) __A : List[str] = PNDMScheduler.from_config(pipe.scheduler.config , skip_prk_steps=_A ) pipe.set_progress_bar_config(disable=_A ) __A : List[str] = self.get_dummy_inputs() __A : Optional[Any] = pipe(**_A ).images __A : Union[str, Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) __A : Union[str, Any] = np.array([0.6_1_7_3_7, 0.5_4_6_4_2, 0.5_3_1_8_3, 0.5_4_4_6_5, 0.5_2_7_4_2, 0.6_0_5_2_5, 0.4_9_9_6_9, 0.4_0_6_5_5, 0.4_8_1_5_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def UpperCAmelCase_ ( self ): __A : Any = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) __A : Optional[Any] = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=_A ) # warmup pass to apply optimizations __A : Tuple = pipe(**self.get_dummy_inputs() ) __A : Any = self.get_dummy_inputs() __A : Dict = pipe(**_A ).images __A : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) __A : int = np.array([0.5_2_7_6_1, 0.5_9_9_7_7, 0.4_9_0_3_3, 0.4_9_6_1_9, 0.5_4_2_8_2, 0.5_0_3_1_1, 0.4_7_6_0_0, 0.4_0_9_1_8, 0.4_5_2_0_3] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def UpperCAmelCase_ ( self ): __A : Optional[int] = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) __A : Any = EulerDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=_A ) __A : Optional[Any] = self.get_dummy_inputs() __A : List[Any] = pipe(**_A ).images __A : Union[str, Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) __A : Optional[Any] = np.array([0.5_2_9_1_1, 0.6_0_0_0_4, 0.4_9_2_2_9, 0.4_9_8_0_5, 0.5_4_5_0_2, 0.5_0_6_8_0, 0.4_7_7_7_7, 0.4_1_0_2_8, 0.4_5_3_0_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def UpperCAmelCase_ ( self ): __A : Any = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) __A : Optional[int] = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=_A ) __A : List[Any] = self.get_dummy_inputs() __A : Tuple = pipe(**_A ).images __A : Dict = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) __A : Any = np.array([0.5_2_9_1_1, 0.6_0_0_0_4, 0.4_9_2_2_9, 0.4_9_8_0_5, 0.5_4_5_0_2, 0.5_0_6_8_0, 0.4_7_7_7_7, 0.4_1_0_2_8, 0.4_5_3_0_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def UpperCAmelCase_ ( self ): __A : Any = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) __A : str = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=_A ) __A : int = self.get_dummy_inputs() __A : Dict = pipe(**_A ).images __A : Dict = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) __A : List[str] = np.array([0.6_5_3_3_1, 0.5_8_2_7_7, 0.4_8_2_0_4, 0.5_6_0_5_9, 0.5_3_6_6_5, 0.5_6_2_3_5, 0.5_0_9_6_9, 0.4_0_0_0_9, 0.4_6_5_5_2] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 @nightly @require_onnxruntime @require_torch_gpu class _A( unittest.TestCase ): """simple docstring""" @property def UpperCAmelCase_ ( self ): return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def UpperCAmelCase_ ( self ): __A : List[str] = ort.SessionOptions() __A : List[str] = False return options def UpperCAmelCase_ ( self ): __A : Optional[int] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/img2img/sketch-mountains-input.jpg' ) __A : Any = init_image.resize((768, 512) ) # using the PNDM scheduler by default __A : Any = OnnxStableDiffusionImgaImgPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='onnx' , safety_checker=_A , feature_extractor=_A , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=_A ) __A : Optional[int] = 'A fantasy landscape, trending on artstation' __A : Any = np.random.RandomState(0 ) __A : Optional[Any] = pipe( prompt=_A , image=_A , strength=0.7_5 , guidance_scale=7.5 , num_inference_steps=10 , generator=_A , output_type='np' , ) __A : Optional[int] = output.images __A : Any = images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 768, 3) __A : Tuple = np.array([0.4_9_0_9, 0.5_0_5_9, 0.5_3_7_2, 0.4_6_2_3, 0.4_8_7_6, 0.5_0_4_9, 0.4_8_2_0, 0.4_9_5_6, 0.5_0_1_9] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 def UpperCAmelCase_ ( self ): __A : Optional[Any] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/img2img/sketch-mountains-input.jpg' ) __A : List[str] = init_image.resize((768, 512) ) __A : Union[str, Any] = LMSDiscreteScheduler.from_pretrained( 'runwayml/stable-diffusion-v1-5' , subfolder='scheduler' , revision='onnx' ) __A : int = OnnxStableDiffusionImgaImgPipeline.from_pretrained( 'runwayml/stable-diffusion-v1-5' , revision='onnx' , scheduler=_A , safety_checker=_A , feature_extractor=_A , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=_A ) __A : List[Any] = 'A fantasy landscape, trending on artstation' __A : Optional[Any] = np.random.RandomState(0 ) __A : List[Any] = pipe( prompt=_A , image=_A , strength=0.7_5 , guidance_scale=7.5 , num_inference_steps=20 , generator=_A , output_type='np' , ) __A : str = output.images __A : Union[str, Any] = images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 768, 3) __A : str = np.array([0.8_0_4_3, 0.9_2_6, 0.9_5_8_1, 0.8_1_1_9, 0.8_9_5_4, 0.9_1_3, 0.7_2_0_9, 0.7_4_6_3, 0.7_4_3_1] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2
280
import argparse import os import gluonnlp as nlp import mxnet as mx import numpy as np import torch from gluonnlp.base import get_home_dir from gluonnlp.model.bert import BERTEncoder from gluonnlp.model.utils import _load_vocab from gluonnlp.vocab import Vocab from packaging import version from torch import nn from transformers import BertConfig, BertForMaskedLM, BertModel, RobertaTokenizer from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertSelfAttention, BertSelfOutput, ) from transformers.utils import logging if version.parse(nlp.__version__) != version.parse('''0.8.3'''): raise Exception('''requires gluonnlp == 0.8.3''') if version.parse(mx.__version__) != version.parse('''1.5.0'''): raise Exception('''requires mxnet == 1.5.0''') logging.set_verbosity_info() UpperCAmelCase : List[Any] = logging.get_logger(__name__) UpperCAmelCase : Optional[Any] = '''The Nymphenburg Palace is a beautiful palace in Munich!''' def _SCREAMING_SNAKE_CASE ( a , a ) -> Optional[Any]: __A : Any = { 'attention_cell': 'multi_head', 'num_layers': 4, 'units': 10_24, 'hidden_size': 7_68, 'max_length': 5_12, 'num_heads': 8, 'scaled': True, 'dropout': 0.1, 'use_residual': True, 'embed_size': 10_24, 'embed_dropout': 0.1, 'word_embed': None, 'layer_norm_eps': 1e-5, 'token_type_vocab_size': 2, } __A : str = bort_4_8_768_1024_hparams # Let's construct the original Bort model here # Taken from official BERT implementation, see: # https://github.com/alexa/bort/blob/master/bort/bort.py __A : Optional[int] = BERTEncoder( attention_cell=predefined_args['attention_cell'] , num_layers=predefined_args['num_layers'] , units=predefined_args['units'] , hidden_size=predefined_args['hidden_size'] , max_length=predefined_args['max_length'] , num_heads=predefined_args['num_heads'] , scaled=predefined_args['scaled'] , dropout=predefined_args['dropout'] , output_attention=a , output_all_encodings=a , use_residual=predefined_args['use_residual'] , activation=predefined_args.get('activation' , 'gelu' ) , layer_norm_eps=predefined_args.get('layer_norm_eps' , a ) , ) # Vocab information needs to be fetched first # It's the same as RoBERTa, so RobertaTokenizer can be used later __A : Union[str, Any] = 'openwebtext_ccnews_stories_books_cased' # Specify download folder to Gluonnlp's vocab __A : Any = os.path.join(get_home_dir() , 'models' ) __A : List[Any] = _load_vocab(a , a , a , cls=a ) __A : Dict = nlp.model.BERTModel( a , len(a ) , units=predefined_args['units'] , embed_size=predefined_args['embed_size'] , embed_dropout=predefined_args['embed_dropout'] , word_embed=predefined_args['word_embed'] , use_pooler=a , use_token_type_embed=a , token_type_vocab_size=predefined_args['token_type_vocab_size'] , use_classifier=a , use_decoder=a , ) original_bort.load_parameters(a , cast_dtype=a , ignore_extra=a ) __A : Union[str, Any] = original_bort._collect_params_with_prefix() # Build our config 🤗 __A : Any = { 'architectures': ['BertForMaskedLM'], 'attention_probs_dropout_prob': predefined_args['dropout'], 'hidden_act': 'gelu', 'hidden_dropout_prob': predefined_args['dropout'], 'hidden_size': predefined_args['embed_size'], 'initializer_range': 0.02, 'intermediate_size': predefined_args['hidden_size'], 'layer_norm_eps': predefined_args['layer_norm_eps'], 'max_position_embeddings': predefined_args['max_length'], 'model_type': 'bort', 'num_attention_heads': predefined_args['num_heads'], 'num_hidden_layers': predefined_args['num_layers'], 'pad_token_id': 1, # 2 = BERT, 1 = RoBERTa 'type_vocab_size': 1, # 2 = BERT, 1 = RoBERTa 'vocab_size': len(a ), } __A : int = BertConfig.from_dict(a ) __A : Union[str, Any] = BertForMaskedLM(a ) hf_bort_model.eval() # Parameter mapping table (Gluonnlp to Transformers) # * denotes layer index # # | Gluon Parameter | Transformers Parameter # | -------------------------------------------------------------- | ---------------------- # | `encoder.layer_norm.beta` | `bert.embeddings.LayerNorm.bias` # | `encoder.layer_norm.gamma` | `bert.embeddings.LayerNorm.weight` # | `encoder.position_weight` | `bert.embeddings.position_embeddings.weight` # | `word_embed.0.weight` | `bert.embeddings.word_embeddings.weight` # | `encoder.transformer_cells.*.attention_cell.proj_key.bias` | `bert.encoder.layer.*.attention.self.key.bias` # | `encoder.transformer_cells.*.attention_cell.proj_key.weight` | `bert.encoder.layer.*.attention.self.key.weight` # | `encoder.transformer_cells.*.attention_cell.proj_query.bias` | `bert.encoder.layer.*.attention.self.query.bias` # | `encoder.transformer_cells.*.attention_cell.proj_query.weight` | `bert.encoder.layer.*.attention.self.query.weight` # | `encoder.transformer_cells.*.attention_cell.proj_value.bias` | `bert.encoder.layer.*.attention.self.value.bias` # | `encoder.transformer_cells.*.attention_cell.proj_value.weight` | `bert.encoder.layer.*.attention.self.value.weight` # | `encoder.transformer_cells.*.ffn.ffn_2.bias` | `bert.encoder.layer.*.attention.output.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_2.weight` | `bert.encoder.layer.*.attention.output.dense.weight` # | `encoder.transformer_cells.*.layer_norm.beta` | `bert.encoder.layer.*.attention.output.LayerNorm.bias` # | `encoder.transformer_cells.*.layer_norm.gamma` | `bert.encoder.layer.*.attention.output.LayerNorm.weight` # | `encoder.transformer_cells.*.ffn.ffn_1.bias` | `bert.encoder.layer.*.intermediate.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_1.weight` | `bert.encoder.layer.*.intermediate.dense.weight` # | `encoder.transformer_cells.*.ffn.layer_norm.beta` | `bert.encoder.layer.*.output.LayerNorm.bias` # | `encoder.transformer_cells.*.ffn.layer_norm.gamma` | `bert.encoder.layer.*.output.LayerNorm.weight` # | `encoder.transformer_cells.*.proj.bias` | `bert.encoder.layer.*.output.dense.bias` # | `encoder.transformer_cells.*.proj.weight` | `bert.encoder.layer.*.output.dense.weight` # Helper function to convert MXNET Arrays to PyTorch def to_torch(a ) -> nn.Parameter: return nn.Parameter(torch.FloatTensor(mx_array.data().asnumpy() ) ) # Check param shapes and map new HF param back def check_and_map_params(a , a ): __A : Tuple = hf_param.shape __A : str = to_torch(params[gluon_param] ) __A : Union[str, Any] = gluon_param.shape assert ( shape_hf == shape_gluon ), F"""The gluon parameter {gluon_param} has shape {shape_gluon}, but expects shape {shape_hf} for Transformers""" return gluon_param __A : str = check_and_map_params( hf_bort_model.bert.embeddings.word_embeddings.weight , 'word_embed.0.weight' ) __A : Tuple = check_and_map_params( hf_bort_model.bert.embeddings.position_embeddings.weight , 'encoder.position_weight' ) __A : List[str] = check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.bias , 'encoder.layer_norm.beta' ) __A : Tuple = check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.weight , 'encoder.layer_norm.gamma' ) # Inspired by RoBERTa conversion script, we just zero them out (Bort does not use them) __A : Tuple = torch.zeros_like( hf_bort_model.bert.embeddings.token_type_embeddings.weight.data ) for i in range(hf_bort_config.num_hidden_layers ): __A : BertLayer = hf_bort_model.bert.encoder.layer[i] # self attention __A : BertSelfAttention = layer.attention.self __A : Optional[Any] = check_and_map_params( self_attn.key.bias.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_key.bias""" ) __A : Optional[int] = check_and_map_params( self_attn.key.weight.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_key.weight""" ) __A : Union[str, Any] = check_and_map_params( self_attn.query.bias.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_query.bias""" ) __A : Optional[Any] = check_and_map_params( self_attn.query.weight.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_query.weight""" ) __A : Union[str, Any] = check_and_map_params( self_attn.value.bias.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_value.bias""" ) __A : Optional[int] = check_and_map_params( self_attn.value.weight.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_value.weight""" ) # self attention output __A : BertSelfOutput = layer.attention.output __A : Tuple = check_and_map_params( self_output.dense.bias , F"""encoder.transformer_cells.{i}.proj.bias""" ) __A : int = check_and_map_params( self_output.dense.weight , F"""encoder.transformer_cells.{i}.proj.weight""" ) __A : List[Any] = check_and_map_params( self_output.LayerNorm.bias , F"""encoder.transformer_cells.{i}.layer_norm.beta""" ) __A : str = check_and_map_params( self_output.LayerNorm.weight , F"""encoder.transformer_cells.{i}.layer_norm.gamma""" ) # intermediate __A : BertIntermediate = layer.intermediate __A : int = check_and_map_params( intermediate.dense.bias , F"""encoder.transformer_cells.{i}.ffn.ffn_1.bias""" ) __A : List[Any] = check_and_map_params( intermediate.dense.weight , F"""encoder.transformer_cells.{i}.ffn.ffn_1.weight""" ) # output __A : BertOutput = layer.output __A : List[Any] = check_and_map_params( bert_output.dense.bias , F"""encoder.transformer_cells.{i}.ffn.ffn_2.bias""" ) __A : Dict = check_and_map_params( bert_output.dense.weight , F"""encoder.transformer_cells.{i}.ffn.ffn_2.weight""" ) __A : Optional[int] = check_and_map_params( bert_output.LayerNorm.bias , F"""encoder.transformer_cells.{i}.ffn.layer_norm.beta""" ) __A : Dict = check_and_map_params( bert_output.LayerNorm.weight , F"""encoder.transformer_cells.{i}.ffn.layer_norm.gamma""" ) # Save space and energy 🎄 hf_bort_model.half() # Compare output of both models __A : Any = RobertaTokenizer.from_pretrained('roberta-base' ) __A : List[str] = tokenizer.encode_plus(a )['input_ids'] # Get gluon output __A : List[str] = mx.nd.array([input_ids] ) __A : Union[str, Any] = original_bort(inputs=a , token_types=[] ) # Get Transformer output (save and reload model again) hf_bort_model.save_pretrained(a ) __A : Optional[Any] = BertModel.from_pretrained(a ) hf_bort_model.eval() __A : Tuple = tokenizer.encode_plus(a , return_tensors='pt' ) __A : Any = hf_bort_model(**a )[0] __A : Union[str, Any] = output_gluon[0].asnumpy() __A : Tuple = output_hf[0].detach().numpy() __A : int = np.max(np.abs(hf_layer - gluon_layer ) ).item() __A : int = np.allclose(a , a , atol=1e-3 ) if success: print('✔️ Both model do output the same tensors' ) else: print('❌ Both model do **NOT** output the same tensors' ) print('Absolute difference is:' , a ) if __name__ == "__main__": UpperCAmelCase : int = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--bort_checkpoint_path''', default=None, type=str, required=True, help='''Path the official Bort params file.''' ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) UpperCAmelCase : Dict = parser.parse_args() convert_bort_checkpoint_to_pytorch(args.bort_checkpoint_path, args.pytorch_dump_folder_path)
280
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) UpperCAmelCase : Dict = {'''configuration_encoder_decoder''': ['''EncoderDecoderConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : int = ['''EncoderDecoderModel'''] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Dict = ['''TFEncoderDecoderModel'''] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : int = ['''FlaxEncoderDecoderModel'''] if TYPE_CHECKING: from .configuration_encoder_decoder import EncoderDecoderConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_encoder_decoder import EncoderDecoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_encoder_decoder import TFEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_encoder_decoder import FlaxEncoderDecoderModel else: import sys UpperCAmelCase : Optional[int] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
280
import colorsys from PIL import Image # type: ignore def _SCREAMING_SNAKE_CASE ( a , a , a ) -> float: __A : List[str] = x __A : str = y for step in range(a ): # noqa: B007 __A : Union[str, Any] = a * a - b * b + x __A : Optional[int] = 2 * a * b + y __A : List[str] = a_new # divergence happens for all complex number with an absolute value # greater than 4 if a * a + b * b > 4: break return step / (max_step - 1) def _SCREAMING_SNAKE_CASE ( a ) -> tuple: if distance == 1: return (0, 0, 0) else: return (2_55, 2_55, 2_55) def _SCREAMING_SNAKE_CASE ( a ) -> tuple: if distance == 1: return (0, 0, 0) else: return tuple(round(i * 2_55 ) for i in colorsys.hsv_to_rgb(a , 1 , 1 ) ) def _SCREAMING_SNAKE_CASE ( a = 8_00 , a = 6_00 , a = -0.6 , a = 0 , a = 3.2 , a = 50 , a = True , ) -> Image.Image: __A : str = Image.new('RGB' , (image_width, image_height) ) __A : Dict = img.load() # loop through the image-coordinates for image_x in range(a ): for image_y in range(a ): # determine the figure-coordinates based on the image-coordinates __A : Dict = figure_width / image_width * image_height __A : Union[str, Any] = figure_center_x + (image_x / image_width - 0.5) * figure_width __A : Optional[Any] = figure_center_y + (image_y / image_height - 0.5) * figure_height __A : Union[str, Any] = get_distance(a , a , a ) # color the corresponding pixel based on the selected coloring-function if use_distance_color_coding: __A : Optional[Any] = get_color_coded_rgb(a ) else: __A : Dict = get_black_and_white_rgb(a ) return img if __name__ == "__main__": import doctest doctest.testmod() # colored version, full figure UpperCAmelCase : str = get_image() # uncomment for colored version, different section, zoomed in # img = get_image(figure_center_x = -0.6, figure_center_y = -0.4, # figure_width = 0.8) # uncomment for black and white version, full figure # img = get_image(use_distance_color_coding = False) # uncomment to save the image # img.save("mandelbrot.png") img.show()
280
1
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import OwlViTImageProcessor, OwlViTProcessor @require_vision class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): __A : List[Any] = tempfile.mkdtemp() # fmt: off __A : List[str] = ['', 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'lo', 'l</w>', 'w</w>', 'r</w>', 't</w>', 'low</w>', 'er</w>', 'lowest</w>', 'newer</w>', 'wider', '<unk>', '<|startoftext|>', '<|endoftext|>'] # fmt: on __A : Union[str, Any] = dict(zip(_A , range(len(_A ) ) ) ) __A : Optional[int] = ['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>', ''] __A : int = {'unk_token': '<unk>'} __A : Optional[int] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) __A : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(_A ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(_A ) ) __A : List[Any] = { 'do_resize': True, 'size': 20, 'do_center_crop': True, 'crop_size': 18, 'do_normalize': True, 'image_mean': [0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3], 'image_std': [0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1], } __A : Optional[int] = os.path.join(self.tmpdirname , _A ) with open(self.image_processor_file , 'w' , encoding='utf-8' ) as fp: json.dump(_A , _A ) def UpperCAmelCase_ ( self , **_A ): return CLIPTokenizer.from_pretrained(self.tmpdirname , pad_token='!' , **_A ) def UpperCAmelCase_ ( self , **_A ): return CLIPTokenizerFast.from_pretrained(self.tmpdirname , pad_token='!' , **_A ) def UpperCAmelCase_ ( self , **_A ): return OwlViTImageProcessor.from_pretrained(self.tmpdirname , **_A ) def UpperCAmelCase_ ( self ): shutil.rmtree(self.tmpdirname ) def UpperCAmelCase_ ( self ): __A : int = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __A : Optional[int] = [Image.fromarray(np.moveaxis(_A , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCAmelCase_ ( self ): __A : List[Any] = self.get_tokenizer() __A : str = self.get_rust_tokenizer() __A : List[str] = self.get_image_processor() __A : Optional[int] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) processor_slow.save_pretrained(self.tmpdirname ) __A : int = OwlViTProcessor.from_pretrained(self.tmpdirname , use_fast=_A ) __A : Optional[Any] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) processor_fast.save_pretrained(self.tmpdirname ) __A : Optional[Any] = OwlViTProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , _A ) self.assertIsInstance(processor_fast.tokenizer , _A ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , _A ) self.assertIsInstance(processor_fast.image_processor , _A ) def UpperCAmelCase_ ( self ): __A : List[str] = OwlViTProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __A : Optional[int] = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) __A : Optional[int] = self.get_image_processor(do_normalize=_A ) __A : Any = OwlViTProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=_A ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , _A ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _A ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.get_image_processor() __A : Optional[Any] = self.get_tokenizer() __A : Union[str, Any] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Union[str, Any] = self.prepare_image_inputs() __A : int = image_processor(_A , return_tensors='np' ) __A : str = processor(images=_A , return_tensors='np' ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1e-2 ) def UpperCAmelCase_ ( self ): __A : str = self.get_image_processor() __A : str = self.get_tokenizer() __A : Tuple = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : str = 'lower newer' __A : str = processor(text=_A , return_tensors='np' ) __A : List[str] = tokenizer(_A , return_tensors='np' ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key][0].tolist() , encoded_processor[key][0].tolist() ) def UpperCAmelCase_ ( self ): __A : int = self.get_image_processor() __A : Optional[int] = self.get_tokenizer() __A : List[str] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Any = 'lower newer' __A : Optional[Any] = self.prepare_image_inputs() __A : List[Any] = processor(text=_A , images=_A ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Any = 'google/owlvit-base-patch32' __A : int = OwlViTProcessor.from_pretrained(_A ) __A : Dict = ['cat', 'nasa badge'] __A : Optional[Any] = processor(text=_A ) __A : Optional[int] = 16 self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (2, seq_length) ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Tuple = 'google/owlvit-base-patch32' __A : Any = OwlViTProcessor.from_pretrained(_A ) __A : Dict = [['cat', 'nasa badge'], ['person']] __A : Dict = processor(text=_A ) __A : Optional[int] = 16 __A : Any = len(_A ) __A : Union[str, Any] = max([len(_A ) for texts in input_texts] ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (batch_size * num_max_text_queries, seq_length) ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : List[Any] = 'google/owlvit-base-patch32' __A : str = OwlViTProcessor.from_pretrained(_A ) __A : Union[str, Any] = ['cat', 'nasa badge'] __A : Tuple = processor(text=_A ) __A : str = 16 __A : int = inputs['input_ids'] __A : List[Any] = [ [49406, 2368, 49407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [49406, 6841, 11301, 49407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (2, seq_length) ) self.assertListEqual(list(input_ids[0] ) , predicted_ids[0] ) self.assertListEqual(list(input_ids[1] ) , predicted_ids[1] ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.get_image_processor() __A : List[str] = self.get_tokenizer() __A : Optional[Any] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Optional[int] = self.prepare_image_inputs() __A : Optional[int] = self.prepare_image_inputs() __A : Optional[int] = processor(images=_A , query_images=_A ) self.assertListEqual(list(inputs.keys() ) , ['query_pixel_values', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.get_image_processor() __A : Union[str, Any] = self.get_tokenizer() __A : str = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Optional[Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __A : Any = processor.batch_decode(_A ) __A : Tuple = tokenizer.batch_decode(_A ) self.assertListEqual(_A , _A )
280
from __future__ import annotations def _SCREAMING_SNAKE_CASE ( a , a , a ) -> float: if days_between_payments <= 0: raise ValueError('days_between_payments must be > 0' ) if daily_interest_rate < 0: raise ValueError('daily_interest_rate must be >= 0' ) if principal <= 0: raise ValueError('principal must be > 0' ) return principal * daily_interest_rate * days_between_payments def _SCREAMING_SNAKE_CASE ( a , a , a , ) -> float: if number_of_compounding_periods <= 0: raise ValueError('number_of_compounding_periods must be > 0' ) if nominal_annual_interest_rate_percentage < 0: raise ValueError('nominal_annual_interest_rate_percentage must be >= 0' ) if principal <= 0: raise ValueError('principal must be > 0' ) return principal * ( (1 + nominal_annual_interest_rate_percentage) ** number_of_compounding_periods - 1 ) def _SCREAMING_SNAKE_CASE ( a , a , a , ) -> float: if number_of_years <= 0: raise ValueError('number_of_years must be > 0' ) if nominal_annual_percentage_rate < 0: raise ValueError('nominal_annual_percentage_rate must be >= 0' ) if principal <= 0: raise ValueError('principal must be > 0' ) return compound_interest( a , nominal_annual_percentage_rate / 3_65 , number_of_years * 3_65 ) if __name__ == "__main__": import doctest doctest.testmod()
280
1
import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, FEATURE_EXTRACTOR_MAPPING, AutoConfig, AutoFeatureExtractor, WavaVecaConfig, WavaVecaFeatureExtractor, ) 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 from test_module.custom_feature_extraction import CustomFeatureExtractor # noqa E402 UpperCAmelCase : Union[str, Any] = get_tests_dir('''fixtures''') UpperCAmelCase : Dict = get_tests_dir('''fixtures/dummy_feature_extractor_config.json''') UpperCAmelCase : List[str] = get_tests_dir('''fixtures/dummy-config.json''') class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): __A : Dict = 0 def UpperCAmelCase_ ( self ): __A : Dict = AutoFeatureExtractor.from_pretrained('facebook/wav2vec2-base-960h' ) self.assertIsInstance(_A , _A ) def UpperCAmelCase_ ( self ): __A : List[str] = AutoFeatureExtractor.from_pretrained(_A ) self.assertIsInstance(_A , _A ) def UpperCAmelCase_ ( self ): with tempfile.TemporaryDirectory() as tmpdirname: __A : List[str] = WavaVecaConfig() # remove feature_extractor_type to make sure config.json alone is enough to load feature processor locally __A : List[str] = AutoFeatureExtractor.from_pretrained(_A ).to_dict() config_dict.pop('feature_extractor_type' ) __A : Optional[int] = WavaVecaFeatureExtractor(**_A ) # save in new folder model_config.save_pretrained(_A ) config.save_pretrained(_A ) __A : Optional[int] = AutoFeatureExtractor.from_pretrained(_A ) # make sure private variable is not incorrectly saved __A : Optional[int] = json.loads(config.to_json_string() ) self.assertTrue('_processor_class' not in dict_as_saved ) self.assertIsInstance(_A , _A ) def UpperCAmelCase_ ( self ): __A : Optional[int] = AutoFeatureExtractor.from_pretrained(_A ) self.assertIsInstance(_A , _A ) def UpperCAmelCase_ ( self ): with self.assertRaisesRegex( _A , 'bert-base is not a local folder and is not a valid model identifier' ): __A : Any = AutoFeatureExtractor.from_pretrained('bert-base' ) def UpperCAmelCase_ ( self ): with self.assertRaisesRegex( _A , R'aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)' ): __A : Union[str, Any] = AutoFeatureExtractor.from_pretrained(_A , revision='aaaaaa' ) def UpperCAmelCase_ ( self ): with self.assertRaisesRegex( _A , 'hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.' , ): __A : Tuple = AutoFeatureExtractor.from_pretrained('hf-internal-testing/config-no-model' ) def UpperCAmelCase_ ( self ): # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(_A ): __A : Any = AutoFeatureExtractor.from_pretrained( 'hf-internal-testing/test_dynamic_feature_extractor' ) # If remote code is disabled, we can't load this config. with self.assertRaises(_A ): __A : str = AutoFeatureExtractor.from_pretrained( 'hf-internal-testing/test_dynamic_feature_extractor' , trust_remote_code=_A ) __A : int = AutoFeatureExtractor.from_pretrained( 'hf-internal-testing/test_dynamic_feature_extractor' , trust_remote_code=_A ) self.assertEqual(feature_extractor.__class__.__name__ , 'NewFeatureExtractor' ) # Test feature extractor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained(_A ) __A : Dict = AutoFeatureExtractor.from_pretrained(_A , trust_remote_code=_A ) self.assertEqual(reloaded_feature_extractor.__class__.__name__ , 'NewFeatureExtractor' ) def UpperCAmelCase_ ( self ): try: AutoConfig.register('custom' , _A ) AutoFeatureExtractor.register(_A , _A ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(_A ): AutoFeatureExtractor.register(_A , _A ) # Now that the config is registered, it can be used as any other config with the auto-API __A : Dict = CustomFeatureExtractor.from_pretrained(_A ) with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained(_A ) __A : Optional[int] = AutoFeatureExtractor.from_pretrained(_A ) self.assertIsInstance(_A , _A ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content: del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig] def UpperCAmelCase_ ( self ): class _A( snake_case__ ): """simple docstring""" UpperCamelCase : Dict = True try: AutoConfig.register('custom' , _A ) AutoFeatureExtractor.register(_A , _A ) # If remote code is not set, the default is to use local __A : Optional[Any] = AutoFeatureExtractor.from_pretrained( 'hf-internal-testing/test_dynamic_feature_extractor' ) self.assertEqual(feature_extractor.__class__.__name__ , 'NewFeatureExtractor' ) self.assertTrue(feature_extractor.is_local ) # If remote code is disabled, we load the local one. __A : List[Any] = AutoFeatureExtractor.from_pretrained( 'hf-internal-testing/test_dynamic_feature_extractor' , trust_remote_code=_A ) self.assertEqual(feature_extractor.__class__.__name__ , 'NewFeatureExtractor' ) self.assertTrue(feature_extractor.is_local ) # If remote is enabled, we load from the Hub __A : List[str] = AutoFeatureExtractor.from_pretrained( 'hf-internal-testing/test_dynamic_feature_extractor' , trust_remote_code=_A ) self.assertEqual(feature_extractor.__class__.__name__ , 'NewFeatureExtractor' ) self.assertTrue(not hasattr(_A , 'is_local' ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content: del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]
280
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) UpperCAmelCase : Any = { '''configuration_falcon''': ['''FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''FalconConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Any = [ '''FALCON_PRETRAINED_MODEL_ARCHIVE_LIST''', '''FalconForCausalLM''', '''FalconModel''', '''FalconPreTrainedModel''', '''FalconForSequenceClassification''', '''FalconForTokenClassification''', '''FalconForQuestionAnswering''', ] if TYPE_CHECKING: from .configuration_falcon import FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP, FalconConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_falcon import ( FALCON_PRETRAINED_MODEL_ARCHIVE_LIST, FalconForCausalLM, FalconForQuestionAnswering, FalconForSequenceClassification, FalconForTokenClassification, FalconModel, FalconPreTrainedModel, ) else: import sys UpperCAmelCase : List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
280
1
import os import tempfile import unittest from transformers import NezhaConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, NezhaModel, ) from transformers.models.nezha.modeling_nezha import NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST class _A: """simple docstring""" def __init__( self , _A , _A=13 , _A=7 , _A=True , _A=True , _A=True , _A=True , _A=99 , _A=32 , _A=5 , _A=4 , _A=37 , _A="gelu" , _A=0.1 , _A=0.1 , _A=128 , _A=32 , _A=16 , _A=2 , _A=0.0_2 , _A=3 , _A=4 , _A=None , ): __A : Any = parent __A : List[Any] = batch_size __A : List[Any] = seq_length __A : str = is_training __A : Tuple = use_input_mask __A : List[Any] = use_token_type_ids __A : List[str] = use_labels __A : Any = vocab_size __A : List[Any] = hidden_size __A : Optional[Any] = num_hidden_layers __A : List[str] = num_attention_heads __A : int = intermediate_size __A : Optional[Any] = hidden_act __A : Tuple = hidden_dropout_prob __A : List[str] = attention_probs_dropout_prob __A : Dict = max_position_embeddings __A : Tuple = type_vocab_size __A : List[Any] = type_sequence_label_size __A : Dict = initializer_range __A : List[Any] = num_labels __A : List[Any] = num_choices __A : List[str] = scope def UpperCAmelCase_ ( self ): __A : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __A : List[Any] = None if self.use_input_mask: __A : Optional[int] = random_attention_mask([self.batch_size, self.seq_length] ) __A : int = None if self.use_token_type_ids: __A : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __A : Union[str, Any] = None __A : List[str] = None __A : List[Any] = None if self.use_labels: __A : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __A : int = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __A : Any = ids_tensor([self.batch_size] , self.num_choices ) __A : Optional[Any] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ ( self ): return NezhaConfig( 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=_A , initializer_range=self.initializer_range , ) def UpperCAmelCase_ ( self ): ( ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ) : int = self.prepare_config_and_inputs() __A : List[str] = True __A : List[str] = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __A : List[Any] = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A ): __A : Tuple = NezhaModel(config=_A ) model.to(_A ) model.eval() __A : Dict = model(_A , attention_mask=_A , token_type_ids=_A ) __A : str = model(_A , token_type_ids=_A ) __A : Dict = model(_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A , _A , _A , ): __A : Optional[int] = True __A : List[str] = NezhaModel(_A ) model.to(_A ) model.eval() __A : Dict = model( _A , attention_mask=_A , token_type_ids=_A , encoder_hidden_states=_A , encoder_attention_mask=_A , ) __A : str = model( _A , attention_mask=_A , token_type_ids=_A , encoder_hidden_states=_A , ) __A : Dict = model(_A , attention_mask=_A , token_type_ids=_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A ): __A : Optional[int] = NezhaForMaskedLM(config=_A ) model.to(_A ) model.eval() __A : int = model(_A , attention_mask=_A , token_type_ids=_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A ): __A : List[Any] = NezhaForNextSentencePrediction(config=_A ) model.to(_A ) model.eval() __A : Dict = model( _A , attention_mask=_A , token_type_ids=_A , labels=_A , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A ): __A : Dict = NezhaForPreTraining(config=_A ) model.to(_A ) model.eval() __A : int = model( _A , attention_mask=_A , token_type_ids=_A , labels=_A , next_sentence_label=_A , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A ): __A : int = NezhaForQuestionAnswering(config=_A ) model.to(_A ) model.eval() __A : str = model( _A , attention_mask=_A , token_type_ids=_A , start_positions=_A , end_positions=_A , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A ): __A : Optional[int] = self.num_labels __A : str = NezhaForSequenceClassification(_A ) model.to(_A ) model.eval() __A : List[Any] = model(_A , attention_mask=_A , token_type_ids=_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A ): __A : str = self.num_labels __A : Tuple = NezhaForTokenClassification(config=_A ) model.to(_A ) model.eval() __A : int = model(_A , attention_mask=_A , token_type_ids=_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A ): __A : Optional[Any] = self.num_choices __A : Tuple = NezhaForMultipleChoice(config=_A ) model.to(_A ) model.eval() __A : str = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __A : List[Any] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __A : Optional[Any] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __A : Tuple = model( _A , attention_mask=_A , token_type_ids=_A , labels=_A , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCAmelCase_ ( self ): __A : Optional[int] = self.prepare_config_and_inputs() ( ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ) : Optional[Any] = config_and_inputs __A : List[str] = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class _A( snake_case__ , snake_case__ , snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : List[Any] = ( ( NezhaModel, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, ) if is_torch_available() else () ) UpperCamelCase : Union[str, Any] = ( { '''feature-extraction''': NezhaModel, '''fill-mask''': NezhaForMaskedLM, '''question-answering''': NezhaForQuestionAnswering, '''text-classification''': NezhaForSequenceClassification, '''token-classification''': NezhaForTokenClassification, '''zero-shot''': NezhaForSequenceClassification, } if is_torch_available() else {} ) UpperCamelCase : Union[str, Any] = True def UpperCAmelCase_ ( self , _A , _A , _A=False ): __A : Tuple = super()._prepare_for_class(_A , _A , return_labels=_A ) if return_labels: if model_class in get_values(_A ): __A : Dict = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=_A ) __A : Dict = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=_A ) return inputs_dict def UpperCAmelCase_ ( self ): __A : Tuple = NezhaModelTester(self ) __A : Any = ConfigTester(self , config_class=_A , hidden_size=37 ) def UpperCAmelCase_ ( self ): self.config_tester.run_common_tests() def UpperCAmelCase_ ( self ): __A : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_A ) def UpperCAmelCase_ ( self ): __A : Optional[int] = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*_A ) def UpperCAmelCase_ ( self ): # This regression test was failing with PyTorch < 1.3 ( ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ) : Dict = self.model_tester.prepare_config_and_inputs_for_decoder() __A : Optional[Any] = None self.model_tester.create_and_check_model_as_decoder( _A , _A , _A , _A , _A , _A , _A , _A , _A , ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_A ) def UpperCAmelCase_ ( self ): __A : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*_A ) def UpperCAmelCase_ ( self ): __A : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_next_sequence_prediction(*_A ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*_A ) def UpperCAmelCase_ ( self ): __A : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*_A ) def UpperCAmelCase_ ( self ): __A : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*_A ) def UpperCAmelCase_ ( self ): __A : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_A ) @slow def UpperCAmelCase_ ( self ): for model_name in NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __A : Dict = NezhaModel.from_pretrained(_A ) self.assertIsNotNone(_A ) @slow @require_torch_gpu def UpperCAmelCase_ ( self ): __A , __A : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # NezhaForMultipleChoice behaves incorrectly in JIT environments. if model_class == NezhaForMultipleChoice: return __A : int = True __A : List[str] = model_class(config=_A ) __A : Dict = self._prepare_for_class(_A , _A ) __A : Optional[Any] = torch.jit.trace( _A , (inputs_dict['input_ids'].to('cpu' ), inputs_dict['attention_mask'].to('cpu' )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(_A , os.path.join(_A , 'bert.pt' ) ) __A : Optional[Any] = torch.jit.load(os.path.join(_A , 'bert.pt' ) , map_location=_A ) loaded(inputs_dict['input_ids'].to(_A ) , inputs_dict['attention_mask'].to(_A ) ) @require_torch class _A( unittest.TestCase ): """simple docstring""" @slow def UpperCAmelCase_ ( self ): __A : Optional[int] = NezhaModel.from_pretrained('sijunhe/nezha-cn-base' ) __A : Dict = torch.tensor([[0, 1, 2, 3, 4, 5]] ) __A : int = torch.tensor([[0, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __A : List[str] = model(_A , attention_mask=_A )[0] __A : Union[str, Any] = torch.Size((1, 6, 768) ) self.assertEqual(output.shape , _A ) __A : Union[str, Any] = torch.tensor([[[0.0_6_8_5, 0.2_4_4_1, 0.1_1_0_2], [0.0_6_0_0, 0.1_9_0_6, 0.1_3_4_9], [0.0_2_2_1, 0.0_8_1_9, 0.0_5_8_6]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , _A , atol=1e-4 ) ) @slow def UpperCAmelCase_ ( self ): __A : Optional[int] = NezhaForMaskedLM.from_pretrained('sijunhe/nezha-cn-base' ) __A : Optional[int] = torch.tensor([[0, 1, 2, 3, 4, 5]] ) __A : Optional[int] = torch.tensor([[1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __A : Optional[int] = model(_A , attention_mask=_A )[0] __A : Tuple = torch.Size((1, 6, 21128) ) self.assertEqual(output.shape , _A ) __A : int = torch.tensor( [[-2.7_9_3_9, -1.7_9_0_2, -2.2_1_8_9], [-2.8_5_8_5, -1.8_9_0_8, -2.3_7_2_3], [-2.6_4_9_9, -1.7_7_5_0, -2.2_5_5_8]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , _A , atol=1e-4 ) )
280
def _SCREAMING_SNAKE_CASE ( a ) -> bool: return str(a ) == str(a )[::-1] def _SCREAMING_SNAKE_CASE ( a ) -> int: return int(a ) + int(str(a )[::-1] ) def _SCREAMING_SNAKE_CASE ( a = 1_00_00 ) -> int: __A : int = [] for num in range(1 , a ): __A : List[str] = 0 __A : List[Any] = num while iterations < 50: __A : str = sum_reverse(a ) iterations += 1 if is_palindrome(a ): break else: lychrel_nums.append(a ) return len(a ) if __name__ == "__main__": print(F"""{solution() = }""")
280
1
from math import factorial UpperCAmelCase : Union[str, Any] = {str(d): factorial(d) for d in range(10)} def _SCREAMING_SNAKE_CASE ( a ) -> int: return sum(DIGIT_FACTORIAL[d] for d in str(a ) ) def _SCREAMING_SNAKE_CASE ( ) -> int: __A : List[Any] = 7 * factorial(9 ) + 1 return sum(i for i in range(3 , a ) if sum_of_digit_factorial(a ) == i ) if __name__ == "__main__": print(F"""{solution() = }""")
280
from __future__ import annotations import math import random from collections.abc import Collection from typing import overload class _A: """simple docstring""" def __init__( self , _A = None ): if components is None: __A : int = [] __A : Tuple = list(_A ) def __len__( self ): return len(self.__components ) def __str__( self ): return "(" + ",".join(map(_A , self.__components ) ) + ")" def __add__( self , _A ): __A : Optional[int] = len(self ) if size == len(_A ): __A : Any = [self.__components[i] + other.component(_A ) for i in range(_A )] return Vector(_A ) else: raise Exception('must have the same size' ) def __sub__( self , _A ): __A : Tuple = len(self ) if size == len(_A ): __A : Union[str, Any] = [self.__components[i] - other.component(_A ) for i in range(_A )] return Vector(_A ) else: # error case raise Exception('must have the same size' ) @overload def __mul__( self , _A ): ... @overload def __mul__( self , _A ): ... def __mul__( self , _A ): if isinstance(_A , (float, int) ): __A : str = [c * other for c in self.__components] return Vector(_A ) elif isinstance(_A , _A ) and len(self ) == len(_A ): __A : Union[str, Any] = len(self ) __A : Dict = [self.__components[i] * other.component(_A ) for i in range(_A )] return sum(_A ) else: # error case raise Exception('invalid operand!' ) def UpperCAmelCase_ ( self ): return Vector(self.__components ) def UpperCAmelCase_ ( self , _A ): if isinstance(_A , _A ) and -len(self.__components ) <= i < len(self.__components ): return self.__components[i] else: raise Exception('index out of range' ) def UpperCAmelCase_ ( self , _A , _A ): assert -len(self.__components ) <= pos < len(self.__components ) __A : Optional[int] = value def UpperCAmelCase_ ( self ): if len(self.__components ) == 0: raise Exception('Vector is empty' ) __A : Optional[Any] = [c**2 for c in self.__components] return math.sqrt(sum(_A ) ) def UpperCAmelCase_ ( self , _A , _A = False ): __A : Optional[Any] = self * other __A : Optional[Any] = self.euclidean_length() * other.euclidean_length() if deg: return math.degrees(math.acos(num / den ) ) else: return math.acos(num / den ) def _SCREAMING_SNAKE_CASE ( a ) -> Vector: assert isinstance(a , a ) return Vector([0] * dimension ) def _SCREAMING_SNAKE_CASE ( a , a ) -> Vector: assert isinstance(a , a ) and (isinstance(a , a )) __A : Optional[Any] = [0] * dimension __A : Tuple = 1 return Vector(a ) def _SCREAMING_SNAKE_CASE ( a , a , a ) -> Vector: assert ( isinstance(a , a ) and isinstance(a , a ) and (isinstance(a , (int, float) )) ) return x * scalar + y def _SCREAMING_SNAKE_CASE ( a , a , a ) -> Vector: random.seed(a ) __A : str = [random.randint(a , a ) for _ in range(a )] return Vector(a ) class _A: """simple docstring""" def __init__( self , _A , _A , _A ): __A : Optional[Any] = matrix __A : Dict = w __A : Optional[int] = h def __str__( self ): __A : Tuple = '' for i in range(self.__height ): ans += "|" for j in range(self.__width ): if j < self.__width - 1: ans += str(self.__matrix[i][j] ) + "," else: ans += str(self.__matrix[i][j] ) + "|\n" return ans def __add__( self , _A ): if self.__width == other.width() and self.__height == other.height(): __A : Optional[Any] = [] for i in range(self.__height ): __A : Optional[Any] = [ self.__matrix[i][j] + other.component(_A , _A ) for j in range(self.__width ) ] matrix.append(_A ) return Matrix(_A , self.__width , self.__height ) else: raise Exception('matrix must have the same dimension!' ) def __sub__( self , _A ): if self.__width == other.width() and self.__height == other.height(): __A : Tuple = [] for i in range(self.__height ): __A : str = [ self.__matrix[i][j] - other.component(_A , _A ) for j in range(self.__width ) ] matrix.append(_A ) return Matrix(_A , self.__width , self.__height ) else: raise Exception('matrices must have the same dimension!' ) @overload def __mul__( self , _A ): ... @overload def __mul__( self , _A ): ... def __mul__( self , _A ): if isinstance(_A , _A ): # matrix-vector if len(_A ) == self.__width: __A : List[Any] = zero_vector(self.__height ) for i in range(self.__height ): __A : List[str] = [ self.__matrix[i][j] * other.component(_A ) for j in range(self.__width ) ] ans.change_component(_A , sum(_A ) ) return ans else: raise Exception( 'vector must have the same size as the ' 'number of columns of the matrix!' ) elif isinstance(_A , (int, float) ): # matrix-scalar __A : List[str] = [ [self.__matrix[i][j] * other for j in range(self.__width )] for i in range(self.__height ) ] return Matrix(_A , self.__width , self.__height ) return None def UpperCAmelCase_ ( self ): return self.__height def UpperCAmelCase_ ( self ): return self.__width def UpperCAmelCase_ ( self , _A , _A ): if 0 <= x < self.__height and 0 <= y < self.__width: return self.__matrix[x][y] else: raise Exception('change_component: indices out of bounds' ) def UpperCAmelCase_ ( self , _A , _A , _A ): if 0 <= x < self.__height and 0 <= y < self.__width: __A : int = value else: raise Exception('change_component: indices out of bounds' ) def UpperCAmelCase_ ( self , _A , _A ): if self.__height != self.__width: raise Exception('Matrix is not square' ) __A : List[str] = self.__matrix[:x] + self.__matrix[x + 1 :] for i in range(len(_A ) ): __A : Optional[int] = minor[i][:y] + minor[i][y + 1 :] return Matrix(_A , self.__width - 1 , self.__height - 1 ).determinant() def UpperCAmelCase_ ( self , _A , _A ): if self.__height != self.__width: raise Exception('Matrix is not square' ) if 0 <= x < self.__height and 0 <= y < self.__width: return (-1) ** (x + y) * self.minor(_A , _A ) else: raise Exception('Indices out of bounds' ) def UpperCAmelCase_ ( self ): if self.__height != self.__width: raise Exception('Matrix is not square' ) if self.__height < 1: raise Exception('Matrix has no element' ) elif self.__height == 1: return self.__matrix[0][0] elif self.__height == 2: return ( self.__matrix[0][0] * self.__matrix[1][1] - self.__matrix[0][1] * self.__matrix[1][0] ) else: __A : List[str] = [ self.__matrix[0][y] * self.cofactor(0 , _A ) for y in range(self.__width ) ] return sum(_A ) def _SCREAMING_SNAKE_CASE ( a ) -> Matrix: __A : list[list[float]] = [[0] * n for _ in range(a )] return Matrix(a , a , a ) def _SCREAMING_SNAKE_CASE ( a , a , a , a ) -> Matrix: random.seed(a ) __A : list[list[float]] = [ [random.randint(a , a ) for _ in range(a )] for _ in range(a ) ] return Matrix(a , a , a )
280
1
import argparse import os from pathlib import Path from typing import Dict import tensorflow as tf import torch from tqdm import tqdm from transformers import PegasusConfig, PegasusForConditionalGeneration, PegasusTokenizer from transformers.models.pegasus.configuration_pegasus import DEFAULTS, task_specific_params UpperCAmelCase : Dict = [ # replace left string with right string to get the relevant state_dict key (identical state dict to bart) ['''memory_attention''', '''encoder_attn'''], ['''attention''', '''attn'''], ['''/''', '''.'''], ['''.LayerNorm.gamma''', '''_layer_norm.weight'''], ['''.LayerNorm.beta''', '''_layer_norm.bias'''], ['''r.layer_''', '''r.layers.'''], ['''output_proj''', '''out_proj'''], ['''ffn.dense_1.''', '''fc2.'''], ['''ffn.dense.''', '''fc1.'''], ['''ffn_layer_norm''', '''final_layer_norm'''], ['''kernel''', '''weight'''], ['''encoder_layer_norm.''', '''encoder.layer_norm.'''], ['''decoder_layer_norm.''', '''decoder.layer_norm.'''], ['''embeddings.weights''', '''shared.weight'''], ] def _SCREAMING_SNAKE_CASE ( a ) -> Dict: for pegasus_name, hf_name in PATTERNS: __A : List[Any] = k.replace(a , a ) return k def _SCREAMING_SNAKE_CASE ( a , a ) -> PegasusForConditionalGeneration: __A : str = DEFAULTS.copy() cfg_kwargs.update(a ) __A : Optional[Any] = PegasusConfig(**a ) __A : int = PegasusForConditionalGeneration(a ) __A : List[str] = torch_model.model.state_dict() __A : int = {} for k, v in tf_weights.items(): __A : Optional[int] = rename_state_dict_key(a ) if new_k not in sd: raise ValueError(F"""could not find new key {new_k} in state dict. (converted from {k})""" ) if "dense" in k or "proj" in new_k: __A : Optional[int] = v.T __A : Optional[int] = torch.tensor(a , dtype=sd[new_k].dtype ) assert v.shape == sd[new_k].shape, F"""{new_k}, {k}, {v.shape}, {sd[new_k].shape}""" # make sure embedding.padding_idx is respected __A : Optional[Any] = torch.zeros_like(mapping['shared.weight'][cfg.pad_token_id + 1] ) __A : Optional[int] = mapping['shared.weight'] __A : Optional[Any] = mapping['shared.weight'] __A : List[str] = {k: torch.zeros_like(a ) for k, v in sd.items() if k.endswith('bias' ) and k not in mapping} mapping.update(**a ) __A , __A : Any = torch_model.model.load_state_dict(a , strict=a ) __A : Any = [ k for k in missing if k not in ['encoder.embed_positions.weight', 'decoder.embed_positions.weight'] ] assert unexpected_missing == [], F"""no matches found for the following torch keys {unexpected_missing}""" assert extra == [], F"""no matches found for the following tf keys {extra}""" return torch_model def _SCREAMING_SNAKE_CASE ( a="./ckpt/aeslc/model.ckpt-32000" ) -> Dict: __A : List[Any] = tf.train.list_variables(a ) __A : Union[str, Any] = {} __A : Optional[Any] = ['Adafactor', 'global_step'] for name, shape in tqdm(a , desc='converting tf checkpoint to dict' ): __A : List[Any] = any(pat in name for pat in ignore_name ) if skip_key: continue __A : Optional[int] = tf.train.load_variable(a , a ) __A : Dict = array return tf_weights def _SCREAMING_SNAKE_CASE ( a , a ) -> str: # save tokenizer first __A : List[str] = Path(a ).parent.name __A : Optional[Any] = task_specific_params[F"""summarization_{dataset}"""]['max_position_embeddings'] __A : str = PegasusTokenizer.from_pretrained('sshleifer/pegasus' , model_max_length=a ) assert tok.model_max_length == desired_max_model_length tok.save_pretrained(a ) # convert model __A : Optional[Any] = get_tf_weights_as_numpy(a ) __A : Any = task_specific_params[F"""summarization_{dataset}"""] if dataset == "large": __A : Tuple = task_specific_params __A : Tuple = convert_pegasus(a , a ) torch_model.save_pretrained(a ) __A : Dict = torch_model.state_dict() sd.pop('model.decoder.embed_positions.weight' ) sd.pop('model.encoder.embed_positions.weight' ) torch.save(a , Path(a ) / 'pytorch_model.bin' ) if __name__ == "__main__": UpperCAmelCase : int = argparse.ArgumentParser() # Required parameters parser.add_argument('''tf_ckpt_path''', type=str, help='''passed to tf.train.list_variables''') parser.add_argument('''save_dir''', default=None, type=str, help='''Path to the output PyTorch model.''') UpperCAmelCase : Optional[Any] = parser.parse_args() if args.save_dir is None: UpperCAmelCase : str = Path(args.tf_ckpt_path).parent.name UpperCAmelCase : Optional[int] = os.path.join('''pegasus''', dataset) convert_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir)
280
import unittest from transformers import BertGenerationTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin UpperCAmelCase : List[str] = '''▁''' UpperCAmelCase : Optional[Any] = get_tests_dir('''fixtures/test_sentencepiece.model''') @require_sentencepiece class _A( snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Optional[int] = BertGenerationTokenizer UpperCamelCase : str = False UpperCamelCase : Tuple = True def UpperCAmelCase_ ( self ): super().setUp() __A : Tuple = BertGenerationTokenizer(_A , keep_accents=_A ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCAmelCase_ ( self ): __A : str = '<s>' __A : str = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_A ) , _A ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_A ) , _A ) def UpperCAmelCase_ ( self ): __A : int = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<unk>' ) self.assertEqual(vocab_keys[1] , '<s>' ) self.assertEqual(vocab_keys[-1] , '<pad>' ) self.assertEqual(len(_A ) , 1002 ) def UpperCAmelCase_ ( self ): self.assertEqual(self.get_tokenizer().vocab_size , 1000 ) def UpperCAmelCase_ ( self ): __A : str = BertGenerationTokenizer(_A , keep_accents=_A ) __A : Dict = tokenizer.tokenize('This is a test' ) self.assertListEqual(_A , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(_A ) , [285, 46, 10, 170, 382] , ) __A : int = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( _A , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.', ] , ) __A : Dict = tokenizer.convert_tokens_to_ids(_A ) self.assertListEqual( _A , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] , ) __A : Optional[int] = tokenizer.convert_ids_to_tokens(_A ) self.assertListEqual( _A , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.', ] , ) @cached_property def UpperCAmelCase_ ( self ): return BertGenerationTokenizer.from_pretrained('google/bert_for_seq_generation_L-24_bbc_encoder' ) @slow def UpperCAmelCase_ ( self ): __A : List[Any] = 'Hello World!' __A : Optional[Any] = [18536, 2260, 101] self.assertListEqual(_A , self.big_tokenizer.encode(_A ) ) @slow def UpperCAmelCase_ ( self ): __A : Dict = ( 'This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will' ' add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth' ) __A : int = [ 871, 419, 358, 946, 991, 2521, 452, 358, 1357, 387, 7751, 3536, 112, 985, 456, 126, 865, 938, 5400, 5734, 458, 1368, 467, 786, 2462, 5246, 1159, 633, 865, 4519, 457, 582, 852, 2557, 427, 916, 508, 405, 34324, 497, 391, 408, 11342, 1244, 385, 100, 938, 985, 456, 574, 362, 12597, 3200, 3129, 1172, ] self.assertListEqual(_A , self.big_tokenizer.encode(_A ) ) @require_torch @slow def UpperCAmelCase_ ( self ): import torch from transformers import BertGenerationConfig, BertGenerationEncoder # Build sequence __A : Tuple = list(self.big_tokenizer.get_vocab().keys() )[:10] __A : List[Any] = ' '.join(_A ) __A : Union[str, Any] = self.big_tokenizer.encode_plus(_A , return_tensors='pt' , return_token_type_ids=_A ) __A : Optional[Any] = self.big_tokenizer.batch_encode_plus( [sequence + ' ' + sequence] , return_tensors='pt' , return_token_type_ids=_A ) __A : int = BertGenerationConfig() __A : List[str] = BertGenerationEncoder(_A ) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**_A ) model(**_A ) @slow def UpperCAmelCase_ ( self ): # fmt: off __A : str = {'input_ids': [[39286, 458, 36335, 2001, 456, 13073, 13266, 455, 113, 7746, 1741, 11157, 391, 13073, 13266, 455, 113, 3967, 35412, 113, 4936, 109, 3870, 2377, 113, 30084, 45720, 458, 134, 17496, 112, 503, 11672, 113, 118, 112, 5665, 13347, 38687, 112, 1496, 31389, 112, 3268, 47264, 134, 962, 112, 16377, 8035, 23130, 430, 12169, 15518, 28592, 458, 146, 41697, 109, 391, 12169, 15518, 16689, 458, 146, 41358, 109, 452, 726, 4034, 111, 763, 35412, 5082, 388, 1903, 111, 9051, 391, 2870, 48918, 1900, 1123, 550, 998, 112, 9586, 15985, 455, 391, 410, 22955, 37636, 114], [448, 17496, 419, 3663, 385, 763, 113, 27533, 2870, 3283, 13043, 1639, 24713, 523, 656, 24013, 18550, 2521, 517, 27014, 21244, 420, 1212, 1465, 391, 927, 4833, 388, 578, 11786, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [484, 2169, 7687, 21932, 18146, 726, 363, 17032, 3391, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=_A , model_name='google/bert_for_seq_generation_L-24_bbc_encoder' , revision='c817d1fd1be2ffa69431227a1fe320544943d4db' , )
280
1
import inspect import os import unittest import torch import accelerate from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_multi_gpu from accelerate.utils import patch_environment class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): __A : str = inspect.getfile(accelerate.test_utils ) __A : Optional[int] = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['scripts', 'test_script.py'] ) __A : List[str] = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ['scripts', 'test_distributed_data_loop.py'] ) __A : List[Any] = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['scripts', 'test_ops.py'] ) @require_multi_gpu def UpperCAmelCase_ ( self ): print(F"""Found {torch.cuda.device_count()} devices.""" ) __A : Tuple = ['torchrun', F"""--nproc_per_node={torch.cuda.device_count()}""", self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(_A , env=os.environ.copy() ) @require_multi_gpu def UpperCAmelCase_ ( self ): print(F"""Found {torch.cuda.device_count()} devices.""" ) __A : Optional[Any] = ['torchrun', F"""--nproc_per_node={torch.cuda.device_count()}""", self.operation_file_path] print(F"""Command: {cmd}""" ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(_A , env=os.environ.copy() ) @require_multi_gpu def UpperCAmelCase_ ( self ): __A : Optional[Any] = ['torchrun', F"""--nproc_per_node={torch.cuda.device_count()}""", inspect.getfile(self.__class__ )] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(_A , env=os.environ.copy() ) @require_multi_gpu def UpperCAmelCase_ ( self ): print(F"""Found {torch.cuda.device_count()} devices, using 2 devices only""" ) __A : List[Any] = ['torchrun', F"""--nproc_per_node={torch.cuda.device_count()}""", self.data_loop_file_path] with patch_environment(omp_num_threads=1 , cuda_visible_devices='0,1' ): execute_subprocess_async(_A , env=os.environ.copy() ) if __name__ == "__main__": UpperCAmelCase : Optional[Any] = Accelerator() UpperCAmelCase : Optional[int] = (accelerator.state.process_index + 2, 10) UpperCAmelCase : List[str] = torch.randint(0, 10, shape).to(accelerator.device) UpperCAmelCase : List[Any] = '''''' UpperCAmelCase : Optional[Any] = accelerator.pad_across_processes(tensor) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0): error_msg += "Padding was not done with the right value (0)." UpperCAmelCase : Tuple = accelerator.pad_across_processes(tensor, pad_first=True) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." UpperCAmelCase : str = accelerator.state.num_processes - accelerator.state.process_index - 1 if not torch.equal(tensora[index:], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[:index] == 0): error_msg += "Padding was not done with the right value (0)." # Raise error at the end to make sure we don't stop at the first failure. if len(error_msg) > 0: raise ValueError(error_msg)
280
import hashlib import unittest from typing import Dict import numpy as np from transformers import ( MODEL_FOR_MASK_GENERATION_MAPPING, TF_MODEL_FOR_MASK_GENERATION_MAPPING, is_vision_available, pipeline, ) from transformers.pipelines import MaskGenerationPipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) if is_vision_available(): from PIL import Image else: class _A: """simple docstring""" @staticmethod def UpperCAmelCase_ ( *_A , **_A ): pass def _SCREAMING_SNAKE_CASE ( a ) -> str: __A : str = hashlib.mda(image.tobytes() ) return m.hexdigest()[:10] def _SCREAMING_SNAKE_CASE ( a ) -> Dict: __A : Dict = np.array(a ) __A : List[Any] = npimg.shape return {"hash": hashimage(a ), "shape": shape} @is_pipeline_test @require_vision @require_torch class _A( unittest.TestCase ): """simple docstring""" UpperCamelCase : str = dict( (list(MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if MODEL_FOR_MASK_GENERATION_MAPPING else []) ) UpperCamelCase : int = dict( (list(TF_MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if TF_MODEL_FOR_MASK_GENERATION_MAPPING else []) ) def UpperCAmelCase_ ( self , _A , _A , _A ): __A : Dict = MaskGenerationPipeline(model=_A , image_processor=_A ) return image_segmenter, [ "./tests/fixtures/tests_samples/COCO/000000039769.png", "./tests/fixtures/tests_samples/COCO/000000039769.png", ] def UpperCAmelCase_ ( self , _A , _A ): pass @require_tf @unittest.skip('Image segmentation not implemented in TF' ) def UpperCAmelCase_ ( self ): pass @slow @require_torch def UpperCAmelCase_ ( self ): __A : Union[str, Any] = pipeline('mask-generation' , model='facebook/sam-vit-huge' ) __A : List[str] = image_segmenter('http://images.cocodataset.org/val2017/000000039769.jpg' , points_per_batch=256 ) # Shortening by hashing __A : List[Any] = [] for i, o in enumerate(outputs['masks'] ): new_outupt += [{"mask": mask_to_test_readable(_A ), "scores": outputs["scores"][i]}] # fmt: off self.assertEqual( nested_simplify(_A , decimals=4 ) , [ {'mask': {'hash': '115ad19f5f', 'shape': (480, 640)}, 'scores': 1.0_4_4_4}, {'mask': {'hash': '6affa964c6', 'shape': (480, 640)}, 'scores': 1.0_2_1}, {'mask': {'hash': 'dfe28a0388', 'shape': (480, 640)}, 'scores': 1.0_1_6_7}, {'mask': {'hash': 'c0a5f4a318', 'shape': (480, 640)}, 'scores': 1.0_1_3_2}, {'mask': {'hash': 'fe8065c197', 'shape': (480, 640)}, 'scores': 1.0_0_5_3}, {'mask': {'hash': 'e2d0b7a0b7', 'shape': (480, 640)}, 'scores': 0.9_9_6_7}, {'mask': {'hash': '453c7844bd', 'shape': (480, 640)}, 'scores': 0.9_9_3}, {'mask': {'hash': '3d44f2926d', 'shape': (480, 640)}, 'scores': 0.9_9_0_9}, {'mask': {'hash': '64033ddc3f', 'shape': (480, 640)}, 'scores': 0.9_8_7_9}, {'mask': {'hash': '801064ff79', 'shape': (480, 640)}, 'scores': 0.9_8_3_4}, {'mask': {'hash': '6172f276ef', 'shape': (480, 640)}, 'scores': 0.9_7_1_6}, {'mask': {'hash': 'b49e60e084', 'shape': (480, 640)}, 'scores': 0.9_6_1_2}, {'mask': {'hash': 'a811e775fd', 'shape': (480, 640)}, 'scores': 0.9_5_9_9}, {'mask': {'hash': 'a6a8ebcf4b', 'shape': (480, 640)}, 'scores': 0.9_5_5_2}, {'mask': {'hash': '9d8257e080', 'shape': (480, 640)}, 'scores': 0.9_5_3_2}, {'mask': {'hash': '32de6454a8', 'shape': (480, 640)}, 'scores': 0.9_5_1_6}, {'mask': {'hash': 'af3d4af2c8', 'shape': (480, 640)}, 'scores': 0.9_4_9_9}, {'mask': {'hash': '3c6db475fb', 'shape': (480, 640)}, 'scores': 0.9_4_8_3}, {'mask': {'hash': 'c290813fb9', 'shape': (480, 640)}, 'scores': 0.9_4_6_4}, {'mask': {'hash': 'b6f0b8f606', 'shape': (480, 640)}, 'scores': 0.9_4_3}, {'mask': {'hash': '92ce16bfdf', 'shape': (480, 640)}, 'scores': 0.9_4_3}, {'mask': {'hash': 'c749b25868', 'shape': (480, 640)}, 'scores': 0.9_4_0_8}, {'mask': {'hash': 'efb6cab859', 'shape': (480, 640)}, 'scores': 0.9_3_3_5}, {'mask': {'hash': '1ff2eafb30', 'shape': (480, 640)}, 'scores': 0.9_3_2_6}, {'mask': {'hash': '788b798e24', 'shape': (480, 640)}, 'scores': 0.9_2_6_2}, {'mask': {'hash': 'abea804f0e', 'shape': (480, 640)}, 'scores': 0.8_9_9_9}, {'mask': {'hash': '7b9e8ddb73', 'shape': (480, 640)}, 'scores': 0.8_9_8_6}, {'mask': {'hash': 'cd24047c8a', 'shape': (480, 640)}, 'scores': 0.8_9_8_4}, {'mask': {'hash': '6943e6bcbd', 'shape': (480, 640)}, 'scores': 0.8_8_7_3}, {'mask': {'hash': 'b5f47c9191', 'shape': (480, 640)}, 'scores': 0.8_8_7_1} ] , ) # fmt: on @require_torch @slow def UpperCAmelCase_ ( self ): __A : Optional[Any] = 'facebook/sam-vit-huge' __A : List[str] = pipeline('mask-generation' , model=_A ) __A : Tuple = image_segmenter( 'http://images.cocodataset.org/val2017/000000039769.jpg' , pred_iou_thresh=1 , points_per_batch=256 ) # Shortening by hashing __A : List[str] = [] for i, o in enumerate(outputs['masks'] ): new_outupt += [{"mask": mask_to_test_readable(_A ), "scores": outputs["scores"][i]}] self.assertEqual( nested_simplify(_A , decimals=4 ) , [ {'mask': {'hash': '115ad19f5f', 'shape': (480, 640)}, 'scores': 1.0_4_4_4}, {'mask': {'hash': '6affa964c6', 'shape': (480, 640)}, 'scores': 1.0_2_1_0}, {'mask': {'hash': 'dfe28a0388', 'shape': (480, 640)}, 'scores': 1.0_1_6_7}, {'mask': {'hash': 'c0a5f4a318', 'shape': (480, 640)}, 'scores': 1.0_1_3_2}, {'mask': {'hash': 'fe8065c197', 'shape': (480, 640)}, 'scores': 1.0_0_5_3}, ] , )
280
1
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re from ..models.auto import AutoProcessor from ..models.vision_encoder_decoder import VisionEncoderDecoderModel from ..utils import is_vision_available from .base import PipelineTool if is_vision_available(): from PIL import Image class _A( snake_case__ ): """simple docstring""" UpperCamelCase : int = '''naver-clova-ix/donut-base-finetuned-docvqa''' UpperCamelCase : Tuple = ( '''This is a tool that answers a question about an document (pdf). It takes an input named `document` which ''' '''should be the document containing the information, as well as a `question` that is the question about the ''' '''document. It returns a text that contains the answer to the question.''' ) UpperCamelCase : Tuple = '''document_qa''' UpperCamelCase : Optional[Any] = AutoProcessor UpperCamelCase : int = VisionEncoderDecoderModel UpperCamelCase : int = ['''image''', '''text'''] UpperCamelCase : Union[str, Any] = ['''text'''] def __init__( self , *_A , **_A ): if not is_vision_available(): raise ValueError('Pillow must be installed to use the DocumentQuestionAnsweringTool.' ) super().__init__(*_A , **_A ) def UpperCAmelCase_ ( self , _A , _A ): __A : List[str] = '<s_docvqa><s_question>{user_input}</s_question><s_answer>' __A : Optional[Any] = task_prompt.replace('{user_input}' , _A ) __A : Optional[int] = self.pre_processor.tokenizer( _A , add_special_tokens=_A , return_tensors='pt' ).input_ids __A : Dict = self.pre_processor(_A , return_tensors='pt' ).pixel_values return {"decoder_input_ids": decoder_input_ids, "pixel_values": pixel_values} def UpperCAmelCase_ ( self , _A ): return self.model.generate( inputs['pixel_values'].to(self.device ) , decoder_input_ids=inputs['decoder_input_ids'].to(self.device ) , max_length=self.model.decoder.config.max_position_embeddings , early_stopping=_A , pad_token_id=self.pre_processor.tokenizer.pad_token_id , eos_token_id=self.pre_processor.tokenizer.eos_token_id , use_cache=_A , num_beams=1 , bad_words_ids=[[self.pre_processor.tokenizer.unk_token_id]] , return_dict_in_generate=_A , ).sequences def UpperCAmelCase_ ( self , _A ): __A : Dict = self.pre_processor.batch_decode(_A )[0] __A : Optional[Any] = sequence.replace(self.pre_processor.tokenizer.eos_token , '' ) __A : Dict = sequence.replace(self.pre_processor.tokenizer.pad_token , '' ) __A : int = re.sub(R'<.*?>' , '' , _A , count=1 ).strip() # remove first task start token __A : Tuple = self.pre_processor.tokenajson(_A ) return sequence["answer"]
280
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import OwlViTImageProcessor, OwlViTProcessor @require_vision class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): __A : List[Any] = tempfile.mkdtemp() # fmt: off __A : List[str] = ['', 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'lo', 'l</w>', 'w</w>', 'r</w>', 't</w>', 'low</w>', 'er</w>', 'lowest</w>', 'newer</w>', 'wider', '<unk>', '<|startoftext|>', '<|endoftext|>'] # fmt: on __A : Union[str, Any] = dict(zip(_A , range(len(_A ) ) ) ) __A : Optional[int] = ['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>', ''] __A : int = {'unk_token': '<unk>'} __A : Optional[int] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) __A : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(_A ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(_A ) ) __A : List[Any] = { 'do_resize': True, 'size': 20, 'do_center_crop': True, 'crop_size': 18, 'do_normalize': True, 'image_mean': [0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3], 'image_std': [0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1], } __A : Optional[int] = os.path.join(self.tmpdirname , _A ) with open(self.image_processor_file , 'w' , encoding='utf-8' ) as fp: json.dump(_A , _A ) def UpperCAmelCase_ ( self , **_A ): return CLIPTokenizer.from_pretrained(self.tmpdirname , pad_token='!' , **_A ) def UpperCAmelCase_ ( self , **_A ): return CLIPTokenizerFast.from_pretrained(self.tmpdirname , pad_token='!' , **_A ) def UpperCAmelCase_ ( self , **_A ): return OwlViTImageProcessor.from_pretrained(self.tmpdirname , **_A ) def UpperCAmelCase_ ( self ): shutil.rmtree(self.tmpdirname ) def UpperCAmelCase_ ( self ): __A : int = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __A : Optional[int] = [Image.fromarray(np.moveaxis(_A , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCAmelCase_ ( self ): __A : List[Any] = self.get_tokenizer() __A : str = self.get_rust_tokenizer() __A : List[str] = self.get_image_processor() __A : Optional[int] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) processor_slow.save_pretrained(self.tmpdirname ) __A : int = OwlViTProcessor.from_pretrained(self.tmpdirname , use_fast=_A ) __A : Optional[Any] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) processor_fast.save_pretrained(self.tmpdirname ) __A : Optional[Any] = OwlViTProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , _A ) self.assertIsInstance(processor_fast.tokenizer , _A ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , _A ) self.assertIsInstance(processor_fast.image_processor , _A ) def UpperCAmelCase_ ( self ): __A : List[str] = OwlViTProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __A : Optional[int] = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) __A : Optional[int] = self.get_image_processor(do_normalize=_A ) __A : Any = OwlViTProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=_A ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , _A ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _A ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.get_image_processor() __A : Optional[Any] = self.get_tokenizer() __A : Union[str, Any] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Union[str, Any] = self.prepare_image_inputs() __A : int = image_processor(_A , return_tensors='np' ) __A : str = processor(images=_A , return_tensors='np' ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1e-2 ) def UpperCAmelCase_ ( self ): __A : str = self.get_image_processor() __A : str = self.get_tokenizer() __A : Tuple = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : str = 'lower newer' __A : str = processor(text=_A , return_tensors='np' ) __A : List[str] = tokenizer(_A , return_tensors='np' ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key][0].tolist() , encoded_processor[key][0].tolist() ) def UpperCAmelCase_ ( self ): __A : int = self.get_image_processor() __A : Optional[int] = self.get_tokenizer() __A : List[str] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Any = 'lower newer' __A : Optional[Any] = self.prepare_image_inputs() __A : List[Any] = processor(text=_A , images=_A ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Any = 'google/owlvit-base-patch32' __A : int = OwlViTProcessor.from_pretrained(_A ) __A : Dict = ['cat', 'nasa badge'] __A : Optional[Any] = processor(text=_A ) __A : Optional[int] = 16 self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (2, seq_length) ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Tuple = 'google/owlvit-base-patch32' __A : Any = OwlViTProcessor.from_pretrained(_A ) __A : Dict = [['cat', 'nasa badge'], ['person']] __A : Dict = processor(text=_A ) __A : Optional[int] = 16 __A : Any = len(_A ) __A : Union[str, Any] = max([len(_A ) for texts in input_texts] ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (batch_size * num_max_text_queries, seq_length) ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : List[Any] = 'google/owlvit-base-patch32' __A : str = OwlViTProcessor.from_pretrained(_A ) __A : Union[str, Any] = ['cat', 'nasa badge'] __A : Tuple = processor(text=_A ) __A : str = 16 __A : int = inputs['input_ids'] __A : List[Any] = [ [49406, 2368, 49407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [49406, 6841, 11301, 49407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (2, seq_length) ) self.assertListEqual(list(input_ids[0] ) , predicted_ids[0] ) self.assertListEqual(list(input_ids[1] ) , predicted_ids[1] ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.get_image_processor() __A : List[str] = self.get_tokenizer() __A : Optional[Any] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Optional[int] = self.prepare_image_inputs() __A : Optional[int] = self.prepare_image_inputs() __A : Optional[int] = processor(images=_A , query_images=_A ) self.assertListEqual(list(inputs.keys() ) , ['query_pixel_values', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.get_image_processor() __A : Union[str, Any] = self.get_tokenizer() __A : str = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Optional[Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __A : Any = processor.batch_decode(_A ) __A : Tuple = tokenizer.batch_decode(_A ) self.assertListEqual(_A , _A )
280
1
import argparse import collections import json from pathlib import Path import requests import torch import yaml from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( MobileViTImageProcessor, MobileViTVaConfig, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, ) from transformers.utils import logging logging.set_verbosity_info() UpperCAmelCase : Dict = logging.get_logger(__name__) def _SCREAMING_SNAKE_CASE ( a ) -> Tuple: print('Loading config file...' ) def flatten_yaml_as_dict(a , a="" , a="." ): __A : Tuple = [] for k, v in d.items(): __A : List[str] = parent_key + sep + k if parent_key else k if isinstance(a , collections.abc.MutableMapping ): items.extend(flatten_yaml_as_dict(a , a , sep=a ).items() ) else: items.append((new_key, v) ) return dict(a ) __A : Optional[int] = argparse.Namespace() with open(a , 'r' ) as yaml_file: try: __A : Dict = yaml.load(a , Loader=yaml.FullLoader ) __A : Union[str, Any] = flatten_yaml_as_dict(a ) for k, v in flat_cfg.items(): setattr(a , a , a ) except yaml.YAMLError as exc: logger.error('Error while loading config file: {}. Error message: {}'.format(a , str(a ) ) ) return config def _SCREAMING_SNAKE_CASE ( a , a ) -> List[str]: __A : Optional[int] = MobileViTVaConfig() __A : Dict = False # dataset if task_name.startswith('imagenet1k_' ): __A : Optional[Any] = 10_00 if int(task_name.strip().split('_' )[-1] ) == 3_84: __A : List[str] = 3_84 else: __A : Optional[Any] = 2_56 __A : int = 'imagenet-1k-id2label.json' elif task_name.startswith('imagenet21k_to_1k_' ): __A : Dict = 2_10_00 if int(task_name.strip().split('_' )[-1] ) == 3_84: __A : List[Any] = 3_84 else: __A : Tuple = 2_56 __A : List[str] = 'imagenet-22k-id2label.json' elif task_name.startswith('ade20k_' ): __A : List[str] = 1_51 __A : Optional[Any] = 5_12 __A : List[Any] = 'ade20k-id2label.json' __A : List[str] = True elif task_name.startswith('voc_' ): __A : Dict = 21 __A : int = 5_12 __A : Tuple = 'pascal-voc-id2label.json' __A : Tuple = True # orig_config __A : Union[str, Any] = load_orig_config_file(a ) assert getattr(a , 'model.classification.name' , -1 ) == "mobilevit_v2", "Invalid model" __A : Optional[Any] = getattr(a , 'model.classification.mitv2.width_multiplier' , 1.0 ) assert ( getattr(a , 'model.classification.mitv2.attn_norm_layer' , -1 ) == "layer_norm_2d" ), "Norm layers other than layer_norm_2d is not supported" __A : Union[str, Any] = getattr(a , 'model.classification.activation.name' , 'swish' ) # config.image_size == getattr(orig_config, 'sampler.bs.crop_size_width', 256) if is_segmentation_model: __A : Union[str, Any] = getattr(a , 'model.segmentation.output_stride' , 16 ) if "_deeplabv3" in task_name: __A : Optional[Any] = getattr(a , 'model.segmentation.deeplabv3.aspp_rates' , [12, 24, 36] ) __A : str = getattr(a , 'model.segmentation.deeplabv3.aspp_out_channels' , 5_12 ) __A : Any = getattr(a , 'model.segmentation.deeplabv3.aspp_dropout' , 0.1 ) # id2label __A : Union[str, Any] = 'huggingface/label-files' __A : Tuple = json.load(open(hf_hub_download(a , a , repo_type='dataset' ) , 'r' ) ) __A : Optional[int] = {int(a ): v for k, v in idalabel.items()} __A : Tuple = idalabel __A : List[str] = {v: k for k, v in idalabel.items()} return config def _SCREAMING_SNAKE_CASE ( a , a , a ) -> Any: __A : List[str] = dct.pop(a ) __A : Optional[int] = val def _SCREAMING_SNAKE_CASE ( a , a=False ) -> Optional[int]: if base_model: __A : str = '' else: __A : Any = 'mobilevitv2.' __A : Union[str, Any] = [] for k in state_dict.keys(): if k[:8] == "encoder.": __A : Any = k[8:] else: __A : Union[str, Any] = k if ".block." in k: __A : Any = k_new.replace('.block.' , '.' ) if ".conv." in k: __A : int = k_new.replace('.conv.' , '.convolution.' ) if ".norm." in k: __A : Optional[int] = k_new.replace('.norm.' , '.normalization.' ) if "conv_1." in k: __A : List[str] = k_new.replace('conv_1.' , F"""{model_prefix}conv_stem.""" ) for i in [1, 2]: if F"""layer_{i}.""" in k: __A : Any = k_new.replace(F"""layer_{i}.""" , F"""{model_prefix}encoder.layer.{i-1}.layer.""" ) if ".exp_1x1." in k: __A : Tuple = k_new.replace('.exp_1x1.' , '.expand_1x1.' ) if ".red_1x1." in k: __A : Tuple = k_new.replace('.red_1x1.' , '.reduce_1x1.' ) for i in [3, 4, 5]: if F"""layer_{i}.0.""" in k: __A : List[Any] = k_new.replace(F"""layer_{i}.0.""" , F"""{model_prefix}encoder.layer.{i-1}.downsampling_layer.""" ) if F"""layer_{i}.1.local_rep.0.""" in k: __A : int = k_new.replace(F"""layer_{i}.1.local_rep.0.""" , F"""{model_prefix}encoder.layer.{i-1}.conv_kxk.""" ) if F"""layer_{i}.1.local_rep.1.""" in k: __A : Optional[Any] = k_new.replace(F"""layer_{i}.1.local_rep.1.""" , F"""{model_prefix}encoder.layer.{i-1}.conv_1x1.""" ) for i in [3, 4, 5]: if i == 3: __A : List[str] = [0, 1] elif i == 4: __A : Dict = [0, 1, 2, 3] elif i == 5: __A : str = [0, 1, 2] for j in j_in: if F"""layer_{i}.1.global_rep.{j}.""" in k: __A : Optional[int] = k_new.replace( F"""layer_{i}.1.global_rep.{j}.""" , F"""{model_prefix}encoder.layer.{i-1}.transformer.layer.{j}.""" ) if F"""layer_{i}.1.global_rep.{j+1}.""" in k: __A : Union[str, Any] = k_new.replace( F"""layer_{i}.1.global_rep.{j+1}.""" , F"""{model_prefix}encoder.layer.{i-1}.layernorm.""" ) if F"""layer_{i}.1.conv_proj.""" in k: __A : Optional[Any] = k_new.replace(F"""layer_{i}.1.conv_proj.""" , F"""{model_prefix}encoder.layer.{i-1}.conv_projection.""" ) if "pre_norm_attn.0." in k: __A : Tuple = k_new.replace('pre_norm_attn.0.' , 'layernorm_before.' ) if "pre_norm_attn.1." in k: __A : Dict = k_new.replace('pre_norm_attn.1.' , 'attention.' ) if "pre_norm_ffn.0." in k: __A : int = k_new.replace('pre_norm_ffn.0.' , 'layernorm_after.' ) if "pre_norm_ffn.1." in k: __A : int = k_new.replace('pre_norm_ffn.1.' , 'ffn.conv1.' ) if "pre_norm_ffn.3." in k: __A : List[str] = k_new.replace('pre_norm_ffn.3.' , 'ffn.conv2.' ) if "classifier.1." in k: __A : str = k_new.replace('classifier.1.' , 'classifier.' ) if "seg_head." in k: __A : str = k_new.replace('seg_head.' , 'segmentation_head.' ) if ".aspp_layer." in k: __A : List[Any] = k_new.replace('.aspp_layer.' , '.' ) if ".aspp_pool." in k: __A : Optional[int] = k_new.replace('.aspp_pool.' , '.' ) rename_keys.append((k, k_new) ) return rename_keys def _SCREAMING_SNAKE_CASE ( a ) -> Optional[Any]: __A : Optional[Any] = [] for k in state_dict.keys(): if k.startswith('seg_head.aux_head.' ): keys_to_ignore.append(a ) for k in keys_to_ignore: state_dict.pop(a , a ) def _SCREAMING_SNAKE_CASE ( ) -> List[str]: __A : Union[str, Any] = 'http://images.cocodataset.org/val2017/000000039769.jpg' # url = "https://cdn.britannica.com/86/141086-050-9D7C75EE/Gulfstream-G450-business-jet-passengers.jpg" __A : List[Any] = Image.open(requests.get(a , stream=a ).raw ) return im @torch.no_grad() def _SCREAMING_SNAKE_CASE ( a , a , a , a ) -> Union[str, Any]: __A : int = get_mobilevitva_config(a , a ) # load original state_dict __A : Tuple = torch.load(a , map_location='cpu' ) # load huggingface model if task_name.startswith('ade20k_' ) or task_name.startswith('voc_' ): __A : Optional[int] = MobileViTVaForSemanticSegmentation(a ).eval() __A : Dict = False else: __A : Optional[int] = MobileViTVaForImageClassification(a ).eval() __A : Dict = False # remove and rename some keys of load the original model __A : Dict = checkpoint remove_unused_keys(a ) __A : int = create_rename_keys(a , base_model=a ) for rename_key_src, rename_key_dest in rename_keys: rename_key(a , a , a ) # load modified state_dict model.load_state_dict(a ) # Check outputs on an image, prepared by MobileViTImageProcessor __A : List[Any] = MobileViTImageProcessor(crop_size=config.image_size , size=config.image_size + 32 ) __A : Tuple = image_processor(images=prepare_img() , return_tensors='pt' ) __A : str = model(**a ) # verify classification model if task_name.startswith('imagenet' ): __A : Optional[int] = outputs.logits __A : int = logits.argmax(-1 ).item() print('Predicted class:' , model.config.idalabel[predicted_class_idx] ) if task_name.startswith('imagenet1k_256' ) and config.width_multiplier == 1.0: # expected_logits for base variant __A : List[Any] = torch.tensor([-1.6_3_3_6e0_0, -7.3_2_0_4e-0_2, -5.1_8_8_3e-0_1] ) assert torch.allclose(logits[0, :3] , a , atol=1e-4 ) Path(a ).mkdir(exist_ok=a ) print(F"""Saving model {task_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(a ) print(F"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(a ) if __name__ == "__main__": UpperCAmelCase : Any = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--task''', default='''imagenet1k_256''', type=str, help=( '''Name of the task for which the MobileViTV2 model you\'d like to convert is trained on . ''' ''' Classification (ImageNet-1k) - MobileViTV2 (256x256) : imagenet1k_256 - MobileViTV2 (Trained on 256x256 and Finetuned on 384x384) : imagenet1k_384 - MobileViTV2 (Trained on ImageNet-21k and Finetuned on ImageNet-1k 256x256) : imagenet21k_to_1k_256 - MobileViTV2 (Trained on ImageNet-21k, Finetuned on ImageNet-1k 256x256, and Finetuned on ImageNet-1k 384x384) : imagenet21k_to_1k_384 Segmentation - ADE20K Dataset : ade20k_deeplabv3 - Pascal VOC 2012 Dataset: voc_deeplabv3 ''' ), choices=[ '''imagenet1k_256''', '''imagenet1k_384''', '''imagenet21k_to_1k_256''', '''imagenet21k_to_1k_384''', '''ade20k_deeplabv3''', '''voc_deeplabv3''', ], ) parser.add_argument( '''--orig_checkpoint_path''', required=True, type=str, help='''Path to the original state dict (.pt file).''' ) parser.add_argument('''--orig_config_path''', required=True, type=str, help='''Path to the original config file.''') parser.add_argument( '''--pytorch_dump_folder_path''', required=True, type=str, help='''Path to the output PyTorch model directory.''' ) UpperCAmelCase : Optional[Any] = parser.parse_args() convert_mobilevitva_checkpoint( args.task, args.orig_checkpoint_path, args.orig_config_path, args.pytorch_dump_folder_path )
280
import math def _SCREAMING_SNAKE_CASE ( a ) -> list[int]: __A : List[str] = [] __A : Any = 2 __A : Union[str, Any] = int(math.sqrt(a ) ) # Size of every segment __A : Any = [True] * (end + 1) __A : List[Any] = [] while start <= end: if temp[start] is True: in_prime.append(a ) for i in range(start * start , end + 1 , a ): __A : Optional[int] = False start += 1 prime += in_prime __A : Any = end + 1 __A : Any = min(2 * end , a ) while low <= n: __A : List[Any] = [True] * (high - low + 1) for each in in_prime: __A : List[str] = math.floor(low / each ) * each if t < low: t += each for j in range(a , high + 1 , a ): __A : Optional[int] = False for j in range(len(a ) ): if temp[j] is True: prime.append(j + low ) __A : Optional[int] = high + 1 __A : Tuple = min(high + end , a ) return prime print(sieve(10**6))
280
1