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 typing import Optional import torch import torch.utils.checkpoint from torch import Tensor, nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import ( BackboneOutput, BaseModelOutputWithNoAttention, BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention, ) from ...modeling_utils import PreTrainedModel from ...utils import ( add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings, ) from ...utils.backbone_utils import BackboneMixin from .configuration_resnet import ResNetConfig lowerCamelCase__ = logging.get_logger(__name__) # General docstring lowerCamelCase__ = """ResNetConfig""" # Base docstring lowerCamelCase__ = """microsoft/resnet-50""" lowerCamelCase__ = [1, 2048, 7, 7] # Image classification docstring lowerCamelCase__ = """microsoft/resnet-50""" lowerCamelCase__ = """tiger cat""" lowerCamelCase__ = [ """microsoft/resnet-50""", # See all resnet models at https://huggingface.co/models?filter=resnet ] class SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : Any , __lowercase : int , __lowercase : int , __lowercase : int = 3 , __lowercase : int = 1 , __lowercase : str = "relu" ): '''simple docstring''' super().__init__() __a = nn.Convad( __lowercase , __lowercase , kernel_size=__lowercase , stride=__lowercase , padding=kernel_size // 2 , bias=__lowercase ) __a = nn.BatchNormad(__lowercase ) __a = ACTaFN[activation] if activation is not None else nn.Identity() def UpperCamelCase_ ( self : Tuple , __lowercase : Tensor ): '''simple docstring''' __a = self.convolution(__lowercase ) __a = self.normalization(__lowercase ) __a = self.activation(__lowercase ) return hidden_state class SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : Union[str, Any] , __lowercase : ResNetConfig ): '''simple docstring''' super().__init__() __a = ResNetConvLayer( config.num_channels , config.embedding_size , kernel_size=7 , stride=2 , activation=config.hidden_act ) __a = nn.MaxPoolad(kernel_size=3 , stride=2 , padding=1 ) __a = config.num_channels def UpperCamelCase_ ( self : Optional[Any] , __lowercase : Tensor ): '''simple docstring''' __a = pixel_values.shape[1] if num_channels != self.num_channels: raise ValueError( """Make sure that the channel dimension of the pixel values match with the one set in the configuration.""" ) __a = self.embedder(__lowercase ) __a = self.pooler(__lowercase ) return embedding class SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : Dict , __lowercase : int , __lowercase : int , __lowercase : int = 2 ): '''simple docstring''' super().__init__() __a = nn.Convad(__lowercase , __lowercase , kernel_size=1 , stride=__lowercase , bias=__lowercase ) __a = nn.BatchNormad(__lowercase ) def UpperCamelCase_ ( self : Any , __lowercase : Tensor ): '''simple docstring''' __a = self.convolution(__lowercase ) __a = self.normalization(__lowercase ) return hidden_state class SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : Any , __lowercase : int , __lowercase : int , __lowercase : int = 1 , __lowercase : str = "relu" ): '''simple docstring''' super().__init__() __a = in_channels != out_channels or stride != 1 __a = ( ResNetShortCut(__lowercase , __lowercase , stride=__lowercase ) if should_apply_shortcut else nn.Identity() ) __a = nn.Sequential( ResNetConvLayer(__lowercase , __lowercase , stride=__lowercase ) , ResNetConvLayer(__lowercase , __lowercase , activation=__lowercase ) , ) __a = ACTaFN[activation] def UpperCamelCase_ ( self : Optional[Any] , __lowercase : Any ): '''simple docstring''' __a = hidden_state __a = self.layer(__lowercase ) __a = self.shortcut(__lowercase ) hidden_state += residual __a = self.activation(__lowercase ) return hidden_state class SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : List[Any] , __lowercase : int , __lowercase : int , __lowercase : int = 1 , __lowercase : str = "relu" , __lowercase : int = 4 ): '''simple docstring''' super().__init__() __a = in_channels != out_channels or stride != 1 __a = out_channels // reduction __a = ( ResNetShortCut(__lowercase , __lowercase , stride=__lowercase ) if should_apply_shortcut else nn.Identity() ) __a = nn.Sequential( ResNetConvLayer(__lowercase , __lowercase , kernel_size=1 ) , ResNetConvLayer(__lowercase , __lowercase , stride=__lowercase ) , ResNetConvLayer(__lowercase , __lowercase , kernel_size=1 , activation=__lowercase ) , ) __a = ACTaFN[activation] def UpperCamelCase_ ( self : List[str] , __lowercase : Dict ): '''simple docstring''' __a = hidden_state __a = self.layer(__lowercase ) __a = self.shortcut(__lowercase ) hidden_state += residual __a = self.activation(__lowercase ) return hidden_state class SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : Optional[Any] , __lowercase : ResNetConfig , __lowercase : int , __lowercase : int , __lowercase : int = 2 , __lowercase : int = 2 , ): '''simple docstring''' super().__init__() __a = ResNetBottleNeckLayer if config.layer_type == """bottleneck""" else ResNetBasicLayer __a = nn.Sequential( # downsampling is done in the first layer with stride of 2 layer(__lowercase , __lowercase , stride=__lowercase , activation=config.hidden_act ) , *[layer(__lowercase , __lowercase , activation=config.hidden_act ) for _ in range(depth - 1 )] , ) def UpperCamelCase_ ( self : str , __lowercase : Tensor ): '''simple docstring''' __a = input for layer in self.layers: __a = layer(__lowercase ) return hidden_state class SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : List[Any] , __lowercase : ResNetConfig ): '''simple docstring''' super().__init__() __a = nn.ModuleList([] ) # based on `downsample_in_first_stage` the first layer of the first stage may or may not downsample the input self.stages.append( ResNetStage( __lowercase , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , ) ) __a = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for (in_channels, out_channels), depth in zip(__lowercase , config.depths[1:] ): self.stages.append(ResNetStage(__lowercase , __lowercase , __lowercase , depth=__lowercase ) ) def UpperCamelCase_ ( self : Optional[Any] , __lowercase : Tensor , __lowercase : bool = False , __lowercase : bool = True ): '''simple docstring''' __a = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: __a = hidden_states + (hidden_state,) __a = stage_module(__lowercase ) if output_hidden_states: __a = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return BaseModelOutputWithNoAttention( last_hidden_state=__lowercase , hidden_states=__lowercase , ) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : List[Any] =ResNetConfig __lowerCamelCase : Union[str, Any] ='resnet' __lowerCamelCase : Dict ='pixel_values' __lowerCamelCase : Dict =True def UpperCamelCase_ ( self : int , __lowercase : str ): '''simple docstring''' if isinstance(__lowercase , nn.Convad ): nn.init.kaiming_normal_(module.weight , mode="""fan_out""" , nonlinearity="""relu""" ) elif isinstance(__lowercase , (nn.BatchNormad, nn.GroupNorm) ): nn.init.constant_(module.weight , 1 ) nn.init.constant_(module.bias , 0 ) def UpperCamelCase_ ( self : Dict , __lowercase : int , __lowercase : List[str]=False ): '''simple docstring''' if isinstance(__lowercase , __lowercase ): __a = value lowerCamelCase__ = r""" This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`ResNetConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. """ lowerCamelCase__ = r""" Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`ConvNextImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. """ @add_start_docstrings( 'The bare ResNet model outputting raw features without any specific head on top.' , lowerCamelCase__ , ) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): def __init__( self : Optional[Any] , __lowercase : Union[str, Any] ): '''simple docstring''' super().__init__(__lowercase ) __a = config __a = ResNetEmbeddings(__lowercase ) __a = ResNetEncoder(__lowercase ) __a = nn.AdaptiveAvgPoolad((1, 1) ) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(__lowercase ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=__lowercase , config_class=_CONFIG_FOR_DOC , modality="""vision""" , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def UpperCamelCase_ ( self : List[str] , __lowercase : Tensor , __lowercase : Optional[bool] = None , __lowercase : Optional[bool] = None ): '''simple docstring''' __a = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __a = return_dict if return_dict is not None else self.config.use_return_dict __a = self.embedder(__lowercase ) __a = self.encoder( __lowercase , output_hidden_states=__lowercase , return_dict=__lowercase ) __a = encoder_outputs[0] __a = self.pooler(__lowercase ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return BaseModelOutputWithPoolingAndNoAttention( last_hidden_state=__lowercase , pooler_output=__lowercase , hidden_states=encoder_outputs.hidden_states , ) @add_start_docstrings( '\n ResNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n ' , lowerCamelCase__ , ) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): def __init__( self : List[Any] , __lowercase : Dict ): '''simple docstring''' super().__init__(__lowercase ) __a = config.num_labels __a = ResNetModel(__lowercase ) # classification head __a = nn.Sequential( nn.Flatten() , nn.Linear(config.hidden_sizes[-1] , config.num_labels ) if config.num_labels > 0 else nn.Identity() , ) # initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(__lowercase ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=__lowercase , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def UpperCamelCase_ ( self : List[Any] , __lowercase : Optional[torch.FloatTensor] = None , __lowercase : Optional[torch.LongTensor] = None , __lowercase : Optional[bool] = None , __lowercase : Optional[bool] = None , ): '''simple docstring''' __a = return_dict if return_dict is not None else self.config.use_return_dict __a = self.resnet(__lowercase , output_hidden_states=__lowercase , return_dict=__lowercase ) __a = outputs.pooler_output if return_dict else outputs[1] __a = self.classifier(__lowercase ) __a = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: __a = """regression""" elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): __a = """single_label_classification""" else: __a = """multi_label_classification""" if self.config.problem_type == "regression": __a = MSELoss() if self.num_labels == 1: __a = loss_fct(logits.squeeze() , labels.squeeze() ) else: __a = loss_fct(__lowercase , __lowercase ) elif self.config.problem_type == "single_label_classification": __a = CrossEntropyLoss() __a = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": __a = BCEWithLogitsLoss() __a = loss_fct(__lowercase , __lowercase ) if not return_dict: __a = (logits,) + outputs[2:] return (loss,) + output if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=__lowercase , logits=__lowercase , hidden_states=outputs.hidden_states ) @add_start_docstrings( '\n ResNet backbone, to be used with frameworks like DETR and MaskFormer.\n ' , lowerCamelCase__ , ) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ , lowerCamelCase__ ): def __init__( self : str , __lowercase : int ): '''simple docstring''' super().__init__(__lowercase ) super()._init_backbone(__lowercase ) __a = [config.embedding_size] + config.hidden_sizes __a = ResNetEmbeddings(__lowercase ) __a = ResNetEncoder(__lowercase ) # initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(__lowercase ) @replace_return_docstrings(output_type=__lowercase , config_class=_CONFIG_FOR_DOC ) def UpperCamelCase_ ( self : Tuple , __lowercase : Tensor , __lowercase : Optional[bool] = None , __lowercase : Optional[bool] = None ): '''simple docstring''' __a = return_dict if return_dict is not None else self.config.use_return_dict __a = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __a = self.embedder(__lowercase ) __a = self.encoder(__lowercase , output_hidden_states=__lowercase , return_dict=__lowercase ) __a = outputs.hidden_states __a = () for idx, stage in enumerate(self.stage_names ): if stage in self.out_features: feature_maps += (hidden_states[idx],) if not return_dict: __a = (feature_maps,) if output_hidden_states: output += (outputs.hidden_states,) return output return BackboneOutput( feature_maps=__lowercase , hidden_states=outputs.hidden_states if output_hidden_states else None , attentions=__lowercase , )
302
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 lowerCamelCase__ = logging.get_logger(__name__) @add_end_docstrings(lowerCamelCase__ ) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): def __init__( self : Optional[int] , **__lowercase : Dict ): '''simple docstring''' super().__init__(**__lowercase ) if self.framework != "pt": raise ValueError(F"The {self.__class__} is only available in PyTorch." ) # No specific FOR_XXX available yet def __call__( self : str , __lowercase : Union[np.ndarray, bytes, str] , **__lowercase : int ): '''simple docstring''' return super().__call__(__lowercase , **__lowercase ) def UpperCamelCase_ ( self : List[Any] , **__lowercase : Union[str, Any] ): '''simple docstring''' __a = {} if "candidate_labels" in kwargs: __a = kwargs["""candidate_labels"""] if "hypothesis_template" in kwargs: __a = kwargs["""hypothesis_template"""] return preprocess_params, {}, {} def UpperCamelCase_ ( self : int , __lowercase : Dict , __lowercase : Dict=None , __lowercase : str="This is a sound of {}." ): '''simple docstring''' if isinstance(__lowercase , __lowercase ): if audio.startswith("""http://""" ) or audio.startswith("""https://""" ): # We need to actually check for a real protocol, otherwise it's impossible to use a local file # like http_huggingface_co.png __a = requests.get(__lowercase ).content else: with open(__lowercase , """rb""" ) as f: __a = f.read() if isinstance(__lowercase , __lowercase ): __a = ffmpeg_read(__lowercase , self.feature_extractor.sampling_rate ) if not isinstance(__lowercase , np.ndarray ): raise ValueError("""We expect a numpy ndarray as input""" ) if len(audio.shape ) != 1: raise ValueError("""We expect a single channel audio input for ZeroShotAudioClassificationPipeline""" ) __a = self.feature_extractor( [audio] , sampling_rate=self.feature_extractor.sampling_rate , return_tensors="""pt""" ) __a = candidate_labels __a = [hypothesis_template.format(__lowercase ) for x in candidate_labels] __a = self.tokenizer(__lowercase , return_tensors=self.framework , padding=__lowercase ) __a = [text_inputs] return inputs def UpperCamelCase_ ( self : Any , __lowercase : Any ): '''simple docstring''' __a = model_inputs.pop("""candidate_labels""" ) __a = model_inputs.pop("""text_inputs""" ) if isinstance(text_inputs[0] , __lowercase ): __a = text_inputs[0] else: # Batching case. __a = text_inputs[0][0] __a = self.model(**__lowercase , **__lowercase ) __a = { """candidate_labels""": candidate_labels, """logits""": outputs.logits_per_audio, } return model_outputs def UpperCamelCase_ ( self : Optional[Any] , __lowercase : Dict ): '''simple docstring''' __a = model_outputs.pop("""candidate_labels""" ) __a = model_outputs["""logits"""][0] if self.framework == "pt": __a = logits.softmax(dim=0 ) __a = probs.tolist() else: raise ValueError("""`tf` framework not supported.""" ) __a = [ {"""score""": score, """label""": candidate_label} for score, candidate_label in sorted(zip(__lowercase , __lowercase ) , key=lambda __lowercase : -x[0] ) ] return result
302
1
def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : str ): """simple docstring""" __a = [0] * len(_SCREAMING_SNAKE_CASE ) for i in range(1 , len(_SCREAMING_SNAKE_CASE ) ): # use last results for better performance - dynamic programming __a = prefix_result[i - 1] while j > 0 and input_string[i] != input_string[j]: __a = prefix_result[j - 1] if input_string[i] == input_string[j]: j += 1 __a = j return prefix_result def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : str ): """simple docstring""" return max(prefix_function(_SCREAMING_SNAKE_CASE ) ) if __name__ == "__main__": import doctest doctest.testmod()
302
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, ChannelDimension, ImageInput, PILImageResampling, is_batched, to_numpy_array, valid_images, ) from ...utils import TensorType, logging lowerCamelCase__ = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : Dict =['pixel_values'] def __init__( self : Optional[int] , __lowercase : bool = True , __lowercase : Optional[Dict[str, int]] = None , __lowercase : PILImageResampling = PILImageResampling.BICUBIC , __lowercase : bool = True , __lowercase : bool = True , __lowercase : Union[int, float] = 1 / 255 , __lowercase : Dict[str, int] = None , __lowercase : bool = True , __lowercase : Optional[Union[float, List[float]]] = None , __lowercase : Optional[Union[float, List[float]]] = None , **__lowercase : Dict , ): '''simple docstring''' super().__init__(**__lowercase ) __a = size if size is not None else {"""height""": 224, """width""": 224} __a = get_size_dict(__lowercase ) __a = crop_size if crop_size is not None else {"""height""": 224, """width""": 224} __a = get_size_dict(__lowercase , default_to_square=__lowercase , param_name="""crop_size""" ) __a = do_resize __a = do_rescale __a = do_normalize __a = do_center_crop __a = crop_size __a = size __a = resample __a = rescale_factor __a = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN __a = image_std if image_std is not None else IMAGENET_DEFAULT_STD def UpperCamelCase_ ( self : Any , __lowercase : np.ndarray , __lowercase : Dict[str, int] , __lowercase : PILImageResampling = PILImageResampling.BILINEAR , __lowercase : Optional[Union[str, ChannelDimension]] = None , **__lowercase : Optional[Any] , ): '''simple docstring''' __a = get_size_dict(__lowercase ) if "shortest_edge" in size: __a = get_resize_output_image_size(__lowercase , size=size["""shortest_edge"""] , default_to_square=__lowercase ) # size = get_resize_output_image_size(image, size["shortest_edge"], size["longest_edge"]) elif "height" in size and "width" in size: __a = (size["""height"""], size["""width"""]) else: raise ValueError(F"Size must contain 'height' and 'width' keys or 'shortest_edge' key. Got {size.keys()}" ) return resize(__lowercase , size=__lowercase , resample=__lowercase , data_format=__lowercase , **__lowercase ) def UpperCamelCase_ ( self : str , __lowercase : np.ndarray , __lowercase : Dict[str, int] , __lowercase : Optional[Union[str, ChannelDimension]] = None , **__lowercase : List[Any] , ): '''simple docstring''' __a = get_size_dict(__lowercase ) if "height" not in size or "width" not in size: raise ValueError(F"The `size` parameter must contain the keys (height, width). Got {size.keys()}" ) return center_crop(__lowercase , size=(size["""height"""], size["""width"""]) , data_format=__lowercase , **__lowercase ) def UpperCamelCase_ ( self : Any , __lowercase : np.ndarray , __lowercase : float , __lowercase : Optional[Union[str, ChannelDimension]] = None , **__lowercase : str ): '''simple docstring''' return rescale(__lowercase , scale=__lowercase , data_format=__lowercase , **__lowercase ) def UpperCamelCase_ ( self : List[Any] , __lowercase : np.ndarray , __lowercase : Union[float, List[float]] , __lowercase : Union[float, List[float]] , __lowercase : Optional[Union[str, ChannelDimension]] = None , **__lowercase : Any , ): '''simple docstring''' return normalize(__lowercase , mean=__lowercase , std=__lowercase , data_format=__lowercase , **__lowercase ) def UpperCamelCase_ ( self : Tuple , __lowercase : ImageInput , __lowercase : Optional[bool] = None , __lowercase : Dict[str, int] = None , __lowercase : PILImageResampling = None , __lowercase : bool = None , __lowercase : int = None , __lowercase : Optional[bool] = None , __lowercase : Optional[float] = None , __lowercase : Optional[bool] = None , __lowercase : Optional[Union[float, List[float]]] = None , __lowercase : Optional[Union[float, List[float]]] = None , __lowercase : Optional[Union[str, TensorType]] = None , __lowercase : Union[str, ChannelDimension] = ChannelDimension.FIRST , **__lowercase : List[Any] , ): '''simple docstring''' __a = do_resize if do_resize is not None else self.do_resize __a = do_rescale if do_rescale is not None else self.do_rescale __a = do_normalize if do_normalize is not None else self.do_normalize __a = do_center_crop if do_center_crop is not None else self.do_center_crop __a = crop_size if crop_size is not None else self.crop_size __a = get_size_dict(__lowercase , param_name="""crop_size""" , default_to_square=__lowercase ) __a = resample if resample is not None else self.resample __a = rescale_factor if rescale_factor is not None else self.rescale_factor __a = image_mean if image_mean is not None else self.image_mean __a = image_std if image_std is not None else self.image_std __a = size if size is not None else self.size __a = get_size_dict(__lowercase ) if not is_batched(__lowercase ): __a = [images] if not valid_images(__lowercase ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None: raise ValueError("""Size must be specified if do_resize is True.""" ) if do_center_crop and crop_size is None: raise ValueError("""Crop size must be specified if do_center_crop is True.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) # All transformations expect numpy arrays. __a = [to_numpy_array(__lowercase ) for image in images] if do_resize: __a = [self.resize(image=__lowercase , size=__lowercase , resample=__lowercase ) for image in images] if do_center_crop: __a = [self.center_crop(image=__lowercase , size=__lowercase ) for image in images] if do_rescale: __a = [self.rescale(image=__lowercase , scale=__lowercase ) for image in images] if do_normalize: __a = [self.normalize(image=__lowercase , mean=__lowercase , std=__lowercase ) for image in images] __a = [to_channel_dimension_format(__lowercase , __lowercase ) for image in images] __a = {"""pixel_values""": images} return BatchFeature(data=__lowercase , tensor_type=__lowercase )
302
1
import json import os import shutil import tempfile import unittest import numpy as np from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer from transformers.testing_utils import require_tokenizers, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor @require_tokenizers @require_vision class SCREAMING_SNAKE_CASE ( unittest.TestCase ): def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' __a = tempfile.mkdtemp() # fmt: off __a = ["""[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest"""] # fmt: on __a = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) __a = { """do_resize""": True, """size""": {"""height""": 18, """width""": 18}, """do_normalize""": True, """image_mean""": [0.5, 0.5, 0.5], """image_std""": [0.5, 0.5, 0.5], } __a = os.path.join(self.tmpdirname , __lowercase ) with open(self.image_processor_file , """w""" , encoding="""utf-8""" ) as fp: json.dump(__lowercase , __lowercase ) def UpperCamelCase_ ( self : Dict , **__lowercase : List[Any] ): '''simple docstring''' return BertTokenizer.from_pretrained(self.tmpdirname , **__lowercase ) def UpperCamelCase_ ( self : Optional[int] , **__lowercase : str ): '''simple docstring''' return ViTImageProcessor.from_pretrained(self.tmpdirname , **__lowercase ) def UpperCamelCase_ ( self : int ): '''simple docstring''' shutil.rmtree(self.tmpdirname ) def UpperCamelCase_ ( self : Optional[int] ): '''simple docstring''' __a = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __a = [Image.fromarray(np.moveaxis(__lowercase , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCamelCase_ ( self : str ): '''simple docstring''' __a = self.get_tokenizer() __a = self.get_image_processor() __a = VisionTextDualEncoderProcessor(tokenizer=__lowercase , image_processor=__lowercase ) processor.save_pretrained(self.tmpdirname ) __a = VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , __lowercase ) def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' __a = VisionTextDualEncoderProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __a = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) __a = self.get_image_processor(do_normalize=__lowercase , padding_value=1.0 ) __a = VisionTextDualEncoderProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=__lowercase , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __lowercase ) def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' __a = self.get_image_processor() __a = self.get_tokenizer() __a = VisionTextDualEncoderProcessor(tokenizer=__lowercase , image_processor=__lowercase ) __a = self.prepare_image_inputs() __a = image_processor(__lowercase , return_tensors="""np""" ) __a = processor(images=__lowercase , 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 : Union[str, Any] ): '''simple docstring''' __a = self.get_image_processor() __a = self.get_tokenizer() __a = VisionTextDualEncoderProcessor(tokenizer=__lowercase , image_processor=__lowercase ) __a = """lower newer""" __a = processor(text=__lowercase ) __a = tokenizer(__lowercase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def UpperCamelCase_ ( self : Dict ): '''simple docstring''' __a = self.get_image_processor() __a = self.get_tokenizer() __a = VisionTextDualEncoderProcessor(tokenizer=__lowercase , image_processor=__lowercase ) __a = """lower newer""" __a = self.prepare_image_inputs() __a = processor(text=__lowercase , images=__lowercase ) self.assertListEqual(list(inputs.keys() ) , ["""input_ids""", """token_type_ids""", """attention_mask""", """pixel_values"""] ) # test if it raises when no input is passed with self.assertRaises(__lowercase ): processor() def UpperCamelCase_ ( self : str ): '''simple docstring''' __a = self.get_image_processor() __a = self.get_tokenizer() __a = VisionTextDualEncoderProcessor(tokenizer=__lowercase , image_processor=__lowercase ) __a = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __a = processor.batch_decode(__lowercase ) __a = tokenizer.batch_decode(__lowercase ) self.assertListEqual(__lowercase , __lowercase ) def UpperCamelCase_ ( self : int ): '''simple docstring''' __a = self.get_image_processor() __a = self.get_tokenizer() __a = VisionTextDualEncoderProcessor(tokenizer=__lowercase , image_processor=__lowercase ) __a = """lower newer""" __a = self.prepare_image_inputs() __a = processor(text=__lowercase , images=__lowercase ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
302
import tempfile import unittest from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from transformers.testing_utils import ( is_torch_available, require_optimum, require_torch, slow, ) if is_torch_available(): import torch @require_torch @require_optimum @slow class SCREAMING_SNAKE_CASE ( unittest.TestCase ): def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' __a = """hf-internal-testing/tiny-random-t5""" __a = AutoTokenizer.from_pretrained(__lowercase ) __a = AutoModelForSeqaSeqLM.from_pretrained(__lowercase ) __a = tokenizer("""This is me""" , return_tensors="""pt""" ) __a = model.to_bettertransformer() self.assertTrue(any("""BetterTransformer""" in mod.__class__.__name__ for _, mod in model.named_modules() ) ) __a = model.generate(**__lowercase ) __a = model.reverse_bettertransformer() self.assertFalse(any("""BetterTransformer""" in mod.__class__.__name__ for _, mod in model.named_modules() ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(__lowercase ) __a = AutoModelForSeqaSeqLM.from_pretrained(__lowercase ) self.assertFalse( any("""BetterTransformer""" in mod.__class__.__name__ for _, mod in model_reloaded.named_modules() ) ) __a = model_reloaded.generate(**__lowercase ) self.assertTrue(torch.allclose(__lowercase , __lowercase ) ) def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' __a = """hf-internal-testing/tiny-random-t5""" __a = AutoModelForSeqaSeqLM.from_pretrained(__lowercase ) __a = model.to_bettertransformer() with tempfile.TemporaryDirectory() as tmpdirname: with self.assertRaises(__lowercase ): model.save_pretrained(__lowercase ) __a = model.reverse_bettertransformer() model.save_pretrained(__lowercase )
302
1
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_electra import ElectraTokenizer lowerCamelCase__ = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""} lowerCamelCase__ = { """vocab_file""": { """google/electra-small-generator""": ( """https://huggingface.co/google/electra-small-generator/resolve/main/vocab.txt""" ), """google/electra-base-generator""": """https://huggingface.co/google/electra-base-generator/resolve/main/vocab.txt""", """google/electra-large-generator""": ( """https://huggingface.co/google/electra-large-generator/resolve/main/vocab.txt""" ), """google/electra-small-discriminator""": ( """https://huggingface.co/google/electra-small-discriminator/resolve/main/vocab.txt""" ), """google/electra-base-discriminator""": ( """https://huggingface.co/google/electra-base-discriminator/resolve/main/vocab.txt""" ), """google/electra-large-discriminator""": ( """https://huggingface.co/google/electra-large-discriminator/resolve/main/vocab.txt""" ), }, """tokenizer_file""": { """google/electra-small-generator""": ( """https://huggingface.co/google/electra-small-generator/resolve/main/tokenizer.json""" ), """google/electra-base-generator""": ( """https://huggingface.co/google/electra-base-generator/resolve/main/tokenizer.json""" ), """google/electra-large-generator""": ( """https://huggingface.co/google/electra-large-generator/resolve/main/tokenizer.json""" ), """google/electra-small-discriminator""": ( """https://huggingface.co/google/electra-small-discriminator/resolve/main/tokenizer.json""" ), """google/electra-base-discriminator""": ( """https://huggingface.co/google/electra-base-discriminator/resolve/main/tokenizer.json""" ), """google/electra-large-discriminator""": ( """https://huggingface.co/google/electra-large-discriminator/resolve/main/tokenizer.json""" ), }, } lowerCamelCase__ = { """google/electra-small-generator""": 512, """google/electra-base-generator""": 512, """google/electra-large-generator""": 512, """google/electra-small-discriminator""": 512, """google/electra-base-discriminator""": 512, """google/electra-large-discriminator""": 512, } lowerCamelCase__ = { """google/electra-small-generator""": {"""do_lower_case""": True}, """google/electra-base-generator""": {"""do_lower_case""": True}, """google/electra-large-generator""": {"""do_lower_case""": True}, """google/electra-small-discriminator""": {"""do_lower_case""": True}, """google/electra-base-discriminator""": {"""do_lower_case""": True}, """google/electra-large-discriminator""": {"""do_lower_case""": True}, } class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : List[Any] =VOCAB_FILES_NAMES __lowerCamelCase : List[str] =PRETRAINED_VOCAB_FILES_MAP __lowerCamelCase : List[str] =PRETRAINED_INIT_CONFIGURATION __lowerCamelCase : Dict =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCamelCase : Optional[int] =ElectraTokenizer def __init__( self : str , __lowercase : Any=None , __lowercase : int=None , __lowercase : Any=True , __lowercase : Optional[Any]="[UNK]" , __lowercase : Optional[Any]="[SEP]" , __lowercase : str="[PAD]" , __lowercase : Optional[Any]="[CLS]" , __lowercase : List[str]="[MASK]" , __lowercase : Optional[int]=True , __lowercase : Any=None , **__lowercase : int , ): '''simple docstring''' super().__init__( __lowercase , tokenizer_file=__lowercase , do_lower_case=__lowercase , unk_token=__lowercase , sep_token=__lowercase , pad_token=__lowercase , cls_token=__lowercase , mask_token=__lowercase , tokenize_chinese_chars=__lowercase , strip_accents=__lowercase , **__lowercase , ) __a = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""" , __lowercase ) != do_lower_case or normalizer_state.get("""strip_accents""" , __lowercase ) != strip_accents or normalizer_state.get("""handle_chinese_chars""" , __lowercase ) != tokenize_chinese_chars ): __a = getattr(__lowercase , normalizer_state.pop("""type""" ) ) __a = do_lower_case __a = strip_accents __a = tokenize_chinese_chars __a = normalizer_class(**__lowercase ) __a = do_lower_case def UpperCamelCase_ ( self : Any , __lowercase : Tuple , __lowercase : Tuple=None ): '''simple docstring''' __a = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def UpperCamelCase_ ( self : Any , __lowercase : List[int] , __lowercase : Optional[List[int]] = None ): '''simple docstring''' __a = [self.sep_token_id] __a = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCamelCase_ ( self : str , __lowercase : str , __lowercase : Optional[str] = None ): '''simple docstring''' __a = self._tokenizer.model.save(__lowercase , name=__lowercase ) return tuple(__lowercase )
302
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig lowerCamelCase__ = { """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/config.json""", """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/config.json""", """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/config.json""", """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/config.json""", """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/config.json""", """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/config.json""", """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/config.json""", """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/config.json""", } class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : Optional[Any] ='albert' def __init__( self : Optional[Any] , __lowercase : Union[str, Any]=30000 , __lowercase : List[str]=128 , __lowercase : Optional[Any]=4096 , __lowercase : Dict=12 , __lowercase : Any=1 , __lowercase : Optional[Any]=64 , __lowercase : Any=16384 , __lowercase : Any=1 , __lowercase : Union[str, Any]="gelu_new" , __lowercase : List[str]=0 , __lowercase : int=0 , __lowercase : Dict=512 , __lowercase : str=2 , __lowercase : List[str]=0.02 , __lowercase : Union[str, Any]=1E-12 , __lowercase : int=0.1 , __lowercase : Any="absolute" , __lowercase : Optional[int]=0 , __lowercase : Dict=2 , __lowercase : Optional[Any]=3 , **__lowercase : Any , ): '''simple docstring''' super().__init__(pad_token_id=__lowercase , bos_token_id=__lowercase , eos_token_id=__lowercase , **__lowercase ) __a = vocab_size __a = embedding_size __a = hidden_size __a = num_hidden_layers __a = num_hidden_groups __a = num_attention_heads __a = inner_group_num __a = hidden_act __a = intermediate_size __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = type_vocab_size __a = initializer_range __a = layer_norm_eps __a = classifier_dropout_prob __a = position_embedding_type class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): @property def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' if self.task == "multiple-choice": __a = {0: """batch""", 1: """choice""", 2: """sequence"""} else: __a = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis), ] )
302
1
from collections import namedtuple lowerCamelCase__ = namedtuple("""from_to""", """from_ to""") lowerCamelCase__ = { """cubicmeter""": from_to(1, 1), """litre""": from_to(0.001, 1000), """kilolitre""": from_to(1, 1), """gallon""": from_to(0.0_0454, 264.172), """cubicyard""": from_to(0.7_6455, 1.3_0795), """cubicfoot""": from_to(0.028, 35.3147), """cup""": from_to(0.0_0023_6588, 4226.75), } def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : float , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : str ): """simple docstring""" if from_type not in METRIC_CONVERSION: raise ValueError( f"Invalid 'from_type' value: {from_type!r} Supported values are:\n" + """, """.join(_SCREAMING_SNAKE_CASE ) ) if to_type not in METRIC_CONVERSION: raise ValueError( f"Invalid 'to_type' value: {to_type!r}. Supported values are:\n" + """, """.join(_SCREAMING_SNAKE_CASE ) ) return value * METRIC_CONVERSION[from_type].from_ * METRIC_CONVERSION[to_type].to if __name__ == "__main__": import doctest doctest.testmod()
302
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) lowerCamelCase__ = { """configuration_blip""": [ """BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP""", """BlipConfig""", """BlipTextConfig""", """BlipVisionConfig""", ], """processing_blip""": ["""BlipProcessor"""], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = ["""BlipImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ """BLIP_PRETRAINED_MODEL_ARCHIVE_LIST""", """BlipModel""", """BlipPreTrainedModel""", """BlipForConditionalGeneration""", """BlipForQuestionAnswering""", """BlipVisionModel""", """BlipTextModel""", """BlipForImageTextRetrieval""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ """TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFBlipModel""", """TFBlipPreTrainedModel""", """TFBlipForConditionalGeneration""", """TFBlipForQuestionAnswering""", """TFBlipVisionModel""", """TFBlipTextModel""", """TFBlipForImageTextRetrieval""", ] if TYPE_CHECKING: from .configuration_blip import BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, BlipConfig, BlipTextConfig, BlipVisionConfig from .processing_blip import BlipProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_blip import BlipImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blip import ( BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, BlipModel, BlipPreTrainedModel, BlipTextModel, BlipVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blip import ( TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFBlipForConditionalGeneration, TFBlipForImageTextRetrieval, TFBlipForQuestionAnswering, TFBlipModel, TFBlipPreTrainedModel, TFBlipTextModel, TFBlipVisionModel, ) else: import sys lowerCamelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
302
1
def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : int ): """simple docstring""" __a = (boundary[1] - boundary[0]) / steps __a = boundary[0] __a = boundary[1] __a = make_points(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __a = 0.0 y += (h / 2.0) * f(_SCREAMING_SNAKE_CASE ) for i in x_i: # print(i) y += h * f(_SCREAMING_SNAKE_CASE ) y += (h / 2.0) * f(_SCREAMING_SNAKE_CASE ) return y def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Optional[int] ): """simple docstring""" __a = a + h while x < (b - h): yield x __a = x + h def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Optional[int] ): # enter your function here """simple docstring""" __a = (x - 0) * (x - 0) return y def lowerCAmelCase__ ( ): """simple docstring""" __a = 0.0 # Lower bound of integration __a = 1.0 # Upper bound of integration __a = 10.0 # define number of steps or resolution __a = [a, b] # define boundary of integration __a = method_a(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) print(f"y = {y}" ) if __name__ == "__main__": main()
302
class SCREAMING_SNAKE_CASE : def __init__( self : List[Any] , __lowercase : Union[str, Any] ): '''simple docstring''' __a = val __a = None __a = None def UpperCamelCase_ ( self : Union[str, Any] , __lowercase : Any ): '''simple docstring''' if self.val: if val < self.val: if self.left is None: __a = Node(__lowercase ) else: self.left.insert(__lowercase ) elif val > self.val: if self.right is None: __a = Node(__lowercase ) else: self.right.insert(__lowercase ) else: __a = val def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : Any ): """simple docstring""" if root: inorder(root.left , _SCREAMING_SNAKE_CASE ) res.append(root.val ) inorder(root.right , _SCREAMING_SNAKE_CASE ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Any ): """simple docstring""" if len(_SCREAMING_SNAKE_CASE ) == 0: return arr __a = Node(arr[0] ) for i in range(1 , len(_SCREAMING_SNAKE_CASE ) ): root.insert(arr[i] ) # Traverse BST in order. __a = [] inorder(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return res if __name__ == "__main__": print(tree_sort([10, 1, 3, 2, 9, 14, 13]))
302
1
from __future__ import annotations import matplotlib.pyplot as plt # type: ignore import numpy # initial triangle of Koch snowflake lowerCamelCase__ = numpy.array([0, 0]) lowerCamelCase__ = numpy.array([0.5, 0.866_0254]) lowerCamelCase__ = numpy.array([1, 0]) lowerCamelCase__ = [VECTOR_1, VECTOR_2, VECTOR_3, VECTOR_1] def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : list[numpy.ndarray] , _SCREAMING_SNAKE_CASE : int ): """simple docstring""" __a = initial_vectors for _ in range(_SCREAMING_SNAKE_CASE ): __a = iteration_step(_SCREAMING_SNAKE_CASE ) return vectors def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : list[numpy.ndarray] ): """simple docstring""" __a = [] for i, start_vector in enumerate(vectors[:-1] ): __a = vectors[i + 1] new_vectors.append(_SCREAMING_SNAKE_CASE ) __a = end_vector - start_vector new_vectors.append(start_vector + difference_vector / 3 ) new_vectors.append( start_vector + difference_vector / 3 + rotate(difference_vector / 3 , 60 ) ) new_vectors.append(start_vector + difference_vector * 2 / 3 ) new_vectors.append(vectors[-1] ) return new_vectors def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : numpy.ndarray , _SCREAMING_SNAKE_CASE : float ): """simple docstring""" __a = numpy.radians(_SCREAMING_SNAKE_CASE ) __a , __a = numpy.cos(_SCREAMING_SNAKE_CASE ), numpy.sin(_SCREAMING_SNAKE_CASE ) __a = numpy.array(((c, -s), (s, c)) ) return numpy.dot(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : list[numpy.ndarray] ): """simple docstring""" __a = plt.gca() axes.set_aspect("""equal""" ) # matplotlib.pyplot.plot takes a list of all x-coordinates and a list of all # y-coordinates as inputs, which are constructed from the vector-list using # zip() __a , __a = zip(*_SCREAMING_SNAKE_CASE ) plt.plot(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) plt.show() if __name__ == "__main__": import doctest doctest.testmod() lowerCamelCase__ = iterate(INITIAL_VECTORS, 5) plot(processed_vectors)
302
import inspect import unittest from transformers import MobileViTVaConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, MobileViTVaModel from transformers.models.mobilevitva.modeling_mobilevitva import ( MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST, make_divisible, ) if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): def UpperCamelCase_ ( self : str ): '''simple docstring''' __a = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(__lowercase , """width_multiplier""" ) ) class SCREAMING_SNAKE_CASE : def __init__( self : Dict , __lowercase : Union[str, Any] , __lowercase : Dict=13 , __lowercase : int=64 , __lowercase : Tuple=2 , __lowercase : Tuple=3 , __lowercase : Tuple="swish" , __lowercase : List[Any]=3 , __lowercase : List[str]=32 , __lowercase : int=0.1 , __lowercase : Union[str, Any]=0.02 , __lowercase : Optional[int]=True , __lowercase : Dict=True , __lowercase : Tuple=10 , __lowercase : str=None , __lowercase : Optional[Any]=0.25 , __lowercase : str=0.0 , __lowercase : Optional[Any]=0.0 , ): '''simple docstring''' __a = parent __a = batch_size __a = image_size __a = patch_size __a = num_channels __a = make_divisible(512 * width_multiplier , divisor=8 ) __a = hidden_act __a = conv_kernel_size __a = output_stride __a = classifier_dropout_prob __a = use_labels __a = is_training __a = num_labels __a = initializer_range __a = scope __a = width_multiplier __a = ffn_dropout __a = attn_dropout def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' __a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a = None __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.num_labels ) __a = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) __a = self.get_config() return config, pixel_values, labels, pixel_labels def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' return MobileViTVaConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_act=self.hidden_act , conv_kernel_size=self.conv_kernel_size , output_stride=self.output_stride , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , width_multiplier=self.width_multiplier , ffn_dropout=self.ffn_dropout_prob , attn_dropout=self.attn_dropout_prob , ) def UpperCamelCase_ ( self : Tuple , __lowercase : Optional[Any] , __lowercase : int , __lowercase : Optional[Any] , __lowercase : Tuple ): '''simple docstring''' __a = MobileViTVaModel(config=__lowercase ) model.to(__lowercase ) model.eval() __a = model(__lowercase ) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def UpperCamelCase_ ( self : Union[str, Any] , __lowercase : List[Any] , __lowercase : str , __lowercase : Optional[int] , __lowercase : Union[str, Any] ): '''simple docstring''' __a = self.num_labels __a = MobileViTVaForImageClassification(__lowercase ) model.to(__lowercase ) model.eval() __a = model(__lowercase , labels=__lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCamelCase_ ( self : int , __lowercase : str , __lowercase : Any , __lowercase : int , __lowercase : List[str] ): '''simple docstring''' __a = self.num_labels __a = MobileViTVaForSemanticSegmentation(__lowercase ) model.to(__lowercase ) model.eval() __a = model(__lowercase ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) __a = model(__lowercase , labels=__lowercase ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def UpperCamelCase_ ( self : Dict ): '''simple docstring''' __a = self.prepare_config_and_inputs() __a , __a , __a , __a = config_and_inputs __a = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE ( lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase ): __lowerCamelCase : List[Any] =( (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation) if is_torch_available() else () ) __lowerCamelCase : Any =( { 'feature-extraction': MobileViTVaModel, 'image-classification': MobileViTVaForImageClassification, 'image-segmentation': MobileViTVaForSemanticSegmentation, } if is_torch_available() else {} ) __lowerCamelCase : Dict =False __lowerCamelCase : Optional[Any] =False __lowerCamelCase : int =False __lowerCamelCase : Any =False def UpperCamelCase_ ( self : Dict ): '''simple docstring''' __a = MobileViTVaModelTester(self ) __a = MobileViTVaConfigTester(self , config_class=__lowercase , has_text_modality=__lowercase ) def UpperCamelCase_ ( self : Dict ): '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason="""MobileViTV2 does not use inputs_embeds""" ) def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' pass @unittest.skip(reason="""MobileViTV2 does not support input and output embeddings""" ) def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' pass @unittest.skip(reason="""MobileViTV2 does not output attentions""" ) def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' pass @require_torch_multi_gpu @unittest.skip(reason="""Got `CUDA error: misaligned address` for tests after this one being run.""" ) def UpperCamelCase_ ( self : int ): '''simple docstring''' pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' pass def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(__lowercase ) __a = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a = [*signature.parameters.keys()] __a = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , __lowercase ) def UpperCamelCase_ ( self : Dict ): '''simple docstring''' __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowercase ) def UpperCamelCase_ ( self : int ): '''simple docstring''' def check_hidden_states_output(__lowercase : List[str] , __lowercase : Optional[int] , __lowercase : List[str] ): __a = model_class(__lowercase ) model.to(__lowercase ) model.eval() with torch.no_grad(): __a = model(**self._prepare_for_class(__lowercase , __lowercase ) ) __a = outputs.hidden_states __a = 5 self.assertEqual(len(__lowercase ) , __lowercase ) # MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width) # with the width and height being successively divided by 2. __a = 2 for i in range(len(__lowercase ) ): self.assertListEqual( list(hidden_states[i].shape[-2:] ) , [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor] , ) divisor *= 2 self.assertEqual(self.model_tester.output_stride , divisor // 2 ) __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = True check_hidden_states_output(__lowercase , __lowercase , __lowercase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __a = True check_hidden_states_output(__lowercase , __lowercase , __lowercase ) def UpperCamelCase_ ( self : Optional[int] ): '''simple docstring''' __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__lowercase ) def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*__lowercase ) @slow def UpperCamelCase_ ( self : Optional[int] ): '''simple docstring''' for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = MobileViTVaModel.from_pretrained(__lowercase ) self.assertIsNotNone(__lowercase ) def lowerCAmelCase__ ( ): """simple docstring""" __a = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class SCREAMING_SNAKE_CASE ( unittest.TestCase ): @cached_property def UpperCamelCase_ ( self : Dict ): '''simple docstring''' return ( MobileViTImageProcessor.from_pretrained("""apple/mobilevitv2-1.0-imagenet1k-256""" ) if is_vision_available() else None ) @slow def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' __a = MobileViTVaForImageClassification.from_pretrained("""apple/mobilevitv2-1.0-imagenet1k-256""" ).to( __lowercase ) __a = self.default_image_processor __a = prepare_img() __a = image_processor(images=__lowercase , return_tensors="""pt""" ).to(__lowercase ) # forward pass with torch.no_grad(): __a = model(**__lowercase ) # verify the logits __a = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , __lowercase ) __a = torch.tensor([-1.6336E00, -7.3204E-02, -5.1883E-01] ).to(__lowercase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __lowercase , atol=1E-4 ) ) @slow def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' __a = MobileViTVaForSemanticSegmentation.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3""" ) __a = model.to(__lowercase ) __a = MobileViTImageProcessor.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3""" ) __a = prepare_img() __a = image_processor(images=__lowercase , return_tensors="""pt""" ).to(__lowercase ) # forward pass with torch.no_grad(): __a = model(**__lowercase ) __a = outputs.logits # verify the logits __a = torch.Size((1, 21, 32, 32) ) self.assertEqual(logits.shape , __lowercase ) __a = torch.tensor( [ [[7.0863, 7.1525, 6.8201], [6.6931, 6.8770, 6.8933], [6.2978, 7.0366, 6.9636]], [[-3.7134, -3.6712, -3.6675], [-3.5825, -3.3549, -3.4777], [-3.3435, -3.3979, -3.2857]], [[-2.9329, -2.8003, -2.7369], [-3.0564, -2.4780, -2.0207], [-2.6889, -1.9298, -1.7640]], ] , device=__lowercase , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , __lowercase , atol=1E-4 ) ) @slow def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' __a = MobileViTVaForSemanticSegmentation.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3""" ) __a = model.to(__lowercase ) __a = MobileViTImageProcessor.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3""" ) __a = prepare_img() __a = image_processor(images=__lowercase , return_tensors="""pt""" ).to(__lowercase ) # forward pass with torch.no_grad(): __a = model(**__lowercase ) __a = outputs.logits.detach().cpu() __a = image_processor.post_process_semantic_segmentation(outputs=__lowercase , target_sizes=[(50, 60)] ) __a = torch.Size((50, 60) ) self.assertEqual(segmentation[0].shape , __lowercase ) __a = image_processor.post_process_semantic_segmentation(outputs=__lowercase ) __a = torch.Size((32, 32) ) self.assertEqual(segmentation[0].shape , __lowercase )
302
1
import importlib import math import os from dataclasses import dataclass from enum import Enum from typing import Any, Dict, Optional, Tuple, Union import flax import jax.numpy as jnp from ..utils import BaseOutput lowerCamelCase__ = """scheduler_config.json""" class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : Union[str, Any] =1 __lowerCamelCase : Any =2 __lowerCamelCase : List[Any] =3 __lowerCamelCase : str =4 __lowerCamelCase : Optional[int] =5 @dataclass class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : jnp.ndarray class SCREAMING_SNAKE_CASE : __lowerCamelCase : Union[str, Any] =SCHEDULER_CONFIG_NAME __lowerCamelCase : List[Any] =['dtype'] __lowerCamelCase : Union[str, Any] =[] __lowerCamelCase : int =True @classmethod def UpperCamelCase_ ( cls : Any , __lowercase : Dict[str, Any] = None , __lowercase : Optional[str] = None , __lowercase : List[str]=False , **__lowercase : str , ): '''simple docstring''' __a , __a = cls.load_config( pretrained_model_name_or_path=__lowercase , subfolder=__lowercase , return_unused_kwargs=__lowercase , **__lowercase , ) __a , __a = cls.from_config(__lowercase , return_unused_kwargs=__lowercase , **__lowercase ) if hasattr(__lowercase , """create_state""" ) and getattr(__lowercase , """has_state""" , __lowercase ): __a = scheduler.create_state() if return_unused_kwargs: return scheduler, state, unused_kwargs return scheduler, state def UpperCamelCase_ ( self : Dict , __lowercase : Union[str, os.PathLike] , __lowercase : bool = False , **__lowercase : Optional[Any] ): '''simple docstring''' self.save_config(save_directory=__lowercase , push_to_hub=__lowercase , **__lowercase ) @property def UpperCamelCase_ ( self : Any ): '''simple docstring''' return self._get_compatibles() @classmethod def UpperCamelCase_ ( cls : Optional[int] ): '''simple docstring''' __a = list(set([cls.__name__] + cls._compatibles ) ) __a = importlib.import_module(__name__.split(""".""" )[0] ) __a = [ getattr(__lowercase , __lowercase ) for c in compatible_classes_str if hasattr(__lowercase , __lowercase ) ] return compatible_classes def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : jnp.ndarray , _SCREAMING_SNAKE_CASE : Tuple[int] ): """simple docstring""" assert len(_SCREAMING_SNAKE_CASE ) >= x.ndim return jnp.broadcast_to(x.reshape(x.shape + (1,) * (len(_SCREAMING_SNAKE_CASE ) - x.ndim) ) , _SCREAMING_SNAKE_CASE ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : List[Any]=0.999 , _SCREAMING_SNAKE_CASE : List[Any]=jnp.floataa ): """simple docstring""" def alpha_bar(_SCREAMING_SNAKE_CASE : Union[str, Any] ): return math.cos((time_step + 0.008) / 1.008 * math.pi / 2 ) ** 2 __a = [] for i in range(_SCREAMING_SNAKE_CASE ): __a = i / num_diffusion_timesteps __a = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar(_SCREAMING_SNAKE_CASE ) / alpha_bar(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) ) return jnp.array(_SCREAMING_SNAKE_CASE , dtype=_SCREAMING_SNAKE_CASE ) @flax.struct.dataclass class SCREAMING_SNAKE_CASE : __lowerCamelCase : jnp.ndarray __lowerCamelCase : jnp.ndarray __lowerCamelCase : jnp.ndarray @classmethod def UpperCamelCase_ ( cls : List[Any] , __lowercase : str ): '''simple docstring''' __a = scheduler.config if config.trained_betas is not None: __a = jnp.asarray(config.trained_betas , dtype=scheduler.dtype ) elif config.beta_schedule == "linear": __a = jnp.linspace(config.beta_start , config.beta_end , config.num_train_timesteps , dtype=scheduler.dtype ) elif config.beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. __a = ( jnp.linspace( config.beta_start**0.5 , config.beta_end**0.5 , config.num_train_timesteps , dtype=scheduler.dtype ) ** 2 ) elif config.beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule __a = betas_for_alpha_bar(config.num_train_timesteps , dtype=scheduler.dtype ) else: raise NotImplementedError( F"beta_schedule {config.beta_schedule} is not implemented for scheduler {scheduler.__class__.__name__}" ) __a = 1.0 - betas __a = jnp.cumprod(__lowercase , axis=0 ) return cls( alphas=__lowercase , betas=__lowercase , alphas_cumprod=__lowercase , ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : CommonSchedulerState , _SCREAMING_SNAKE_CASE : jnp.ndarray , _SCREAMING_SNAKE_CASE : jnp.ndarray , _SCREAMING_SNAKE_CASE : jnp.ndarray ): """simple docstring""" __a = state.alphas_cumprod __a = alphas_cumprod[timesteps] ** 0.5 __a = sqrt_alpha_prod.flatten() __a = broadcast_to_shape_from_left(_SCREAMING_SNAKE_CASE , original_samples.shape ) __a = (1 - alphas_cumprod[timesteps]) ** 0.5 __a = sqrt_one_minus_alpha_prod.flatten() __a = broadcast_to_shape_from_left(_SCREAMING_SNAKE_CASE , original_samples.shape ) return sqrt_alpha_prod, sqrt_one_minus_alpha_prod def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : CommonSchedulerState , _SCREAMING_SNAKE_CASE : jnp.ndarray , _SCREAMING_SNAKE_CASE : jnp.ndarray , _SCREAMING_SNAKE_CASE : jnp.ndarray ): """simple docstring""" __a , __a = get_sqrt_alpha_prod(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __a = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise return noisy_samples def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : CommonSchedulerState , _SCREAMING_SNAKE_CASE : jnp.ndarray , _SCREAMING_SNAKE_CASE : jnp.ndarray , _SCREAMING_SNAKE_CASE : jnp.ndarray ): """simple docstring""" __a , __a = get_sqrt_alpha_prod(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __a = sqrt_alpha_prod * noise - sqrt_one_minus_alpha_prod * sample return velocity
302
from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import torch from ...utils import BaseOutput, OptionalDependencyNotAvailable, is_torch_available, is_transformers_available @dataclass class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : Union[List[np.ndarray], torch.FloatTensor] 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_text_to_video_synth import TextToVideoSDPipeline from .pipeline_text_to_video_synth_imgaimg import VideoToVideoSDPipeline # noqa: F401 from .pipeline_text_to_video_zero import TextToVideoZeroPipeline
302
1
import inspect import unittest from transformers import SegformerConfig, is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_MAPPING, SegformerForImageClassification, SegformerForSemanticSegmentation, SegformerModel, ) from transformers.models.segformer.modeling_segformer import SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import SegformerImageProcessor class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' __a = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(__lowercase , """hidden_sizes""" ) ) self.parent.assertTrue(hasattr(__lowercase , """num_attention_heads""" ) ) self.parent.assertTrue(hasattr(__lowercase , """num_encoder_blocks""" ) ) class SCREAMING_SNAKE_CASE : def __init__( self : Union[str, Any] , __lowercase : List[str] , __lowercase : int=13 , __lowercase : Dict=64 , __lowercase : Union[str, Any]=3 , __lowercase : str=4 , __lowercase : List[Any]=[2, 2, 2, 2] , __lowercase : Any=[8, 4, 2, 1] , __lowercase : int=[16, 32, 64, 128] , __lowercase : Dict=[1, 4, 8, 16] , __lowercase : Tuple=[1, 2, 4, 8] , __lowercase : List[Any]=True , __lowercase : Any=True , __lowercase : str="gelu" , __lowercase : List[Any]=0.1 , __lowercase : Any=0.1 , __lowercase : str=0.02 , __lowercase : Optional[Any]=3 , __lowercase : Any=None , ): '''simple docstring''' __a = parent __a = batch_size __a = image_size __a = num_channels __a = num_encoder_blocks __a = sr_ratios __a = depths __a = hidden_sizes __a = downsampling_rates __a = num_attention_heads __a = is_training __a = use_labels __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = initializer_range __a = num_labels __a = scope def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' __a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a = None if self.use_labels: __a = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) __a = self.get_config() return config, pixel_values, labels def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' return SegformerConfig( image_size=self.image_size , num_channels=self.num_channels , num_encoder_blocks=self.num_encoder_blocks , depths=self.depths , hidden_sizes=self.hidden_sizes , num_attention_heads=self.num_attention_heads , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , initializer_range=self.initializer_range , ) def UpperCamelCase_ ( self : Any , __lowercase : Tuple , __lowercase : Tuple , __lowercase : Tuple ): '''simple docstring''' __a = SegformerModel(config=__lowercase ) model.to(__lowercase ) model.eval() __a = model(__lowercase ) __a = __a = self.image_size // (self.downsampling_rates[-1] * 2) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], expected_height, expected_width) ) def UpperCamelCase_ ( self : Union[str, Any] , __lowercase : List[str] , __lowercase : Union[str, Any] , __lowercase : Optional[int] ): '''simple docstring''' __a = self.num_labels __a = SegformerForSemanticSegmentation(__lowercase ) model.to(__lowercase ) model.eval() __a = model(__lowercase ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4) ) __a = model(__lowercase , labels=__lowercase ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4) ) self.parent.assertGreater(result.loss , 0.0 ) def UpperCamelCase_ ( self : Union[str, Any] , __lowercase : Any , __lowercase : Optional[Any] , __lowercase : str ): '''simple docstring''' __a = 1 __a = SegformerForSemanticSegmentation(config=__lowercase ) model.to(__lowercase ) model.eval() __a = torch.randint(0 , 1 , (self.batch_size, self.image_size, self.image_size) ).to(__lowercase ) __a = model(__lowercase , labels=__lowercase ) self.parent.assertGreater(result.loss , 0.0 ) def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' __a = self.prepare_config_and_inputs() __a , __a , __a = config_and_inputs __a = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE ( lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase ): __lowerCamelCase : Optional[Any] =( ( SegformerModel, SegformerForSemanticSegmentation, SegformerForImageClassification, ) if is_torch_available() else () ) __lowerCamelCase : Union[str, Any] =( { 'feature-extraction': SegformerModel, 'image-classification': SegformerForImageClassification, 'image-segmentation': SegformerForSemanticSegmentation, } if is_torch_available() else {} ) __lowerCamelCase : Optional[int] =True __lowerCamelCase : Tuple =False __lowerCamelCase : Optional[Any] =False __lowerCamelCase : List[Any] =False def UpperCamelCase_ ( self : str ): '''simple docstring''' __a = SegformerModelTester(self ) __a = SegformerConfigTester(self , config_class=__lowercase ) def UpperCamelCase_ ( self : Any ): '''simple docstring''' self.config_tester.run_common_tests() def UpperCamelCase_ ( self : int ): '''simple docstring''' __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowercase ) def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_binary_image_segmentation(*__lowercase ) def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_segmentation(*__lowercase ) @unittest.skip("""SegFormer does not use inputs_embeds""" ) def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' pass @unittest.skip("""SegFormer does not have get_input_embeddings method and get_output_embeddings methods""" ) def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' pass def UpperCamelCase_ ( self : int ): '''simple docstring''' __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(__lowercase ) __a = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a = [*signature.parameters.keys()] __a = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , __lowercase ) def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' __a , __a = self.model_tester.prepare_config_and_inputs_for_common() __a = True for model_class in self.all_model_classes: __a = True __a = False __a = True __a = model_class(__lowercase ) model.to(__lowercase ) model.eval() with torch.no_grad(): __a = model(**self._prepare_for_class(__lowercase , __lowercase ) ) __a = outputs.attentions __a = sum(self.model_tester.depths ) self.assertEqual(len(__lowercase ) , __lowercase ) # check that output_attentions also work using config del inputs_dict["output_attentions"] __a = True __a = model_class(__lowercase ) model.to(__lowercase ) model.eval() with torch.no_grad(): __a = model(**self._prepare_for_class(__lowercase , __lowercase ) ) __a = outputs.attentions self.assertEqual(len(__lowercase ) , __lowercase ) # verify the first attentions (first block, first layer) __a = (self.model_tester.image_size // 4) ** 2 __a = (self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2 self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len] , ) # verify the last attentions (last block, last layer) __a = (self.model_tester.image_size // 32) ** 2 __a = (self.model_tester.image_size // (32 * self.model_tester.sr_ratios[-1])) ** 2 self.assertListEqual( list(attentions[-1].shape[-3:] ) , [self.model_tester.num_attention_heads[-1], expected_seq_len, expected_reduced_seq_len] , ) __a = len(__lowercase ) # Check attention is always last and order is fine __a = True __a = True __a = model_class(__lowercase ) model.to(__lowercase ) model.eval() with torch.no_grad(): __a = model(**self._prepare_for_class(__lowercase , __lowercase ) ) self.assertEqual(out_len + 1 , len(__lowercase ) ) __a = outputs.attentions self.assertEqual(len(__lowercase ) , __lowercase ) # verify the first attentions (first block, first layer) __a = (self.model_tester.image_size // 4) ** 2 __a = (self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2 self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len] , ) def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' def check_hidden_states_output(__lowercase : Optional[int] , __lowercase : Optional[Any] , __lowercase : Optional[Any] ): __a = model_class(__lowercase ) model.to(__lowercase ) model.eval() with torch.no_grad(): __a = model(**self._prepare_for_class(__lowercase , __lowercase ) ) __a = outputs.hidden_states __a = self.model_tester.num_encoder_blocks self.assertEqual(len(__lowercase ) , __lowercase ) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-3:] ) , [ self.model_tester.hidden_sizes[0], self.model_tester.image_size // 4, self.model_tester.image_size // 4, ] , ) __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = True check_hidden_states_output(__lowercase , __lowercase , __lowercase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __a = True check_hidden_states_output(__lowercase , __lowercase , __lowercase ) def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' if not self.model_tester.is_training: return __a , __a = self.model_tester.prepare_config_and_inputs_for_common() __a = True for model_class in self.all_model_classes: if model_class in get_values(__lowercase ): continue __a = model_class(__lowercase ) model.to(__lowercase ) model.train() __a = self._prepare_for_class(__lowercase , __lowercase , return_labels=__lowercase ) __a = model(**__lowercase ).loss loss.backward() @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def UpperCamelCase_ ( self : Optional[int] ): '''simple docstring''' pass @slow def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' for model_name in SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = SegformerModel.from_pretrained(__lowercase ) self.assertIsNotNone(__lowercase ) def lowerCAmelCase__ ( ): """simple docstring""" __a = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch class SCREAMING_SNAKE_CASE ( unittest.TestCase ): @slow def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' # only resize + normalize __a = SegformerImageProcessor( image_scale=(512, 512) , keep_ratio=__lowercase , align=__lowercase , do_random_crop=__lowercase ) __a = SegformerForSemanticSegmentation.from_pretrained("""nvidia/segformer-b0-finetuned-ade-512-512""" ).to( __lowercase ) __a = prepare_img() __a = image_processor(images=__lowercase , return_tensors="""pt""" ) __a = encoded_inputs.pixel_values.to(__lowercase ) with torch.no_grad(): __a = model(__lowercase ) __a = torch.Size((1, model.config.num_labels, 128, 128) ) self.assertEqual(outputs.logits.shape , __lowercase ) __a = torch.tensor( [ [[-4.6310, -5.5232, -6.2356], [-5.1921, -6.1444, -6.5996], [-5.4424, -6.2790, -6.7574]], [[-12.1391, -13.3122, -13.9554], [-12.8732, -13.9352, -14.3563], [-12.9438, -13.8226, -14.2513]], [[-12.5134, -13.4686, -14.4915], [-12.8669, -14.4343, -14.7758], [-13.2523, -14.5819, -15.0694]], ] ).to(__lowercase ) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3] , __lowercase , atol=1E-4 ) ) @slow def UpperCamelCase_ ( self : str ): '''simple docstring''' # only resize + normalize __a = SegformerImageProcessor( image_scale=(512, 512) , keep_ratio=__lowercase , align=__lowercase , do_random_crop=__lowercase ) __a = SegformerForSemanticSegmentation.from_pretrained( """nvidia/segformer-b1-finetuned-cityscapes-1024-1024""" ).to(__lowercase ) __a = prepare_img() __a = image_processor(images=__lowercase , return_tensors="""pt""" ) __a = encoded_inputs.pixel_values.to(__lowercase ) with torch.no_grad(): __a = model(__lowercase ) __a = torch.Size((1, model.config.num_labels, 128, 128) ) self.assertEqual(outputs.logits.shape , __lowercase ) __a = torch.tensor( [ [[-13.5748, -13.9111, -12.6500], [-14.3500, -15.3683, -14.2328], [-14.7532, -16.0424, -15.6087]], [[-17.1651, -15.8725, -12.9653], [-17.2580, -17.3718, -14.8223], [-16.6058, -16.8783, -16.7452]], [[-3.6456, -3.0209, -1.4203], [-3.0797, -3.1959, -2.0000], [-1.8757, -1.9217, -1.6997]], ] ).to(__lowercase ) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3] , __lowercase , atol=1E-1 ) ) @slow def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' # only resize + normalize __a = SegformerImageProcessor( image_scale=(512, 512) , keep_ratio=__lowercase , align=__lowercase , do_random_crop=__lowercase ) __a = SegformerForSemanticSegmentation.from_pretrained("""nvidia/segformer-b0-finetuned-ade-512-512""" ).to( __lowercase ) __a = prepare_img() __a = image_processor(images=__lowercase , return_tensors="""pt""" ) __a = encoded_inputs.pixel_values.to(__lowercase ) with torch.no_grad(): __a = model(__lowercase ) __a = outputs.logits.detach().cpu() __a = image_processor.post_process_semantic_segmentation(outputs=__lowercase , target_sizes=[(500, 300)] ) __a = torch.Size((500, 300) ) self.assertEqual(segmentation[0].shape , __lowercase ) __a = image_processor.post_process_semantic_segmentation(outputs=__lowercase ) __a = torch.Size((128, 128) ) self.assertEqual(segmentation[0].shape , __lowercase )
302
import string import numpy def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int ): """simple docstring""" return b if a == 0 else greatest_common_divisor(b % a , _SCREAMING_SNAKE_CASE ) class SCREAMING_SNAKE_CASE : __lowerCamelCase : List[str] =string.ascii_uppercase + string.digits # This cipher takes alphanumerics into account # i.e. a total of 36 characters # take x and return x % len(key_string) __lowerCamelCase : List[Any] =numpy.vectorize(lambda lowerCamelCase__ : x % 36 ) __lowerCamelCase : Optional[Any] =numpy.vectorize(lowerCamelCase__ ) def __init__( self : Union[str, Any] , __lowercase : numpy.ndarray ): '''simple docstring''' __a = self.modulus(__lowercase ) # mod36 calc's on the encrypt key self.check_determinant() # validate the determinant of the encryption key __a = encrypt_key.shape[0] def UpperCamelCase_ ( self : Dict , __lowercase : str ): '''simple docstring''' return self.key_string.index(__lowercase ) def UpperCamelCase_ ( self : Dict , __lowercase : int ): '''simple docstring''' return self.key_string[round(__lowercase )] def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' __a = round(numpy.linalg.det(self.encrypt_key ) ) if det < 0: __a = det % len(self.key_string ) __a = len(self.key_string ) if greatest_common_divisor(__lowercase , len(self.key_string ) ) != 1: __a = ( F"determinant modular {req_l} of encryption key({det}) " F"is not co prime w.r.t {req_l}.\nTry another key." ) raise ValueError(__lowercase ) def UpperCamelCase_ ( self : Dict , __lowercase : str ): '''simple docstring''' __a = [char for char in text.upper() if char in self.key_string] __a = chars[-1] while len(__lowercase ) % self.break_key != 0: chars.append(__lowercase ) return "".join(__lowercase ) def UpperCamelCase_ ( self : List[str] , __lowercase : str ): '''simple docstring''' __a = self.process_text(text.upper() ) __a = """""" for i in range(0 , len(__lowercase ) - self.break_key + 1 , self.break_key ): __a = text[i : i + self.break_key] __a = [self.replace_letters(__lowercase ) for char in batch] __a = numpy.array([vec] ).T __a = self.modulus(self.encrypt_key.dot(__lowercase ) ).T.tolist()[ 0 ] __a = """""".join( self.replace_digits(__lowercase ) for num in batch_encrypted ) encrypted += encrypted_batch return encrypted def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' __a = round(numpy.linalg.det(self.encrypt_key ) ) if det < 0: __a = det % len(self.key_string ) __a = None for i in range(len(self.key_string ) ): if (det * i) % len(self.key_string ) == 1: __a = i break __a = ( det_inv * numpy.linalg.det(self.encrypt_key ) * numpy.linalg.inv(self.encrypt_key ) ) return self.to_int(self.modulus(__lowercase ) ) def UpperCamelCase_ ( self : Any , __lowercase : str ): '''simple docstring''' __a = self.make_decrypt_key() __a = self.process_text(text.upper() ) __a = """""" for i in range(0 , len(__lowercase ) - self.break_key + 1 , self.break_key ): __a = text[i : i + self.break_key] __a = [self.replace_letters(__lowercase ) for char in batch] __a = numpy.array([vec] ).T __a = self.modulus(decrypt_key.dot(__lowercase ) ).T.tolist()[0] __a = """""".join( self.replace_digits(__lowercase ) for num in batch_decrypted ) decrypted += decrypted_batch return decrypted def lowerCAmelCase__ ( ): """simple docstring""" __a = int(input("""Enter the order of the encryption key: """ ) ) __a = [] print("""Enter each row of the encryption key with space separated integers""" ) for _ in range(_SCREAMING_SNAKE_CASE ): __a = [int(_SCREAMING_SNAKE_CASE ) for x in input().split()] hill_matrix.append(_SCREAMING_SNAKE_CASE ) __a = HillCipher(numpy.array(_SCREAMING_SNAKE_CASE ) ) print("""Would you like to encrypt or decrypt some text? (1 or 2)""" ) __a = input("""\n1. Encrypt\n2. Decrypt\n""" ) if option == "1": __a = input("""What text would you like to encrypt?: """ ) print("""Your encrypted text is:""" ) print(hc.encrypt(_SCREAMING_SNAKE_CASE ) ) elif option == "2": __a = input("""What text would you like to decrypt?: """ ) print("""Your decrypted text is:""" ) print(hc.decrypt(_SCREAMING_SNAKE_CASE ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
302
1
from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import torch from ...utils import BaseOutput, OptionalDependencyNotAvailable, is_torch_available, is_transformers_available @dataclass class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : Union[List[np.ndarray], torch.FloatTensor] 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_text_to_video_synth import TextToVideoSDPipeline from .pipeline_text_to_video_synth_imgaimg import VideoToVideoSDPipeline # noqa: F401 from .pipeline_text_to_video_zero import TextToVideoZeroPipeline
302
from typing import List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { """huggingface/autoformer-tourism-monthly""": """https://huggingface.co/huggingface/autoformer-tourism-monthly/resolve/main/config.json""", } class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : List[Any] ='autoformer' __lowerCamelCase : str ={ 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', 'num_hidden_layers': 'encoder_layers', } def __init__( self : List[Any] , __lowercase : Optional[int] = None , __lowercase : Optional[int] = None , __lowercase : str = "student_t" , __lowercase : str = "nll" , __lowercase : int = 1 , __lowercase : List[int] = [1, 2, 3, 4, 5, 6, 7] , __lowercase : bool = True , __lowercase : int = 0 , __lowercase : int = 0 , __lowercase : int = 0 , __lowercase : int = 0 , __lowercase : Optional[List[int]] = None , __lowercase : Optional[List[int]] = None , __lowercase : int = 64 , __lowercase : int = 2 , __lowercase : int = 2 , __lowercase : int = 2 , __lowercase : int = 2 , __lowercase : int = 32 , __lowercase : int = 32 , __lowercase : str = "gelu" , __lowercase : float = 0.1 , __lowercase : float = 0.1 , __lowercase : float = 0.1 , __lowercase : float = 0.1 , __lowercase : float = 0.1 , __lowercase : int = 100 , __lowercase : float = 0.02 , __lowercase : bool = True , __lowercase : List[Any]=True , __lowercase : int = 10 , __lowercase : int = 25 , __lowercase : int = 3 , **__lowercase : Optional[int] , ): '''simple docstring''' # time series specific configuration __a = prediction_length __a = context_length if context_length is not None else prediction_length __a = distribution_output __a = loss __a = input_size __a = num_time_features __a = lags_sequence __a = scaling __a = num_dynamic_real_features __a = num_static_real_features __a = num_static_categorical_features if cardinality is not None and num_static_categorical_features > 0: if len(__lowercase ) != num_static_categorical_features: raise ValueError( """The cardinality should be a list of the same length as `num_static_categorical_features`""" ) __a = cardinality else: __a = [0] if embedding_dimension is not None and num_static_categorical_features > 0: if len(__lowercase ) != num_static_categorical_features: raise ValueError( """The embedding dimension should be a list of the same length as `num_static_categorical_features`""" ) __a = embedding_dimension else: __a = [min(50 , (cat + 1) // 2 ) for cat in self.cardinality] __a = num_parallel_samples # Transformer architecture configuration __a = input_size * len(self.lags_sequence ) + self._number_of_features __a = d_model __a = encoder_attention_heads __a = decoder_attention_heads __a = encoder_ffn_dim __a = decoder_ffn_dim __a = encoder_layers __a = decoder_layers __a = dropout __a = attention_dropout __a = activation_dropout __a = encoder_layerdrop __a = decoder_layerdrop __a = activation_function __a = init_std __a = use_cache # Autoformer __a = label_length __a = moving_average __a = autocorrelation_factor super().__init__(is_encoder_decoder=__lowercase , **__lowercase ) @property def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' return ( sum(self.embedding_dimension ) + self.num_dynamic_real_features + self.num_time_features + self.num_static_real_features + self.input_size * 2 # the log1p(abs(loc)) and log(scale) features )
302
1
import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoImageProcessor, ViTImageProcessor from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test sys.path.append(str(Path(__file__).parent.parent / """utils""")) from test_module.custom_image_processing import CustomImageProcessor # noqa E402 lowerCamelCase__ = get_tests_dir("""fixtures""") class SCREAMING_SNAKE_CASE ( unittest.TestCase ): def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' # A mock response for an HTTP head request to emulate server down __a = mock.Mock() __a = 500 __a = {} __a = HTTPError __a = {} # Download this model to make sure it's in the cache. __a = ViTImageProcessor.from_pretrained("""hf-internal-testing/tiny-random-vit""" ) # Under the mock environment we get a 500 error when trying to reach the model. with mock.patch("""requests.Session.request""" , return_value=__lowercase ) as mock_head: __a = ViTImageProcessor.from_pretrained("""hf-internal-testing/tiny-random-vit""" ) # This check we did call the fake head request mock_head.assert_called() def UpperCamelCase_ ( self : int ): '''simple docstring''' # This test is for deprecated behavior and can be removed in v5 __a = ViTImageProcessor.from_pretrained( """https://huggingface.co/hf-internal-testing/tiny-random-vit/resolve/main/preprocessor_config.json""" ) def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' with self.assertRaises(__lowercase ): # config is in subfolder, the following should not work without specifying the subfolder __a = AutoImageProcessor.from_pretrained("""hf-internal-testing/stable-diffusion-all-variants""" ) __a = AutoImageProcessor.from_pretrained( """hf-internal-testing/stable-diffusion-all-variants""" , subfolder="""feature_extractor""" ) self.assertIsNotNone(__lowercase ) @is_staging_test class SCREAMING_SNAKE_CASE ( unittest.TestCase ): @classmethod def UpperCamelCase_ ( cls : Optional[int] ): '''simple docstring''' __a = TOKEN HfFolder.save_token(__lowercase ) @classmethod def UpperCamelCase_ ( cls : Optional[int] ): '''simple docstring''' try: delete_repo(token=cls._token , repo_id="""test-image-processor""" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="""valid_org/test-image-processor-org""" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="""test-dynamic-image-processor""" ) except HTTPError: pass def UpperCamelCase_ ( self : str ): '''simple docstring''' __a = ViTImageProcessor.from_pretrained(__lowercase ) image_processor.push_to_hub("""test-image-processor""" , use_auth_token=self._token ) __a = ViTImageProcessor.from_pretrained(F"{USER}/test-image-processor" ) for k, v in image_processor.__dict__.items(): self.assertEqual(__lowercase , getattr(__lowercase , __lowercase ) ) # Reset repo delete_repo(token=self._token , repo_id="""test-image-processor""" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained( __lowercase , repo_id="""test-image-processor""" , push_to_hub=__lowercase , use_auth_token=self._token ) __a = ViTImageProcessor.from_pretrained(F"{USER}/test-image-processor" ) for k, v in image_processor.__dict__.items(): self.assertEqual(__lowercase , getattr(__lowercase , __lowercase ) ) def UpperCamelCase_ ( self : Dict ): '''simple docstring''' __a = ViTImageProcessor.from_pretrained(__lowercase ) image_processor.push_to_hub("""valid_org/test-image-processor""" , use_auth_token=self._token ) __a = ViTImageProcessor.from_pretrained("""valid_org/test-image-processor""" ) for k, v in image_processor.__dict__.items(): self.assertEqual(__lowercase , getattr(__lowercase , __lowercase ) ) # Reset repo delete_repo(token=self._token , repo_id="""valid_org/test-image-processor""" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained( __lowercase , repo_id="""valid_org/test-image-processor-org""" , push_to_hub=__lowercase , use_auth_token=self._token ) __a = ViTImageProcessor.from_pretrained("""valid_org/test-image-processor-org""" ) for k, v in image_processor.__dict__.items(): self.assertEqual(__lowercase , getattr(__lowercase , __lowercase ) ) def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' CustomImageProcessor.register_for_auto_class() __a = CustomImageProcessor.from_pretrained(__lowercase ) image_processor.push_to_hub("""test-dynamic-image-processor""" , use_auth_token=self._token ) # This has added the proper auto_map field to the config self.assertDictEqual( image_processor.auto_map , {"""AutoImageProcessor""": """custom_image_processing.CustomImageProcessor"""} , ) __a = AutoImageProcessor.from_pretrained( F"{USER}/test-dynamic-image-processor" , trust_remote_code=__lowercase ) # Can't make an isinstance check because the new_image_processor is from the CustomImageProcessor class of a dynamic module self.assertEqual(new_image_processor.__class__.__name__ , """CustomImageProcessor""" )
302
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase__ = { """configuration_electra""": ["""ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ElectraConfig""", """ElectraOnnxConfig"""], """tokenization_electra""": ["""ElectraTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = ["""ElectraTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ """ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST""", """ElectraForCausalLM""", """ElectraForMaskedLM""", """ElectraForMultipleChoice""", """ElectraForPreTraining""", """ElectraForQuestionAnswering""", """ElectraForSequenceClassification""", """ElectraForTokenClassification""", """ElectraModel""", """ElectraPreTrainedModel""", """load_tf_weights_in_electra""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ """TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFElectraForMaskedLM""", """TFElectraForMultipleChoice""", """TFElectraForPreTraining""", """TFElectraForQuestionAnswering""", """TFElectraForSequenceClassification""", """TFElectraForTokenClassification""", """TFElectraModel""", """TFElectraPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ """FlaxElectraForCausalLM""", """FlaxElectraForMaskedLM""", """FlaxElectraForMultipleChoice""", """FlaxElectraForPreTraining""", """FlaxElectraForQuestionAnswering""", """FlaxElectraForSequenceClassification""", """FlaxElectraForTokenClassification""", """FlaxElectraModel""", """FlaxElectraPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_electra import ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ElectraConfig, ElectraOnnxConfig from .tokenization_electra import ElectraTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_electra_fast import ElectraTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_electra import ( ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST, ElectraForCausalLM, ElectraForMaskedLM, ElectraForMultipleChoice, ElectraForPreTraining, ElectraForQuestionAnswering, ElectraForSequenceClassification, ElectraForTokenClassification, ElectraModel, ElectraPreTrainedModel, load_tf_weights_in_electra, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_electra import ( TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST, TFElectraForMaskedLM, TFElectraForMultipleChoice, TFElectraForPreTraining, TFElectraForQuestionAnswering, TFElectraForSequenceClassification, TFElectraForTokenClassification, TFElectraModel, TFElectraPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_electra import ( FlaxElectraForCausalLM, FlaxElectraForMaskedLM, FlaxElectraForMultipleChoice, FlaxElectraForPreTraining, FlaxElectraForQuestionAnswering, FlaxElectraForSequenceClassification, FlaxElectraForTokenClassification, FlaxElectraModel, FlaxElectraPreTrainedModel, ) else: import sys lowerCamelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
302
1
# this script reports modified .py files under the desired list of top-level sub-dirs passed as a list of arguments, e.g.: # python ./utils/get_modified_files.py utils src tests examples # # it uses git to find the forking point and which files were modified - i.e. files not under git won't be considered # since the output of this script is fed into Makefile commands it doesn't print a newline after the results import re import subprocess import sys lowerCamelCase__ = subprocess.check_output("""git merge-base main HEAD""".split()).decode("""utf-8""") lowerCamelCase__ = ( subprocess.check_output(F"""git diff --diff-filter=d --name-only {fork_point_sha}""".split()).decode("""utf-8""").split() ) lowerCamelCase__ = """|""".join(sys.argv[1:]) lowerCamelCase__ = re.compile(rF"""^({joined_dirs}).*?\.py$""") lowerCamelCase__ = [x for x in modified_files if regex.match(x)] print(""" """.join(relevant_modified_files), end="""""")
302
from __future__ import annotations lowerCamelCase__ = """#""" class SCREAMING_SNAKE_CASE : def __init__( self : Optional[Any] ): '''simple docstring''' __a = {} def UpperCamelCase_ ( self : Optional[Any] , __lowercase : str ): '''simple docstring''' __a = self._trie for char in text: if char not in trie: __a = {} __a = trie[char] __a = True def UpperCamelCase_ ( self : Tuple , __lowercase : str ): '''simple docstring''' __a = self._trie for char in prefix: if char in trie: __a = trie[char] else: return [] return self._elements(__lowercase ) def UpperCamelCase_ ( self : Optional[int] , __lowercase : dict ): '''simple docstring''' __a = [] for c, v in d.items(): __a = [""" """] if c == END else [(c + s) for s in self._elements(__lowercase )] result.extend(__lowercase ) return tuple(__lowercase ) lowerCamelCase__ = Trie() lowerCamelCase__ = ("""depart""", """detergent""", """daring""", """dog""", """deer""", """deal""") for word in words: trie.insert_word(word) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : str ): """simple docstring""" __a = trie.find_word(_SCREAMING_SNAKE_CASE ) return tuple(string + word for word in suffixes ) def lowerCAmelCase__ ( ): """simple docstring""" print(autocomplete_using_trie("""de""" ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
302
1
import gc import unittest import numpy as np import torch import torch.nn.functional as F from transformers import ( ClapTextConfig, ClapTextModelWithProjection, RobertaTokenizer, SpeechTaHifiGan, SpeechTaHifiGanConfig, ) from diffusers import ( AudioLDMPipeline, AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.utils import is_xformers_available, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism from ..pipeline_params import TEXT_TO_AUDIO_BATCH_PARAMS, TEXT_TO_AUDIO_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class SCREAMING_SNAKE_CASE ( lowerCamelCase__ , unittest.TestCase ): __lowerCamelCase : Any =AudioLDMPipeline __lowerCamelCase : Union[str, Any] =TEXT_TO_AUDIO_PARAMS __lowerCamelCase : Union[str, Any] =TEXT_TO_AUDIO_BATCH_PARAMS __lowerCamelCase : Dict =frozenset( [ 'num_inference_steps', 'num_waveforms_per_prompt', 'generator', 'latents', 'output_type', 'return_dict', 'callback', 'callback_steps', ] ) def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' torch.manual_seed(0 ) __a = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=(32, 64) , class_embed_type="""simple_projection""" , projection_class_embeddings_input_dim=32 , class_embeddings_concat=__lowercase , ) __a = DDIMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=__lowercase , set_alpha_to_one=__lowercase , ) torch.manual_seed(0 ) __a = AutoencoderKL( block_out_channels=[32, 64] , in_channels=1 , out_channels=1 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) torch.manual_seed(0 ) __a = ClapTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , projection_dim=32 , ) __a = ClapTextModelWithProjection(__lowercase ) __a = RobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-random-roberta""" , model_max_length=77 ) __a = SpeechTaHifiGanConfig( model_in_dim=8 , sampling_rate=16000 , upsample_initial_channel=16 , upsample_rates=[2, 2] , upsample_kernel_sizes=[4, 4] , resblock_kernel_sizes=[3, 7] , resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5]] , normalize_before=__lowercase , ) __a = SpeechTaHifiGan(__lowercase ) __a = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """vocoder""": vocoder, } return components def UpperCamelCase_ ( self : Any , __lowercase : List[Any] , __lowercase : Union[str, Any]=0 ): '''simple docstring''' if str(__lowercase ).startswith("""mps""" ): __a = torch.manual_seed(__lowercase ) else: __a = torch.Generator(device=__lowercase ).manual_seed(__lowercase ) __a = { """prompt""": """A hammer hitting a wooden surface""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, } return inputs def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' __a = """cpu""" # ensure determinism for the device-dependent torch.Generator __a = self.get_dummy_components() __a = AudioLDMPipeline(**__lowercase ) __a = audioldm_pipe.to(__lowercase ) audioldm_pipe.set_progress_bar_config(disable=__lowercase ) __a = self.get_dummy_inputs(__lowercase ) __a = audioldm_pipe(**__lowercase ) __a = output.audios[0] assert audio.ndim == 1 assert len(__lowercase ) == 256 __a = audio[:10] __a = np.array( [-0.0050, 0.0050, -0.0060, 0.0033, -0.0026, 0.0033, -0.0027, 0.0033, -0.0028, 0.0033] ) assert np.abs(audio_slice - expected_slice ).max() < 1E-2 def UpperCamelCase_ ( self : Any ): '''simple docstring''' __a = self.get_dummy_components() __a = AudioLDMPipeline(**__lowercase ) __a = audioldm_pipe.to(__lowercase ) __a = audioldm_pipe.to(__lowercase ) audioldm_pipe.set_progress_bar_config(disable=__lowercase ) __a = self.get_dummy_inputs(__lowercase ) __a = 3 * [inputs["""prompt"""]] # forward __a = audioldm_pipe(**__lowercase ) __a = output.audios[0] __a = self.get_dummy_inputs(__lowercase ) __a = 3 * [inputs.pop("""prompt""" )] __a = audioldm_pipe.tokenizer( __lowercase , padding="""max_length""" , max_length=audioldm_pipe.tokenizer.model_max_length , truncation=__lowercase , return_tensors="""pt""" , ) __a = text_inputs["""input_ids"""].to(__lowercase ) __a = audioldm_pipe.text_encoder( __lowercase , ) __a = prompt_embeds.text_embeds # additional L_2 normalization over each hidden-state __a = F.normalize(__lowercase , dim=-1 ) __a = prompt_embeds # forward __a = audioldm_pipe(**__lowercase ) __a = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1E-2 def UpperCamelCase_ ( self : str ): '''simple docstring''' __a = self.get_dummy_components() __a = AudioLDMPipeline(**__lowercase ) __a = audioldm_pipe.to(__lowercase ) __a = audioldm_pipe.to(__lowercase ) audioldm_pipe.set_progress_bar_config(disable=__lowercase ) __a = self.get_dummy_inputs(__lowercase ) __a = 3 * ["""this is a negative prompt"""] __a = negative_prompt __a = 3 * [inputs["""prompt"""]] # forward __a = audioldm_pipe(**__lowercase ) __a = output.audios[0] __a = self.get_dummy_inputs(__lowercase ) __a = 3 * [inputs.pop("""prompt""" )] __a = [] for p in [prompt, negative_prompt]: __a = audioldm_pipe.tokenizer( __lowercase , padding="""max_length""" , max_length=audioldm_pipe.tokenizer.model_max_length , truncation=__lowercase , return_tensors="""pt""" , ) __a = text_inputs["""input_ids"""].to(__lowercase ) __a = audioldm_pipe.text_encoder( __lowercase , ) __a = text_embeds.text_embeds # additional L_2 normalization over each hidden-state __a = F.normalize(__lowercase , dim=-1 ) embeds.append(__lowercase ) __a , __a = embeds # forward __a = audioldm_pipe(**__lowercase ) __a = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1E-2 def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' __a = """cpu""" # ensure determinism for the device-dependent torch.Generator __a = self.get_dummy_components() __a = PNDMScheduler(skip_prk_steps=__lowercase ) __a = AudioLDMPipeline(**__lowercase ) __a = audioldm_pipe.to(__lowercase ) audioldm_pipe.set_progress_bar_config(disable=__lowercase ) __a = self.get_dummy_inputs(__lowercase ) __a = """egg cracking""" __a = audioldm_pipe(**__lowercase , negative_prompt=__lowercase ) __a = output.audios[0] assert audio.ndim == 1 assert len(__lowercase ) == 256 __a = audio[:10] __a = np.array( [-0.0051, 0.0050, -0.0060, 0.0034, -0.0026, 0.0033, -0.0027, 0.0033, -0.0028, 0.0032] ) assert np.abs(audio_slice - expected_slice ).max() < 1E-2 def UpperCamelCase_ ( self : str ): '''simple docstring''' __a = """cpu""" # ensure determinism for the device-dependent torch.Generator __a = self.get_dummy_components() __a = PNDMScheduler(skip_prk_steps=__lowercase ) __a = AudioLDMPipeline(**__lowercase ) __a = audioldm_pipe.to(__lowercase ) audioldm_pipe.set_progress_bar_config(disable=__lowercase ) __a = """A hammer hitting a wooden surface""" # test num_waveforms_per_prompt=1 (default) __a = audioldm_pipe(__lowercase , num_inference_steps=2 ).audios assert audios.shape == (1, 256) # test num_waveforms_per_prompt=1 (default) for batch of prompts __a = 2 __a = audioldm_pipe([prompt] * batch_size , num_inference_steps=2 ).audios assert audios.shape == (batch_size, 256) # test num_waveforms_per_prompt for single prompt __a = 2 __a = audioldm_pipe(__lowercase , num_inference_steps=2 , num_waveforms_per_prompt=__lowercase ).audios assert audios.shape == (num_waveforms_per_prompt, 256) # test num_waveforms_per_prompt for batch of prompts __a = 2 __a = audioldm_pipe( [prompt] * batch_size , num_inference_steps=2 , num_waveforms_per_prompt=__lowercase ).audios assert audios.shape == (batch_size * num_waveforms_per_prompt, 256) def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' __a = """cpu""" # ensure determinism for the device-dependent torch.Generator __a = self.get_dummy_components() __a = AudioLDMPipeline(**__lowercase ) __a = audioldm_pipe.to(__lowercase ) audioldm_pipe.set_progress_bar_config(disable=__lowercase ) __a = audioldm_pipe.vocoder.config.sampling_rate __a = self.get_dummy_inputs(__lowercase ) __a = audioldm_pipe(audio_length_in_s=0.016 , **__lowercase ) __a = output.audios[0] assert audio.ndim == 1 assert len(__lowercase ) / vocoder_sampling_rate == 0.016 __a = audioldm_pipe(audio_length_in_s=0.032 , **__lowercase ) __a = output.audios[0] assert audio.ndim == 1 assert len(__lowercase ) / vocoder_sampling_rate == 0.032 def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' __a = self.get_dummy_components() __a = AudioLDMPipeline(**__lowercase ) __a = audioldm_pipe.to(__lowercase ) audioldm_pipe.set_progress_bar_config(disable=__lowercase ) __a = ["""hey"""] __a = audioldm_pipe(__lowercase , num_inference_steps=1 ) __a = output.audios.shape assert audio_shape == (1, 256) __a = audioldm_pipe.vocoder.config config.model_in_dim *= 2 __a = SpeechTaHifiGan(__lowercase ).to(__lowercase ) __a = audioldm_pipe(__lowercase , num_inference_steps=1 ) __a = output.audios.shape # waveform shape is unchanged, we just have 2x the number of mel channels in the spectrogram assert audio_shape == (1, 256) def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' self._test_attention_slicing_forward_pass(test_mean_pixel_difference=__lowercase ) def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' self._test_inference_batch_single_identical(test_mean_pixel_difference=__lowercase ) @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=__lowercase ) @slow class SCREAMING_SNAKE_CASE ( unittest.TestCase ): def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase_ ( self : str , __lowercase : str , __lowercase : Optional[Any]="cpu" , __lowercase : Optional[Any]=torch.floataa , __lowercase : str=0 ): '''simple docstring''' __a = torch.Generator(device=__lowercase ).manual_seed(__lowercase ) __a = np.random.RandomState(__lowercase ).standard_normal((1, 8, 128, 16) ) __a = torch.from_numpy(__lowercase ).to(device=__lowercase , dtype=__lowercase ) __a = { """prompt""": """A hammer hitting a wooden surface""", """latents""": latents, """generator""": generator, """num_inference_steps""": 3, """guidance_scale""": 2.5, } return inputs def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' __a = AudioLDMPipeline.from_pretrained("""cvssp/audioldm""" ) __a = audioldm_pipe.to(__lowercase ) audioldm_pipe.set_progress_bar_config(disable=__lowercase ) __a = self.get_inputs(__lowercase ) __a = 25 __a = audioldm_pipe(**__lowercase ).audios[0] assert audio.ndim == 1 assert len(__lowercase ) == 81920 __a = audio[77230:77240] __a = np.array( [-0.4884, -0.4607, 0.0023, 0.5007, 0.5896, 0.5151, 0.3813, -0.0208, -0.3687, -0.4315] ) __a = np.abs(expected_slice - audio_slice ).max() assert max_diff < 1E-2 def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' __a = AudioLDMPipeline.from_pretrained("""cvssp/audioldm""" ) __a = LMSDiscreteScheduler.from_config(audioldm_pipe.scheduler.config ) __a = audioldm_pipe.to(__lowercase ) audioldm_pipe.set_progress_bar_config(disable=__lowercase ) __a = self.get_inputs(__lowercase ) __a = audioldm_pipe(**__lowercase ).audios[0] assert audio.ndim == 1 assert len(__lowercase ) == 81920 __a = audio[27780:27790] __a = np.array([-0.2131, -0.0873, -0.0124, -0.0189, 0.0569, 0.1373, 0.1883, 0.2886, 0.3297, 0.2212] ) __a = np.abs(expected_slice - audio_slice ).max() assert max_diff < 3E-2
302
from dataclasses import dataclass from typing import Dict, Optional, Union import torch import torch.nn.functional as F from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .attention import BasicTransformerBlock from .attention_processor import AttentionProcessor, AttnProcessor from .embeddings import TimestepEmbedding, Timesteps from .modeling_utils import ModelMixin @dataclass class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : torch.FloatTensor class SCREAMING_SNAKE_CASE ( lowerCamelCase__ , lowerCamelCase__ ): @register_to_config def __init__( self : Dict , __lowercase : int = 32 , __lowercase : int = 64 , __lowercase : int = 20 , __lowercase : int = 768 , __lowercase : Any=77 , __lowercase : Optional[int]=4 , __lowercase : float = 0.0 , __lowercase : str = "silu" , __lowercase : Optional[str] = None , __lowercase : Optional[str] = None , __lowercase : Optional[str] = "linear" , __lowercase : Optional[str] = "prd" , __lowercase : Optional[int] = None , __lowercase : Optional[int] = None , __lowercase : Optional[int] = None , ): '''simple docstring''' super().__init__() __a = num_attention_heads __a = attention_head_dim __a = num_attention_heads * attention_head_dim __a = additional_embeddings __a = time_embed_dim or inner_dim __a = embedding_proj_dim or embedding_dim __a = clip_embed_dim or embedding_dim __a = Timesteps(__lowercase , __lowercase , 0 ) __a = TimestepEmbedding(__lowercase , __lowercase , out_dim=__lowercase , act_fn=__lowercase ) __a = nn.Linear(__lowercase , __lowercase ) if embedding_proj_norm_type is None: __a = None elif embedding_proj_norm_type == "layer": __a = nn.LayerNorm(__lowercase ) else: raise ValueError(F"unsupported embedding_proj_norm_type: {embedding_proj_norm_type}" ) __a = nn.Linear(__lowercase , __lowercase ) if encoder_hid_proj_type is None: __a = None elif encoder_hid_proj_type == "linear": __a = nn.Linear(__lowercase , __lowercase ) else: raise ValueError(F"unsupported encoder_hid_proj_type: {encoder_hid_proj_type}" ) __a = nn.Parameter(torch.zeros(1 , num_embeddings + additional_embeddings , __lowercase ) ) if added_emb_type == "prd": __a = nn.Parameter(torch.zeros(1 , 1 , __lowercase ) ) elif added_emb_type is None: __a = None else: raise ValueError( F"`added_emb_type`: {added_emb_type} is not supported. Make sure to choose one of `'prd'` or `None`." ) __a = nn.ModuleList( [ BasicTransformerBlock( __lowercase , __lowercase , __lowercase , dropout=__lowercase , activation_fn="""gelu""" , attention_bias=__lowercase , ) for d in range(__lowercase ) ] ) if norm_in_type == "layer": __a = nn.LayerNorm(__lowercase ) elif norm_in_type is None: __a = None else: raise ValueError(F"Unsupported norm_in_type: {norm_in_type}." ) __a = nn.LayerNorm(__lowercase ) __a = nn.Linear(__lowercase , __lowercase ) __a = torch.full( [num_embeddings + additional_embeddings, num_embeddings + additional_embeddings] , -10000.0 ) causal_attention_mask.triu_(1 ) __a = causal_attention_mask[None, ...] self.register_buffer("""causal_attention_mask""" , __lowercase , persistent=__lowercase ) __a = nn.Parameter(torch.zeros(1 , __lowercase ) ) __a = nn.Parameter(torch.zeros(1 , __lowercase ) ) @property # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' __a = {} def fn_recursive_add_processors(__lowercase : str , __lowercase : torch.nn.Module , __lowercase : Dict[str, AttentionProcessor] ): if hasattr(__lowercase , """set_processor""" ): __a = module.processor for sub_name, child in module.named_children(): fn_recursive_add_processors(F"{name}.{sub_name}" , __lowercase , __lowercase ) return processors for name, module in self.named_children(): fn_recursive_add_processors(__lowercase , __lowercase , __lowercase ) return processors def UpperCamelCase_ ( self : List[str] , __lowercase : Union[AttentionProcessor, Dict[str, AttentionProcessor]] ): '''simple docstring''' __a = len(self.attn_processors.keys() ) if isinstance(__lowercase , __lowercase ) and len(__lowercase ) != count: raise ValueError( F"A dict of processors was passed, but the number of processors {len(__lowercase )} does not match the" F" number of attention layers: {count}. Please make sure to pass {count} processor classes." ) def fn_recursive_attn_processor(__lowercase : str , __lowercase : torch.nn.Module , __lowercase : Dict ): if hasattr(__lowercase , """set_processor""" ): if not isinstance(__lowercase , __lowercase ): module.set_processor(__lowercase ) else: module.set_processor(processor.pop(F"{name}.processor" ) ) for sub_name, child in module.named_children(): fn_recursive_attn_processor(F"{name}.{sub_name}" , __lowercase , __lowercase ) for name, module in self.named_children(): fn_recursive_attn_processor(__lowercase , __lowercase , __lowercase ) def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' self.set_attn_processor(AttnProcessor() ) def UpperCamelCase_ ( self : Union[str, Any] , __lowercase : Optional[int] , __lowercase : Union[torch.Tensor, float, int] , __lowercase : torch.FloatTensor , __lowercase : Optional[torch.FloatTensor] = None , __lowercase : Optional[torch.BoolTensor] = None , __lowercase : bool = True , ): '''simple docstring''' __a = hidden_states.shape[0] __a = timestep if not torch.is_tensor(__lowercase ): __a = torch.tensor([timesteps] , dtype=torch.long , device=hidden_states.device ) elif torch.is_tensor(__lowercase ) and len(timesteps.shape ) == 0: __a = timesteps[None].to(hidden_states.device ) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML __a = timesteps * torch.ones(__lowercase , dtype=timesteps.dtype , device=timesteps.device ) __a = self.time_proj(__lowercase ) # timesteps does not contain any weights and will always return f32 tensors # but time_embedding might be fp16, so we need to cast here. __a = timesteps_projected.to(dtype=self.dtype ) __a = self.time_embedding(__lowercase ) if self.embedding_proj_norm is not None: __a = self.embedding_proj_norm(__lowercase ) __a = self.embedding_proj(__lowercase ) if self.encoder_hidden_states_proj is not None and encoder_hidden_states is not None: __a = self.encoder_hidden_states_proj(__lowercase ) elif self.encoder_hidden_states_proj is not None and encoder_hidden_states is None: raise ValueError("""`encoder_hidden_states_proj` requires `encoder_hidden_states` to be set""" ) __a = self.proj_in(__lowercase ) __a = self.positional_embedding.to(hidden_states.dtype ) __a = [] __a = 0 if encoder_hidden_states is not None: additional_embeds.append(__lowercase ) additional_embeddings_len += encoder_hidden_states.shape[1] if len(proj_embeddings.shape ) == 2: __a = proj_embeddings[:, None, :] if len(hidden_states.shape ) == 2: __a = hidden_states[:, None, :] __a = additional_embeds + [ proj_embeddings, time_embeddings[:, None, :], hidden_states, ] if self.prd_embedding is not None: __a = self.prd_embedding.to(hidden_states.dtype ).expand(__lowercase , -1 , -1 ) additional_embeds.append(__lowercase ) __a = torch.cat( __lowercase , dim=1 , ) # Allow positional_embedding to not include the `addtional_embeddings` and instead pad it with zeros for these additional tokens __a = additional_embeddings_len + proj_embeddings.shape[1] + 1 if positional_embeddings.shape[1] < hidden_states.shape[1]: __a = F.pad( __lowercase , ( 0, 0, additional_embeddings_len, self.prd_embedding.shape[1] if self.prd_embedding is not None else 0, ) , value=0.0 , ) __a = hidden_states + positional_embeddings if attention_mask is not None: __a = (1 - attention_mask.to(hidden_states.dtype )) * -10000.0 __a = F.pad(__lowercase , (0, self.additional_embeddings) , value=0.0 ) __a = (attention_mask[:, None, :] + self.causal_attention_mask).to(hidden_states.dtype ) __a = attention_mask.repeat_interleave(self.config.num_attention_heads , dim=0 ) if self.norm_in is not None: __a = self.norm_in(__lowercase ) for block in self.transformer_blocks: __a = block(__lowercase , attention_mask=__lowercase ) __a = self.norm_out(__lowercase ) if self.prd_embedding is not None: __a = hidden_states[:, -1] else: __a = hidden_states[:, additional_embeddings_len:] __a = self.proj_to_clip_embeddings(__lowercase ) if not return_dict: return (predicted_image_embedding,) return PriorTransformerOutput(predicted_image_embedding=__lowercase ) def UpperCamelCase_ ( self : Any , __lowercase : Tuple ): '''simple docstring''' __a = (prior_latents * self.clip_std) + self.clip_mean return prior_latents
302
1
import absl # noqa: F401 # Here to have a nice missing dependency error message early on import nltk # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import six # noqa: F401 # Here to have a nice missing dependency error message early on from rouge_score import rouge_scorer, scoring import datasets lowerCamelCase__ = """\ @inproceedings{lin-2004-rouge, title = \"{ROUGE}: A Package for Automatic Evaluation of Summaries\", author = \"Lin, Chin-Yew\", booktitle = \"Text Summarization Branches Out\", month = jul, year = \"2004\", address = \"Barcelona, Spain\", publisher = \"Association for Computational Linguistics\", url = \"https://www.aclweb.org/anthology/W04-1013\", pages = \"74--81\", } """ lowerCamelCase__ = """\ ROUGE, or Recall-Oriented Understudy for Gisting Evaluation, is a set of metrics and a software package used for evaluating automatic summarization and machine translation software in natural language processing. The metrics compare an automatically produced summary or translation against a reference or a set of references (human-produced) summary or translation. Note that ROUGE is case insensitive, meaning that upper case letters are treated the same way as lower case letters. This metrics is a wrapper around Google Research reimplementation of ROUGE: https://github.com/google-research/google-research/tree/master/rouge """ lowerCamelCase__ = """ Calculates average rouge scores for a list of hypotheses and 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. rouge_types: A list of rouge types to calculate. Valid names: `\"rouge{n}\"` (e.g. `\"rouge1\"`, `\"rouge2\"`) where: {n} is the n-gram based scoring, `\"rougeL\"`: Longest common subsequence based scoring. `\"rougeLSum\"`: rougeLsum splits text using `\"\n\"`. See details in https://github.com/huggingface/datasets/issues/617 use_stemmer: Bool indicating whether Porter stemmer should be used to strip word suffixes. use_aggregator: Return aggregates if this is set to True Returns: rouge1: rouge_1 (precision, recall, f1), rouge2: rouge_2 (precision, recall, f1), rougeL: rouge_l (precision, recall, f1), rougeLsum: rouge_lsum (precision, recall, f1) Examples: >>> rouge = datasets.load_metric('rouge') >>> predictions = [\"hello there\", \"general kenobi\"] >>> references = [\"hello there\", \"general kenobi\"] >>> results = rouge.compute(predictions=predictions, references=references) >>> print(list(results.keys())) ['rouge1', 'rouge2', 'rougeL', 'rougeLsum'] >>> print(results[\"rouge1\"]) AggregateScore(low=Score(precision=1.0, recall=1.0, fmeasure=1.0), mid=Score(precision=1.0, recall=1.0, fmeasure=1.0), high=Score(precision=1.0, recall=1.0, fmeasure=1.0)) >>> print(results[\"rouge1\"].mid.fmeasure) 1.0 """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class SCREAMING_SNAKE_CASE ( datasets.Metric ): def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""string""" , id="""sequence""" ), """references""": datasets.Value("""string""" , id="""sequence""" ), } ) , codebase_urls=["""https://github.com/google-research/google-research/tree/master/rouge"""] , reference_urls=[ """https://en.wikipedia.org/wiki/ROUGE_(metric)""", """https://github.com/google-research/google-research/tree/master/rouge""", ] , ) def UpperCamelCase_ ( self : Any , __lowercase : str , __lowercase : Dict , __lowercase : int=None , __lowercase : List[str]=True , __lowercase : int=False ): '''simple docstring''' if rouge_types is None: __a = ["""rouge1""", """rouge2""", """rougeL""", """rougeLsum"""] __a = rouge_scorer.RougeScorer(rouge_types=__lowercase , use_stemmer=__lowercase ) if use_aggregator: __a = scoring.BootstrapAggregator() else: __a = [] for ref, pred in zip(__lowercase , __lowercase ): __a = scorer.score(__lowercase , __lowercase ) if use_aggregator: aggregator.add_scores(__lowercase ) else: scores.append(__lowercase ) if use_aggregator: __a = aggregator.aggregate() else: __a = {} for key in scores[0]: __a = [score[key] for score in scores] return result
302
from functools import lru_cache def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int ): """simple docstring""" __a = 2 __a = set() while i * i <= n: if n % i: i += 1 else: n //= i factors.add(_SCREAMING_SNAKE_CASE ) if n > 1: factors.add(_SCREAMING_SNAKE_CASE ) return factors @lru_cache def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int ): """simple docstring""" return len(unique_prime_factors(_SCREAMING_SNAKE_CASE ) ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : list ): """simple docstring""" return len(set(_SCREAMING_SNAKE_CASE ) ) in (0, 1) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int ): """simple docstring""" __a = 2 while True: # Increment each value of a generated range __a = [base + i for i in range(_SCREAMING_SNAKE_CASE )] # Run elements through out unique_prime_factors function # Append our target number to the end. __a = [upf_len(_SCREAMING_SNAKE_CASE ) for x in group] checker.append(_SCREAMING_SNAKE_CASE ) # If all numbers in the list are equal, return the group variable. if equality(_SCREAMING_SNAKE_CASE ): return group # Increment our base variable by 1 base += 1 def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int = 4 ): """simple docstring""" __a = run(_SCREAMING_SNAKE_CASE ) return results[0] if len(_SCREAMING_SNAKE_CASE ) else None if __name__ == "__main__": print(solution())
302
1
from functools import lru_cache def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int ): """simple docstring""" __a = 2 __a = set() while i * i <= n: if n % i: i += 1 else: n //= i factors.add(_SCREAMING_SNAKE_CASE ) if n > 1: factors.add(_SCREAMING_SNAKE_CASE ) return factors @lru_cache def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int ): """simple docstring""" return len(unique_prime_factors(_SCREAMING_SNAKE_CASE ) ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : list ): """simple docstring""" return len(set(_SCREAMING_SNAKE_CASE ) ) in (0, 1) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int ): """simple docstring""" __a = 2 while True: # Increment each value of a generated range __a = [base + i for i in range(_SCREAMING_SNAKE_CASE )] # Run elements through out unique_prime_factors function # Append our target number to the end. __a = [upf_len(_SCREAMING_SNAKE_CASE ) for x in group] checker.append(_SCREAMING_SNAKE_CASE ) # If all numbers in the list are equal, return the group variable. if equality(_SCREAMING_SNAKE_CASE ): return group # Increment our base variable by 1 base += 1 def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int = 4 ): """simple docstring""" __a = run(_SCREAMING_SNAKE_CASE ) return results[0] if len(_SCREAMING_SNAKE_CASE ) else None if __name__ == "__main__": print(solution())
302
import argparse import json from pathlib import Path import torch import torchaudio from datasets import load_dataset from huggingface_hub import hf_hub_download from transformers import ASTConfig, ASTFeatureExtractor, ASTForAudioClassification from transformers.utils import logging logging.set_verbosity_info() lowerCamelCase__ = logging.get_logger(__name__) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Any ): """simple docstring""" __a = ASTConfig() if "10-10" in model_name: pass elif "speech-commands" in model_name: __a = 128 elif "12-12" in model_name: __a = 12 __a = 12 elif "14-14" in model_name: __a = 14 __a = 14 elif "16-16" in model_name: __a = 16 __a = 16 else: raise ValueError("""Model not supported""" ) __a = """huggingface/label-files""" if "speech-commands" in model_name: __a = 35 __a = """speech-commands-v2-id2label.json""" else: __a = 527 __a = """audioset-id2label.json""" __a = json.load(open(hf_hub_download(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , repo_type="""dataset""" ) , """r""" ) ) __a = {int(_SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()} __a = idalabel __a = {v: k for k, v in idalabel.items()} return config def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" if "module.v" in name: __a = name.replace("""module.v""" , """audio_spectrogram_transformer""" ) if "cls_token" in name: __a = name.replace("""cls_token""" , """embeddings.cls_token""" ) if "dist_token" in name: __a = name.replace("""dist_token""" , """embeddings.distillation_token""" ) if "pos_embed" in name: __a = name.replace("""pos_embed""" , """embeddings.position_embeddings""" ) if "patch_embed.proj" in name: __a = name.replace("""patch_embed.proj""" , """embeddings.patch_embeddings.projection""" ) # transformer blocks if "blocks" in name: __a = name.replace("""blocks""" , """encoder.layer""" ) if "attn.proj" in name: __a = name.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in name: __a = name.replace("""attn""" , """attention.self""" ) if "norm1" in name: __a = name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: __a = name.replace("""norm2""" , """layernorm_after""" ) if "mlp.fc1" in name: __a = name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: __a = name.replace("""mlp.fc2""" , """output.dense""" ) # final layernorm if "audio_spectrogram_transformer.norm" in name: __a = name.replace("""audio_spectrogram_transformer.norm""" , """audio_spectrogram_transformer.layernorm""" ) # classifier head if "module.mlp_head.0" in name: __a = name.replace("""module.mlp_head.0""" , """classifier.layernorm""" ) if "module.mlp_head.1" in name: __a = name.replace("""module.mlp_head.1""" , """classifier.dense""" ) return name def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" for key in orig_state_dict.copy().keys(): __a = orig_state_dict.pop(_SCREAMING_SNAKE_CASE ) if "qkv" in key: __a = key.split(""".""" ) __a = int(key_split[3] ) __a = config.hidden_size if "weight" in key: __a = val[:dim, :] __a = val[dim : dim * 2, :] __a = val[-dim:, :] else: __a = val[:dim] __a = val[dim : dim * 2] __a = val[-dim:] else: __a = val return orig_state_dict def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" __a = [ """module.v.head.weight""", """module.v.head.bias""", """module.v.head_dist.weight""", """module.v.head_dist.bias""", ] for k in ignore_keys: state_dict.pop(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @torch.no_grad() def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : List[str]=False ): """simple docstring""" __a = get_audio_spectrogram_transformer_config(_SCREAMING_SNAKE_CASE ) __a = { """ast-finetuned-audioset-10-10-0.4593""": ( """https://www.dropbox.com/s/ca0b1v2nlxzyeb4/audioset_10_10_0.4593.pth?dl=1""" ), """ast-finetuned-audioset-10-10-0.450""": ( """https://www.dropbox.com/s/1tv0hovue1bxupk/audioset_10_10_0.4495.pth?dl=1""" ), """ast-finetuned-audioset-10-10-0.448""": ( """https://www.dropbox.com/s/6u5sikl4b9wo4u5/audioset_10_10_0.4483.pth?dl=1""" ), """ast-finetuned-audioset-10-10-0.448-v2""": ( """https://www.dropbox.com/s/kt6i0v9fvfm1mbq/audioset_10_10_0.4475.pth?dl=1""" ), """ast-finetuned-audioset-12-12-0.447""": ( """https://www.dropbox.com/s/snfhx3tizr4nuc8/audioset_12_12_0.4467.pth?dl=1""" ), """ast-finetuned-audioset-14-14-0.443""": ( """https://www.dropbox.com/s/z18s6pemtnxm4k7/audioset_14_14_0.4431.pth?dl=1""" ), """ast-finetuned-audioset-16-16-0.442""": ( """https://www.dropbox.com/s/mdsa4t1xmcimia6/audioset_16_16_0.4422.pth?dl=1""" ), """ast-finetuned-speech-commands-v2""": ( """https://www.dropbox.com/s/q0tbqpwv44pquwy/speechcommands_10_10_0.9812.pth?dl=1""" ), } # load original state_dict __a = model_name_to_url[model_name] __a = torch.hub.load_state_dict_from_url(_SCREAMING_SNAKE_CASE , map_location="""cpu""" ) # remove some keys remove_keys(_SCREAMING_SNAKE_CASE ) # rename some keys __a = convert_state_dict(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # load 🤗 model __a = ASTForAudioClassification(_SCREAMING_SNAKE_CASE ) model.eval() model.load_state_dict(_SCREAMING_SNAKE_CASE ) # verify outputs on dummy input # source: https://github.com/YuanGongND/ast/blob/79e873b8a54d0a3b330dd522584ff2b9926cd581/src/run.py#L62 __a = -4.267_7393 if """speech-commands""" not in model_name else -6.84_5978 __a = 4.568_9974 if """speech-commands""" not in model_name else 5.565_4526 __a = 1024 if """speech-commands""" not in model_name else 128 __a = ASTFeatureExtractor(mean=_SCREAMING_SNAKE_CASE , std=_SCREAMING_SNAKE_CASE , max_length=_SCREAMING_SNAKE_CASE ) if "speech-commands" in model_name: __a = load_dataset("""speech_commands""" , """v0.02""" , split="""validation""" ) __a = dataset[0]["""audio"""]["""array"""] else: __a = hf_hub_download( repo_id="""nielsr/audio-spectogram-transformer-checkpoint""" , filename="""sample_audio.flac""" , repo_type="""dataset""" , ) __a , __a = torchaudio.load(_SCREAMING_SNAKE_CASE ) __a = waveform.squeeze().numpy() __a = feature_extractor(_SCREAMING_SNAKE_CASE , sampling_rate=1_6000 , return_tensors="""pt""" ) # forward pass __a = model(**_SCREAMING_SNAKE_CASE ) __a = outputs.logits if model_name == "ast-finetuned-audioset-10-10-0.4593": __a = torch.tensor([-0.8760, -7.0042, -8.6602] ) elif model_name == "ast-finetuned-audioset-10-10-0.450": __a = torch.tensor([-1.1986, -7.0903, -8.2718] ) elif model_name == "ast-finetuned-audioset-10-10-0.448": __a = torch.tensor([-2.6128, -8.0080, -9.4344] ) elif model_name == "ast-finetuned-audioset-10-10-0.448-v2": __a = torch.tensor([-1.5080, -7.4534, -8.8917] ) elif model_name == "ast-finetuned-audioset-12-12-0.447": __a = torch.tensor([-0.5050, -6.5833, -8.0843] ) elif model_name == "ast-finetuned-audioset-14-14-0.443": __a = torch.tensor([-0.3826, -7.0336, -8.2413] ) elif model_name == "ast-finetuned-audioset-16-16-0.442": __a = torch.tensor([-1.2113, -6.9101, -8.3470] ) elif model_name == "ast-finetuned-speech-commands-v2": __a = torch.tensor([6.1589, -8.0566, -8.7984] ) else: raise ValueError("""Unknown model name""" ) if not torch.allclose(logits[0, :3] , _SCREAMING_SNAKE_CASE , atol=1e-4 ): raise ValueError("""Logits don't match""" ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) print(f"Saving model {model_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) print(f"Saving feature extractor to {pytorch_dump_folder_path}" ) feature_extractor.save_pretrained(_SCREAMING_SNAKE_CASE ) if push_to_hub: print("""Pushing model and feature extractor to the hub...""" ) model.push_to_hub(f"MIT/{model_name}" ) feature_extractor.push_to_hub(f"MIT/{model_name}" ) if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default="""ast-finetuned-audioset-10-10-0.4593""", type=str, help="""Name of the Audio Spectrogram Transformer model you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) parser.add_argument( """--push_to_hub""", action="""store_true""", help="""Whether or not to push the converted model to the 🤗 hub.""" ) lowerCamelCase__ = parser.parse_args() convert_audio_spectrogram_transformer_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
302
1
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { """google/switch-base-8""": """https://huggingface.co/google/switch-base-8/blob/main/config.json""", } class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : Optional[int] ='switch_transformers' __lowerCamelCase : str =['past_key_values'] __lowerCamelCase : Dict ={'hidden_size': 'd_model', 'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers'} def __init__( self : Optional[Any] , __lowercase : Any=32128 , __lowercase : int=768 , __lowercase : Tuple=64 , __lowercase : Dict=2048 , __lowercase : str=64 , __lowercase : Optional[Any]=12 , __lowercase : int=3 , __lowercase : int=12 , __lowercase : Optional[int]=3 , __lowercase : Dict=12 , __lowercase : Tuple=8 , __lowercase : Tuple=False , __lowercase : Optional[Any]=0.01 , __lowercase : Tuple="float32" , __lowercase : str=False , __lowercase : Any=32 , __lowercase : Dict=128 , __lowercase : Tuple=0.1 , __lowercase : List[str]=1E-6 , __lowercase : Dict=0.001 , __lowercase : Dict=0.001 , __lowercase : List[str]=1.0 , __lowercase : Any="relu" , __lowercase : Any=True , __lowercase : Tuple=False , __lowercase : Any=True , __lowercase : int=0 , __lowercase : Any=1 , **__lowercase : Tuple , ): '''simple docstring''' __a = vocab_size __a = d_model __a = d_kv __a = d_ff __a = num_sparse_encoder_layers __a = num_layers __a = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry __a = num_sparse_decoder_layers # This tells us, each how many encoder layer we'll have to set a sparse layer. if self.num_sparse_encoder_layers > 0: __a = self.num_layers // self.num_sparse_encoder_layers else: __a = self.num_layers # HACK: this will create 0 sparse layers # This tells us, each how many encoder layer we'll have to set a sparse layer. if self.num_sparse_decoder_layers > 0: __a = self.num_decoder_layers // self.num_sparse_decoder_layers else: __a = self.num_decoder_layers # HACK: this will create 0 sparse layers __a = num_heads __a = num_experts __a = expert_capacity __a = router_bias __a = router_jitter_noise if router_dtype not in ["float32", "float16", "bfloat16"]: raise ValueError(F"`router_dtype` must be one of 'float32', 'float16' or 'bfloat16', got {router_dtype}" ) __a = router_dtype __a = router_ignore_padding_tokens __a = relative_attention_num_buckets __a = relative_attention_max_distance __a = dropout_rate __a = layer_norm_epsilon __a = initializer_factor __a = feed_forward_proj __a = use_cache __a = add_router_probs __a = router_z_loss_coef __a = router_aux_loss_coef __a = self.feed_forward_proj.split("""-""" ) __a = act_info[-1] __a = act_info[0] == """gated""" if len(__lowercase ) > 1 and act_info[0] != "gated" or len(__lowercase ) > 2: raise ValueError( F"`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer." """Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. """ """'gated-gelu' or 'relu'""" ) # for backwards compatibility if feed_forward_proj == "gated-gelu": __a = """gelu_new""" super().__init__( pad_token_id=__lowercase , eos_token_id=__lowercase , is_encoder_decoder=__lowercase , **__lowercase , )
302
import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_albert import AlbertTokenizer else: lowerCamelCase__ = None lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = {"""vocab_file""": """spiece.model""", """tokenizer_file""": """tokenizer.json"""} lowerCamelCase__ = { """vocab_file""": { """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/spiece.model""", """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/spiece.model""", """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model""", """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model""", """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/spiece.model""", """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/spiece.model""", """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model""", """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model""", }, """tokenizer_file""": { """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/tokenizer.json""", """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/tokenizer.json""", """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/tokenizer.json""", """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/tokenizer.json""", """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/tokenizer.json""", """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/tokenizer.json""", """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/tokenizer.json""", """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/tokenizer.json""", }, } lowerCamelCase__ = { """albert-base-v1""": 512, """albert-large-v1""": 512, """albert-xlarge-v1""": 512, """albert-xxlarge-v1""": 512, """albert-base-v2""": 512, """albert-large-v2""": 512, """albert-xlarge-v2""": 512, """albert-xxlarge-v2""": 512, } lowerCamelCase__ = """▁""" class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : List[Any] =VOCAB_FILES_NAMES __lowerCamelCase : Union[str, Any] =PRETRAINED_VOCAB_FILES_MAP __lowerCamelCase : List[str] =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCamelCase : Any =AlbertTokenizer def __init__( self : Tuple , __lowercase : Union[str, Any]=None , __lowercase : Optional[int]=None , __lowercase : int=True , __lowercase : Dict=True , __lowercase : str=False , __lowercase : str="[CLS]" , __lowercase : List[Any]="[SEP]" , __lowercase : Any="<unk>" , __lowercase : List[Any]="[SEP]" , __lowercase : List[Any]="<pad>" , __lowercase : Optional[Any]="[CLS]" , __lowercase : List[str]="[MASK]" , **__lowercase : str , ): '''simple docstring''' # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. __a = ( AddedToken(__lowercase , lstrip=__lowercase , rstrip=__lowercase , normalized=__lowercase ) if isinstance(__lowercase , __lowercase ) else mask_token ) super().__init__( __lowercase , tokenizer_file=__lowercase , do_lower_case=__lowercase , remove_space=__lowercase , keep_accents=__lowercase , bos_token=__lowercase , eos_token=__lowercase , unk_token=__lowercase , sep_token=__lowercase , pad_token=__lowercase , cls_token=__lowercase , mask_token=__lowercase , **__lowercase , ) __a = do_lower_case __a = remove_space __a = keep_accents __a = vocab_file __a = False if not self.vocab_file else True def UpperCamelCase_ ( self : Dict , __lowercase : List[int] , __lowercase : Optional[List[int]] = None ): '''simple docstring''' __a = [self.sep_token_id] __a = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def UpperCamelCase_ ( self : str , __lowercase : List[int] , __lowercase : Optional[List[int]] = None ): '''simple docstring''' __a = [self.sep_token_id] __a = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCamelCase_ ( self : Tuple , __lowercase : str , __lowercase : Optional[str] = None ): '''simple docstring''' if not self.can_save_slow_tokenizer: raise ValueError( """Your fast tokenizer does not have the necessary information to save the vocabulary for a slow """ """tokenizer.""" ) if not os.path.isdir(__lowercase ): logger.error(F"Vocabulary path ({save_directory}) should be a directory" ) return __a = os.path.join( __lowercase , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__lowercase ): copyfile(self.vocab_file , __lowercase ) return (out_vocab_file,)
302
1
import logging import os import sys from dataclasses import dataclass, field from importlib import import_module from typing import Dict, List, Optional, Tuple import numpy as np from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torch import nn from utils_ner import Split, TokenClassificationDataset, TokenClassificationTask import transformers from transformers import ( AutoConfig, AutoModelForTokenClassification, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process lowerCamelCase__ = logging.getLogger(__name__) @dataclass class SCREAMING_SNAKE_CASE : __lowerCamelCase : str =field( metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'} ) __lowerCamelCase : Optional[str] =field( default=lowerCamelCase__ , metadata={'help': 'Pretrained config name or path if not the same as model_name'} ) __lowerCamelCase : Optional[str] =field( default='NER' , metadata={'help': 'Task type to fine tune in training (e.g. NER, POS, etc)'} ) __lowerCamelCase : Optional[str] =field( default=lowerCamelCase__ , metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'} ) __lowerCamelCase : bool =field(default=lowerCamelCase__ , metadata={'help': 'Set this flag to use fast tokenization.'} ) # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script, # or just modify its tokenizer_config.json. __lowerCamelCase : Optional[str] =field( default=lowerCamelCase__ , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'} , ) @dataclass class SCREAMING_SNAKE_CASE : __lowerCamelCase : str =field( metadata={'help': 'The input data dir. Should contain the .txt files for a CoNLL-2003-formatted task.'} ) __lowerCamelCase : Optional[str] =field( default=lowerCamelCase__ , metadata={'help': 'Path to a file containing all labels. If not specified, CoNLL-2003 labels are used.'} , ) __lowerCamelCase : 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.' ) } , ) __lowerCamelCase : bool =field( default=lowerCamelCase__ , metadata={'help': 'Overwrite the cached training and evaluation sets'} ) def lowerCAmelCase__ ( ): """simple docstring""" __a = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(""".json""" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. __a , __a , __a = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: __a , __a , __a = 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.""" ) __a = import_module("""tasks""" ) try: __a = getattr(_SCREAMING_SNAKE_CASE , model_args.task_type ) __a = token_classification_task_clazz() except AttributeError: raise ValueError( f"Task {model_args.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. " f"Available tasks classes are: {TokenClassificationTask.__subclasses__()}" ) # 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""" , _SCREAMING_SNAKE_CASE ) # Set seed set_seed(training_args.seed ) # Prepare CONLL-2003 task __a = token_classification_task.get_labels(data_args.labels ) __a = dict(enumerate(_SCREAMING_SNAKE_CASE ) ) __a = len(_SCREAMING_SNAKE_CASE ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. __a = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=_SCREAMING_SNAKE_CASE , idalabel=_SCREAMING_SNAKE_CASE , labelaid={label: i for i, label in enumerate(_SCREAMING_SNAKE_CASE )} , cache_dir=model_args.cache_dir , ) __a = 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 , use_fast=model_args.use_fast , ) __a = AutoModelForTokenClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) , config=_SCREAMING_SNAKE_CASE , cache_dir=model_args.cache_dir , ) # Get datasets __a = ( TokenClassificationDataset( token_classification_task=_SCREAMING_SNAKE_CASE , data_dir=data_args.data_dir , tokenizer=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE , model_type=config.model_type , 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 = ( TokenClassificationDataset( token_classification_task=_SCREAMING_SNAKE_CASE , data_dir=data_args.data_dir , tokenizer=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE , model_type=config.model_type , 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 align_predictions(_SCREAMING_SNAKE_CASE : np.ndarray , _SCREAMING_SNAKE_CASE : np.ndarray ) -> Tuple[List[int], List[int]]: __a = np.argmax(_SCREAMING_SNAKE_CASE , axis=2 ) __a , __a = preds.shape __a = [[] for _ in range(_SCREAMING_SNAKE_CASE )] __a = [[] for _ in range(_SCREAMING_SNAKE_CASE )] for i in range(_SCREAMING_SNAKE_CASE ): for j in range(_SCREAMING_SNAKE_CASE ): if label_ids[i, j] != nn.CrossEntropyLoss().ignore_index: out_label_list[i].append(label_map[label_ids[i][j]] ) preds_list[i].append(label_map[preds[i][j]] ) return preds_list, out_label_list def compute_metrics(_SCREAMING_SNAKE_CASE : EvalPrediction ) -> Dict: __a , __a = align_predictions(p.predictions , p.label_ids ) return { "accuracy_score": accuracy_score(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ), "precision": precision_score(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ), "recall": recall_score(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ), "f1": fa_score(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ), } # Data collator __a = DataCollatorWithPadding(_SCREAMING_SNAKE_CASE , pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer __a = Trainer( model=_SCREAMING_SNAKE_CASE , args=_SCREAMING_SNAKE_CASE , train_dataset=_SCREAMING_SNAKE_CASE , eval_dataset=_SCREAMING_SNAKE_CASE , compute_metrics=_SCREAMING_SNAKE_CASE , data_collator=_SCREAMING_SNAKE_CASE , ) # 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_process_zero(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation __a = {} if training_args.do_eval: logger.info("""*** Evaluate ***""" ) __a = trainer.evaluate() __a = os.path.join(training_args.output_dir , """eval_results.txt""" ) if trainer.is_world_process_zero(): with open(_SCREAMING_SNAKE_CASE , """w""" ) as writer: logger.info("""***** Eval results *****""" ) for key, value in result.items(): logger.info(""" %s = %s""" , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) writer.write("""%s = %s\n""" % (key, value) ) results.update(_SCREAMING_SNAKE_CASE ) # Predict if training_args.do_predict: __a = TokenClassificationDataset( token_classification_task=_SCREAMING_SNAKE_CASE , data_dir=data_args.data_dir , tokenizer=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.test , ) __a , __a , __a = trainer.predict(_SCREAMING_SNAKE_CASE ) __a , __a = align_predictions(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __a = os.path.join(training_args.output_dir , """test_results.txt""" ) if trainer.is_world_process_zero(): with open(_SCREAMING_SNAKE_CASE , """w""" ) as writer: for key, value in metrics.items(): logger.info(""" %s = %s""" , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) writer.write("""%s = %s\n""" % (key, value) ) # Save predictions __a = os.path.join(training_args.output_dir , """test_predictions.txt""" ) if trainer.is_world_process_zero(): with open(_SCREAMING_SNAKE_CASE , """w""" ) as writer: with open(os.path.join(data_args.data_dir , """test.txt""" ) , """r""" ) as f: token_classification_task.write_predictions_to_file(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return results def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : List[Any] ): """simple docstring""" main() if __name__ == "__main__": main()
302
import tempfile import torch from diffusers import IPNDMScheduler from .test_schedulers import SchedulerCommonTest class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : Optional[int] =(IPNDMScheduler,) __lowerCamelCase : int =(('num_inference_steps', 50),) def UpperCamelCase_ ( self : str , **__lowercase : Dict ): '''simple docstring''' __a = {"""num_train_timesteps""": 1000} config.update(**__lowercase ) return config def UpperCamelCase_ ( self : Any , __lowercase : Tuple=0 , **__lowercase : Dict ): '''simple docstring''' __a = dict(self.forward_default_kwargs ) __a = kwargs.pop("""num_inference_steps""" , __lowercase ) __a = self.dummy_sample __a = 0.1 * sample __a = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: __a = self.get_scheduler_config(**__lowercase ) __a = scheduler_class(**__lowercase ) scheduler.set_timesteps(__lowercase ) # copy over dummy past residuals __a = dummy_past_residuals[:] if time_step is None: __a = scheduler.timesteps[len(scheduler.timesteps ) // 2] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(__lowercase ) __a = scheduler_class.from_pretrained(__lowercase ) new_scheduler.set_timesteps(__lowercase ) # copy over dummy past residuals __a = dummy_past_residuals[:] __a = scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample __a = new_scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" __a = scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample __a = new_scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def UpperCamelCase_ ( self : str ): '''simple docstring''' pass def UpperCamelCase_ ( self : str , __lowercase : int=0 , **__lowercase : Dict ): '''simple docstring''' __a = dict(self.forward_default_kwargs ) __a = kwargs.pop("""num_inference_steps""" , __lowercase ) __a = self.dummy_sample __a = 0.1 * sample __a = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: __a = self.get_scheduler_config() __a = scheduler_class(**__lowercase ) scheduler.set_timesteps(__lowercase ) # copy over dummy past residuals (must be after setting timesteps) __a = dummy_past_residuals[:] if time_step is None: __a = scheduler.timesteps[len(scheduler.timesteps ) // 2] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(__lowercase ) __a = scheduler_class.from_pretrained(__lowercase ) # copy over dummy past residuals new_scheduler.set_timesteps(__lowercase ) # copy over dummy past residual (must be after setting timesteps) __a = dummy_past_residuals[:] __a = scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample __a = new_scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" __a = scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample __a = new_scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def UpperCamelCase_ ( self : List[str] , **__lowercase : Dict ): '''simple docstring''' __a = self.scheduler_classes[0] __a = self.get_scheduler_config(**__lowercase ) __a = scheduler_class(**__lowercase ) __a = 10 __a = self.dummy_model() __a = self.dummy_sample_deter scheduler.set_timesteps(__lowercase ) for i, t in enumerate(scheduler.timesteps ): __a = model(__lowercase , __lowercase ) __a = scheduler.step(__lowercase , __lowercase , __lowercase ).prev_sample for i, t in enumerate(scheduler.timesteps ): __a = model(__lowercase , __lowercase ) __a = scheduler.step(__lowercase , __lowercase , __lowercase ).prev_sample return sample def UpperCamelCase_ ( self : str ): '''simple docstring''' __a = dict(self.forward_default_kwargs ) __a = kwargs.pop("""num_inference_steps""" , __lowercase ) for scheduler_class in self.scheduler_classes: __a = self.get_scheduler_config() __a = scheduler_class(**__lowercase ) __a = self.dummy_sample __a = 0.1 * sample if num_inference_steps is not None and hasattr(__lowercase , """set_timesteps""" ): scheduler.set_timesteps(__lowercase ) elif num_inference_steps is not None and not hasattr(__lowercase , """set_timesteps""" ): __a = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) __a = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] __a = dummy_past_residuals[:] __a = scheduler.timesteps[5] __a = scheduler.timesteps[6] __a = scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample __a = scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) __a = scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample __a = scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' for timesteps in [100, 1000]: self.check_over_configs(num_train_timesteps=__lowercase , time_step=__lowercase ) def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' for t, num_inference_steps in zip([1, 5, 10] , [10, 50, 100] ): self.check_over_forward(num_inference_steps=__lowercase , time_step=__lowercase ) def UpperCamelCase_ ( self : int ): '''simple docstring''' __a = self.full_loop() __a = torch.mean(torch.abs(__lowercase ) ) assert abs(result_mean.item() - 2540529 ) < 10
302
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 numpy as np import torch from ..models.clipseg import CLIPSegForImageSegmentation from ..utils import is_vision_available, requires_backends from .base import PipelineTool if is_vision_available(): from PIL import Image class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : Dict =( 'This is a tool that creates a segmentation mask of an image according to a label. It cannot create an image.' 'It takes two arguments named `image` which should be the original image, and `label` which should be a text ' 'describing the elements what should be identified in the segmentation mask. The tool returns the mask.' ) __lowerCamelCase : Any ='CIDAS/clipseg-rd64-refined' __lowerCamelCase : List[Any] ='image_segmenter' __lowerCamelCase : Dict =CLIPSegForImageSegmentation __lowerCamelCase : Tuple =['image', 'text'] __lowerCamelCase : Tuple =['image'] def __init__( self : Any , *__lowercase : Union[str, Any] , **__lowercase : Optional[Any] ): '''simple docstring''' requires_backends(self , ["""vision"""] ) super().__init__(*__lowercase , **__lowercase ) def UpperCamelCase_ ( self : Any , __lowercase : "Image" , __lowercase : str ): '''simple docstring''' return self.pre_processor(text=[label] , images=[image] , padding=__lowercase , return_tensors="""pt""" ) def UpperCamelCase_ ( self : Tuple , __lowercase : Union[str, Any] ): '''simple docstring''' with torch.no_grad(): __a = self.model(**__lowercase ).logits return logits def UpperCamelCase_ ( self : str , __lowercase : Optional[Any] ): '''simple docstring''' __a = outputs.cpu().detach().numpy() __a = 0 __a = 1 return Image.fromarray((array * 255).astype(np.uinta ) )
302
from __future__ import annotations lowerCamelCase__ = { """A""": ["""B""", """C""", """E"""], """B""": ["""A""", """D""", """E"""], """C""": ["""A""", """F""", """G"""], """D""": ["""B"""], """E""": ["""A""", """B""", """D"""], """F""": ["""C"""], """G""": ["""C"""], } class SCREAMING_SNAKE_CASE : def __init__( self : Tuple , __lowercase : dict[str, list[str]] , __lowercase : str ): '''simple docstring''' __a = graph # mapping node to its parent in resulting breadth first tree __a = {} __a = source_vertex def UpperCamelCase_ ( self : Any ): '''simple docstring''' __a = {self.source_vertex} __a = None __a = [self.source_vertex] # first in first out queue while queue: __a = queue.pop(0 ) for adjacent_vertex in self.graph[vertex]: if adjacent_vertex not in visited: visited.add(__lowercase ) __a = vertex queue.append(__lowercase ) def UpperCamelCase_ ( self : Optional[int] , __lowercase : str ): '''simple docstring''' if target_vertex == self.source_vertex: return self.source_vertex __a = self.parent.get(__lowercase ) if target_vertex_parent is None: __a = ( F"No path from vertex: {self.source_vertex} to vertex: {target_vertex}" ) raise ValueError(__lowercase ) return self.shortest_path(__lowercase ) + F"->{target_vertex}" if __name__ == "__main__": lowerCamelCase__ = Graph(graph, """G""") g.breath_first_search() print(g.shortest_path("""D""")) print(g.shortest_path("""G""")) print(g.shortest_path("""Foo"""))
302
1
from __future__ import annotations def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : list ): """simple docstring""" if not nums: raise ValueError("""List is empty""" ) return sum(_SCREAMING_SNAKE_CASE ) / len(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": import doctest doctest.testmod()
302
import unittest import numpy as np import torch from torch import nn from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import KandinskyVaaPriorPipeline, PriorTransformer, UnCLIPScheduler from diffusers.utils import torch_device from diffusers.utils.testing_utils import enable_full_determinism, skip_mps from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class SCREAMING_SNAKE_CASE ( lowerCamelCase__ , unittest.TestCase ): __lowerCamelCase : Tuple =KandinskyVaaPriorPipeline __lowerCamelCase : Union[str, Any] =['prompt'] __lowerCamelCase : Any =['prompt', 'negative_prompt'] __lowerCamelCase : List[str] =[ 'num_images_per_prompt', 'generator', 'num_inference_steps', 'latents', 'negative_prompt', 'guidance_scale', 'output_type', 'return_dict', ] __lowerCamelCase : List[Any] =False @property def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' return 32 @property def UpperCamelCase_ ( self : Any ): '''simple docstring''' return 32 @property def UpperCamelCase_ ( self : str ): '''simple docstring''' return self.time_input_dim @property def UpperCamelCase_ ( self : str ): '''simple docstring''' return self.time_input_dim * 4 @property def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' return 100 @property def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' __a = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) return tokenizer @property def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' torch.manual_seed(0 ) __a = 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-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(__lowercase ) @property def UpperCamelCase_ ( self : int ): '''simple docstring''' torch.manual_seed(0 ) __a = { """num_attention_heads""": 2, """attention_head_dim""": 12, """embedding_dim""": self.text_embedder_hidden_size, """num_layers""": 1, } __a = PriorTransformer(**__lowercase ) # clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0 __a = nn.Parameter(torch.ones(model.clip_std.shape ) ) return model @property def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' torch.manual_seed(0 ) __a = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=224 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=14 , ) __a = CLIPVisionModelWithProjection(__lowercase ) return model @property def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' __a = CLIPImageProcessor( crop_size=224 , do_center_crop=__lowercase , do_normalize=__lowercase , do_resize=__lowercase , image_mean=[0.48145466, 0.4578275, 0.40821073] , image_std=[0.26862954, 0.26130258, 0.27577711] , resample=3 , size=224 , ) return image_processor def UpperCamelCase_ ( self : str ): '''simple docstring''' __a = self.dummy_prior __a = self.dummy_image_encoder __a = self.dummy_text_encoder __a = self.dummy_tokenizer __a = self.dummy_image_processor __a = UnCLIPScheduler( variance_type="""fixed_small_log""" , prediction_type="""sample""" , num_train_timesteps=1000 , clip_sample=__lowercase , clip_sample_range=10.0 , ) __a = { """prior""": prior, """image_encoder""": image_encoder, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """scheduler""": scheduler, """image_processor""": image_processor, } return components def UpperCamelCase_ ( self : Optional[int] , __lowercase : List[str] , __lowercase : Any=0 ): '''simple docstring''' if str(__lowercase ).startswith("""mps""" ): __a = torch.manual_seed(__lowercase ) else: __a = torch.Generator(device=__lowercase ).manual_seed(__lowercase ) __a = { """prompt""": """horse""", """generator""": generator, """guidance_scale""": 4.0, """num_inference_steps""": 2, """output_type""": """np""", } return inputs def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' __a = """cpu""" __a = self.get_dummy_components() __a = self.pipeline_class(**__lowercase ) __a = pipe.to(__lowercase ) pipe.set_progress_bar_config(disable=__lowercase ) __a = pipe(**self.get_dummy_inputs(__lowercase ) ) __a = output.image_embeds __a = pipe( **self.get_dummy_inputs(__lowercase ) , return_dict=__lowercase , )[0] __a = image[0, -10:] __a = image_from_tuple[0, -10:] assert image.shape == (1, 32) __a = np.array( [-0.0532, 1.7120, 0.3656, -1.0852, -0.8946, -1.1756, 0.4348, 0.2482, 0.5146, -0.1156] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 @skip_mps def UpperCamelCase_ ( self : Dict ): '''simple docstring''' __a = torch_device == """cpu""" __a = True __a = False self._test_inference_batch_single_identical( test_max_difference=__lowercase , relax_max_difference=__lowercase , test_mean_pixel_difference=__lowercase , ) @skip_mps def UpperCamelCase_ ( self : Any ): '''simple docstring''' __a = torch_device == """cpu""" __a = False self._test_attention_slicing_forward_pass( test_max_difference=__lowercase , test_mean_pixel_difference=__lowercase , )
302
1
import os import shutil import sys import tempfile import unittest from pathlib import Path import pytest import transformers from transformers import ( BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, AutoTokenizer, BertConfig, BertTokenizer, BertTokenizerFast, CTRLTokenizer, GPTaTokenizer, GPTaTokenizerFast, PreTrainedTokenizerFast, RobertaTokenizer, RobertaTokenizerFast, is_tokenizers_available, ) from transformers.models.auto.configuration_auto import CONFIG_MAPPING, AutoConfig from transformers.models.auto.tokenization_auto import ( TOKENIZER_MAPPING, get_tokenizer_config, tokenizer_class_from_name, ) from transformers.models.roberta.configuration_roberta import RobertaConfig from transformers.testing_utils import ( DUMMY_DIFF_TOKENIZER_IDENTIFIER, DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, RequestCounter, require_tokenizers, slow, ) sys.path.append(str(Path(__file__).parent.parent.parent.parent / """utils""")) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_tokenization import CustomTokenizer # noqa E402 if is_tokenizers_available(): from test_module.custom_tokenization_fast import CustomTokenizerFast class SCREAMING_SNAKE_CASE ( unittest.TestCase ): def UpperCamelCase_ ( self : int ): '''simple docstring''' __a = 0 @slow def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' for model_name in (x for x in BERT_PRETRAINED_CONFIG_ARCHIVE_MAP.keys() if "japanese" not in x): __a = AutoTokenizer.from_pretrained(__lowercase ) self.assertIsNotNone(__lowercase ) self.assertIsInstance(__lowercase , (BertTokenizer, BertTokenizerFast) ) self.assertGreater(len(__lowercase ) , 0 ) for model_name in GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP.keys(): __a = AutoTokenizer.from_pretrained(__lowercase ) self.assertIsNotNone(__lowercase ) self.assertIsInstance(__lowercase , (GPTaTokenizer, GPTaTokenizerFast) ) self.assertGreater(len(__lowercase ) , 0 ) def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' __a = AutoTokenizer.from_pretrained(__lowercase ) self.assertIsInstance(__lowercase , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(tokenizer.vocab_size , 12 ) def UpperCamelCase_ ( self : str ): '''simple docstring''' __a = AutoTokenizer.from_pretrained(__lowercase ) self.assertIsInstance(__lowercase , (RobertaTokenizer, RobertaTokenizerFast) ) self.assertEqual(tokenizer.vocab_size , 20 ) def UpperCamelCase_ ( self : Dict ): '''simple docstring''' __a = AutoConfig.from_pretrained(__lowercase ) self.assertIsInstance(__lowercase , __lowercase ) # Check that tokenizer_type ≠ model_type __a = AutoTokenizer.from_pretrained(__lowercase , config=__lowercase ) self.assertIsInstance(__lowercase , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(tokenizer.vocab_size , 12 ) def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy("""./tests/fixtures/vocab.txt""" , os.path.join(__lowercase , """vocab.txt""" ) ) __a = AutoTokenizer.from_pretrained(__lowercase , tokenizer_type="""bert""" , use_fast=__lowercase ) self.assertIsInstance(__lowercase , __lowercase ) with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy("""./tests/fixtures/vocab.json""" , os.path.join(__lowercase , """vocab.json""" ) ) shutil.copy("""./tests/fixtures/merges.txt""" , os.path.join(__lowercase , """merges.txt""" ) ) __a = AutoTokenizer.from_pretrained(__lowercase , tokenizer_type="""gpt2""" , use_fast=__lowercase ) self.assertIsInstance(__lowercase , __lowercase ) @require_tokenizers def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy("""./tests/fixtures/vocab.txt""" , os.path.join(__lowercase , """vocab.txt""" ) ) __a = AutoTokenizer.from_pretrained(__lowercase , tokenizer_type="""bert""" ) self.assertIsInstance(__lowercase , __lowercase ) with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy("""./tests/fixtures/vocab.json""" , os.path.join(__lowercase , """vocab.json""" ) ) shutil.copy("""./tests/fixtures/merges.txt""" , os.path.join(__lowercase , """merges.txt""" ) ) __a = AutoTokenizer.from_pretrained(__lowercase , tokenizer_type="""gpt2""" ) self.assertIsInstance(__lowercase , __lowercase ) def UpperCamelCase_ ( self : str ): '''simple docstring''' with pytest.raises(__lowercase ): AutoTokenizer.from_pretrained("""./""" , tokenizer_type="""xxx""" ) @require_tokenizers def UpperCamelCase_ ( self : str ): '''simple docstring''' for tokenizer_class in [BertTokenizer, BertTokenizerFast, AutoTokenizer]: __a = tokenizer_class.from_pretrained("""wietsedv/bert-base-dutch-cased""" ) self.assertIsInstance(__lowercase , (BertTokenizer, BertTokenizerFast) ) if isinstance(__lowercase , __lowercase ): self.assertEqual(tokenizer.basic_tokenizer.do_lower_case , __lowercase ) else: self.assertEqual(tokenizer.do_lower_case , __lowercase ) self.assertEqual(tokenizer.model_max_length , 512 ) @require_tokenizers def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' for tokenizer_class in [BertTokenizer, BertTokenizerFast, AutoTokenizer]: with self.assertRaisesRegex( __lowercase , """julien-c/herlolip-not-exists is not a local folder and is not a valid model identifier""" , ): __a = tokenizer_class.from_pretrained("""julien-c/herlolip-not-exists""" ) def UpperCamelCase_ ( self : str ): '''simple docstring''' # tests: https://github.com/huggingface/transformers/pull/13251 # 1. models with `-`, e.g. xlm-roberta -> xlm_roberta # 2. models that don't remap 1-1 from model-name to model file, e.g., openai-gpt -> openai __a = TOKENIZER_MAPPING.values() __a = [] for slow_tok, fast_tok in tokenizers: if slow_tok is not None: tokenizer_names.append(slow_tok.__name__ ) if fast_tok is not None: tokenizer_names.append(fast_tok.__name__ ) for tokenizer_name in tokenizer_names: # must find the right class tokenizer_class_from_name(__lowercase ) @require_tokenizers def UpperCamelCase_ ( self : Optional[int] ): '''simple docstring''' self.assertIsInstance(AutoTokenizer.from_pretrained("""bert-base-cased""" , use_fast=__lowercase ) , __lowercase ) self.assertIsInstance(AutoTokenizer.from_pretrained("""bert-base-cased""" ) , __lowercase ) @require_tokenizers def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' __a = AutoTokenizer.from_pretrained("""distilbert-base-uncased""" , do_lower_case=__lowercase ) __a = """Hello, world. How are you?""" __a = tokenizer.tokenize(__lowercase ) self.assertEqual("""[UNK]""" , tokens[0] ) __a = AutoTokenizer.from_pretrained("""microsoft/mpnet-base""" , do_lower_case=__lowercase ) __a = tokenizer.tokenize(__lowercase ) self.assertEqual("""[UNK]""" , tokens[0] ) @require_tokenizers def UpperCamelCase_ ( self : Dict ): '''simple docstring''' __a = AutoTokenizer.from_pretrained("""robot-test/dummy-tokenizer-fast-with-model-config""" ) self.assertEqual(type(__lowercase ) , __lowercase ) self.assertEqual(tokenizer.model_max_length , 512 ) self.assertEqual(tokenizer.vocab_size , 30000 ) self.assertEqual(tokenizer.unk_token , """[UNK]""" ) self.assertEqual(tokenizer.padding_side , """right""" ) self.assertEqual(tokenizer.truncation_side , """right""" ) def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' __a = AutoTokenizer.from_pretrained(__lowercase ) self.assertIsInstance(__lowercase , (BertTokenizer, BertTokenizerFast) ) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(__lowercase ) __a = AutoTokenizer.from_pretrained(__lowercase ) self.assertIsInstance(__lowercase , tokenizer.__class__ ) self.assertEqual(tokenizera.vocab_size , 12 ) def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' __a = AutoTokenizer.from_pretrained("""ctrl""" ) # There is no fast CTRL so this always gives us a slow tokenizer. self.assertIsInstance(__lowercase , __lowercase ) def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' # Check we can load the tokenizer config of an online model. __a = get_tokenizer_config("""bert-base-cased""" ) __a = config.pop("""_commit_hash""" , __lowercase ) # If we ever update bert-base-cased tokenizer config, this dict here will need to be updated. self.assertEqual(__lowercase , {"""do_lower_case""": False} ) # This model does not have a tokenizer_config so we get back an empty dict. __a = get_tokenizer_config(__lowercase ) self.assertDictEqual(__lowercase , {} ) # A tokenizer saved with `save_pretrained` always creates a tokenizer config. __a = AutoTokenizer.from_pretrained(__lowercase ) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(__lowercase ) __a = get_tokenizer_config(__lowercase ) # Check the class of the tokenizer was properly saved (note that it always saves the slow class). self.assertEqual(config["""tokenizer_class"""] , """BertTokenizer""" ) def UpperCamelCase_ ( self : Optional[int] ): '''simple docstring''' try: AutoConfig.register("""custom""" , __lowercase ) AutoTokenizer.register(__lowercase , slow_tokenizer_class=__lowercase ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(__lowercase ): AutoTokenizer.register(__lowercase , slow_tokenizer_class=__lowercase ) __a = CustomTokenizer.from_pretrained(__lowercase ) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(__lowercase ) __a = AutoTokenizer.from_pretrained(__lowercase ) self.assertIsInstance(__lowercase , __lowercase ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] @require_tokenizers def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' try: AutoConfig.register("""custom""" , __lowercase ) # Can register in two steps AutoTokenizer.register(__lowercase , slow_tokenizer_class=__lowercase ) self.assertEqual(TOKENIZER_MAPPING[CustomConfig] , (CustomTokenizer, None) ) AutoTokenizer.register(__lowercase , fast_tokenizer_class=__lowercase ) self.assertEqual(TOKENIZER_MAPPING[CustomConfig] , (CustomTokenizer, CustomTokenizerFast) ) del TOKENIZER_MAPPING._extra_content[CustomConfig] # Can register in one step AutoTokenizer.register( __lowercase , slow_tokenizer_class=__lowercase , fast_tokenizer_class=__lowercase ) self.assertEqual(TOKENIZER_MAPPING[CustomConfig] , (CustomTokenizer, CustomTokenizerFast) ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(__lowercase ): AutoTokenizer.register(__lowercase , fast_tokenizer_class=__lowercase ) # We pass through a bert tokenizer fast cause there is no converter slow to fast for our new toknizer # and that model does not have a tokenizer.json with tempfile.TemporaryDirectory() as tmp_dir: __a = BertTokenizerFast.from_pretrained(__lowercase ) bert_tokenizer.save_pretrained(__lowercase ) __a = CustomTokenizerFast.from_pretrained(__lowercase ) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(__lowercase ) __a = AutoTokenizer.from_pretrained(__lowercase ) self.assertIsInstance(__lowercase , __lowercase ) __a = AutoTokenizer.from_pretrained(__lowercase , use_fast=__lowercase ) self.assertIsInstance(__lowercase , __lowercase ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] def UpperCamelCase_ ( self : Optional[int] ): '''simple docstring''' # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(__lowercase ): __a = AutoTokenizer.from_pretrained("""hf-internal-testing/test_dynamic_tokenizer""" ) # If remote code is disabled, we can't load this config. with self.assertRaises(__lowercase ): __a = AutoTokenizer.from_pretrained( """hf-internal-testing/test_dynamic_tokenizer""" , trust_remote_code=__lowercase ) __a = AutoTokenizer.from_pretrained("""hf-internal-testing/test_dynamic_tokenizer""" , trust_remote_code=__lowercase ) self.assertTrue(tokenizer.special_attribute_present ) # Test tokenizer can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(__lowercase ) __a = AutoTokenizer.from_pretrained(__lowercase , trust_remote_code=__lowercase ) self.assertTrue(reloaded_tokenizer.special_attribute_present ) if is_tokenizers_available(): self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizerFast""" ) self.assertEqual(reloaded_tokenizer.__class__.__name__ , """NewTokenizerFast""" ) # Test we can also load the slow version __a = AutoTokenizer.from_pretrained( """hf-internal-testing/test_dynamic_tokenizer""" , trust_remote_code=__lowercase , use_fast=__lowercase ) self.assertTrue(tokenizer.special_attribute_present ) self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizer""" ) # Test tokenizer can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(__lowercase ) __a = AutoTokenizer.from_pretrained(__lowercase , trust_remote_code=__lowercase , use_fast=__lowercase ) self.assertEqual(reloaded_tokenizer.__class__.__name__ , """NewTokenizer""" ) self.assertTrue(reloaded_tokenizer.special_attribute_present ) else: self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizer""" ) self.assertEqual(reloaded_tokenizer.__class__.__name__ , """NewTokenizer""" ) @require_tokenizers def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : List[str] =False class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : Tuple =NewTokenizer __lowerCamelCase : Tuple =False try: AutoConfig.register("""custom""" , __lowercase ) AutoTokenizer.register(__lowercase , slow_tokenizer_class=__lowercase ) AutoTokenizer.register(__lowercase , fast_tokenizer_class=__lowercase ) # If remote code is not set, the default is to use local __a = AutoTokenizer.from_pretrained("""hf-internal-testing/test_dynamic_tokenizer""" ) self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizerFast""" ) self.assertFalse(tokenizer.special_attribute_present ) __a = AutoTokenizer.from_pretrained("""hf-internal-testing/test_dynamic_tokenizer""" , use_fast=__lowercase ) self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizer""" ) self.assertFalse(tokenizer.special_attribute_present ) # If remote code is disabled, we load the local one. __a = AutoTokenizer.from_pretrained( """hf-internal-testing/test_dynamic_tokenizer""" , trust_remote_code=__lowercase ) self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizerFast""" ) self.assertFalse(tokenizer.special_attribute_present ) __a = AutoTokenizer.from_pretrained( """hf-internal-testing/test_dynamic_tokenizer""" , trust_remote_code=__lowercase , use_fast=__lowercase ) self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizer""" ) self.assertFalse(tokenizer.special_attribute_present ) # If remote is enabled, we load from the Hub __a = AutoTokenizer.from_pretrained( """hf-internal-testing/test_dynamic_tokenizer""" , trust_remote_code=__lowercase ) self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizerFast""" ) self.assertTrue(tokenizer.special_attribute_present ) __a = AutoTokenizer.from_pretrained( """hf-internal-testing/test_dynamic_tokenizer""" , trust_remote_code=__lowercase , use_fast=__lowercase ) self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizer""" ) self.assertTrue(tokenizer.special_attribute_present ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' __a = AutoTokenizer.from_pretrained( """hf-internal-testing/test_dynamic_tokenizer_legacy""" , trust_remote_code=__lowercase ) self.assertTrue(tokenizer.special_attribute_present ) if is_tokenizers_available(): self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizerFast""" ) # Test we can also load the slow version __a = AutoTokenizer.from_pretrained( """hf-internal-testing/test_dynamic_tokenizer_legacy""" , trust_remote_code=__lowercase , use_fast=__lowercase ) self.assertTrue(tokenizer.special_attribute_present ) self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizer""" ) else: self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizer""" ) def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' with self.assertRaisesRegex( __lowercase , """bert-base is not a local folder and is not a valid model identifier""" ): __a = AutoTokenizer.from_pretrained("""bert-base""" ) def UpperCamelCase_ ( self : Optional[int] ): '''simple docstring''' with self.assertRaisesRegex( __lowercase , r"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)""" ): __a = AutoTokenizer.from_pretrained(__lowercase , revision="""aaaaaa""" ) def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' # Make sure we have cached the tokenizer. __a = AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-bert""" ) with RequestCounter() as counter: __a = AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-bert""" ) self.assertEqual(counter.get_request_count , 0 ) self.assertEqual(counter.head_request_count , 1 ) self.assertEqual(counter.other_request_count , 0 )
302
from typing import Any, Dict, List, Union from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from ..image_utils import load_image if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_OBJECT_DETECTION_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = Dict[str, Any] lowerCamelCase__ = List[Prediction] @add_end_docstrings(lowerCamelCase__ ) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): def __init__( self : Tuple , *__lowercase : Tuple , **__lowercase : Optional[int] ): '''simple docstring''' super().__init__(*__lowercase , **__lowercase ) if self.framework == "tf": raise ValueError(F"The {self.__class__} is only available in PyTorch." ) requires_backends(self , """vision""" ) self.check_model_type( dict(MODEL_FOR_OBJECT_DETECTION_MAPPING.items() + MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING.items() ) ) def UpperCamelCase_ ( self : Optional[int] , **__lowercase : List[str] ): '''simple docstring''' __a = {} if "threshold" in kwargs: __a = kwargs["""threshold"""] return {}, {}, postprocess_kwargs def __call__( self : List[Any] , *__lowercase : Any , **__lowercase : Tuple ): '''simple docstring''' return super().__call__(*__lowercase , **__lowercase ) def UpperCamelCase_ ( self : str , __lowercase : Tuple ): '''simple docstring''' __a = load_image(__lowercase ) __a = torch.IntTensor([[image.height, image.width]] ) __a = self.image_processor(images=[image] , return_tensors="""pt""" ) if self.tokenizer is not None: __a = self.tokenizer(text=inputs["""words"""] , boxes=inputs["""boxes"""] , return_tensors="""pt""" ) __a = target_size return inputs def UpperCamelCase_ ( self : Dict , __lowercase : List[str] ): '''simple docstring''' __a = model_inputs.pop("""target_size""" ) __a = self.model(**__lowercase ) __a = outputs.__class__({"""target_size""": target_size, **outputs} ) if self.tokenizer is not None: __a = model_inputs["""bbox"""] return model_outputs def UpperCamelCase_ ( self : Optional[int] , __lowercase : List[Any] , __lowercase : List[Any]=0.9 ): '''simple docstring''' __a = model_outputs["""target_size"""] if self.tokenizer is not None: # This is a LayoutLMForTokenClassification variant. # The OCR got the boxes and the model classified the words. __a , __a = target_size[0].tolist() def unnormalize(__lowercase : Optional[Any] ): return self._get_bounding_box( torch.Tensor( [ (width * bbox[0] / 1000), (height * bbox[1] / 1000), (width * bbox[2] / 1000), (height * bbox[3] / 1000), ] ) ) __a , __a = model_outputs["""logits"""].squeeze(0 ).softmax(dim=-1 ).max(dim=-1 ) __a = [self.model.config.idalabel[prediction] for prediction in classes.tolist()] __a = [unnormalize(__lowercase ) for bbox in model_outputs["""bbox"""].squeeze(0 )] __a = ["""score""", """label""", """box"""] __a = [dict(zip(__lowercase , __lowercase ) ) for vals in zip(scores.tolist() , __lowercase , __lowercase ) if vals[0] > threshold] else: # This is a regular ForObjectDetectionModel __a = self.image_processor.post_process_object_detection(__lowercase , __lowercase , __lowercase ) __a = raw_annotations[0] __a = raw_annotation["""scores"""] __a = raw_annotation["""labels"""] __a = raw_annotation["""boxes"""] __a = scores.tolist() __a = [self.model.config.idalabel[label.item()] for label in labels] __a = [self._get_bounding_box(__lowercase ) for box in boxes] # {"scores": [...], ...} --> [{"score":x, ...}, ...] __a = ["""score""", """label""", """box"""] __a = [ dict(zip(__lowercase , __lowercase ) ) for vals in zip(raw_annotation["""scores"""] , raw_annotation["""labels"""] , raw_annotation["""boxes"""] ) ] return annotation def UpperCamelCase_ ( self : Optional[int] , __lowercase : "torch.Tensor" ): '''simple docstring''' if self.framework != "pt": raise ValueError("""The ObjectDetectionPipeline is only available in PyTorch.""" ) __a , __a , __a , __a = box.int().tolist() __a = { """xmin""": xmin, """ymin""": ymin, """xmax""": xmax, """ymax""": ymax, } return bbox
302
1
import math import os import sys def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : str ): """simple docstring""" __a = """""" try: with open(_SCREAMING_SNAKE_CASE , """rb""" ) as binary_file: __a = binary_file.read() for dat in data: __a = f"{dat:08b}" result += curr_byte return result except OSError: print("""File not accessible""" ) sys.exit() def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : dict[str, str] , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : str ): """simple docstring""" lexicon.pop(_SCREAMING_SNAKE_CASE ) __a = last_match_id if math.loga(_SCREAMING_SNAKE_CASE ).is_integer(): for curr_key in lexicon: __a = """0""" + lexicon[curr_key] __a = bin(_SCREAMING_SNAKE_CASE )[2:] def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : str ): """simple docstring""" __a = {"""0""": """0""", """1""": """1"""} __a , __a = """""", """""" __a = len(_SCREAMING_SNAKE_CASE ) for i in range(len(_SCREAMING_SNAKE_CASE ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue __a = lexicon[curr_string] result += last_match_id add_key_to_lexicon(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) index += 1 __a = """""" while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": __a = lexicon[curr_string] result += last_match_id return result def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : str ): """simple docstring""" __a = os.path.getsize(_SCREAMING_SNAKE_CASE ) __a = bin(_SCREAMING_SNAKE_CASE )[2:] __a = len(_SCREAMING_SNAKE_CASE ) return "0" * (length_length - 1) + file_length_binary + compressed def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : str ): """simple docstring""" __a = 8 try: with open(_SCREAMING_SNAKE_CASE , """wb""" ) as opened_file: __a = [ to_write[i : i + byte_length] for i in range(0 , len(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append("""10000000""" ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array: opened_file.write(int(_SCREAMING_SNAKE_CASE , 2 ).to_bytes(1 , byteorder="""big""" ) ) except OSError: print("""File not accessible""" ) sys.exit() def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : str ): """simple docstring""" __a = read_file_binary(_SCREAMING_SNAKE_CASE ) __a = compress_data(_SCREAMING_SNAKE_CASE ) __a = add_file_length(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) write_file_binary(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
302
# 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 # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowerCamelCase__ = { """configuration_efficientnet""": [ """EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP""", """EfficientNetConfig""", """EfficientNetOnnxConfig""", ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = ["""EfficientNetImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ """EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST""", """EfficientNetForImageClassification""", """EfficientNetModel""", """EfficientNetPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_efficientnet import ( EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP, EfficientNetConfig, EfficientNetOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_efficientnet import EfficientNetImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_efficientnet import ( EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST, EfficientNetForImageClassification, EfficientNetModel, EfficientNetPreTrainedModel, ) else: import sys lowerCamelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure)
302
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 lowerCamelCase__ = logging.get_logger(__name__) @add_end_docstrings(lowerCamelCase__ ) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): def __init__( self : Optional[int] , **__lowercase : Dict ): '''simple docstring''' super().__init__(**__lowercase ) if self.framework != "pt": raise ValueError(F"The {self.__class__} is only available in PyTorch." ) # No specific FOR_XXX available yet def __call__( self : str , __lowercase : Union[np.ndarray, bytes, str] , **__lowercase : int ): '''simple docstring''' return super().__call__(__lowercase , **__lowercase ) def UpperCamelCase_ ( self : List[Any] , **__lowercase : Union[str, Any] ): '''simple docstring''' __a = {} if "candidate_labels" in kwargs: __a = kwargs["""candidate_labels"""] if "hypothesis_template" in kwargs: __a = kwargs["""hypothesis_template"""] return preprocess_params, {}, {} def UpperCamelCase_ ( self : int , __lowercase : Dict , __lowercase : Dict=None , __lowercase : str="This is a sound of {}." ): '''simple docstring''' if isinstance(__lowercase , __lowercase ): if audio.startswith("""http://""" ) or audio.startswith("""https://""" ): # We need to actually check for a real protocol, otherwise it's impossible to use a local file # like http_huggingface_co.png __a = requests.get(__lowercase ).content else: with open(__lowercase , """rb""" ) as f: __a = f.read() if isinstance(__lowercase , __lowercase ): __a = ffmpeg_read(__lowercase , self.feature_extractor.sampling_rate ) if not isinstance(__lowercase , np.ndarray ): raise ValueError("""We expect a numpy ndarray as input""" ) if len(audio.shape ) != 1: raise ValueError("""We expect a single channel audio input for ZeroShotAudioClassificationPipeline""" ) __a = self.feature_extractor( [audio] , sampling_rate=self.feature_extractor.sampling_rate , return_tensors="""pt""" ) __a = candidate_labels __a = [hypothesis_template.format(__lowercase ) for x in candidate_labels] __a = self.tokenizer(__lowercase , return_tensors=self.framework , padding=__lowercase ) __a = [text_inputs] return inputs def UpperCamelCase_ ( self : Any , __lowercase : Any ): '''simple docstring''' __a = model_inputs.pop("""candidate_labels""" ) __a = model_inputs.pop("""text_inputs""" ) if isinstance(text_inputs[0] , __lowercase ): __a = text_inputs[0] else: # Batching case. __a = text_inputs[0][0] __a = self.model(**__lowercase , **__lowercase ) __a = { """candidate_labels""": candidate_labels, """logits""": outputs.logits_per_audio, } return model_outputs def UpperCamelCase_ ( self : Optional[Any] , __lowercase : Dict ): '''simple docstring''' __a = model_outputs.pop("""candidate_labels""" ) __a = model_outputs["""logits"""][0] if self.framework == "pt": __a = logits.softmax(dim=0 ) __a = probs.tolist() else: raise ValueError("""`tf` framework not supported.""" ) __a = [ {"""score""": score, """label""": candidate_label} for score, candidate_label in sorted(zip(__lowercase , __lowercase ) , key=lambda __lowercase : -x[0] ) ] return result
302
import random def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : list , _SCREAMING_SNAKE_CASE : List[Any] ): """simple docstring""" __a , __a , __a = [], [], [] for element in data: if element < pivot: less.append(_SCREAMING_SNAKE_CASE ) elif element > pivot: greater.append(_SCREAMING_SNAKE_CASE ) else: equal.append(_SCREAMING_SNAKE_CASE ) return less, equal, greater def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : list , _SCREAMING_SNAKE_CASE : int ): """simple docstring""" if index >= len(_SCREAMING_SNAKE_CASE ) or index < 0: return None __a = items[random.randint(0 , len(_SCREAMING_SNAKE_CASE ) - 1 )] __a = 0 __a , __a , __a = _partition(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __a = len(_SCREAMING_SNAKE_CASE ) __a = len(_SCREAMING_SNAKE_CASE ) # index is the pivot if m <= index < m + count: return pivot # must be in smaller elif m > index: return quick_select(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # must be in larger else: return quick_select(_SCREAMING_SNAKE_CASE , index - (m + count) )
302
1
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, ChannelDimension, ImageInput, PILImageResampling, is_batched, to_numpy_array, valid_images, ) from ...utils import TensorType, logging lowerCamelCase__ = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : Dict =['pixel_values'] def __init__( self : Optional[int] , __lowercase : bool = True , __lowercase : Optional[Dict[str, int]] = None , __lowercase : PILImageResampling = PILImageResampling.BICUBIC , __lowercase : bool = True , __lowercase : bool = True , __lowercase : Union[int, float] = 1 / 255 , __lowercase : Dict[str, int] = None , __lowercase : bool = True , __lowercase : Optional[Union[float, List[float]]] = None , __lowercase : Optional[Union[float, List[float]]] = None , **__lowercase : Dict , ): '''simple docstring''' super().__init__(**__lowercase ) __a = size if size is not None else {"""height""": 224, """width""": 224} __a = get_size_dict(__lowercase ) __a = crop_size if crop_size is not None else {"""height""": 224, """width""": 224} __a = get_size_dict(__lowercase , default_to_square=__lowercase , param_name="""crop_size""" ) __a = do_resize __a = do_rescale __a = do_normalize __a = do_center_crop __a = crop_size __a = size __a = resample __a = rescale_factor __a = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN __a = image_std if image_std is not None else IMAGENET_DEFAULT_STD def UpperCamelCase_ ( self : Any , __lowercase : np.ndarray , __lowercase : Dict[str, int] , __lowercase : PILImageResampling = PILImageResampling.BILINEAR , __lowercase : Optional[Union[str, ChannelDimension]] = None , **__lowercase : Optional[Any] , ): '''simple docstring''' __a = get_size_dict(__lowercase ) if "shortest_edge" in size: __a = get_resize_output_image_size(__lowercase , size=size["""shortest_edge"""] , default_to_square=__lowercase ) # size = get_resize_output_image_size(image, size["shortest_edge"], size["longest_edge"]) elif "height" in size and "width" in size: __a = (size["""height"""], size["""width"""]) else: raise ValueError(F"Size must contain 'height' and 'width' keys or 'shortest_edge' key. Got {size.keys()}" ) return resize(__lowercase , size=__lowercase , resample=__lowercase , data_format=__lowercase , **__lowercase ) def UpperCamelCase_ ( self : str , __lowercase : np.ndarray , __lowercase : Dict[str, int] , __lowercase : Optional[Union[str, ChannelDimension]] = None , **__lowercase : List[Any] , ): '''simple docstring''' __a = get_size_dict(__lowercase ) if "height" not in size or "width" not in size: raise ValueError(F"The `size` parameter must contain the keys (height, width). Got {size.keys()}" ) return center_crop(__lowercase , size=(size["""height"""], size["""width"""]) , data_format=__lowercase , **__lowercase ) def UpperCamelCase_ ( self : Any , __lowercase : np.ndarray , __lowercase : float , __lowercase : Optional[Union[str, ChannelDimension]] = None , **__lowercase : str ): '''simple docstring''' return rescale(__lowercase , scale=__lowercase , data_format=__lowercase , **__lowercase ) def UpperCamelCase_ ( self : List[Any] , __lowercase : np.ndarray , __lowercase : Union[float, List[float]] , __lowercase : Union[float, List[float]] , __lowercase : Optional[Union[str, ChannelDimension]] = None , **__lowercase : Any , ): '''simple docstring''' return normalize(__lowercase , mean=__lowercase , std=__lowercase , data_format=__lowercase , **__lowercase ) def UpperCamelCase_ ( self : Tuple , __lowercase : ImageInput , __lowercase : Optional[bool] = None , __lowercase : Dict[str, int] = None , __lowercase : PILImageResampling = None , __lowercase : bool = None , __lowercase : int = None , __lowercase : Optional[bool] = None , __lowercase : Optional[float] = None , __lowercase : Optional[bool] = None , __lowercase : Optional[Union[float, List[float]]] = None , __lowercase : Optional[Union[float, List[float]]] = None , __lowercase : Optional[Union[str, TensorType]] = None , __lowercase : Union[str, ChannelDimension] = ChannelDimension.FIRST , **__lowercase : List[Any] , ): '''simple docstring''' __a = do_resize if do_resize is not None else self.do_resize __a = do_rescale if do_rescale is not None else self.do_rescale __a = do_normalize if do_normalize is not None else self.do_normalize __a = do_center_crop if do_center_crop is not None else self.do_center_crop __a = crop_size if crop_size is not None else self.crop_size __a = get_size_dict(__lowercase , param_name="""crop_size""" , default_to_square=__lowercase ) __a = resample if resample is not None else self.resample __a = rescale_factor if rescale_factor is not None else self.rescale_factor __a = image_mean if image_mean is not None else self.image_mean __a = image_std if image_std is not None else self.image_std __a = size if size is not None else self.size __a = get_size_dict(__lowercase ) if not is_batched(__lowercase ): __a = [images] if not valid_images(__lowercase ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None: raise ValueError("""Size must be specified if do_resize is True.""" ) if do_center_crop and crop_size is None: raise ValueError("""Crop size must be specified if do_center_crop is True.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) # All transformations expect numpy arrays. __a = [to_numpy_array(__lowercase ) for image in images] if do_resize: __a = [self.resize(image=__lowercase , size=__lowercase , resample=__lowercase ) for image in images] if do_center_crop: __a = [self.center_crop(image=__lowercase , size=__lowercase ) for image in images] if do_rescale: __a = [self.rescale(image=__lowercase , scale=__lowercase ) for image in images] if do_normalize: __a = [self.normalize(image=__lowercase , mean=__lowercase , std=__lowercase ) for image in images] __a = [to_channel_dimension_format(__lowercase , __lowercase ) for image in images] __a = {"""pixel_values""": images} return BatchFeature(data=__lowercase , tensor_type=__lowercase )
302
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 lowerCamelCase__ = logging.get_logger(__name__) @add_end_docstrings(lowerCamelCase__ ) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): def __init__( self : Optional[int] , **__lowercase : Dict ): '''simple docstring''' super().__init__(**__lowercase ) if self.framework != "pt": raise ValueError(F"The {self.__class__} is only available in PyTorch." ) # No specific FOR_XXX available yet def __call__( self : str , __lowercase : Union[np.ndarray, bytes, str] , **__lowercase : int ): '''simple docstring''' return super().__call__(__lowercase , **__lowercase ) def UpperCamelCase_ ( self : List[Any] , **__lowercase : Union[str, Any] ): '''simple docstring''' __a = {} if "candidate_labels" in kwargs: __a = kwargs["""candidate_labels"""] if "hypothesis_template" in kwargs: __a = kwargs["""hypothesis_template"""] return preprocess_params, {}, {} def UpperCamelCase_ ( self : int , __lowercase : Dict , __lowercase : Dict=None , __lowercase : str="This is a sound of {}." ): '''simple docstring''' if isinstance(__lowercase , __lowercase ): if audio.startswith("""http://""" ) or audio.startswith("""https://""" ): # We need to actually check for a real protocol, otherwise it's impossible to use a local file # like http_huggingface_co.png __a = requests.get(__lowercase ).content else: with open(__lowercase , """rb""" ) as f: __a = f.read() if isinstance(__lowercase , __lowercase ): __a = ffmpeg_read(__lowercase , self.feature_extractor.sampling_rate ) if not isinstance(__lowercase , np.ndarray ): raise ValueError("""We expect a numpy ndarray as input""" ) if len(audio.shape ) != 1: raise ValueError("""We expect a single channel audio input for ZeroShotAudioClassificationPipeline""" ) __a = self.feature_extractor( [audio] , sampling_rate=self.feature_extractor.sampling_rate , return_tensors="""pt""" ) __a = candidate_labels __a = [hypothesis_template.format(__lowercase ) for x in candidate_labels] __a = self.tokenizer(__lowercase , return_tensors=self.framework , padding=__lowercase ) __a = [text_inputs] return inputs def UpperCamelCase_ ( self : Any , __lowercase : Any ): '''simple docstring''' __a = model_inputs.pop("""candidate_labels""" ) __a = model_inputs.pop("""text_inputs""" ) if isinstance(text_inputs[0] , __lowercase ): __a = text_inputs[0] else: # Batching case. __a = text_inputs[0][0] __a = self.model(**__lowercase , **__lowercase ) __a = { """candidate_labels""": candidate_labels, """logits""": outputs.logits_per_audio, } return model_outputs def UpperCamelCase_ ( self : Optional[Any] , __lowercase : Dict ): '''simple docstring''' __a = model_outputs.pop("""candidate_labels""" ) __a = model_outputs["""logits"""][0] if self.framework == "pt": __a = logits.softmax(dim=0 ) __a = probs.tolist() else: raise ValueError("""`tf` framework not supported.""" ) __a = [ {"""score""": score, """label""": candidate_label} for score, candidate_label in sorted(zip(__lowercase , __lowercase ) , key=lambda __lowercase : -x[0] ) ] return result
302
1
lowerCamelCase__ = 9.8_0665 def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : float , _SCREAMING_SNAKE_CASE : float , _SCREAMING_SNAKE_CASE : float = g ): """simple docstring""" if fluid_density <= 0: raise ValueError("""Impossible fluid density""" ) if volume < 0: raise ValueError("""Impossible Object volume""" ) if gravity <= 0: raise ValueError("""Impossible Gravity""" ) return fluid_density * gravity * volume if __name__ == "__main__": import doctest # run doctest doctest.testmod()
302
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, ChannelDimension, ImageInput, PILImageResampling, is_batched, to_numpy_array, valid_images, ) from ...utils import TensorType, logging lowerCamelCase__ = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : Dict =['pixel_values'] def __init__( self : Optional[int] , __lowercase : bool = True , __lowercase : Optional[Dict[str, int]] = None , __lowercase : PILImageResampling = PILImageResampling.BICUBIC , __lowercase : bool = True , __lowercase : bool = True , __lowercase : Union[int, float] = 1 / 255 , __lowercase : Dict[str, int] = None , __lowercase : bool = True , __lowercase : Optional[Union[float, List[float]]] = None , __lowercase : Optional[Union[float, List[float]]] = None , **__lowercase : Dict , ): '''simple docstring''' super().__init__(**__lowercase ) __a = size if size is not None else {"""height""": 224, """width""": 224} __a = get_size_dict(__lowercase ) __a = crop_size if crop_size is not None else {"""height""": 224, """width""": 224} __a = get_size_dict(__lowercase , default_to_square=__lowercase , param_name="""crop_size""" ) __a = do_resize __a = do_rescale __a = do_normalize __a = do_center_crop __a = crop_size __a = size __a = resample __a = rescale_factor __a = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN __a = image_std if image_std is not None else IMAGENET_DEFAULT_STD def UpperCamelCase_ ( self : Any , __lowercase : np.ndarray , __lowercase : Dict[str, int] , __lowercase : PILImageResampling = PILImageResampling.BILINEAR , __lowercase : Optional[Union[str, ChannelDimension]] = None , **__lowercase : Optional[Any] , ): '''simple docstring''' __a = get_size_dict(__lowercase ) if "shortest_edge" in size: __a = get_resize_output_image_size(__lowercase , size=size["""shortest_edge"""] , default_to_square=__lowercase ) # size = get_resize_output_image_size(image, size["shortest_edge"], size["longest_edge"]) elif "height" in size and "width" in size: __a = (size["""height"""], size["""width"""]) else: raise ValueError(F"Size must contain 'height' and 'width' keys or 'shortest_edge' key. Got {size.keys()}" ) return resize(__lowercase , size=__lowercase , resample=__lowercase , data_format=__lowercase , **__lowercase ) def UpperCamelCase_ ( self : str , __lowercase : np.ndarray , __lowercase : Dict[str, int] , __lowercase : Optional[Union[str, ChannelDimension]] = None , **__lowercase : List[Any] , ): '''simple docstring''' __a = get_size_dict(__lowercase ) if "height" not in size or "width" not in size: raise ValueError(F"The `size` parameter must contain the keys (height, width). Got {size.keys()}" ) return center_crop(__lowercase , size=(size["""height"""], size["""width"""]) , data_format=__lowercase , **__lowercase ) def UpperCamelCase_ ( self : Any , __lowercase : np.ndarray , __lowercase : float , __lowercase : Optional[Union[str, ChannelDimension]] = None , **__lowercase : str ): '''simple docstring''' return rescale(__lowercase , scale=__lowercase , data_format=__lowercase , **__lowercase ) def UpperCamelCase_ ( self : List[Any] , __lowercase : np.ndarray , __lowercase : Union[float, List[float]] , __lowercase : Union[float, List[float]] , __lowercase : Optional[Union[str, ChannelDimension]] = None , **__lowercase : Any , ): '''simple docstring''' return normalize(__lowercase , mean=__lowercase , std=__lowercase , data_format=__lowercase , **__lowercase ) def UpperCamelCase_ ( self : Tuple , __lowercase : ImageInput , __lowercase : Optional[bool] = None , __lowercase : Dict[str, int] = None , __lowercase : PILImageResampling = None , __lowercase : bool = None , __lowercase : int = None , __lowercase : Optional[bool] = None , __lowercase : Optional[float] = None , __lowercase : Optional[bool] = None , __lowercase : Optional[Union[float, List[float]]] = None , __lowercase : Optional[Union[float, List[float]]] = None , __lowercase : Optional[Union[str, TensorType]] = None , __lowercase : Union[str, ChannelDimension] = ChannelDimension.FIRST , **__lowercase : List[Any] , ): '''simple docstring''' __a = do_resize if do_resize is not None else self.do_resize __a = do_rescale if do_rescale is not None else self.do_rescale __a = do_normalize if do_normalize is not None else self.do_normalize __a = do_center_crop if do_center_crop is not None else self.do_center_crop __a = crop_size if crop_size is not None else self.crop_size __a = get_size_dict(__lowercase , param_name="""crop_size""" , default_to_square=__lowercase ) __a = resample if resample is not None else self.resample __a = rescale_factor if rescale_factor is not None else self.rescale_factor __a = image_mean if image_mean is not None else self.image_mean __a = image_std if image_std is not None else self.image_std __a = size if size is not None else self.size __a = get_size_dict(__lowercase ) if not is_batched(__lowercase ): __a = [images] if not valid_images(__lowercase ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None: raise ValueError("""Size must be specified if do_resize is True.""" ) if do_center_crop and crop_size is None: raise ValueError("""Crop size must be specified if do_center_crop is True.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) # All transformations expect numpy arrays. __a = [to_numpy_array(__lowercase ) for image in images] if do_resize: __a = [self.resize(image=__lowercase , size=__lowercase , resample=__lowercase ) for image in images] if do_center_crop: __a = [self.center_crop(image=__lowercase , size=__lowercase ) for image in images] if do_rescale: __a = [self.rescale(image=__lowercase , scale=__lowercase ) for image in images] if do_normalize: __a = [self.normalize(image=__lowercase , mean=__lowercase , std=__lowercase ) for image in images] __a = [to_channel_dimension_format(__lowercase , __lowercase ) for image in images] __a = {"""pixel_values""": images} return BatchFeature(data=__lowercase , tensor_type=__lowercase )
302
1
def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" __a = [0] * len(_SCREAMING_SNAKE_CASE ) __a = [] __a = [1] * len(_SCREAMING_SNAKE_CASE ) for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(_SCREAMING_SNAKE_CASE ) ): if indegree[i] == 0: queue.append(_SCREAMING_SNAKE_CASE ) while queue: __a = queue.pop(0 ) for x in graph[vertex]: indegree[x] -= 1 if long_dist[vertex] + 1 > long_dist[x]: __a = long_dist[vertex] + 1 if indegree[x] == 0: queue.append(_SCREAMING_SNAKE_CASE ) print(max(_SCREAMING_SNAKE_CASE ) ) # Adjacency list of Graph lowerCamelCase__ = {0: [2, 3, 4], 1: [2, 7], 2: [5], 3: [5, 7], 4: [7], 5: [6], 6: [7], 7: []} longest_distance(graph)
302
import tempfile import unittest from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from transformers.testing_utils import ( is_torch_available, require_optimum, require_torch, slow, ) if is_torch_available(): import torch @require_torch @require_optimum @slow class SCREAMING_SNAKE_CASE ( unittest.TestCase ): def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' __a = """hf-internal-testing/tiny-random-t5""" __a = AutoTokenizer.from_pretrained(__lowercase ) __a = AutoModelForSeqaSeqLM.from_pretrained(__lowercase ) __a = tokenizer("""This is me""" , return_tensors="""pt""" ) __a = model.to_bettertransformer() self.assertTrue(any("""BetterTransformer""" in mod.__class__.__name__ for _, mod in model.named_modules() ) ) __a = model.generate(**__lowercase ) __a = model.reverse_bettertransformer() self.assertFalse(any("""BetterTransformer""" in mod.__class__.__name__ for _, mod in model.named_modules() ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(__lowercase ) __a = AutoModelForSeqaSeqLM.from_pretrained(__lowercase ) self.assertFalse( any("""BetterTransformer""" in mod.__class__.__name__ for _, mod in model_reloaded.named_modules() ) ) __a = model_reloaded.generate(**__lowercase ) self.assertTrue(torch.allclose(__lowercase , __lowercase ) ) def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' __a = """hf-internal-testing/tiny-random-t5""" __a = AutoModelForSeqaSeqLM.from_pretrained(__lowercase ) __a = model.to_bettertransformer() with tempfile.TemporaryDirectory() as tmpdirname: with self.assertRaises(__lowercase ): model.save_pretrained(__lowercase ) __a = model.reverse_bettertransformer() model.save_pretrained(__lowercase )
302
1
import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = {"""tokenizer_file""": """tokenizer.json"""} lowerCamelCase__ = { """tokenizer_file""": { """bigscience/tokenizer""": """https://huggingface.co/bigscience/tokenizer/blob/main/tokenizer.json""", """bigscience/bloom-560m""": """https://huggingface.co/bigscience/bloom-560m/blob/main/tokenizer.json""", """bigscience/bloom-1b1""": """https://huggingface.co/bigscience/bloom-1b1/blob/main/tokenizer.json""", """bigscience/bloom-1b7""": """https://huggingface.co/bigscience/bloom-1b7/blob/main/tokenizer.json""", """bigscience/bloom-3b""": """https://huggingface.co/bigscience/bloom-3b/blob/main/tokenizer.json""", """bigscience/bloom-7b1""": """https://huggingface.co/bigscience/bloom-7b1/blob/main/tokenizer.json""", """bigscience/bloom""": """https://huggingface.co/bigscience/bloom/blob/main/tokenizer.json""", }, } class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : int =VOCAB_FILES_NAMES __lowerCamelCase : Optional[Any] =PRETRAINED_VOCAB_FILES_MAP __lowerCamelCase : Any =['input_ids', 'attention_mask'] __lowerCamelCase : Dict =None def __init__( self : List[str] , __lowercase : List[Any]=None , __lowercase : List[Any]=None , __lowercase : Union[str, Any]=None , __lowercase : int="<unk>" , __lowercase : Tuple="<s>" , __lowercase : Any="</s>" , __lowercase : Union[str, Any]="<pad>" , __lowercase : List[str]=False , __lowercase : List[str]=False , **__lowercase : List[str] , ): '''simple docstring''' super().__init__( __lowercase , __lowercase , tokenizer_file=__lowercase , unk_token=__lowercase , bos_token=__lowercase , eos_token=__lowercase , pad_token=__lowercase , add_prefix_space=__lowercase , clean_up_tokenization_spaces=__lowercase , **__lowercase , ) __a = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("""add_prefix_space""" , __lowercase ) != add_prefix_space: __a = getattr(__lowercase , pre_tok_state.pop("""type""" ) ) __a = add_prefix_space __a = pre_tok_class(**__lowercase ) __a = add_prefix_space def UpperCamelCase_ ( self : str , *__lowercase : int , **__lowercase : int ): '''simple docstring''' __a = kwargs.get("""is_split_into_words""" , __lowercase ) if not (self.add_prefix_space or not is_split_into_words): raise Exception( F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with" """ pretokenized inputs.""" ) return super()._batch_encode_plus(*__lowercase , **__lowercase ) def UpperCamelCase_ ( self : Optional[Any] , *__lowercase : Optional[Any] , **__lowercase : Union[str, Any] ): '''simple docstring''' __a = kwargs.get("""is_split_into_words""" , __lowercase ) if not (self.add_prefix_space or not is_split_into_words): raise Exception( F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with" """ pretokenized inputs.""" ) return super()._encode_plus(*__lowercase , **__lowercase ) def UpperCamelCase_ ( self : Any , __lowercase : str , __lowercase : Optional[str] = None ): '''simple docstring''' __a = self._tokenizer.model.save(__lowercase , name=__lowercase ) return tuple(__lowercase ) def UpperCamelCase_ ( self : str , __lowercase : "Conversation" ): '''simple docstring''' __a = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(__lowercase , add_special_tokens=__lowercase ) + [self.eos_token_id] ) if len(__lowercase ) > self.model_max_length: __a = input_ids[-self.model_max_length :] return input_ids
302
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig lowerCamelCase__ = { """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/config.json""", """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/config.json""", """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/config.json""", """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/config.json""", """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/config.json""", """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/config.json""", """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/config.json""", """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/config.json""", } class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : Optional[Any] ='albert' def __init__( self : Optional[Any] , __lowercase : Union[str, Any]=30000 , __lowercase : List[str]=128 , __lowercase : Optional[Any]=4096 , __lowercase : Dict=12 , __lowercase : Any=1 , __lowercase : Optional[Any]=64 , __lowercase : Any=16384 , __lowercase : Any=1 , __lowercase : Union[str, Any]="gelu_new" , __lowercase : List[str]=0 , __lowercase : int=0 , __lowercase : Dict=512 , __lowercase : str=2 , __lowercase : List[str]=0.02 , __lowercase : Union[str, Any]=1E-12 , __lowercase : int=0.1 , __lowercase : Any="absolute" , __lowercase : Optional[int]=0 , __lowercase : Dict=2 , __lowercase : Optional[Any]=3 , **__lowercase : Any , ): '''simple docstring''' super().__init__(pad_token_id=__lowercase , bos_token_id=__lowercase , eos_token_id=__lowercase , **__lowercase ) __a = vocab_size __a = embedding_size __a = hidden_size __a = num_hidden_layers __a = num_hidden_groups __a = num_attention_heads __a = inner_group_num __a = hidden_act __a = intermediate_size __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = type_vocab_size __a = initializer_range __a = layer_norm_eps __a = classifier_dropout_prob __a = position_embedding_type class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): @property def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' if self.task == "multiple-choice": __a = {0: """batch""", 1: """choice""", 2: """sequence"""} else: __a = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis), ] )
302
1
from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCamelCase__ = { """configuration_autoformer""": [ """AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """AutoformerConfig""", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ """AUTOFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """AutoformerForPrediction""", """AutoformerModel""", """AutoformerPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_autoformer import ( AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, AutoformerConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_autoformer import ( AUTOFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, AutoformerForPrediction, AutoformerModel, AutoformerPreTrainedModel, ) else: import sys lowerCamelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
302
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) lowerCamelCase__ = { """configuration_blip""": [ """BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP""", """BlipConfig""", """BlipTextConfig""", """BlipVisionConfig""", ], """processing_blip""": ["""BlipProcessor"""], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = ["""BlipImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ """BLIP_PRETRAINED_MODEL_ARCHIVE_LIST""", """BlipModel""", """BlipPreTrainedModel""", """BlipForConditionalGeneration""", """BlipForQuestionAnswering""", """BlipVisionModel""", """BlipTextModel""", """BlipForImageTextRetrieval""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ """TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFBlipModel""", """TFBlipPreTrainedModel""", """TFBlipForConditionalGeneration""", """TFBlipForQuestionAnswering""", """TFBlipVisionModel""", """TFBlipTextModel""", """TFBlipForImageTextRetrieval""", ] if TYPE_CHECKING: from .configuration_blip import BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, BlipConfig, BlipTextConfig, BlipVisionConfig from .processing_blip import BlipProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_blip import BlipImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blip import ( BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, BlipModel, BlipPreTrainedModel, BlipTextModel, BlipVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blip import ( TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFBlipForConditionalGeneration, TFBlipForImageTextRetrieval, TFBlipForQuestionAnswering, TFBlipModel, TFBlipPreTrainedModel, TFBlipTextModel, TFBlipVisionModel, ) else: import sys lowerCamelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
302
1
import argparse import torch from transformers import RemBertConfig, RemBertModel, load_tf_weights_in_rembert from transformers.utils import logging logging.set_verbosity_info() def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : Any ): """simple docstring""" __a = RemBertConfig.from_json_file(_SCREAMING_SNAKE_CASE ) print("""Building PyTorch model from configuration: {}""".format(str(_SCREAMING_SNAKE_CASE ) ) ) __a = RemBertModel(_SCREAMING_SNAKE_CASE ) # Load weights from tf checkpoint load_tf_weights_in_rembert(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Save pytorch-model print("""Save PyTorch model to {}""".format(_SCREAMING_SNAKE_CASE ) ) torch.save(model.state_dict() , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--rembert_config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained RemBERT model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) lowerCamelCase__ = parser.parse_args() convert_rembert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.rembert_config_file, args.pytorch_dump_path)
302
class SCREAMING_SNAKE_CASE : def __init__( self : List[Any] , __lowercase : Union[str, Any] ): '''simple docstring''' __a = val __a = None __a = None def UpperCamelCase_ ( self : Union[str, Any] , __lowercase : Any ): '''simple docstring''' if self.val: if val < self.val: if self.left is None: __a = Node(__lowercase ) else: self.left.insert(__lowercase ) elif val > self.val: if self.right is None: __a = Node(__lowercase ) else: self.right.insert(__lowercase ) else: __a = val def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : Any ): """simple docstring""" if root: inorder(root.left , _SCREAMING_SNAKE_CASE ) res.append(root.val ) inorder(root.right , _SCREAMING_SNAKE_CASE ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Any ): """simple docstring""" if len(_SCREAMING_SNAKE_CASE ) == 0: return arr __a = Node(arr[0] ) for i in range(1 , len(_SCREAMING_SNAKE_CASE ) ): root.insert(arr[i] ) # Traverse BST in order. __a = [] inorder(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return res if __name__ == "__main__": print(tree_sort([10, 1, 3, 2, 9, 14, 13]))
302
1
import inspect import warnings from typing import Any, Dict, Optional, Union from packaging import version def lowerCAmelCase__ ( *_SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : Optional[Union[Dict, Any]] = None , _SCREAMING_SNAKE_CASE : Tuple=True , _SCREAMING_SNAKE_CASE : Optional[Any]=2 ): """simple docstring""" from .. import __version__ __a = take_from __a = () if not isinstance(args[0] , _SCREAMING_SNAKE_CASE ): __a = (args,) for attribute, version_name, message in args: if version.parse(version.parse(_SCREAMING_SNAKE_CASE ).base_version ) >= version.parse(_SCREAMING_SNAKE_CASE ): raise ValueError( f"The deprecation tuple {(attribute, version_name, message)} should be removed since diffusers'" f" version {__version__} is >= {version_name}" ) __a = None if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) and attribute in deprecated_kwargs: values += (deprecated_kwargs.pop(_SCREAMING_SNAKE_CASE ),) __a = f"The `{attribute}` argument is deprecated and will be removed in version {version_name}." elif hasattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): values += (getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ),) __a = f"The `{attribute}` attribute is deprecated and will be removed in version {version_name}." elif deprecated_kwargs is None: __a = f"`{attribute}` is deprecated and will be removed in version {version_name}." if warning is not None: __a = warning + """ """ if standard_warn else """""" warnings.warn(warning + message , _SCREAMING_SNAKE_CASE , stacklevel=_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) and len(_SCREAMING_SNAKE_CASE ) > 0: __a = inspect.getouterframes(inspect.currentframe() )[1] __a = call_frame.filename __a = call_frame.lineno __a = call_frame.function __a , __a = next(iter(deprecated_kwargs.items() ) ) raise TypeError(f"{function} in {filename} line {line_number-1} got an unexpected keyword argument `{key}`" ) if len(_SCREAMING_SNAKE_CASE ) == 0: return elif len(_SCREAMING_SNAKE_CASE ) == 1: return values[0] return values
302
import inspect import unittest from transformers import MobileViTVaConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, MobileViTVaModel from transformers.models.mobilevitva.modeling_mobilevitva import ( MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST, make_divisible, ) if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): def UpperCamelCase_ ( self : str ): '''simple docstring''' __a = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(__lowercase , """width_multiplier""" ) ) class SCREAMING_SNAKE_CASE : def __init__( self : Dict , __lowercase : Union[str, Any] , __lowercase : Dict=13 , __lowercase : int=64 , __lowercase : Tuple=2 , __lowercase : Tuple=3 , __lowercase : Tuple="swish" , __lowercase : List[Any]=3 , __lowercase : List[str]=32 , __lowercase : int=0.1 , __lowercase : Union[str, Any]=0.02 , __lowercase : Optional[int]=True , __lowercase : Dict=True , __lowercase : Tuple=10 , __lowercase : str=None , __lowercase : Optional[Any]=0.25 , __lowercase : str=0.0 , __lowercase : Optional[Any]=0.0 , ): '''simple docstring''' __a = parent __a = batch_size __a = image_size __a = patch_size __a = num_channels __a = make_divisible(512 * width_multiplier , divisor=8 ) __a = hidden_act __a = conv_kernel_size __a = output_stride __a = classifier_dropout_prob __a = use_labels __a = is_training __a = num_labels __a = initializer_range __a = scope __a = width_multiplier __a = ffn_dropout __a = attn_dropout def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' __a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a = None __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.num_labels ) __a = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) __a = self.get_config() return config, pixel_values, labels, pixel_labels def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' return MobileViTVaConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_act=self.hidden_act , conv_kernel_size=self.conv_kernel_size , output_stride=self.output_stride , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , width_multiplier=self.width_multiplier , ffn_dropout=self.ffn_dropout_prob , attn_dropout=self.attn_dropout_prob , ) def UpperCamelCase_ ( self : Tuple , __lowercase : Optional[Any] , __lowercase : int , __lowercase : Optional[Any] , __lowercase : Tuple ): '''simple docstring''' __a = MobileViTVaModel(config=__lowercase ) model.to(__lowercase ) model.eval() __a = model(__lowercase ) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def UpperCamelCase_ ( self : Union[str, Any] , __lowercase : List[Any] , __lowercase : str , __lowercase : Optional[int] , __lowercase : Union[str, Any] ): '''simple docstring''' __a = self.num_labels __a = MobileViTVaForImageClassification(__lowercase ) model.to(__lowercase ) model.eval() __a = model(__lowercase , labels=__lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCamelCase_ ( self : int , __lowercase : str , __lowercase : Any , __lowercase : int , __lowercase : List[str] ): '''simple docstring''' __a = self.num_labels __a = MobileViTVaForSemanticSegmentation(__lowercase ) model.to(__lowercase ) model.eval() __a = model(__lowercase ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) __a = model(__lowercase , labels=__lowercase ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def UpperCamelCase_ ( self : Dict ): '''simple docstring''' __a = self.prepare_config_and_inputs() __a , __a , __a , __a = config_and_inputs __a = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE ( lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase ): __lowerCamelCase : List[Any] =( (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation) if is_torch_available() else () ) __lowerCamelCase : Any =( { 'feature-extraction': MobileViTVaModel, 'image-classification': MobileViTVaForImageClassification, 'image-segmentation': MobileViTVaForSemanticSegmentation, } if is_torch_available() else {} ) __lowerCamelCase : Dict =False __lowerCamelCase : Optional[Any] =False __lowerCamelCase : int =False __lowerCamelCase : Any =False def UpperCamelCase_ ( self : Dict ): '''simple docstring''' __a = MobileViTVaModelTester(self ) __a = MobileViTVaConfigTester(self , config_class=__lowercase , has_text_modality=__lowercase ) def UpperCamelCase_ ( self : Dict ): '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason="""MobileViTV2 does not use inputs_embeds""" ) def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' pass @unittest.skip(reason="""MobileViTV2 does not support input and output embeddings""" ) def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' pass @unittest.skip(reason="""MobileViTV2 does not output attentions""" ) def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' pass @require_torch_multi_gpu @unittest.skip(reason="""Got `CUDA error: misaligned address` for tests after this one being run.""" ) def UpperCamelCase_ ( self : int ): '''simple docstring''' pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' pass def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(__lowercase ) __a = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a = [*signature.parameters.keys()] __a = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , __lowercase ) def UpperCamelCase_ ( self : Dict ): '''simple docstring''' __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowercase ) def UpperCamelCase_ ( self : int ): '''simple docstring''' def check_hidden_states_output(__lowercase : List[str] , __lowercase : Optional[int] , __lowercase : List[str] ): __a = model_class(__lowercase ) model.to(__lowercase ) model.eval() with torch.no_grad(): __a = model(**self._prepare_for_class(__lowercase , __lowercase ) ) __a = outputs.hidden_states __a = 5 self.assertEqual(len(__lowercase ) , __lowercase ) # MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width) # with the width and height being successively divided by 2. __a = 2 for i in range(len(__lowercase ) ): self.assertListEqual( list(hidden_states[i].shape[-2:] ) , [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor] , ) divisor *= 2 self.assertEqual(self.model_tester.output_stride , divisor // 2 ) __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = True check_hidden_states_output(__lowercase , __lowercase , __lowercase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __a = True check_hidden_states_output(__lowercase , __lowercase , __lowercase ) def UpperCamelCase_ ( self : Optional[int] ): '''simple docstring''' __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__lowercase ) def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*__lowercase ) @slow def UpperCamelCase_ ( self : Optional[int] ): '''simple docstring''' for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = MobileViTVaModel.from_pretrained(__lowercase ) self.assertIsNotNone(__lowercase ) def lowerCAmelCase__ ( ): """simple docstring""" __a = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class SCREAMING_SNAKE_CASE ( unittest.TestCase ): @cached_property def UpperCamelCase_ ( self : Dict ): '''simple docstring''' return ( MobileViTImageProcessor.from_pretrained("""apple/mobilevitv2-1.0-imagenet1k-256""" ) if is_vision_available() else None ) @slow def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' __a = MobileViTVaForImageClassification.from_pretrained("""apple/mobilevitv2-1.0-imagenet1k-256""" ).to( __lowercase ) __a = self.default_image_processor __a = prepare_img() __a = image_processor(images=__lowercase , return_tensors="""pt""" ).to(__lowercase ) # forward pass with torch.no_grad(): __a = model(**__lowercase ) # verify the logits __a = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , __lowercase ) __a = torch.tensor([-1.6336E00, -7.3204E-02, -5.1883E-01] ).to(__lowercase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __lowercase , atol=1E-4 ) ) @slow def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' __a = MobileViTVaForSemanticSegmentation.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3""" ) __a = model.to(__lowercase ) __a = MobileViTImageProcessor.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3""" ) __a = prepare_img() __a = image_processor(images=__lowercase , return_tensors="""pt""" ).to(__lowercase ) # forward pass with torch.no_grad(): __a = model(**__lowercase ) __a = outputs.logits # verify the logits __a = torch.Size((1, 21, 32, 32) ) self.assertEqual(logits.shape , __lowercase ) __a = torch.tensor( [ [[7.0863, 7.1525, 6.8201], [6.6931, 6.8770, 6.8933], [6.2978, 7.0366, 6.9636]], [[-3.7134, -3.6712, -3.6675], [-3.5825, -3.3549, -3.4777], [-3.3435, -3.3979, -3.2857]], [[-2.9329, -2.8003, -2.7369], [-3.0564, -2.4780, -2.0207], [-2.6889, -1.9298, -1.7640]], ] , device=__lowercase , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , __lowercase , atol=1E-4 ) ) @slow def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' __a = MobileViTVaForSemanticSegmentation.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3""" ) __a = model.to(__lowercase ) __a = MobileViTImageProcessor.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3""" ) __a = prepare_img() __a = image_processor(images=__lowercase , return_tensors="""pt""" ).to(__lowercase ) # forward pass with torch.no_grad(): __a = model(**__lowercase ) __a = outputs.logits.detach().cpu() __a = image_processor.post_process_semantic_segmentation(outputs=__lowercase , target_sizes=[(50, 60)] ) __a = torch.Size((50, 60) ) self.assertEqual(segmentation[0].shape , __lowercase ) __a = image_processor.post_process_semantic_segmentation(outputs=__lowercase ) __a = torch.Size((32, 32) ) self.assertEqual(segmentation[0].shape , __lowercase )
302
1
import importlib import inspect import os import re # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_config_docstrings.py lowerCamelCase__ = """src/transformers""" # This is to make sure the transformers module imported is the one in the repo. lowerCamelCase__ = importlib.util.spec_from_file_location( """transformers""", os.path.join(PATH_TO_TRANSFORMERS, """__init__.py"""), submodule_search_locations=[PATH_TO_TRANSFORMERS], ) lowerCamelCase__ = spec.loader.load_module() lowerCamelCase__ = 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)` lowerCamelCase__ = re.compile("""\[(.+?)\]\((https://huggingface\.co/.+?)\)""") lowerCamelCase__ = { """CLIPConfigMixin""", """DecisionTransformerConfigMixin""", """EncoderDecoderConfigMixin""", """RagConfigMixin""", """SpeechEncoderDecoderConfigMixin""", """VisionEncoderDecoderConfigMixin""", """VisionTextDualEncoderConfigMixin""", } def lowerCAmelCase__ ( ): """simple docstring""" __a = [] for config_class in list(CONFIG_MAPPING.values() ): __a = False # source code of `config_class` __a = inspect.getsource(_SCREAMING_SNAKE_CASE ) __a = _re_checkpoint.findall(_SCREAMING_SNAKE_CASE ) for checkpoint in checkpoints: # Each `checkpoint` is a tuple of a checkpoint name and a checkpoint link. # For example, `('bert-base-uncased', 'https://huggingface.co/bert-base-uncased')` __a , __a = checkpoint # verify the checkpoint name corresponds to the checkpoint link __a = f"https://huggingface.co/{ckpt_name}" if ckpt_link == ckpt_link_from_name: __a = True break __a = config_class.__name__ if not checkpoint_found and name not in CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK: configs_without_checkpoint.append(_SCREAMING_SNAKE_CASE ) if len(_SCREAMING_SNAKE_CASE ) > 0: __a = """\n""".join(sorted(_SCREAMING_SNAKE_CASE ) ) raise ValueError(f"The following configurations don't contain any valid checkpoint:\n{message}" ) if __name__ == "__main__": check_config_docstrings_have_checkpoints()
302
from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import torch from ...utils import BaseOutput, OptionalDependencyNotAvailable, is_torch_available, is_transformers_available @dataclass class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : Union[List[np.ndarray], torch.FloatTensor] 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_text_to_video_synth import TextToVideoSDPipeline from .pipeline_text_to_video_synth_imgaimg import VideoToVideoSDPipeline # noqa: F401 from .pipeline_text_to_video_zero import TextToVideoZeroPipeline
302
1
def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : list ): """simple docstring""" if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): raise ValueError("""Input series is not valid, valid series - [2, 4, 6]""" ) if len(_SCREAMING_SNAKE_CASE ) == 0: raise ValueError("""Input list must be a non empty list""" ) if len(_SCREAMING_SNAKE_CASE ) == 1: return True __a = series[1] - series[0] for index in range(len(_SCREAMING_SNAKE_CASE ) - 1 ): if series[index + 1] - series[index] != common_diff: return False return True def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : list ): """simple docstring""" if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): raise ValueError("""Input series is not valid, valid series - [2, 4, 6]""" ) if len(_SCREAMING_SNAKE_CASE ) == 0: raise ValueError("""Input list must be a non empty list""" ) __a = 0 for val in series: answer += val return answer / len(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": import doctest doctest.testmod()
302
import string import numpy def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int ): """simple docstring""" return b if a == 0 else greatest_common_divisor(b % a , _SCREAMING_SNAKE_CASE ) class SCREAMING_SNAKE_CASE : __lowerCamelCase : List[str] =string.ascii_uppercase + string.digits # This cipher takes alphanumerics into account # i.e. a total of 36 characters # take x and return x % len(key_string) __lowerCamelCase : List[Any] =numpy.vectorize(lambda lowerCamelCase__ : x % 36 ) __lowerCamelCase : Optional[Any] =numpy.vectorize(lowerCamelCase__ ) def __init__( self : Union[str, Any] , __lowercase : numpy.ndarray ): '''simple docstring''' __a = self.modulus(__lowercase ) # mod36 calc's on the encrypt key self.check_determinant() # validate the determinant of the encryption key __a = encrypt_key.shape[0] def UpperCamelCase_ ( self : Dict , __lowercase : str ): '''simple docstring''' return self.key_string.index(__lowercase ) def UpperCamelCase_ ( self : Dict , __lowercase : int ): '''simple docstring''' return self.key_string[round(__lowercase )] def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' __a = round(numpy.linalg.det(self.encrypt_key ) ) if det < 0: __a = det % len(self.key_string ) __a = len(self.key_string ) if greatest_common_divisor(__lowercase , len(self.key_string ) ) != 1: __a = ( F"determinant modular {req_l} of encryption key({det}) " F"is not co prime w.r.t {req_l}.\nTry another key." ) raise ValueError(__lowercase ) def UpperCamelCase_ ( self : Dict , __lowercase : str ): '''simple docstring''' __a = [char for char in text.upper() if char in self.key_string] __a = chars[-1] while len(__lowercase ) % self.break_key != 0: chars.append(__lowercase ) return "".join(__lowercase ) def UpperCamelCase_ ( self : List[str] , __lowercase : str ): '''simple docstring''' __a = self.process_text(text.upper() ) __a = """""" for i in range(0 , len(__lowercase ) - self.break_key + 1 , self.break_key ): __a = text[i : i + self.break_key] __a = [self.replace_letters(__lowercase ) for char in batch] __a = numpy.array([vec] ).T __a = self.modulus(self.encrypt_key.dot(__lowercase ) ).T.tolist()[ 0 ] __a = """""".join( self.replace_digits(__lowercase ) for num in batch_encrypted ) encrypted += encrypted_batch return encrypted def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' __a = round(numpy.linalg.det(self.encrypt_key ) ) if det < 0: __a = det % len(self.key_string ) __a = None for i in range(len(self.key_string ) ): if (det * i) % len(self.key_string ) == 1: __a = i break __a = ( det_inv * numpy.linalg.det(self.encrypt_key ) * numpy.linalg.inv(self.encrypt_key ) ) return self.to_int(self.modulus(__lowercase ) ) def UpperCamelCase_ ( self : Any , __lowercase : str ): '''simple docstring''' __a = self.make_decrypt_key() __a = self.process_text(text.upper() ) __a = """""" for i in range(0 , len(__lowercase ) - self.break_key + 1 , self.break_key ): __a = text[i : i + self.break_key] __a = [self.replace_letters(__lowercase ) for char in batch] __a = numpy.array([vec] ).T __a = self.modulus(decrypt_key.dot(__lowercase ) ).T.tolist()[0] __a = """""".join( self.replace_digits(__lowercase ) for num in batch_decrypted ) decrypted += decrypted_batch return decrypted def lowerCAmelCase__ ( ): """simple docstring""" __a = int(input("""Enter the order of the encryption key: """ ) ) __a = [] print("""Enter each row of the encryption key with space separated integers""" ) for _ in range(_SCREAMING_SNAKE_CASE ): __a = [int(_SCREAMING_SNAKE_CASE ) for x in input().split()] hill_matrix.append(_SCREAMING_SNAKE_CASE ) __a = HillCipher(numpy.array(_SCREAMING_SNAKE_CASE ) ) print("""Would you like to encrypt or decrypt some text? (1 or 2)""" ) __a = input("""\n1. Encrypt\n2. Decrypt\n""" ) if option == "1": __a = input("""What text would you like to encrypt?: """ ) print("""Your encrypted text is:""" ) print(hc.encrypt(_SCREAMING_SNAKE_CASE ) ) elif option == "2": __a = input("""What text would you like to decrypt?: """ ) print("""Your decrypted text is:""" ) print(hc.decrypt(_SCREAMING_SNAKE_CASE ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
302
1
from __future__ import annotations import collections import tempfile import unittest import numpy as np from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import is_tf_available, is_vision_available from ...test_modeling_tf_common import floats_tensor, ids_tensor, random_attention_mask from ..bert.test_modeling_tf_bert import TFBertModelTester from ..clip.test_modeling_tf_clip import TFCLIPVisionModelTester from ..deit.test_modeling_tf_deit import TFDeiTModelTester from ..roberta.test_modeling_tf_roberta import TFRobertaModelTester from ..vit.test_modeling_tf_vit import TFViTModelTester if is_tf_available(): from transformers import ( TFBertModel, TFCLIPVisionModel, TFDeiTModel, TFRobertaModel, TFVisionTextDualEncoderModel, TFViTModel, VisionTextDualEncoderConfig, ) if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" if isinstance(_SCREAMING_SNAKE_CASE , collections.abc.Iterable ): return x return (x, x) @require_tf class SCREAMING_SNAKE_CASE : def UpperCamelCase_ ( self : Optional[Any] , __lowercase : int , __lowercase : str ): '''simple docstring''' pass def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' pass def UpperCamelCase_ ( self : str ): '''simple docstring''' pass def UpperCamelCase_ ( self : Optional[Any] , __lowercase : Any , __lowercase : Optional[Any] , __lowercase : str , __lowercase : List[Any] , __lowercase : List[Any]=None , **__lowercase : int ): '''simple docstring''' __a = VisionTextDualEncoderConfig.from_vision_text_configs(__lowercase , __lowercase ) __a = TFVisionTextDualEncoderModel(__lowercase ) __a = model(input_ids=__lowercase , pixel_values=__lowercase , attention_mask=__lowercase ) self.assertEqual(output["""text_embeds"""].shape , (input_ids.shape[0], config.projection_dim) ) self.assertEqual(output["""image_embeds"""].shape , (pixel_values.shape[0], config.projection_dim) ) def UpperCamelCase_ ( self : Optional[Any] , __lowercase : Union[str, Any] , __lowercase : str , __lowercase : str , __lowercase : Optional[int] , __lowercase : List[str]=None , **__lowercase : Tuple ): '''simple docstring''' __a , __a = self.get_vision_text_model(__lowercase , __lowercase ) __a = TFVisionTextDualEncoderModel(vision_model=__lowercase , text_model=__lowercase ) __a = model(input_ids=__lowercase , pixel_values=__lowercase , attention_mask=__lowercase ) self.assertEqual(output["""text_embeds"""].shape , (input_ids.shape[0], model.config.projection_dim) ) self.assertEqual(output["""image_embeds"""].shape , (pixel_values.shape[0], model.config.projection_dim) ) def UpperCamelCase_ ( self : Dict , __lowercase : Any , __lowercase : Any , __lowercase : Union[str, Any] , __lowercase : List[Any] , __lowercase : List[Any]=None , **__lowercase : List[str] ): '''simple docstring''' __a , __a = self.get_vision_text_model(__lowercase , __lowercase ) __a = {"""vision_model""": vision_model, """text_model""": text_model} __a = TFVisionTextDualEncoderModel.from_vision_text_pretrained(**__lowercase ) __a = model(input_ids=__lowercase , pixel_values=__lowercase , attention_mask=__lowercase ) self.assertEqual(output["""text_embeds"""].shape , (input_ids.shape[0], model.config.projection_dim) ) self.assertEqual(output["""image_embeds"""].shape , (pixel_values.shape[0], model.config.projection_dim) ) def UpperCamelCase_ ( self : int , __lowercase : str , __lowercase : List[Any] , __lowercase : Optional[int] , __lowercase : int , __lowercase : List[str]=None , **__lowercase : List[str] ): '''simple docstring''' __a , __a = self.get_vision_text_model(__lowercase , __lowercase ) __a = TFVisionTextDualEncoderModel(vision_model=__lowercase , text_model=__lowercase ) __a = model(input_ids=__lowercase , pixel_values=__lowercase , attention_mask=__lowercase ) __a = output[0].numpy() with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(__lowercase ) __a = TFVisionTextDualEncoderModel.from_pretrained(__lowercase ) __a = model(input_ids=__lowercase , pixel_values=__lowercase , attention_mask=__lowercase ) __a = after_output[0].numpy() __a = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(__lowercase , 1E-5 ) def UpperCamelCase_ ( self : Optional[Any] , __lowercase : Tuple , __lowercase : Any , __lowercase : List[Any] , __lowercase : List[str] , __lowercase : Dict=None , **__lowercase : List[Any] ): '''simple docstring''' __a , __a = self.get_vision_text_model(__lowercase , __lowercase ) __a = TFVisionTextDualEncoderModel(vision_model=__lowercase , text_model=__lowercase ) __a = model( input_ids=__lowercase , pixel_values=__lowercase , attention_mask=__lowercase , output_attentions=__lowercase ) __a = output.vision_model_output.attentions self.assertEqual(len(__lowercase ) , vision_config.num_hidden_layers ) # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token) __a = to_atuple(vision_model.config.image_size ) __a = to_atuple(vision_model.config.patch_size ) __a = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) __a = num_patches + 1 self.assertEqual(vision_attentions[0].shape[-3:] , (vision_config.num_attention_heads, seq_len, seq_len) ) __a = output.text_model_output.attentions self.assertEqual(len(__lowercase ) , text_config.num_hidden_layers ) self.assertEqual( text_attentions[0].shape[-3:] , (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]) , ) def UpperCamelCase_ ( self : Optional[Any] , __lowercase : np.ndarray , __lowercase : np.ndarray , __lowercase : float ): '''simple docstring''' __a = np.abs((a - b) ).max() self.assertLessEqual(__lowercase , __lowercase , F"Difference between torch and flax is {diff} (>= {tol})." ) def UpperCamelCase_ ( self : int ): '''simple docstring''' __a = self.prepare_config_and_inputs() self.check_vision_text_dual_encoder_model(**__lowercase ) def UpperCamelCase_ ( self : Dict ): '''simple docstring''' __a = self.prepare_config_and_inputs() self.check_model_from_pretrained_configs(**__lowercase ) def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' __a = self.prepare_config_and_inputs() self.check_vision_text_dual_encoder_from_pretrained(**__lowercase ) def UpperCamelCase_ ( self : str ): '''simple docstring''' __a = self.prepare_config_and_inputs() self.check_save_load(**__lowercase ) def UpperCamelCase_ ( self : Optional[int] ): '''simple docstring''' __a = self.prepare_config_and_inputs() self.check_vision_text_output_attention(**__lowercase ) @slow def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' __a , __a = self.get_pretrained_model_and_inputs() __a = model_a(**__lowercase ) __a = outputs[0].numpy() with tempfile.TemporaryDirectory() as tmp_dirname: model_a.save_pretrained(__lowercase ) __a = TFVisionTextDualEncoderModel.from_pretrained(__lowercase ) __a = model_a(**__lowercase ) __a = after_outputs[0].numpy() __a = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(__lowercase , 1E-5 ) @require_tf class SCREAMING_SNAKE_CASE ( lowerCamelCase__ , unittest.TestCase ): def UpperCamelCase_ ( self : int ): '''simple docstring''' __a = TFVisionTextDualEncoderModel.from_vision_text_pretrained( """hf-internal-testing/tiny-random-vit""" , """hf-internal-testing/tiny-random-bert""" ) __a = 13 __a = floats_tensor( [ batch_size, model.vision_model.config.num_channels, model.vision_model.config.image_size, model.vision_model.config.image_size, ] ) __a = ids_tensor([batch_size, 4] , model.text_model.config.vocab_size ) __a = random_attention_mask([batch_size, 4] ) __a = {"""pixel_values""": pixel_values, """input_ids""": input_ids, """attention_mask""": attention_mask} return model, inputs def UpperCamelCase_ ( self : int , __lowercase : Dict , __lowercase : int ): '''simple docstring''' __a = TFViTModel(__lowercase , name="""vision_model""" ) __a = TFBertModel(__lowercase , name="""text_model""" ) return vision_model, text_model def UpperCamelCase_ ( self : Optional[int] ): '''simple docstring''' __a = TFViTModelTester(self ) __a = TFBertModelTester(self ) __a = vit_model_tester.prepare_config_and_inputs() __a = bert_model_tester.prepare_config_and_inputs() __a , __a , __a = vision_config_and_inputs ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) = text_config_and_inputs return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": input_mask, "input_ids": input_ids, "text_token_type_ids": token_type_ids, "text_sequence_labels": sequence_labels, "text_token_labels": token_labels, "text_choice_labels": choice_labels, } @require_tf class SCREAMING_SNAKE_CASE ( lowerCamelCase__ , unittest.TestCase ): def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' # DeiT repo doesn't have TF weights, but we don't actually use the weights at all so let's # just reinitialize it. __a = TFVisionTextDualEncoderModel.from_vision_text_pretrained( """Rocketknight1/tiny-random-deit-tf""" , """hf-internal-testing/tiny-random-roberta""" ) __a = 13 __a = floats_tensor( [ batch_size, model.vision_model.config.num_channels, model.vision_model.config.image_size, model.vision_model.config.image_size, ] ) __a = ids_tensor([batch_size, 4] , model.text_model.config.vocab_size ) __a = random_attention_mask([batch_size, 4] ) __a = {"""pixel_values""": pixel_values, """input_ids""": input_ids, """attention_mask""": attention_mask} return model, inputs def UpperCamelCase_ ( self : int , __lowercase : Union[str, Any] , __lowercase : str , __lowercase : str , __lowercase : Optional[Any] , __lowercase : List[Any]=None , **__lowercase : List[Any] ): '''simple docstring''' __a , __a = self.get_vision_text_model(__lowercase , __lowercase ) __a = TFVisionTextDualEncoderModel(vision_model=__lowercase , text_model=__lowercase ) __a = model( input_ids=__lowercase , pixel_values=__lowercase , attention_mask=__lowercase , output_attentions=__lowercase ) __a = output.vision_model_output.attentions self.assertEqual(len(__lowercase ) , vision_config.num_hidden_layers ) # in DEiT, the seq_len equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens) __a = to_atuple(vision_model.config.image_size ) __a = to_atuple(vision_model.config.patch_size ) __a = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) __a = num_patches + 2 self.assertEqual(vision_attentions[0].shape[-3:] , (vision_config.num_attention_heads, seq_len, seq_len) ) __a = output.text_model_output.attentions self.assertEqual(len(__lowercase ) , text_config.num_hidden_layers ) self.assertEqual( text_attentions[0].shape[-3:] , (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]) , ) def UpperCamelCase_ ( self : Any , __lowercase : Union[str, Any] , __lowercase : Optional[Any] ): '''simple docstring''' __a = TFDeiTModel(__lowercase , name="""vision_model""" ) __a = TFRobertaModel(__lowercase , name="""text_model""" ) return vision_model, text_model def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' __a = TFDeiTModelTester(self ) __a = TFRobertaModelTester(self ) __a = vit_model_tester.prepare_config_and_inputs() __a = bert_model_tester.prepare_config_and_inputs() __a , __a , __a = vision_config_and_inputs ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) = text_config_and_inputs return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": input_mask, "input_ids": input_ids, "text_token_type_ids": token_type_ids, "text_sequence_labels": sequence_labels, "text_token_labels": token_labels, "text_choice_labels": choice_labels, } @require_tf class SCREAMING_SNAKE_CASE ( lowerCamelCase__ , unittest.TestCase ): def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' __a = TFVisionTextDualEncoderModel.from_vision_text_pretrained( """Rocketknight1/tiny-random-clip-tf""" , """hf-internal-testing/tiny-random-bert""" ) __a = 13 __a = floats_tensor( [ batch_size, model.vision_model.config.num_channels, model.vision_model.config.image_size, model.vision_model.config.image_size, ] ) __a = ids_tensor([batch_size, 4] , model.text_model.config.vocab_size ) __a = random_attention_mask([batch_size, 4] ) __a = {"""pixel_values""": pixel_values, """input_ids""": input_ids, """attention_mask""": attention_mask} return model, inputs def UpperCamelCase_ ( self : Union[str, Any] , __lowercase : Any , __lowercase : Union[str, Any] ): '''simple docstring''' __a = TFCLIPVisionModel(__lowercase , name="""vision_model""" ) __a = TFBertModel(__lowercase , name="""text_model""" ) return vision_model, text_model def UpperCamelCase_ ( self : Any ): '''simple docstring''' __a = TFCLIPVisionModelTester(self ) __a = TFBertModelTester(self ) __a = clip_model_tester.prepare_config_and_inputs() __a = bert_model_tester.prepare_config_and_inputs() __a , __a = vision_config_and_inputs ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) = text_config_and_inputs return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": input_mask, "input_ids": input_ids, "text_token_type_ids": token_type_ids, "text_sequence_labels": sequence_labels, "text_token_labels": token_labels, "text_choice_labels": choice_labels, } @require_vision @require_tf class SCREAMING_SNAKE_CASE ( unittest.TestCase ): @slow def UpperCamelCase_ ( self : Dict ): '''simple docstring''' __a = TFVisionTextDualEncoderModel.from_pretrained( """clip-italian/clip-italian""" , logit_scale_init_value=1.0 , from_pt=__lowercase ) __a = VisionTextDualEncoderProcessor.from_pretrained("""clip-italian/clip-italian""" ) __a = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) __a = processor( text=["""una foto di un gatto""", """una foto di un cane"""] , images=__lowercase , padding=__lowercase , return_tensors="""np""" ) __a = model(**__lowercase ) # verify the logits self.assertEqual(outputs.logits_per_image.shape , (inputs.pixel_values.shape[0], inputs.input_ids.shape[0]) ) self.assertEqual( outputs.logits_per_text.shape , (inputs.input_ids.shape[0], inputs.pixel_values.shape[0]) , ) __a = np.array([[1.2284727, 0.3104122]] ) self.assertTrue(np.allclose(outputs.logits_per_image.numpy() , __lowercase , atol=1E-3 ) )
302
from typing import List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { """huggingface/autoformer-tourism-monthly""": """https://huggingface.co/huggingface/autoformer-tourism-monthly/resolve/main/config.json""", } class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : List[Any] ='autoformer' __lowerCamelCase : str ={ 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', 'num_hidden_layers': 'encoder_layers', } def __init__( self : List[Any] , __lowercase : Optional[int] = None , __lowercase : Optional[int] = None , __lowercase : str = "student_t" , __lowercase : str = "nll" , __lowercase : int = 1 , __lowercase : List[int] = [1, 2, 3, 4, 5, 6, 7] , __lowercase : bool = True , __lowercase : int = 0 , __lowercase : int = 0 , __lowercase : int = 0 , __lowercase : int = 0 , __lowercase : Optional[List[int]] = None , __lowercase : Optional[List[int]] = None , __lowercase : int = 64 , __lowercase : int = 2 , __lowercase : int = 2 , __lowercase : int = 2 , __lowercase : int = 2 , __lowercase : int = 32 , __lowercase : int = 32 , __lowercase : str = "gelu" , __lowercase : float = 0.1 , __lowercase : float = 0.1 , __lowercase : float = 0.1 , __lowercase : float = 0.1 , __lowercase : float = 0.1 , __lowercase : int = 100 , __lowercase : float = 0.02 , __lowercase : bool = True , __lowercase : List[Any]=True , __lowercase : int = 10 , __lowercase : int = 25 , __lowercase : int = 3 , **__lowercase : Optional[int] , ): '''simple docstring''' # time series specific configuration __a = prediction_length __a = context_length if context_length is not None else prediction_length __a = distribution_output __a = loss __a = input_size __a = num_time_features __a = lags_sequence __a = scaling __a = num_dynamic_real_features __a = num_static_real_features __a = num_static_categorical_features if cardinality is not None and num_static_categorical_features > 0: if len(__lowercase ) != num_static_categorical_features: raise ValueError( """The cardinality should be a list of the same length as `num_static_categorical_features`""" ) __a = cardinality else: __a = [0] if embedding_dimension is not None and num_static_categorical_features > 0: if len(__lowercase ) != num_static_categorical_features: raise ValueError( """The embedding dimension should be a list of the same length as `num_static_categorical_features`""" ) __a = embedding_dimension else: __a = [min(50 , (cat + 1) // 2 ) for cat in self.cardinality] __a = num_parallel_samples # Transformer architecture configuration __a = input_size * len(self.lags_sequence ) + self._number_of_features __a = d_model __a = encoder_attention_heads __a = decoder_attention_heads __a = encoder_ffn_dim __a = decoder_ffn_dim __a = encoder_layers __a = decoder_layers __a = dropout __a = attention_dropout __a = activation_dropout __a = encoder_layerdrop __a = decoder_layerdrop __a = activation_function __a = init_std __a = use_cache # Autoformer __a = label_length __a = moving_average __a = autocorrelation_factor super().__init__(is_encoder_decoder=__lowercase , **__lowercase ) @property def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' return ( sum(self.embedding_dimension ) + self.num_dynamic_real_features + self.num_time_features + self.num_static_real_features + self.input_size * 2 # the log1p(abs(loc)) and log(scale) features )
302
1
import tempfile import unittest from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from transformers.testing_utils import ( is_torch_available, require_optimum, require_torch, slow, ) if is_torch_available(): import torch @require_torch @require_optimum @slow class SCREAMING_SNAKE_CASE ( unittest.TestCase ): def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' __a = """hf-internal-testing/tiny-random-t5""" __a = AutoTokenizer.from_pretrained(__lowercase ) __a = AutoModelForSeqaSeqLM.from_pretrained(__lowercase ) __a = tokenizer("""This is me""" , return_tensors="""pt""" ) __a = model.to_bettertransformer() self.assertTrue(any("""BetterTransformer""" in mod.__class__.__name__ for _, mod in model.named_modules() ) ) __a = model.generate(**__lowercase ) __a = model.reverse_bettertransformer() self.assertFalse(any("""BetterTransformer""" in mod.__class__.__name__ for _, mod in model.named_modules() ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(__lowercase ) __a = AutoModelForSeqaSeqLM.from_pretrained(__lowercase ) self.assertFalse( any("""BetterTransformer""" in mod.__class__.__name__ for _, mod in model_reloaded.named_modules() ) ) __a = model_reloaded.generate(**__lowercase ) self.assertTrue(torch.allclose(__lowercase , __lowercase ) ) def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' __a = """hf-internal-testing/tiny-random-t5""" __a = AutoModelForSeqaSeqLM.from_pretrained(__lowercase ) __a = model.to_bettertransformer() with tempfile.TemporaryDirectory() as tmpdirname: with self.assertRaises(__lowercase ): model.save_pretrained(__lowercase ) __a = model.reverse_bettertransformer() model.save_pretrained(__lowercase )
302
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase__ = { """configuration_electra""": ["""ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ElectraConfig""", """ElectraOnnxConfig"""], """tokenization_electra""": ["""ElectraTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = ["""ElectraTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ """ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST""", """ElectraForCausalLM""", """ElectraForMaskedLM""", """ElectraForMultipleChoice""", """ElectraForPreTraining""", """ElectraForQuestionAnswering""", """ElectraForSequenceClassification""", """ElectraForTokenClassification""", """ElectraModel""", """ElectraPreTrainedModel""", """load_tf_weights_in_electra""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ """TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFElectraForMaskedLM""", """TFElectraForMultipleChoice""", """TFElectraForPreTraining""", """TFElectraForQuestionAnswering""", """TFElectraForSequenceClassification""", """TFElectraForTokenClassification""", """TFElectraModel""", """TFElectraPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ """FlaxElectraForCausalLM""", """FlaxElectraForMaskedLM""", """FlaxElectraForMultipleChoice""", """FlaxElectraForPreTraining""", """FlaxElectraForQuestionAnswering""", """FlaxElectraForSequenceClassification""", """FlaxElectraForTokenClassification""", """FlaxElectraModel""", """FlaxElectraPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_electra import ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ElectraConfig, ElectraOnnxConfig from .tokenization_electra import ElectraTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_electra_fast import ElectraTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_electra import ( ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST, ElectraForCausalLM, ElectraForMaskedLM, ElectraForMultipleChoice, ElectraForPreTraining, ElectraForQuestionAnswering, ElectraForSequenceClassification, ElectraForTokenClassification, ElectraModel, ElectraPreTrainedModel, load_tf_weights_in_electra, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_electra import ( TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST, TFElectraForMaskedLM, TFElectraForMultipleChoice, TFElectraForPreTraining, TFElectraForQuestionAnswering, TFElectraForSequenceClassification, TFElectraForTokenClassification, TFElectraModel, TFElectraPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_electra import ( FlaxElectraForCausalLM, FlaxElectraForMaskedLM, FlaxElectraForMultipleChoice, FlaxElectraForPreTraining, FlaxElectraForQuestionAnswering, FlaxElectraForSequenceClassification, FlaxElectraForTokenClassification, FlaxElectraModel, FlaxElectraPreTrainedModel, ) else: import sys lowerCamelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
302
1
from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descriptor_pool from google.protobuf import symbol_database as _symbol_database from google.protobuf.internal import builder as _builder # @@protoc_insertion_point(imports) lowerCamelCase__ = _symbol_database.Default() lowerCamelCase__ = _descriptor_pool.Default().AddSerializedFile( B"""\n\x19sentencepiece_model.proto\x12\rsentencepiece\"\x80\x0c\n\x0bTrainerSpec\x12\r\n\x05input\x18\x01 \x03(\t\x12\x14\n\x0cinput_format\x18\x07 \x01(\t\x12\x14\n\x0cmodel_prefix\x18\x02 \x01(\t\x12\x41\n\nmodel_type\x18\x03 \x01(\x0e\x32$.sentencepiece.TrainerSpec.ModelType:\x07UNIGRAM\x12\x18\n\nvocab_size\x18\x04 \x01(\x05:\x04\x38\x30\x30\x30\x12\x17\n\x0f\x61\x63\x63\x65pt_language\x18\x05 \x03(\t\x12 \n\x15self_test_sample_size\x18\x06 \x01(\x05:\x01\x30\x12*\n\x1b\x65nable_differential_privacy\x18\x32 \x01(\x08:\x05\x66\x61lse\x12+\n differential_privacy_noise_level\x18\x33 \x01(\x02:\x01\x30\x12\x32\n\'differential_privacy_clipping_threshold\x18\x34 \x01(\x04:\x01\x30\x12\"\n\x12\x63haracter_coverage\x18\n \x01(\x02:\x06\x30.9995\x12\x1e\n\x13input_sentence_size\x18\x0b \x01(\x04:\x01\x30\x12$\n\x16shuffle_input_sentence\x18\x13 \x01(\x08:\x04true\x12 \n\x14mining_sentence_size\x18\x0c \x01(\x05\x42\x02\x18\x01\x12\"\n\x16training_sentence_size\x18\r \x01(\x05\x42\x02\x18\x01\x12(\n\x17seed_sentencepiece_size\x18\x0e \x01(\x05:\x07\x31\x30\x30\x30\x30\x30\x30\x12\x1e\n\x10shrinking_factor\x18\x0f \x01(\x02:\x04\x30.75\x12!\n\x13max_sentence_length\x18\x12 \x01(\x05:\x04\x34\x31\x39\x32\x12\x17\n\x0bnum_threads\x18\x10 \x01(\x05:\x02\x31\x36\x12\x1d\n\x12num_sub_iterations\x18\x11 \x01(\x05:\x01\x32\x12$\n\x18max_sentencepiece_length\x18\x14 \x01(\x05:\x02\x31\x36\x12%\n\x17split_by_unicode_script\x18\x15 \x01(\x08:\x04true\x12\x1d\n\x0fsplit_by_number\x18\x17 \x01(\x08:\x04true\x12!\n\x13split_by_whitespace\x18\x16 \x01(\x08:\x04true\x12)\n\x1atreat_whitespace_as_suffix\x18\x18 \x01(\x08:\x05\x66\x61lse\x12+\n\x1c\x61llow_whitespace_only_pieces\x18\x1a \x01(\x08:\x05\x66\x61lse\x12\x1b\n\x0csplit_digits\x18\x19 \x01(\x08:\x05\x66\x61lse\x12#\n\x19pretokenization_delimiter\x18\x35 \x01(\t:\x00\x12\x17\n\x0f\x63ontrol_symbols\x18\x1e \x03(\t\x12\x1c\n\x14user_defined_symbols\x18\x1f \x03(\t\x12\x16\n\x0erequired_chars\x18$ \x01(\t\x12\x1c\n\rbyte_fallback\x18# \x01(\x08:\x05\x66\x61lse\x12+\n\x1dvocabulary_output_piece_score\x18 \x01(\x08:\x04true\x12\x1e\n\x10hard_vocab_limit\x18! \x01(\x08:\x04true\x12\x1c\n\ruse_all_vocab\x18\" \x01(\x08:\x05\x66\x61lse\x12\x11\n\x06unk_id\x18( \x01(\x05:\x01\x30\x12\x11\n\x06\x62os_id\x18) \x01(\x05:\x01\x31\x12\x11\n\x06\x65os_id\x18* \x01(\x05:\x01\x32\x12\x12\n\x06pad_id\x18+ \x01(\x05:\x02-1\x12\x18\n\tunk_piece\x18- \x01(\t:\x05<unk>\x12\x16\n\tbos_piece\x18. \x01(\t:\x03<s>\x12\x17\n\teos_piece\x18/ \x01(\t:\x04</s>\x12\x18\n\tpad_piece\x18\x30 \x01(\t:\x05<pad>\x12\x1a\n\x0bunk_surface\x18, \x01(\t:\x05 \xe2\x81\x87 \x12+\n\x1ctrain_extremely_large_corpus\x18\x31 \x01(\x08:\x05\x66\x61lse\"5\n\tModelType\x12\x0b\n\x07UNIGRAM\x10\x01\x12\x07\n\x03\x42PE\x10\x02\x12\x08\n\x04WORD\x10\x03\x12\x08\n\x04\x43HAR\x10\x04*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\"\xd1\x01\n\x0eNormalizerSpec\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x1c\n\x14precompiled_charsmap\x18\x02 \x01(\x0c\x12\x1e\n\x10\x61\x64\x64_dummy_prefix\x18\x03 \x01(\x08:\x04true\x12&\n\x18remove_extra_whitespaces\x18\x04 \x01(\x08:\x04true\x12 \n\x12\x65scape_whitespaces\x18\x05 \x01(\x08:\x04true\x12\x1e\n\x16normalization_rule_tsv\x18\x06 \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\"y\n\x0cSelfTestData\x12\x33\n\x07samples\x18\x01 \x03(\x0b\x32\".sentencepiece.SelfTestData.Sample\x1a)\n\x06Sample\x12\r\n\x05input\x18\x01 \x01(\t\x12\x10\n\x08\x65xpected\x18\x02 \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\"\xfe\x03\n\nModelProto\x12\x37\n\x06pieces\x18\x01 \x03(\x0b\x32\'.sentencepiece.ModelProto.SentencePiece\x12\x30\n\x0ctrainer_spec\x18\x02 \x01(\x0b\x32\x1a.sentencepiece.TrainerSpec\x12\x36\n\x0fnormalizer_spec\x18\x03 \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x12\x33\n\x0eself_test_data\x18\x04 \x01(\x0b\x32\x1b.sentencepiece.SelfTestData\x12\x38\n\x11\x64\x65normalizer_spec\x18\x05 \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x1a\xd2\x01\n\rSentencePiece\x12\r\n\x05piece\x18\x01 \x01(\t\x12\r\n\x05score\x18\x02 \x01(\x02\x12\x42\n\x04type\x18\x03 \x01(\x0e\x32,.sentencepiece.ModelProto.SentencePiece.Type:\x06NORMAL\"T\n\x04Type\x12\n\n\x06NORMAL\x10\x01\x12\x0b\n\x07UNKNOWN\x10\x02\x12\x0b\n\x07\x43ONTROL\x10\x03\x12\x10\n\x0cUSER_DEFINED\x10\x04\x12\x08\n\x04\x42YTE\x10\x06\x12\n\n\x06UNUSED\x10\x05*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\x42\x02H\x03""" ) lowerCamelCase__ = globals() _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, """sentencepiece_model_pb2""", _globals) if _descriptor._USE_C_DESCRIPTORS is False: lowerCamelCase__ = None lowerCamelCase__ = B"""H\003""" # (generated by protobuf compiler, but `_TRAINERSPEC` is not defined) # _TRAINERSPEC.fields_by_name["mining_sentence_size"]._options = None # _TRAINERSPEC.fields_by_name["mining_sentence_size"]._serialized_options = b"\030\001" # _TRAINERSPEC.fields_by_name["training_sentence_size"]._options = None # _TRAINERSPEC.fields_by_name["training_sentence_size"]._serialized_options = b"\030\001" lowerCamelCase__ = 45 lowerCamelCase__ = 1581 lowerCamelCase__ = 1517 lowerCamelCase__ = 1570 lowerCamelCase__ = 1584 lowerCamelCase__ = 1793 lowerCamelCase__ = 1795 lowerCamelCase__ = 1916 lowerCamelCase__ = 1864 lowerCamelCase__ = 1905 lowerCamelCase__ = 1919 lowerCamelCase__ = 2429 lowerCamelCase__ = 2208 lowerCamelCase__ = 2418 lowerCamelCase__ = 2323 lowerCamelCase__ = 2407 # @@protoc_insertion_point(module_scope)
302
from __future__ import annotations lowerCamelCase__ = """#""" class SCREAMING_SNAKE_CASE : def __init__( self : Optional[Any] ): '''simple docstring''' __a = {} def UpperCamelCase_ ( self : Optional[Any] , __lowercase : str ): '''simple docstring''' __a = self._trie for char in text: if char not in trie: __a = {} __a = trie[char] __a = True def UpperCamelCase_ ( self : Tuple , __lowercase : str ): '''simple docstring''' __a = self._trie for char in prefix: if char in trie: __a = trie[char] else: return [] return self._elements(__lowercase ) def UpperCamelCase_ ( self : Optional[int] , __lowercase : dict ): '''simple docstring''' __a = [] for c, v in d.items(): __a = [""" """] if c == END else [(c + s) for s in self._elements(__lowercase )] result.extend(__lowercase ) return tuple(__lowercase ) lowerCamelCase__ = Trie() lowerCamelCase__ = ("""depart""", """detergent""", """daring""", """dog""", """deer""", """deal""") for word in words: trie.insert_word(word) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : str ): """simple docstring""" __a = trie.find_word(_SCREAMING_SNAKE_CASE ) return tuple(string + word for word in suffixes ) def lowerCAmelCase__ ( ): """simple docstring""" print(autocomplete_using_trie("""de""" ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
302
1
import os from shutil import copyfile from typing import List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = {"""vocab_file""": """sentencepiece.model"""} lowerCamelCase__ = { """vocab_file""": { """google/rembert""": """https://huggingface.co/google/rembert/resolve/main/sentencepiece.model""", }, } lowerCamelCase__ = { """google/rembert""": 256, } class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : Tuple =VOCAB_FILES_NAMES __lowerCamelCase : str =PRETRAINED_VOCAB_FILES_MAP __lowerCamelCase : Optional[int] =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : str , __lowercase : List[str] , __lowercase : Dict=False , __lowercase : List[Any]=True , __lowercase : str=True , __lowercase : int="[CLS]" , __lowercase : List[str]="[SEP]" , __lowercase : Dict="[UNK]" , __lowercase : str="[SEP]" , __lowercase : Any="[PAD]" , __lowercase : Tuple="[CLS]" , __lowercase : str="[MASK]" , **__lowercase : Dict , ): '''simple docstring''' super().__init__( do_lower_case=__lowercase , remove_space=__lowercase , keep_accents=__lowercase , bos_token=__lowercase , eos_token=__lowercase , unk_token=__lowercase , sep_token=__lowercase , pad_token=__lowercase , cls_token=__lowercase , mask_token=__lowercase , **__lowercase , ) __a = do_lower_case __a = remove_space __a = keep_accents __a = vocab_file __a = spm.SentencePieceProcessor() self.sp_model.Load(__lowercase ) @property def UpperCamelCase_ ( self : Any ): '''simple docstring''' return len(self.sp_model ) def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' __a = {self.convert_ids_to_tokens(__lowercase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Tuple ): '''simple docstring''' __a = self.__dict__.copy() __a = None return state def __setstate__( self : Tuple , __lowercase : Any ): '''simple docstring''' __a = d __a = spm.SentencePieceProcessor() self.sp_model.Load(self.vocab_file ) def UpperCamelCase_ ( self : str , __lowercase : Optional[int] , __lowercase : Optional[int]=False ): '''simple docstring''' __a = self.sp_model.EncodeAsPieces(__lowercase ) return pieces def UpperCamelCase_ ( self : str , __lowercase : Optional[Any] ): '''simple docstring''' return self.sp_model.PieceToId(__lowercase ) def UpperCamelCase_ ( self : Optional[int] , __lowercase : Optional[Any] ): '''simple docstring''' return self.sp_model.IdToPiece(__lowercase ) def UpperCamelCase_ ( self : Optional[Any] , __lowercase : Tuple ): '''simple docstring''' __a = self.sp_model.decode_pieces(__lowercase ) return out_string def UpperCamelCase_ ( self : List[str] , __lowercase : List[int] , __lowercase : Optional[List[int]] = None ): '''simple docstring''' __a = [self.sep_token_id] __a = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def UpperCamelCase_ ( self : int , __lowercase : List[int] , __lowercase : Optional[List[int]] = None , __lowercase : bool = False ): '''simple docstring''' if already_has_special_tokens: if token_ids_a is not None: raise ValueError( """You should not supply a second sequence if the provided sequence of """ """ids is already formatted with special tokens for the model.""" ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is not None: return [1] + ([0] * len(__lowercase )) + [1] + ([0] * len(__lowercase )) + [1] return [1] + ([0] * len(__lowercase )) + [1] def UpperCamelCase_ ( self : Union[str, Any] , __lowercase : List[int] , __lowercase : Optional[List[int]] = None ): '''simple docstring''' __a = [self.sep_token_id] __a = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCamelCase_ ( self : int , __lowercase : str , __lowercase : Optional[str] = None ): '''simple docstring''' if not os.path.isdir(__lowercase ): logger.error("""Vocabulary path ({}) should be a directory""".format(__lowercase ) ) return __a = os.path.join( __lowercase , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__lowercase ): copyfile(self.vocab_file , __lowercase ) return (out_vocab_file,)
302
from dataclasses import dataclass from typing import Dict, Optional, Union import torch import torch.nn.functional as F from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .attention import BasicTransformerBlock from .attention_processor import AttentionProcessor, AttnProcessor from .embeddings import TimestepEmbedding, Timesteps from .modeling_utils import ModelMixin @dataclass class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : torch.FloatTensor class SCREAMING_SNAKE_CASE ( lowerCamelCase__ , lowerCamelCase__ ): @register_to_config def __init__( self : Dict , __lowercase : int = 32 , __lowercase : int = 64 , __lowercase : int = 20 , __lowercase : int = 768 , __lowercase : Any=77 , __lowercase : Optional[int]=4 , __lowercase : float = 0.0 , __lowercase : str = "silu" , __lowercase : Optional[str] = None , __lowercase : Optional[str] = None , __lowercase : Optional[str] = "linear" , __lowercase : Optional[str] = "prd" , __lowercase : Optional[int] = None , __lowercase : Optional[int] = None , __lowercase : Optional[int] = None , ): '''simple docstring''' super().__init__() __a = num_attention_heads __a = attention_head_dim __a = num_attention_heads * attention_head_dim __a = additional_embeddings __a = time_embed_dim or inner_dim __a = embedding_proj_dim or embedding_dim __a = clip_embed_dim or embedding_dim __a = Timesteps(__lowercase , __lowercase , 0 ) __a = TimestepEmbedding(__lowercase , __lowercase , out_dim=__lowercase , act_fn=__lowercase ) __a = nn.Linear(__lowercase , __lowercase ) if embedding_proj_norm_type is None: __a = None elif embedding_proj_norm_type == "layer": __a = nn.LayerNorm(__lowercase ) else: raise ValueError(F"unsupported embedding_proj_norm_type: {embedding_proj_norm_type}" ) __a = nn.Linear(__lowercase , __lowercase ) if encoder_hid_proj_type is None: __a = None elif encoder_hid_proj_type == "linear": __a = nn.Linear(__lowercase , __lowercase ) else: raise ValueError(F"unsupported encoder_hid_proj_type: {encoder_hid_proj_type}" ) __a = nn.Parameter(torch.zeros(1 , num_embeddings + additional_embeddings , __lowercase ) ) if added_emb_type == "prd": __a = nn.Parameter(torch.zeros(1 , 1 , __lowercase ) ) elif added_emb_type is None: __a = None else: raise ValueError( F"`added_emb_type`: {added_emb_type} is not supported. Make sure to choose one of `'prd'` or `None`." ) __a = nn.ModuleList( [ BasicTransformerBlock( __lowercase , __lowercase , __lowercase , dropout=__lowercase , activation_fn="""gelu""" , attention_bias=__lowercase , ) for d in range(__lowercase ) ] ) if norm_in_type == "layer": __a = nn.LayerNorm(__lowercase ) elif norm_in_type is None: __a = None else: raise ValueError(F"Unsupported norm_in_type: {norm_in_type}." ) __a = nn.LayerNorm(__lowercase ) __a = nn.Linear(__lowercase , __lowercase ) __a = torch.full( [num_embeddings + additional_embeddings, num_embeddings + additional_embeddings] , -10000.0 ) causal_attention_mask.triu_(1 ) __a = causal_attention_mask[None, ...] self.register_buffer("""causal_attention_mask""" , __lowercase , persistent=__lowercase ) __a = nn.Parameter(torch.zeros(1 , __lowercase ) ) __a = nn.Parameter(torch.zeros(1 , __lowercase ) ) @property # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' __a = {} def fn_recursive_add_processors(__lowercase : str , __lowercase : torch.nn.Module , __lowercase : Dict[str, AttentionProcessor] ): if hasattr(__lowercase , """set_processor""" ): __a = module.processor for sub_name, child in module.named_children(): fn_recursive_add_processors(F"{name}.{sub_name}" , __lowercase , __lowercase ) return processors for name, module in self.named_children(): fn_recursive_add_processors(__lowercase , __lowercase , __lowercase ) return processors def UpperCamelCase_ ( self : List[str] , __lowercase : Union[AttentionProcessor, Dict[str, AttentionProcessor]] ): '''simple docstring''' __a = len(self.attn_processors.keys() ) if isinstance(__lowercase , __lowercase ) and len(__lowercase ) != count: raise ValueError( F"A dict of processors was passed, but the number of processors {len(__lowercase )} does not match the" F" number of attention layers: {count}. Please make sure to pass {count} processor classes." ) def fn_recursive_attn_processor(__lowercase : str , __lowercase : torch.nn.Module , __lowercase : Dict ): if hasattr(__lowercase , """set_processor""" ): if not isinstance(__lowercase , __lowercase ): module.set_processor(__lowercase ) else: module.set_processor(processor.pop(F"{name}.processor" ) ) for sub_name, child in module.named_children(): fn_recursive_attn_processor(F"{name}.{sub_name}" , __lowercase , __lowercase ) for name, module in self.named_children(): fn_recursive_attn_processor(__lowercase , __lowercase , __lowercase ) def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' self.set_attn_processor(AttnProcessor() ) def UpperCamelCase_ ( self : Union[str, Any] , __lowercase : Optional[int] , __lowercase : Union[torch.Tensor, float, int] , __lowercase : torch.FloatTensor , __lowercase : Optional[torch.FloatTensor] = None , __lowercase : Optional[torch.BoolTensor] = None , __lowercase : bool = True , ): '''simple docstring''' __a = hidden_states.shape[0] __a = timestep if not torch.is_tensor(__lowercase ): __a = torch.tensor([timesteps] , dtype=torch.long , device=hidden_states.device ) elif torch.is_tensor(__lowercase ) and len(timesteps.shape ) == 0: __a = timesteps[None].to(hidden_states.device ) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML __a = timesteps * torch.ones(__lowercase , dtype=timesteps.dtype , device=timesteps.device ) __a = self.time_proj(__lowercase ) # timesteps does not contain any weights and will always return f32 tensors # but time_embedding might be fp16, so we need to cast here. __a = timesteps_projected.to(dtype=self.dtype ) __a = self.time_embedding(__lowercase ) if self.embedding_proj_norm is not None: __a = self.embedding_proj_norm(__lowercase ) __a = self.embedding_proj(__lowercase ) if self.encoder_hidden_states_proj is not None and encoder_hidden_states is not None: __a = self.encoder_hidden_states_proj(__lowercase ) elif self.encoder_hidden_states_proj is not None and encoder_hidden_states is None: raise ValueError("""`encoder_hidden_states_proj` requires `encoder_hidden_states` to be set""" ) __a = self.proj_in(__lowercase ) __a = self.positional_embedding.to(hidden_states.dtype ) __a = [] __a = 0 if encoder_hidden_states is not None: additional_embeds.append(__lowercase ) additional_embeddings_len += encoder_hidden_states.shape[1] if len(proj_embeddings.shape ) == 2: __a = proj_embeddings[:, None, :] if len(hidden_states.shape ) == 2: __a = hidden_states[:, None, :] __a = additional_embeds + [ proj_embeddings, time_embeddings[:, None, :], hidden_states, ] if self.prd_embedding is not None: __a = self.prd_embedding.to(hidden_states.dtype ).expand(__lowercase , -1 , -1 ) additional_embeds.append(__lowercase ) __a = torch.cat( __lowercase , dim=1 , ) # Allow positional_embedding to not include the `addtional_embeddings` and instead pad it with zeros for these additional tokens __a = additional_embeddings_len + proj_embeddings.shape[1] + 1 if positional_embeddings.shape[1] < hidden_states.shape[1]: __a = F.pad( __lowercase , ( 0, 0, additional_embeddings_len, self.prd_embedding.shape[1] if self.prd_embedding is not None else 0, ) , value=0.0 , ) __a = hidden_states + positional_embeddings if attention_mask is not None: __a = (1 - attention_mask.to(hidden_states.dtype )) * -10000.0 __a = F.pad(__lowercase , (0, self.additional_embeddings) , value=0.0 ) __a = (attention_mask[:, None, :] + self.causal_attention_mask).to(hidden_states.dtype ) __a = attention_mask.repeat_interleave(self.config.num_attention_heads , dim=0 ) if self.norm_in is not None: __a = self.norm_in(__lowercase ) for block in self.transformer_blocks: __a = block(__lowercase , attention_mask=__lowercase ) __a = self.norm_out(__lowercase ) if self.prd_embedding is not None: __a = hidden_states[:, -1] else: __a = hidden_states[:, additional_embeddings_len:] __a = self.proj_to_clip_embeddings(__lowercase ) if not return_dict: return (predicted_image_embedding,) return PriorTransformerOutput(predicted_image_embedding=__lowercase ) def UpperCamelCase_ ( self : Any , __lowercase : Tuple ): '''simple docstring''' __a = (prior_latents * self.clip_std) + self.clip_mean return prior_latents
302
1
import json import logging import math import os import sys from dataclasses import dataclass, field from typing import Optional from datasets import Dataset, load_dataset import transformers from transformers import ( CONFIG_MAPPING, MODEL_FOR_MASKED_LM_MAPPING, AutoConfig, AutoModelForMaskedLM, AutoTokenizer, DataCollatorForWholeWordMask, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import get_last_checkpoint, is_main_process lowerCamelCase__ = logging.getLogger(__name__) lowerCamelCase__ = list(MODEL_FOR_MASKED_LM_MAPPING.keys()) lowerCamelCase__ = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class SCREAMING_SNAKE_CASE : __lowerCamelCase : Optional[str] =field( default=lowerCamelCase__ , metadata={ 'help': ( 'The model checkpoint for weights initialization.Don\'t set if you want to train a model from scratch.' ) } , ) __lowerCamelCase : Optional[str] =field( default=lowerCamelCase__ , metadata={'help': 'If training from scratch, pass a model type from the list: ' + ', '.join(lowerCamelCase__ )} , ) __lowerCamelCase : Optional[str] =field( default=lowerCamelCase__ , metadata={ 'help': ( 'Override some existing default config settings when a model is trained from scratch. Example: ' 'n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index' ) } , ) __lowerCamelCase : Optional[str] =field( default=lowerCamelCase__ , metadata={'help': 'Pretrained config name or path if not the same as model_name'} ) __lowerCamelCase : Optional[str] =field( default=lowerCamelCase__ , metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'} ) __lowerCamelCase : Optional[str] =field( default=lowerCamelCase__ , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'} , ) __lowerCamelCase : bool =field( default=lowerCamelCase__ , metadata={'help': 'Whether to use one of the fast tokenizer (backed by the tokenizers library) or not.'} , ) __lowerCamelCase : str =field( default='main' , metadata={'help': 'The specific model version to use (can be a branch name, tag name or commit id).'} , ) __lowerCamelCase : bool =field( default=lowerCamelCase__ , metadata={ 'help': ( 'Will use the token generated when running `huggingface-cli login` (necessary to use this script ' 'with private models).' ) } , ) def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' if self.config_overrides is not None and (self.config_name is not None or self.model_name_or_path is not None): raise ValueError( """--config_overrides can't be used in combination with --config_name or --model_name_or_path""" ) @dataclass class SCREAMING_SNAKE_CASE : __lowerCamelCase : Optional[str] =field( default=lowerCamelCase__ , metadata={'help': 'The name of the dataset to use (via the datasets library).'} ) __lowerCamelCase : Optional[str] =field( default=lowerCamelCase__ , metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'} ) __lowerCamelCase : Optional[str] =field(default=lowerCamelCase__ , metadata={'help': 'The input training data file (a text file).'} ) __lowerCamelCase : Optional[str] =field( default=lowerCamelCase__ , metadata={'help': 'An optional input evaluation data file to evaluate the perplexity on (a text file).'} , ) __lowerCamelCase : Optional[str] =field( default=lowerCamelCase__ , metadata={'help': 'An optional input train ref data file for whole word masking in Chinese.'} , ) __lowerCamelCase : Optional[str] =field( default=lowerCamelCase__ , metadata={'help': 'An optional input validation ref data file for whole word masking in Chinese.'} , ) __lowerCamelCase : bool =field( default=lowerCamelCase__ , metadata={'help': 'Overwrite the cached training and evaluation sets'} ) __lowerCamelCase : Optional[int] =field( default=5 , metadata={ 'help': 'The percentage of the train set used as validation set in case there\'s no validation split' } , ) __lowerCamelCase : Optional[int] =field( default=lowerCamelCase__ , metadata={ 'help': ( 'The maximum total input sequence length after tokenization. Sequences longer ' 'than this will be truncated. Default to the max input length of the model.' ) } , ) __lowerCamelCase : Optional[int] =field( default=lowerCamelCase__ , metadata={'help': 'The number of processes to use for the preprocessing.'} , ) __lowerCamelCase : float =field( default=0.15 , metadata={'help': 'Ratio of tokens to mask for masked language modeling loss'} ) __lowerCamelCase : bool =field( default=lowerCamelCase__ , metadata={ 'help': ( 'Whether to pad all samples to `max_seq_length`. ' 'If False, will pad the samples dynamically when batching to the maximum length in the batch.' ) } , ) def UpperCamelCase_ ( self : Optional[int] ): '''simple docstring''' if self.train_file is not None: __a = self.train_file.split(""".""" )[-1] assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file." if self.validation_file is not None: __a = self.validation_file.split(""".""" )[-1] assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file." def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" with open(_SCREAMING_SNAKE_CASE , """r""" , encoding="""utf-8""" ) as f: __a = [json.loads(_SCREAMING_SNAKE_CASE ) for line in f.read().splitlines() if (len(_SCREAMING_SNAKE_CASE ) > 0 and not line.isspace())] assert len(_SCREAMING_SNAKE_CASE ) == len(_SCREAMING_SNAKE_CASE ) __a = {c: dataset[c] for c in dataset.column_names} __a = refs return Dataset.from_dict(_SCREAMING_SNAKE_CASE ) def lowerCAmelCase__ ( ): """simple docstring""" __a = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(""".json""" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. __a , __a , __a = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: __a , __a , __a = parser.parse_args_into_dataclasses() # Detecting last checkpoint. __a = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: __a = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f"Output directory ({training_args.output_dir}) already exists and is not empty. " """Use --overwrite_output_dir to overcome.""" ) elif last_checkpoint is not None: logger.info( f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change " """the `--output_dir` or add `--overwrite_output_dir` to train from scratch.""" ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , handlers=[logging.StreamHandler(sys.stdout )] , ) logger.setLevel(logging.INFO if is_main_process(training_args.local_rank ) else logging.WARN ) # Log on each process the small summary: logger.warning( f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}" + f"distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}" ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info("""Training/evaluation parameters %s""" , _SCREAMING_SNAKE_CASE ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). # # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.dataset_name is not None: # Downloading and loading a dataset from the hub. __a = load_dataset(data_args.dataset_name , data_args.dataset_config_name ) if "validation" not in datasets.keys(): __a = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=f"train[:{data_args.validation_split_percentage}%]" , ) __a = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=f"train[{data_args.validation_split_percentage}%:]" , ) else: __a = {} if data_args.train_file is not None: __a = data_args.train_file if data_args.validation_file is not None: __a = data_args.validation_file __a = data_args.train_file.split(""".""" )[-1] if extension == "txt": __a = """text""" __a = load_dataset(_SCREAMING_SNAKE_CASE , data_files=_SCREAMING_SNAKE_CASE ) # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. __a = { """cache_dir""": model_args.cache_dir, """revision""": model_args.model_revision, """use_auth_token""": True if model_args.use_auth_token else None, } if model_args.config_name: __a = AutoConfig.from_pretrained(model_args.config_name , **_SCREAMING_SNAKE_CASE ) elif model_args.model_name_or_path: __a = AutoConfig.from_pretrained(model_args.model_name_or_path , **_SCREAMING_SNAKE_CASE ) else: __a = CONFIG_MAPPING[model_args.model_type]() logger.warning("""You are instantiating a new config instance from scratch.""" ) if model_args.config_overrides is not None: logger.info(f"Overriding config: {model_args.config_overrides}" ) config.update_from_string(model_args.config_overrides ) logger.info(f"New config: {config}" ) __a = { """cache_dir""": model_args.cache_dir, """use_fast""": model_args.use_fast_tokenizer, """revision""": model_args.model_revision, """use_auth_token""": True if model_args.use_auth_token else None, } if model_args.tokenizer_name: __a = AutoTokenizer.from_pretrained(model_args.tokenizer_name , **_SCREAMING_SNAKE_CASE ) elif model_args.model_name_or_path: __a = AutoTokenizer.from_pretrained(model_args.model_name_or_path , **_SCREAMING_SNAKE_CASE ) else: raise ValueError( """You are instantiating a new tokenizer from scratch. This is not supported by this script.""" """You can do it from another script, save it, and load it from here, using --tokenizer_name.""" ) if model_args.model_name_or_path: __a = AutoModelForMaskedLM.from_pretrained( model_args.model_name_or_path , from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) , config=_SCREAMING_SNAKE_CASE , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) else: logger.info("""Training new model from scratch""" ) __a = AutoModelForMaskedLM.from_config(_SCREAMING_SNAKE_CASE ) model.resize_token_embeddings(len(_SCREAMING_SNAKE_CASE ) ) # Preprocessing the datasets. # First we tokenize all the texts. if training_args.do_train: __a = datasets["""train"""].column_names else: __a = datasets["""validation"""].column_names __a = """text""" if """text""" in column_names else column_names[0] __a = """max_length""" if data_args.pad_to_max_length else False def tokenize_function(_SCREAMING_SNAKE_CASE : Dict ): # Remove empty lines __a = [line for line in examples["""text"""] if len(_SCREAMING_SNAKE_CASE ) > 0 and not line.isspace()] return tokenizer(examples["""text"""] , padding=_SCREAMING_SNAKE_CASE , truncation=_SCREAMING_SNAKE_CASE , max_length=data_args.max_seq_length ) __a = datasets.map( _SCREAMING_SNAKE_CASE , batched=_SCREAMING_SNAKE_CASE , num_proc=data_args.preprocessing_num_workers , remove_columns=[text_column_name] , load_from_cache_file=not data_args.overwrite_cache , ) # Add the chinese references if provided if data_args.train_ref_file is not None: __a = add_chinese_references(tokenized_datasets["""train"""] , data_args.train_ref_file ) if data_args.validation_ref_file is not None: __a = add_chinese_references( tokenized_datasets["""validation"""] , data_args.validation_ref_file ) # If we have ref files, need to avoid it removed by trainer __a = data_args.train_ref_file or data_args.validation_ref_file if has_ref: __a = False # Data collator # This one will take care of randomly masking the tokens. __a = DataCollatorForWholeWordMask(tokenizer=_SCREAMING_SNAKE_CASE , mlm_probability=data_args.mlm_probability ) # Initialize our Trainer __a = Trainer( model=_SCREAMING_SNAKE_CASE , args=_SCREAMING_SNAKE_CASE , train_dataset=tokenized_datasets["""train"""] if training_args.do_train else None , eval_dataset=tokenized_datasets["""validation"""] if training_args.do_eval else None , tokenizer=_SCREAMING_SNAKE_CASE , data_collator=_SCREAMING_SNAKE_CASE , ) # Training if training_args.do_train: if last_checkpoint is not None: __a = last_checkpoint elif model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path ): __a = model_args.model_name_or_path else: __a = None __a = trainer.train(resume_from_checkpoint=_SCREAMING_SNAKE_CASE ) trainer.save_model() # Saves the tokenizer too for easy upload __a = os.path.join(training_args.output_dir , """train_results.txt""" ) if trainer.is_world_process_zero(): with open(_SCREAMING_SNAKE_CASE , """w""" ) as writer: logger.info("""***** Train results *****""" ) for key, value in sorted(train_result.metrics.items() ): logger.info(f" {key} = {value}" ) writer.write(f"{key} = {value}\n" ) # Need to save the state, since Trainer.save_model saves only the tokenizer with the model trainer.state.save_to_json(os.path.join(training_args.output_dir , """trainer_state.json""" ) ) # Evaluation __a = {} if training_args.do_eval: logger.info("""*** Evaluate ***""" ) __a = trainer.evaluate() __a = math.exp(eval_output["""eval_loss"""] ) __a = perplexity __a = os.path.join(training_args.output_dir , """eval_results_mlm_wwm.txt""" ) if trainer.is_world_process_zero(): with open(_SCREAMING_SNAKE_CASE , """w""" ) as writer: logger.info("""***** Eval results *****""" ) for key, value in sorted(results.items() ): logger.info(f" {key} = {value}" ) writer.write(f"{key} = {value}\n" ) return results def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : List[Any] ): """simple docstring""" main() if __name__ == "__main__": main()
302
from functools import lru_cache def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int ): """simple docstring""" __a = 2 __a = set() while i * i <= n: if n % i: i += 1 else: n //= i factors.add(_SCREAMING_SNAKE_CASE ) if n > 1: factors.add(_SCREAMING_SNAKE_CASE ) return factors @lru_cache def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int ): """simple docstring""" return len(unique_prime_factors(_SCREAMING_SNAKE_CASE ) ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : list ): """simple docstring""" return len(set(_SCREAMING_SNAKE_CASE ) ) in (0, 1) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int ): """simple docstring""" __a = 2 while True: # Increment each value of a generated range __a = [base + i for i in range(_SCREAMING_SNAKE_CASE )] # Run elements through out unique_prime_factors function # Append our target number to the end. __a = [upf_len(_SCREAMING_SNAKE_CASE ) for x in group] checker.append(_SCREAMING_SNAKE_CASE ) # If all numbers in the list are equal, return the group variable. if equality(_SCREAMING_SNAKE_CASE ): return group # Increment our base variable by 1 base += 1 def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int = 4 ): """simple docstring""" __a = run(_SCREAMING_SNAKE_CASE ) return results[0] if len(_SCREAMING_SNAKE_CASE ) else None if __name__ == "__main__": print(solution())
302
1
from ..utils import DummyObject, requires_backends class SCREAMING_SNAKE_CASE ( metaclass=lowerCamelCase__ ): __lowerCamelCase : List[str] =['flax'] def __init__( self : int , *__lowercase : Union[str, Any] , **__lowercase : List[Any] ): '''simple docstring''' requires_backends(self , ["""flax"""] ) @classmethod def UpperCamelCase_ ( cls : Dict , *__lowercase : List[Any] , **__lowercase : Optional[Any] ): '''simple docstring''' requires_backends(cls , ["""flax"""] ) @classmethod def UpperCamelCase_ ( cls : Tuple , *__lowercase : Any , **__lowercase : Dict ): '''simple docstring''' requires_backends(cls , ["""flax"""] ) class SCREAMING_SNAKE_CASE ( metaclass=lowerCamelCase__ ): __lowerCamelCase : Union[str, Any] =['flax'] def __init__( self : Dict , *__lowercase : Tuple , **__lowercase : Any ): '''simple docstring''' requires_backends(self , ["""flax"""] ) @classmethod def UpperCamelCase_ ( cls : Tuple , *__lowercase : Optional[int] , **__lowercase : Any ): '''simple docstring''' requires_backends(cls , ["""flax"""] ) @classmethod def UpperCamelCase_ ( cls : str , *__lowercase : Any , **__lowercase : str ): '''simple docstring''' requires_backends(cls , ["""flax"""] ) class SCREAMING_SNAKE_CASE ( metaclass=lowerCamelCase__ ): __lowerCamelCase : List[Any] =['flax'] def __init__( self : int , *__lowercase : Optional[Any] , **__lowercase : Dict ): '''simple docstring''' requires_backends(self , ["""flax"""] ) @classmethod def UpperCamelCase_ ( cls : Dict , *__lowercase : str , **__lowercase : Optional[int] ): '''simple docstring''' requires_backends(cls , ["""flax"""] ) @classmethod def UpperCamelCase_ ( cls : int , *__lowercase : str , **__lowercase : str ): '''simple docstring''' requires_backends(cls , ["""flax"""] ) class SCREAMING_SNAKE_CASE ( metaclass=lowerCamelCase__ ): __lowerCamelCase : Union[str, Any] =['flax'] def __init__( self : Optional[Any] , *__lowercase : Tuple , **__lowercase : List[Any] ): '''simple docstring''' requires_backends(self , ["""flax"""] ) @classmethod def UpperCamelCase_ ( cls : Optional[Any] , *__lowercase : Optional[Any] , **__lowercase : Any ): '''simple docstring''' requires_backends(cls , ["""flax"""] ) @classmethod def UpperCamelCase_ ( cls : Union[str, Any] , *__lowercase : List[str] , **__lowercase : List[Any] ): '''simple docstring''' requires_backends(cls , ["""flax"""] ) class SCREAMING_SNAKE_CASE ( metaclass=lowerCamelCase__ ): __lowerCamelCase : str =['flax'] def __init__( self : Tuple , *__lowercase : int , **__lowercase : int ): '''simple docstring''' requires_backends(self , ["""flax"""] ) @classmethod def UpperCamelCase_ ( cls : Tuple , *__lowercase : str , **__lowercase : List[str] ): '''simple docstring''' requires_backends(cls , ["""flax"""] ) @classmethod def UpperCamelCase_ ( cls : str , *__lowercase : List[Any] , **__lowercase : int ): '''simple docstring''' requires_backends(cls , ["""flax"""] ) class SCREAMING_SNAKE_CASE ( metaclass=lowerCamelCase__ ): __lowerCamelCase : List[Any] =['flax'] def __init__( self : List[str] , *__lowercase : List[str] , **__lowercase : Optional[Any] ): '''simple docstring''' requires_backends(self , ["""flax"""] ) @classmethod def UpperCamelCase_ ( cls : Optional[Any] , *__lowercase : str , **__lowercase : List[Any] ): '''simple docstring''' requires_backends(cls , ["""flax"""] ) @classmethod def UpperCamelCase_ ( cls : Optional[int] , *__lowercase : Dict , **__lowercase : Dict ): '''simple docstring''' requires_backends(cls , ["""flax"""] ) class SCREAMING_SNAKE_CASE ( metaclass=lowerCamelCase__ ): __lowerCamelCase : List[str] =['flax'] def __init__( self : Optional[int] , *__lowercase : Dict , **__lowercase : List[str] ): '''simple docstring''' requires_backends(self , ["""flax"""] ) @classmethod def UpperCamelCase_ ( cls : List[Any] , *__lowercase : Optional[int] , **__lowercase : Optional[Any] ): '''simple docstring''' requires_backends(cls , ["""flax"""] ) @classmethod def UpperCamelCase_ ( cls : Dict , *__lowercase : Any , **__lowercase : str ): '''simple docstring''' requires_backends(cls , ["""flax"""] ) class SCREAMING_SNAKE_CASE ( metaclass=lowerCamelCase__ ): __lowerCamelCase : str =['flax'] def __init__( self : str , *__lowercase : Any , **__lowercase : List[Any] ): '''simple docstring''' requires_backends(self , ["""flax"""] ) @classmethod def UpperCamelCase_ ( cls : int , *__lowercase : int , **__lowercase : int ): '''simple docstring''' requires_backends(cls , ["""flax"""] ) @classmethod def UpperCamelCase_ ( cls : Tuple , *__lowercase : str , **__lowercase : Any ): '''simple docstring''' requires_backends(cls , ["""flax"""] ) class SCREAMING_SNAKE_CASE ( metaclass=lowerCamelCase__ ): __lowerCamelCase : Optional[Any] =['flax'] def __init__( self : List[str] , *__lowercase : int , **__lowercase : int ): '''simple docstring''' requires_backends(self , ["""flax"""] ) @classmethod def UpperCamelCase_ ( cls : List[Any] , *__lowercase : Optional[Any] , **__lowercase : str ): '''simple docstring''' requires_backends(cls , ["""flax"""] ) @classmethod def UpperCamelCase_ ( cls : Dict , *__lowercase : str , **__lowercase : List[Any] ): '''simple docstring''' requires_backends(cls , ["""flax"""] ) class SCREAMING_SNAKE_CASE ( metaclass=lowerCamelCase__ ): __lowerCamelCase : Tuple =['flax'] def __init__( self : str , *__lowercase : Optional[int] , **__lowercase : Any ): '''simple docstring''' requires_backends(self , ["""flax"""] ) @classmethod def UpperCamelCase_ ( cls : List[str] , *__lowercase : str , **__lowercase : int ): '''simple docstring''' requires_backends(cls , ["""flax"""] ) @classmethod def UpperCamelCase_ ( cls : List[Any] , *__lowercase : List[str] , **__lowercase : int ): '''simple docstring''' requires_backends(cls , ["""flax"""] ) class SCREAMING_SNAKE_CASE ( metaclass=lowerCamelCase__ ): __lowerCamelCase : Dict =['flax'] def __init__( self : Optional[Any] , *__lowercase : List[Any] , **__lowercase : List[str] ): '''simple docstring''' requires_backends(self , ["""flax"""] ) @classmethod def UpperCamelCase_ ( cls : List[str] , *__lowercase : List[str] , **__lowercase : List[Any] ): '''simple docstring''' requires_backends(cls , ["""flax"""] ) @classmethod def UpperCamelCase_ ( cls : Optional[Any] , *__lowercase : List[str] , **__lowercase : List[str] ): '''simple docstring''' requires_backends(cls , ["""flax"""] ) class SCREAMING_SNAKE_CASE ( metaclass=lowerCamelCase__ ): __lowerCamelCase : Any =['flax'] def __init__( self : Optional[Any] , *__lowercase : Tuple , **__lowercase : int ): '''simple docstring''' requires_backends(self , ["""flax"""] ) @classmethod def UpperCamelCase_ ( cls : List[str] , *__lowercase : List[str] , **__lowercase : Dict ): '''simple docstring''' requires_backends(cls , ["""flax"""] ) @classmethod def UpperCamelCase_ ( cls : Union[str, Any] , *__lowercase : Union[str, Any] , **__lowercase : Optional[int] ): '''simple docstring''' requires_backends(cls , ["""flax"""] ) class SCREAMING_SNAKE_CASE ( metaclass=lowerCamelCase__ ): __lowerCamelCase : Optional[Any] =['flax'] def __init__( self : Dict , *__lowercase : int , **__lowercase : Any ): '''simple docstring''' requires_backends(self , ["""flax"""] ) @classmethod def UpperCamelCase_ ( cls : Any , *__lowercase : List[Any] , **__lowercase : Optional[Any] ): '''simple docstring''' requires_backends(cls , ["""flax"""] ) @classmethod def UpperCamelCase_ ( cls : int , *__lowercase : Optional[Any] , **__lowercase : Union[str, Any] ): '''simple docstring''' requires_backends(cls , ["""flax"""] )
302
import argparse import json from pathlib import Path import torch import torchaudio from datasets import load_dataset from huggingface_hub import hf_hub_download from transformers import ASTConfig, ASTFeatureExtractor, ASTForAudioClassification from transformers.utils import logging logging.set_verbosity_info() lowerCamelCase__ = logging.get_logger(__name__) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Any ): """simple docstring""" __a = ASTConfig() if "10-10" in model_name: pass elif "speech-commands" in model_name: __a = 128 elif "12-12" in model_name: __a = 12 __a = 12 elif "14-14" in model_name: __a = 14 __a = 14 elif "16-16" in model_name: __a = 16 __a = 16 else: raise ValueError("""Model not supported""" ) __a = """huggingface/label-files""" if "speech-commands" in model_name: __a = 35 __a = """speech-commands-v2-id2label.json""" else: __a = 527 __a = """audioset-id2label.json""" __a = json.load(open(hf_hub_download(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , repo_type="""dataset""" ) , """r""" ) ) __a = {int(_SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()} __a = idalabel __a = {v: k for k, v in idalabel.items()} return config def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" if "module.v" in name: __a = name.replace("""module.v""" , """audio_spectrogram_transformer""" ) if "cls_token" in name: __a = name.replace("""cls_token""" , """embeddings.cls_token""" ) if "dist_token" in name: __a = name.replace("""dist_token""" , """embeddings.distillation_token""" ) if "pos_embed" in name: __a = name.replace("""pos_embed""" , """embeddings.position_embeddings""" ) if "patch_embed.proj" in name: __a = name.replace("""patch_embed.proj""" , """embeddings.patch_embeddings.projection""" ) # transformer blocks if "blocks" in name: __a = name.replace("""blocks""" , """encoder.layer""" ) if "attn.proj" in name: __a = name.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in name: __a = name.replace("""attn""" , """attention.self""" ) if "norm1" in name: __a = name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: __a = name.replace("""norm2""" , """layernorm_after""" ) if "mlp.fc1" in name: __a = name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: __a = name.replace("""mlp.fc2""" , """output.dense""" ) # final layernorm if "audio_spectrogram_transformer.norm" in name: __a = name.replace("""audio_spectrogram_transformer.norm""" , """audio_spectrogram_transformer.layernorm""" ) # classifier head if "module.mlp_head.0" in name: __a = name.replace("""module.mlp_head.0""" , """classifier.layernorm""" ) if "module.mlp_head.1" in name: __a = name.replace("""module.mlp_head.1""" , """classifier.dense""" ) return name def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" for key in orig_state_dict.copy().keys(): __a = orig_state_dict.pop(_SCREAMING_SNAKE_CASE ) if "qkv" in key: __a = key.split(""".""" ) __a = int(key_split[3] ) __a = config.hidden_size if "weight" in key: __a = val[:dim, :] __a = val[dim : dim * 2, :] __a = val[-dim:, :] else: __a = val[:dim] __a = val[dim : dim * 2] __a = val[-dim:] else: __a = val return orig_state_dict def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" __a = [ """module.v.head.weight""", """module.v.head.bias""", """module.v.head_dist.weight""", """module.v.head_dist.bias""", ] for k in ignore_keys: state_dict.pop(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @torch.no_grad() def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : List[str]=False ): """simple docstring""" __a = get_audio_spectrogram_transformer_config(_SCREAMING_SNAKE_CASE ) __a = { """ast-finetuned-audioset-10-10-0.4593""": ( """https://www.dropbox.com/s/ca0b1v2nlxzyeb4/audioset_10_10_0.4593.pth?dl=1""" ), """ast-finetuned-audioset-10-10-0.450""": ( """https://www.dropbox.com/s/1tv0hovue1bxupk/audioset_10_10_0.4495.pth?dl=1""" ), """ast-finetuned-audioset-10-10-0.448""": ( """https://www.dropbox.com/s/6u5sikl4b9wo4u5/audioset_10_10_0.4483.pth?dl=1""" ), """ast-finetuned-audioset-10-10-0.448-v2""": ( """https://www.dropbox.com/s/kt6i0v9fvfm1mbq/audioset_10_10_0.4475.pth?dl=1""" ), """ast-finetuned-audioset-12-12-0.447""": ( """https://www.dropbox.com/s/snfhx3tizr4nuc8/audioset_12_12_0.4467.pth?dl=1""" ), """ast-finetuned-audioset-14-14-0.443""": ( """https://www.dropbox.com/s/z18s6pemtnxm4k7/audioset_14_14_0.4431.pth?dl=1""" ), """ast-finetuned-audioset-16-16-0.442""": ( """https://www.dropbox.com/s/mdsa4t1xmcimia6/audioset_16_16_0.4422.pth?dl=1""" ), """ast-finetuned-speech-commands-v2""": ( """https://www.dropbox.com/s/q0tbqpwv44pquwy/speechcommands_10_10_0.9812.pth?dl=1""" ), } # load original state_dict __a = model_name_to_url[model_name] __a = torch.hub.load_state_dict_from_url(_SCREAMING_SNAKE_CASE , map_location="""cpu""" ) # remove some keys remove_keys(_SCREAMING_SNAKE_CASE ) # rename some keys __a = convert_state_dict(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # load 🤗 model __a = ASTForAudioClassification(_SCREAMING_SNAKE_CASE ) model.eval() model.load_state_dict(_SCREAMING_SNAKE_CASE ) # verify outputs on dummy input # source: https://github.com/YuanGongND/ast/blob/79e873b8a54d0a3b330dd522584ff2b9926cd581/src/run.py#L62 __a = -4.267_7393 if """speech-commands""" not in model_name else -6.84_5978 __a = 4.568_9974 if """speech-commands""" not in model_name else 5.565_4526 __a = 1024 if """speech-commands""" not in model_name else 128 __a = ASTFeatureExtractor(mean=_SCREAMING_SNAKE_CASE , std=_SCREAMING_SNAKE_CASE , max_length=_SCREAMING_SNAKE_CASE ) if "speech-commands" in model_name: __a = load_dataset("""speech_commands""" , """v0.02""" , split="""validation""" ) __a = dataset[0]["""audio"""]["""array"""] else: __a = hf_hub_download( repo_id="""nielsr/audio-spectogram-transformer-checkpoint""" , filename="""sample_audio.flac""" , repo_type="""dataset""" , ) __a , __a = torchaudio.load(_SCREAMING_SNAKE_CASE ) __a = waveform.squeeze().numpy() __a = feature_extractor(_SCREAMING_SNAKE_CASE , sampling_rate=1_6000 , return_tensors="""pt""" ) # forward pass __a = model(**_SCREAMING_SNAKE_CASE ) __a = outputs.logits if model_name == "ast-finetuned-audioset-10-10-0.4593": __a = torch.tensor([-0.8760, -7.0042, -8.6602] ) elif model_name == "ast-finetuned-audioset-10-10-0.450": __a = torch.tensor([-1.1986, -7.0903, -8.2718] ) elif model_name == "ast-finetuned-audioset-10-10-0.448": __a = torch.tensor([-2.6128, -8.0080, -9.4344] ) elif model_name == "ast-finetuned-audioset-10-10-0.448-v2": __a = torch.tensor([-1.5080, -7.4534, -8.8917] ) elif model_name == "ast-finetuned-audioset-12-12-0.447": __a = torch.tensor([-0.5050, -6.5833, -8.0843] ) elif model_name == "ast-finetuned-audioset-14-14-0.443": __a = torch.tensor([-0.3826, -7.0336, -8.2413] ) elif model_name == "ast-finetuned-audioset-16-16-0.442": __a = torch.tensor([-1.2113, -6.9101, -8.3470] ) elif model_name == "ast-finetuned-speech-commands-v2": __a = torch.tensor([6.1589, -8.0566, -8.7984] ) else: raise ValueError("""Unknown model name""" ) if not torch.allclose(logits[0, :3] , _SCREAMING_SNAKE_CASE , atol=1e-4 ): raise ValueError("""Logits don't match""" ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) print(f"Saving model {model_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) print(f"Saving feature extractor to {pytorch_dump_folder_path}" ) feature_extractor.save_pretrained(_SCREAMING_SNAKE_CASE ) if push_to_hub: print("""Pushing model and feature extractor to the hub...""" ) model.push_to_hub(f"MIT/{model_name}" ) feature_extractor.push_to_hub(f"MIT/{model_name}" ) if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default="""ast-finetuned-audioset-10-10-0.4593""", type=str, help="""Name of the Audio Spectrogram Transformer model you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) parser.add_argument( """--push_to_hub""", action="""store_true""", help="""Whether or not to push the converted model to the 🤗 hub.""" ) lowerCamelCase__ = parser.parse_args() convert_audio_spectrogram_transformer_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
302
1
import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_albert import AlbertTokenizer else: lowerCamelCase__ = None lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = {"""vocab_file""": """spiece.model""", """tokenizer_file""": """tokenizer.json"""} lowerCamelCase__ = { """vocab_file""": { """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/spiece.model""", """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/spiece.model""", """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model""", """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model""", """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/spiece.model""", """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/spiece.model""", """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model""", """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model""", }, """tokenizer_file""": { """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/tokenizer.json""", """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/tokenizer.json""", """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/tokenizer.json""", """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/tokenizer.json""", """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/tokenizer.json""", """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/tokenizer.json""", """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/tokenizer.json""", """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/tokenizer.json""", }, } lowerCamelCase__ = { """albert-base-v1""": 512, """albert-large-v1""": 512, """albert-xlarge-v1""": 512, """albert-xxlarge-v1""": 512, """albert-base-v2""": 512, """albert-large-v2""": 512, """albert-xlarge-v2""": 512, """albert-xxlarge-v2""": 512, } lowerCamelCase__ = """▁""" class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : List[Any] =VOCAB_FILES_NAMES __lowerCamelCase : Union[str, Any] =PRETRAINED_VOCAB_FILES_MAP __lowerCamelCase : List[str] =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCamelCase : Any =AlbertTokenizer def __init__( self : Tuple , __lowercase : Union[str, Any]=None , __lowercase : Optional[int]=None , __lowercase : int=True , __lowercase : Dict=True , __lowercase : str=False , __lowercase : str="[CLS]" , __lowercase : List[Any]="[SEP]" , __lowercase : Any="<unk>" , __lowercase : List[Any]="[SEP]" , __lowercase : List[Any]="<pad>" , __lowercase : Optional[Any]="[CLS]" , __lowercase : List[str]="[MASK]" , **__lowercase : str , ): '''simple docstring''' # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. __a = ( AddedToken(__lowercase , lstrip=__lowercase , rstrip=__lowercase , normalized=__lowercase ) if isinstance(__lowercase , __lowercase ) else mask_token ) super().__init__( __lowercase , tokenizer_file=__lowercase , do_lower_case=__lowercase , remove_space=__lowercase , keep_accents=__lowercase , bos_token=__lowercase , eos_token=__lowercase , unk_token=__lowercase , sep_token=__lowercase , pad_token=__lowercase , cls_token=__lowercase , mask_token=__lowercase , **__lowercase , ) __a = do_lower_case __a = remove_space __a = keep_accents __a = vocab_file __a = False if not self.vocab_file else True def UpperCamelCase_ ( self : Dict , __lowercase : List[int] , __lowercase : Optional[List[int]] = None ): '''simple docstring''' __a = [self.sep_token_id] __a = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def UpperCamelCase_ ( self : str , __lowercase : List[int] , __lowercase : Optional[List[int]] = None ): '''simple docstring''' __a = [self.sep_token_id] __a = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCamelCase_ ( self : Tuple , __lowercase : str , __lowercase : Optional[str] = None ): '''simple docstring''' if not self.can_save_slow_tokenizer: raise ValueError( """Your fast tokenizer does not have the necessary information to save the vocabulary for a slow """ """tokenizer.""" ) if not os.path.isdir(__lowercase ): logger.error(F"Vocabulary path ({save_directory}) should be a directory" ) return __a = os.path.join( __lowercase , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__lowercase ): copyfile(self.vocab_file , __lowercase ) return (out_vocab_file,)
302
import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_albert import AlbertTokenizer else: lowerCamelCase__ = None lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = {"""vocab_file""": """spiece.model""", """tokenizer_file""": """tokenizer.json"""} lowerCamelCase__ = { """vocab_file""": { """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/spiece.model""", """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/spiece.model""", """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model""", """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model""", """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/spiece.model""", """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/spiece.model""", """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model""", """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model""", }, """tokenizer_file""": { """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/tokenizer.json""", """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/tokenizer.json""", """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/tokenizer.json""", """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/tokenizer.json""", """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/tokenizer.json""", """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/tokenizer.json""", """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/tokenizer.json""", """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/tokenizer.json""", }, } lowerCamelCase__ = { """albert-base-v1""": 512, """albert-large-v1""": 512, """albert-xlarge-v1""": 512, """albert-xxlarge-v1""": 512, """albert-base-v2""": 512, """albert-large-v2""": 512, """albert-xlarge-v2""": 512, """albert-xxlarge-v2""": 512, } lowerCamelCase__ = """▁""" class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : List[Any] =VOCAB_FILES_NAMES __lowerCamelCase : Union[str, Any] =PRETRAINED_VOCAB_FILES_MAP __lowerCamelCase : List[str] =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCamelCase : Any =AlbertTokenizer def __init__( self : Tuple , __lowercase : Union[str, Any]=None , __lowercase : Optional[int]=None , __lowercase : int=True , __lowercase : Dict=True , __lowercase : str=False , __lowercase : str="[CLS]" , __lowercase : List[Any]="[SEP]" , __lowercase : Any="<unk>" , __lowercase : List[Any]="[SEP]" , __lowercase : List[Any]="<pad>" , __lowercase : Optional[Any]="[CLS]" , __lowercase : List[str]="[MASK]" , **__lowercase : str , ): '''simple docstring''' # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. __a = ( AddedToken(__lowercase , lstrip=__lowercase , rstrip=__lowercase , normalized=__lowercase ) if isinstance(__lowercase , __lowercase ) else mask_token ) super().__init__( __lowercase , tokenizer_file=__lowercase , do_lower_case=__lowercase , remove_space=__lowercase , keep_accents=__lowercase , bos_token=__lowercase , eos_token=__lowercase , unk_token=__lowercase , sep_token=__lowercase , pad_token=__lowercase , cls_token=__lowercase , mask_token=__lowercase , **__lowercase , ) __a = do_lower_case __a = remove_space __a = keep_accents __a = vocab_file __a = False if not self.vocab_file else True def UpperCamelCase_ ( self : Dict , __lowercase : List[int] , __lowercase : Optional[List[int]] = None ): '''simple docstring''' __a = [self.sep_token_id] __a = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def UpperCamelCase_ ( self : str , __lowercase : List[int] , __lowercase : Optional[List[int]] = None ): '''simple docstring''' __a = [self.sep_token_id] __a = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCamelCase_ ( self : Tuple , __lowercase : str , __lowercase : Optional[str] = None ): '''simple docstring''' if not self.can_save_slow_tokenizer: raise ValueError( """Your fast tokenizer does not have the necessary information to save the vocabulary for a slow """ """tokenizer.""" ) if not os.path.isdir(__lowercase ): logger.error(F"Vocabulary path ({save_directory}) should be a directory" ) return __a = os.path.join( __lowercase , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__lowercase ): copyfile(self.vocab_file , __lowercase ) return (out_vocab_file,)
302
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase__ = { """configuration_roformer""": ["""ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """RoFormerConfig""", """RoFormerOnnxConfig"""], """tokenization_roformer""": ["""RoFormerTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = ["""RoFormerTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ """ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """RoFormerForCausalLM""", """RoFormerForMaskedLM""", """RoFormerForMultipleChoice""", """RoFormerForQuestionAnswering""", """RoFormerForSequenceClassification""", """RoFormerForTokenClassification""", """RoFormerLayer""", """RoFormerModel""", """RoFormerPreTrainedModel""", """load_tf_weights_in_roformer""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ """TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFRoFormerForCausalLM""", """TFRoFormerForMaskedLM""", """TFRoFormerForMultipleChoice""", """TFRoFormerForQuestionAnswering""", """TFRoFormerForSequenceClassification""", """TFRoFormerForTokenClassification""", """TFRoFormerLayer""", """TFRoFormerModel""", """TFRoFormerPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ """FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """FlaxRoFormerForMaskedLM""", """FlaxRoFormerForMultipleChoice""", """FlaxRoFormerForQuestionAnswering""", """FlaxRoFormerForSequenceClassification""", """FlaxRoFormerForTokenClassification""", """FlaxRoFormerModel""", """FlaxRoFormerPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_roformer import ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, RoFormerConfig, RoFormerOnnxConfig from .tokenization_roformer import RoFormerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roformer_fast import RoFormerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roformer import ( ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, RoFormerForCausalLM, RoFormerForMaskedLM, RoFormerForMultipleChoice, RoFormerForQuestionAnswering, RoFormerForSequenceClassification, RoFormerForTokenClassification, RoFormerLayer, RoFormerModel, RoFormerPreTrainedModel, load_tf_weights_in_roformer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roformer import ( TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerLayer, TFRoFormerModel, TFRoFormerPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roformer import ( FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, FlaxRoFormerPreTrainedModel, ) else: import sys lowerCamelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
302
import tempfile import torch from diffusers import IPNDMScheduler from .test_schedulers import SchedulerCommonTest class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : Optional[int] =(IPNDMScheduler,) __lowerCamelCase : int =(('num_inference_steps', 50),) def UpperCamelCase_ ( self : str , **__lowercase : Dict ): '''simple docstring''' __a = {"""num_train_timesteps""": 1000} config.update(**__lowercase ) return config def UpperCamelCase_ ( self : Any , __lowercase : Tuple=0 , **__lowercase : Dict ): '''simple docstring''' __a = dict(self.forward_default_kwargs ) __a = kwargs.pop("""num_inference_steps""" , __lowercase ) __a = self.dummy_sample __a = 0.1 * sample __a = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: __a = self.get_scheduler_config(**__lowercase ) __a = scheduler_class(**__lowercase ) scheduler.set_timesteps(__lowercase ) # copy over dummy past residuals __a = dummy_past_residuals[:] if time_step is None: __a = scheduler.timesteps[len(scheduler.timesteps ) // 2] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(__lowercase ) __a = scheduler_class.from_pretrained(__lowercase ) new_scheduler.set_timesteps(__lowercase ) # copy over dummy past residuals __a = dummy_past_residuals[:] __a = scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample __a = new_scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" __a = scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample __a = new_scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def UpperCamelCase_ ( self : str ): '''simple docstring''' pass def UpperCamelCase_ ( self : str , __lowercase : int=0 , **__lowercase : Dict ): '''simple docstring''' __a = dict(self.forward_default_kwargs ) __a = kwargs.pop("""num_inference_steps""" , __lowercase ) __a = self.dummy_sample __a = 0.1 * sample __a = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: __a = self.get_scheduler_config() __a = scheduler_class(**__lowercase ) scheduler.set_timesteps(__lowercase ) # copy over dummy past residuals (must be after setting timesteps) __a = dummy_past_residuals[:] if time_step is None: __a = scheduler.timesteps[len(scheduler.timesteps ) // 2] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(__lowercase ) __a = scheduler_class.from_pretrained(__lowercase ) # copy over dummy past residuals new_scheduler.set_timesteps(__lowercase ) # copy over dummy past residual (must be after setting timesteps) __a = dummy_past_residuals[:] __a = scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample __a = new_scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" __a = scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample __a = new_scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def UpperCamelCase_ ( self : List[str] , **__lowercase : Dict ): '''simple docstring''' __a = self.scheduler_classes[0] __a = self.get_scheduler_config(**__lowercase ) __a = scheduler_class(**__lowercase ) __a = 10 __a = self.dummy_model() __a = self.dummy_sample_deter scheduler.set_timesteps(__lowercase ) for i, t in enumerate(scheduler.timesteps ): __a = model(__lowercase , __lowercase ) __a = scheduler.step(__lowercase , __lowercase , __lowercase ).prev_sample for i, t in enumerate(scheduler.timesteps ): __a = model(__lowercase , __lowercase ) __a = scheduler.step(__lowercase , __lowercase , __lowercase ).prev_sample return sample def UpperCamelCase_ ( self : str ): '''simple docstring''' __a = dict(self.forward_default_kwargs ) __a = kwargs.pop("""num_inference_steps""" , __lowercase ) for scheduler_class in self.scheduler_classes: __a = self.get_scheduler_config() __a = scheduler_class(**__lowercase ) __a = self.dummy_sample __a = 0.1 * sample if num_inference_steps is not None and hasattr(__lowercase , """set_timesteps""" ): scheduler.set_timesteps(__lowercase ) elif num_inference_steps is not None and not hasattr(__lowercase , """set_timesteps""" ): __a = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) __a = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] __a = dummy_past_residuals[:] __a = scheduler.timesteps[5] __a = scheduler.timesteps[6] __a = scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample __a = scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) __a = scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample __a = scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' for timesteps in [100, 1000]: self.check_over_configs(num_train_timesteps=__lowercase , time_step=__lowercase ) def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' for t, num_inference_steps in zip([1, 5, 10] , [10, 50, 100] ): self.check_over_forward(num_inference_steps=__lowercase , time_step=__lowercase ) def UpperCamelCase_ ( self : int ): '''simple docstring''' __a = self.full_loop() __a = torch.mean(torch.abs(__lowercase ) ) assert abs(result_mean.item() - 2540529 ) < 10
302
1
import warnings from ...utils import logging from .image_processing_poolformer import PoolFormerImageProcessor lowerCamelCase__ = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): def __init__( self : Dict , *__lowercase : Union[str, Any] , **__lowercase : Any ): '''simple docstring''' warnings.warn( """The class PoolFormerFeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use PoolFormerImageProcessor instead.""" , __lowercase , ) super().__init__(*__lowercase , **__lowercase )
302
from __future__ import annotations lowerCamelCase__ = { """A""": ["""B""", """C""", """E"""], """B""": ["""A""", """D""", """E"""], """C""": ["""A""", """F""", """G"""], """D""": ["""B"""], """E""": ["""A""", """B""", """D"""], """F""": ["""C"""], """G""": ["""C"""], } class SCREAMING_SNAKE_CASE : def __init__( self : Tuple , __lowercase : dict[str, list[str]] , __lowercase : str ): '''simple docstring''' __a = graph # mapping node to its parent in resulting breadth first tree __a = {} __a = source_vertex def UpperCamelCase_ ( self : Any ): '''simple docstring''' __a = {self.source_vertex} __a = None __a = [self.source_vertex] # first in first out queue while queue: __a = queue.pop(0 ) for adjacent_vertex in self.graph[vertex]: if adjacent_vertex not in visited: visited.add(__lowercase ) __a = vertex queue.append(__lowercase ) def UpperCamelCase_ ( self : Optional[int] , __lowercase : str ): '''simple docstring''' if target_vertex == self.source_vertex: return self.source_vertex __a = self.parent.get(__lowercase ) if target_vertex_parent is None: __a = ( F"No path from vertex: {self.source_vertex} to vertex: {target_vertex}" ) raise ValueError(__lowercase ) return self.shortest_path(__lowercase ) + F"->{target_vertex}" if __name__ == "__main__": lowerCamelCase__ = Graph(graph, """G""") g.breath_first_search() print(g.shortest_path("""D""")) print(g.shortest_path("""G""")) print(g.shortest_path("""Foo"""))
302
1
from dataclasses import dataclass from typing import Dict, Optional, Union import torch import torch.nn.functional as F from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .attention import BasicTransformerBlock from .attention_processor import AttentionProcessor, AttnProcessor from .embeddings import TimestepEmbedding, Timesteps from .modeling_utils import ModelMixin @dataclass class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : torch.FloatTensor class SCREAMING_SNAKE_CASE ( lowerCamelCase__ , lowerCamelCase__ ): @register_to_config def __init__( self : Dict , __lowercase : int = 32 , __lowercase : int = 64 , __lowercase : int = 20 , __lowercase : int = 768 , __lowercase : Any=77 , __lowercase : Optional[int]=4 , __lowercase : float = 0.0 , __lowercase : str = "silu" , __lowercase : Optional[str] = None , __lowercase : Optional[str] = None , __lowercase : Optional[str] = "linear" , __lowercase : Optional[str] = "prd" , __lowercase : Optional[int] = None , __lowercase : Optional[int] = None , __lowercase : Optional[int] = None , ): '''simple docstring''' super().__init__() __a = num_attention_heads __a = attention_head_dim __a = num_attention_heads * attention_head_dim __a = additional_embeddings __a = time_embed_dim or inner_dim __a = embedding_proj_dim or embedding_dim __a = clip_embed_dim or embedding_dim __a = Timesteps(__lowercase , __lowercase , 0 ) __a = TimestepEmbedding(__lowercase , __lowercase , out_dim=__lowercase , act_fn=__lowercase ) __a = nn.Linear(__lowercase , __lowercase ) if embedding_proj_norm_type is None: __a = None elif embedding_proj_norm_type == "layer": __a = nn.LayerNorm(__lowercase ) else: raise ValueError(F"unsupported embedding_proj_norm_type: {embedding_proj_norm_type}" ) __a = nn.Linear(__lowercase , __lowercase ) if encoder_hid_proj_type is None: __a = None elif encoder_hid_proj_type == "linear": __a = nn.Linear(__lowercase , __lowercase ) else: raise ValueError(F"unsupported encoder_hid_proj_type: {encoder_hid_proj_type}" ) __a = nn.Parameter(torch.zeros(1 , num_embeddings + additional_embeddings , __lowercase ) ) if added_emb_type == "prd": __a = nn.Parameter(torch.zeros(1 , 1 , __lowercase ) ) elif added_emb_type is None: __a = None else: raise ValueError( F"`added_emb_type`: {added_emb_type} is not supported. Make sure to choose one of `'prd'` or `None`." ) __a = nn.ModuleList( [ BasicTransformerBlock( __lowercase , __lowercase , __lowercase , dropout=__lowercase , activation_fn="""gelu""" , attention_bias=__lowercase , ) for d in range(__lowercase ) ] ) if norm_in_type == "layer": __a = nn.LayerNorm(__lowercase ) elif norm_in_type is None: __a = None else: raise ValueError(F"Unsupported norm_in_type: {norm_in_type}." ) __a = nn.LayerNorm(__lowercase ) __a = nn.Linear(__lowercase , __lowercase ) __a = torch.full( [num_embeddings + additional_embeddings, num_embeddings + additional_embeddings] , -10000.0 ) causal_attention_mask.triu_(1 ) __a = causal_attention_mask[None, ...] self.register_buffer("""causal_attention_mask""" , __lowercase , persistent=__lowercase ) __a = nn.Parameter(torch.zeros(1 , __lowercase ) ) __a = nn.Parameter(torch.zeros(1 , __lowercase ) ) @property # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' __a = {} def fn_recursive_add_processors(__lowercase : str , __lowercase : torch.nn.Module , __lowercase : Dict[str, AttentionProcessor] ): if hasattr(__lowercase , """set_processor""" ): __a = module.processor for sub_name, child in module.named_children(): fn_recursive_add_processors(F"{name}.{sub_name}" , __lowercase , __lowercase ) return processors for name, module in self.named_children(): fn_recursive_add_processors(__lowercase , __lowercase , __lowercase ) return processors def UpperCamelCase_ ( self : List[str] , __lowercase : Union[AttentionProcessor, Dict[str, AttentionProcessor]] ): '''simple docstring''' __a = len(self.attn_processors.keys() ) if isinstance(__lowercase , __lowercase ) and len(__lowercase ) != count: raise ValueError( F"A dict of processors was passed, but the number of processors {len(__lowercase )} does not match the" F" number of attention layers: {count}. Please make sure to pass {count} processor classes." ) def fn_recursive_attn_processor(__lowercase : str , __lowercase : torch.nn.Module , __lowercase : Dict ): if hasattr(__lowercase , """set_processor""" ): if not isinstance(__lowercase , __lowercase ): module.set_processor(__lowercase ) else: module.set_processor(processor.pop(F"{name}.processor" ) ) for sub_name, child in module.named_children(): fn_recursive_attn_processor(F"{name}.{sub_name}" , __lowercase , __lowercase ) for name, module in self.named_children(): fn_recursive_attn_processor(__lowercase , __lowercase , __lowercase ) def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' self.set_attn_processor(AttnProcessor() ) def UpperCamelCase_ ( self : Union[str, Any] , __lowercase : Optional[int] , __lowercase : Union[torch.Tensor, float, int] , __lowercase : torch.FloatTensor , __lowercase : Optional[torch.FloatTensor] = None , __lowercase : Optional[torch.BoolTensor] = None , __lowercase : bool = True , ): '''simple docstring''' __a = hidden_states.shape[0] __a = timestep if not torch.is_tensor(__lowercase ): __a = torch.tensor([timesteps] , dtype=torch.long , device=hidden_states.device ) elif torch.is_tensor(__lowercase ) and len(timesteps.shape ) == 0: __a = timesteps[None].to(hidden_states.device ) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML __a = timesteps * torch.ones(__lowercase , dtype=timesteps.dtype , device=timesteps.device ) __a = self.time_proj(__lowercase ) # timesteps does not contain any weights and will always return f32 tensors # but time_embedding might be fp16, so we need to cast here. __a = timesteps_projected.to(dtype=self.dtype ) __a = self.time_embedding(__lowercase ) if self.embedding_proj_norm is not None: __a = self.embedding_proj_norm(__lowercase ) __a = self.embedding_proj(__lowercase ) if self.encoder_hidden_states_proj is not None and encoder_hidden_states is not None: __a = self.encoder_hidden_states_proj(__lowercase ) elif self.encoder_hidden_states_proj is not None and encoder_hidden_states is None: raise ValueError("""`encoder_hidden_states_proj` requires `encoder_hidden_states` to be set""" ) __a = self.proj_in(__lowercase ) __a = self.positional_embedding.to(hidden_states.dtype ) __a = [] __a = 0 if encoder_hidden_states is not None: additional_embeds.append(__lowercase ) additional_embeddings_len += encoder_hidden_states.shape[1] if len(proj_embeddings.shape ) == 2: __a = proj_embeddings[:, None, :] if len(hidden_states.shape ) == 2: __a = hidden_states[:, None, :] __a = additional_embeds + [ proj_embeddings, time_embeddings[:, None, :], hidden_states, ] if self.prd_embedding is not None: __a = self.prd_embedding.to(hidden_states.dtype ).expand(__lowercase , -1 , -1 ) additional_embeds.append(__lowercase ) __a = torch.cat( __lowercase , dim=1 , ) # Allow positional_embedding to not include the `addtional_embeddings` and instead pad it with zeros for these additional tokens __a = additional_embeddings_len + proj_embeddings.shape[1] + 1 if positional_embeddings.shape[1] < hidden_states.shape[1]: __a = F.pad( __lowercase , ( 0, 0, additional_embeddings_len, self.prd_embedding.shape[1] if self.prd_embedding is not None else 0, ) , value=0.0 , ) __a = hidden_states + positional_embeddings if attention_mask is not None: __a = (1 - attention_mask.to(hidden_states.dtype )) * -10000.0 __a = F.pad(__lowercase , (0, self.additional_embeddings) , value=0.0 ) __a = (attention_mask[:, None, :] + self.causal_attention_mask).to(hidden_states.dtype ) __a = attention_mask.repeat_interleave(self.config.num_attention_heads , dim=0 ) if self.norm_in is not None: __a = self.norm_in(__lowercase ) for block in self.transformer_blocks: __a = block(__lowercase , attention_mask=__lowercase ) __a = self.norm_out(__lowercase ) if self.prd_embedding is not None: __a = hidden_states[:, -1] else: __a = hidden_states[:, additional_embeddings_len:] __a = self.proj_to_clip_embeddings(__lowercase ) if not return_dict: return (predicted_image_embedding,) return PriorTransformerOutput(predicted_image_embedding=__lowercase ) def UpperCamelCase_ ( self : Any , __lowercase : Tuple ): '''simple docstring''' __a = (prior_latents * self.clip_std) + self.clip_mean return prior_latents
302
import unittest import numpy as np import torch from torch import nn from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import KandinskyVaaPriorPipeline, PriorTransformer, UnCLIPScheduler from diffusers.utils import torch_device from diffusers.utils.testing_utils import enable_full_determinism, skip_mps from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class SCREAMING_SNAKE_CASE ( lowerCamelCase__ , unittest.TestCase ): __lowerCamelCase : Tuple =KandinskyVaaPriorPipeline __lowerCamelCase : Union[str, Any] =['prompt'] __lowerCamelCase : Any =['prompt', 'negative_prompt'] __lowerCamelCase : List[str] =[ 'num_images_per_prompt', 'generator', 'num_inference_steps', 'latents', 'negative_prompt', 'guidance_scale', 'output_type', 'return_dict', ] __lowerCamelCase : List[Any] =False @property def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' return 32 @property def UpperCamelCase_ ( self : Any ): '''simple docstring''' return 32 @property def UpperCamelCase_ ( self : str ): '''simple docstring''' return self.time_input_dim @property def UpperCamelCase_ ( self : str ): '''simple docstring''' return self.time_input_dim * 4 @property def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' return 100 @property def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' __a = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) return tokenizer @property def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' torch.manual_seed(0 ) __a = 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-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(__lowercase ) @property def UpperCamelCase_ ( self : int ): '''simple docstring''' torch.manual_seed(0 ) __a = { """num_attention_heads""": 2, """attention_head_dim""": 12, """embedding_dim""": self.text_embedder_hidden_size, """num_layers""": 1, } __a = PriorTransformer(**__lowercase ) # clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0 __a = nn.Parameter(torch.ones(model.clip_std.shape ) ) return model @property def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' torch.manual_seed(0 ) __a = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=224 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=14 , ) __a = CLIPVisionModelWithProjection(__lowercase ) return model @property def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' __a = CLIPImageProcessor( crop_size=224 , do_center_crop=__lowercase , do_normalize=__lowercase , do_resize=__lowercase , image_mean=[0.48145466, 0.4578275, 0.40821073] , image_std=[0.26862954, 0.26130258, 0.27577711] , resample=3 , size=224 , ) return image_processor def UpperCamelCase_ ( self : str ): '''simple docstring''' __a = self.dummy_prior __a = self.dummy_image_encoder __a = self.dummy_text_encoder __a = self.dummy_tokenizer __a = self.dummy_image_processor __a = UnCLIPScheduler( variance_type="""fixed_small_log""" , prediction_type="""sample""" , num_train_timesteps=1000 , clip_sample=__lowercase , clip_sample_range=10.0 , ) __a = { """prior""": prior, """image_encoder""": image_encoder, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """scheduler""": scheduler, """image_processor""": image_processor, } return components def UpperCamelCase_ ( self : Optional[int] , __lowercase : List[str] , __lowercase : Any=0 ): '''simple docstring''' if str(__lowercase ).startswith("""mps""" ): __a = torch.manual_seed(__lowercase ) else: __a = torch.Generator(device=__lowercase ).manual_seed(__lowercase ) __a = { """prompt""": """horse""", """generator""": generator, """guidance_scale""": 4.0, """num_inference_steps""": 2, """output_type""": """np""", } return inputs def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' __a = """cpu""" __a = self.get_dummy_components() __a = self.pipeline_class(**__lowercase ) __a = pipe.to(__lowercase ) pipe.set_progress_bar_config(disable=__lowercase ) __a = pipe(**self.get_dummy_inputs(__lowercase ) ) __a = output.image_embeds __a = pipe( **self.get_dummy_inputs(__lowercase ) , return_dict=__lowercase , )[0] __a = image[0, -10:] __a = image_from_tuple[0, -10:] assert image.shape == (1, 32) __a = np.array( [-0.0532, 1.7120, 0.3656, -1.0852, -0.8946, -1.1756, 0.4348, 0.2482, 0.5146, -0.1156] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 @skip_mps def UpperCamelCase_ ( self : Dict ): '''simple docstring''' __a = torch_device == """cpu""" __a = True __a = False self._test_inference_batch_single_identical( test_max_difference=__lowercase , relax_max_difference=__lowercase , test_mean_pixel_difference=__lowercase , ) @skip_mps def UpperCamelCase_ ( self : Any ): '''simple docstring''' __a = torch_device == """cpu""" __a = False self._test_attention_slicing_forward_pass( test_max_difference=__lowercase , test_mean_pixel_difference=__lowercase , )
302
1
from tempfile import TemporaryDirectory from unittest import TestCase from unittest.mock import MagicMock, patch from transformers import AutoModel, TFAutoModel from transformers.onnx import FeaturesManager from transformers.testing_utils import SMALL_MODEL_IDENTIFIER, require_tf, require_torch @require_torch @require_tf class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): def UpperCamelCase_ ( self : int ): '''simple docstring''' __a = SMALL_MODEL_IDENTIFIER __a = """pt""" __a = """tf""" def UpperCamelCase_ ( self : Optional[int] , __lowercase : str ): '''simple docstring''' __a = AutoModel.from_pretrained(self.test_model ) model_pt.save_pretrained(__lowercase ) def UpperCamelCase_ ( self : Any , __lowercase : Dict ): '''simple docstring''' __a = TFAutoModel.from_pretrained(self.test_model , from_pt=__lowercase ) model_tf.save_pretrained(__lowercase ) def UpperCamelCase_ ( self : Optional[int] ): '''simple docstring''' __a = """mock_framework""" # Framework provided - return whatever the user provides __a = FeaturesManager.determine_framework(self.test_model , __lowercase ) self.assertEqual(__lowercase , __lowercase ) # Local checkpoint and framework provided - return provided framework # PyTorch checkpoint with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(__lowercase ) __a = FeaturesManager.determine_framework(__lowercase , __lowercase ) self.assertEqual(__lowercase , __lowercase ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(__lowercase ) __a = FeaturesManager.determine_framework(__lowercase , __lowercase ) self.assertEqual(__lowercase , __lowercase ) def UpperCamelCase_ ( self : int ): '''simple docstring''' # PyTorch checkpoint with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(__lowercase ) __a = FeaturesManager.determine_framework(__lowercase ) self.assertEqual(__lowercase , self.framework_pt ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(__lowercase ) __a = FeaturesManager.determine_framework(__lowercase ) self.assertEqual(__lowercase , self.framework_tf ) # Invalid local checkpoint with TemporaryDirectory() as local_invalid_ckpt: with self.assertRaises(__lowercase ): __a = FeaturesManager.determine_framework(__lowercase ) def UpperCamelCase_ ( self : Any ): '''simple docstring''' __a = MagicMock(return_value=__lowercase ) with patch("""transformers.onnx.features.is_tf_available""" , __lowercase ): __a = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__lowercase , self.framework_pt ) # PyTorch not in environment -> use TensorFlow __a = MagicMock(return_value=__lowercase ) with patch("""transformers.onnx.features.is_torch_available""" , __lowercase ): __a = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__lowercase , self.framework_tf ) # Both in environment -> use PyTorch __a = MagicMock(return_value=__lowercase ) __a = MagicMock(return_value=__lowercase ) with patch("""transformers.onnx.features.is_tf_available""" , __lowercase ), patch( """transformers.onnx.features.is_torch_available""" , __lowercase ): __a = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__lowercase , self.framework_pt ) # Both not in environment -> raise error __a = MagicMock(return_value=__lowercase ) __a = MagicMock(return_value=__lowercase ) with patch("""transformers.onnx.features.is_tf_available""" , __lowercase ), patch( """transformers.onnx.features.is_torch_available""" , __lowercase ): with self.assertRaises(__lowercase ): __a = FeaturesManager.determine_framework(self.test_model )
302
from typing import Any, Dict, List, Union from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from ..image_utils import load_image if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_OBJECT_DETECTION_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = Dict[str, Any] lowerCamelCase__ = List[Prediction] @add_end_docstrings(lowerCamelCase__ ) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): def __init__( self : Tuple , *__lowercase : Tuple , **__lowercase : Optional[int] ): '''simple docstring''' super().__init__(*__lowercase , **__lowercase ) if self.framework == "tf": raise ValueError(F"The {self.__class__} is only available in PyTorch." ) requires_backends(self , """vision""" ) self.check_model_type( dict(MODEL_FOR_OBJECT_DETECTION_MAPPING.items() + MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING.items() ) ) def UpperCamelCase_ ( self : Optional[int] , **__lowercase : List[str] ): '''simple docstring''' __a = {} if "threshold" in kwargs: __a = kwargs["""threshold"""] return {}, {}, postprocess_kwargs def __call__( self : List[Any] , *__lowercase : Any , **__lowercase : Tuple ): '''simple docstring''' return super().__call__(*__lowercase , **__lowercase ) def UpperCamelCase_ ( self : str , __lowercase : Tuple ): '''simple docstring''' __a = load_image(__lowercase ) __a = torch.IntTensor([[image.height, image.width]] ) __a = self.image_processor(images=[image] , return_tensors="""pt""" ) if self.tokenizer is not None: __a = self.tokenizer(text=inputs["""words"""] , boxes=inputs["""boxes"""] , return_tensors="""pt""" ) __a = target_size return inputs def UpperCamelCase_ ( self : Dict , __lowercase : List[str] ): '''simple docstring''' __a = model_inputs.pop("""target_size""" ) __a = self.model(**__lowercase ) __a = outputs.__class__({"""target_size""": target_size, **outputs} ) if self.tokenizer is not None: __a = model_inputs["""bbox"""] return model_outputs def UpperCamelCase_ ( self : Optional[int] , __lowercase : List[Any] , __lowercase : List[Any]=0.9 ): '''simple docstring''' __a = model_outputs["""target_size"""] if self.tokenizer is not None: # This is a LayoutLMForTokenClassification variant. # The OCR got the boxes and the model classified the words. __a , __a = target_size[0].tolist() def unnormalize(__lowercase : Optional[Any] ): return self._get_bounding_box( torch.Tensor( [ (width * bbox[0] / 1000), (height * bbox[1] / 1000), (width * bbox[2] / 1000), (height * bbox[3] / 1000), ] ) ) __a , __a = model_outputs["""logits"""].squeeze(0 ).softmax(dim=-1 ).max(dim=-1 ) __a = [self.model.config.idalabel[prediction] for prediction in classes.tolist()] __a = [unnormalize(__lowercase ) for bbox in model_outputs["""bbox"""].squeeze(0 )] __a = ["""score""", """label""", """box"""] __a = [dict(zip(__lowercase , __lowercase ) ) for vals in zip(scores.tolist() , __lowercase , __lowercase ) if vals[0] > threshold] else: # This is a regular ForObjectDetectionModel __a = self.image_processor.post_process_object_detection(__lowercase , __lowercase , __lowercase ) __a = raw_annotations[0] __a = raw_annotation["""scores"""] __a = raw_annotation["""labels"""] __a = raw_annotation["""boxes"""] __a = scores.tolist() __a = [self.model.config.idalabel[label.item()] for label in labels] __a = [self._get_bounding_box(__lowercase ) for box in boxes] # {"scores": [...], ...} --> [{"score":x, ...}, ...] __a = ["""score""", """label""", """box"""] __a = [ dict(zip(__lowercase , __lowercase ) ) for vals in zip(raw_annotation["""scores"""] , raw_annotation["""labels"""] , raw_annotation["""boxes"""] ) ] return annotation def UpperCamelCase_ ( self : Optional[int] , __lowercase : "torch.Tensor" ): '''simple docstring''' if self.framework != "pt": raise ValueError("""The ObjectDetectionPipeline is only available in PyTorch.""" ) __a , __a , __a , __a = box.int().tolist() __a = { """xmin""": xmin, """ymin""": ymin, """xmax""": xmax, """ymax""": ymax, } return bbox
302
1
import inspect import math import tempfile import unittest import numpy as np from transformers import ViTMAEConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ViTMAEForPreTraining, ViTMAEModel from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class SCREAMING_SNAKE_CASE : def __init__( self : Optional[int] , __lowercase : Any , __lowercase : Any=13 , __lowercase : int=30 , __lowercase : Optional[Any]=2 , __lowercase : List[str]=3 , __lowercase : Union[str, Any]=True , __lowercase : List[Any]=True , __lowercase : Tuple=32 , __lowercase : str=5 , __lowercase : Optional[Any]=4 , __lowercase : Any=37 , __lowercase : Optional[int]="gelu" , __lowercase : Union[str, Any]=0.1 , __lowercase : Optional[int]=0.1 , __lowercase : Any=10 , __lowercase : List[str]=0.02 , __lowercase : Tuple=3 , __lowercase : Optional[int]=0.6 , __lowercase : Optional[int]=None , ): '''simple docstring''' __a = parent __a = batch_size __a = image_size __a = patch_size __a = num_channels __a = is_training __a = use_labels __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = type_sequence_label_size __a = initializer_range __a = mask_ratio __a = scope # in ViTMAE, the expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above # (we add 1 for the [CLS] token) __a = (image_size // patch_size) ** 2 __a = int(math.ceil((1 - mask_ratio) * (num_patches + 1) ) ) def UpperCamelCase_ ( self : int ): '''simple docstring''' __a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = self.get_config() return config, pixel_values, labels def UpperCamelCase_ ( self : Dict ): '''simple docstring''' return ViTMAEConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=__lowercase , initializer_range=self.initializer_range , mask_ratio=self.mask_ratio , ) def UpperCamelCase_ ( self : Union[str, Any] , __lowercase : Union[str, Any] , __lowercase : Union[str, Any] , __lowercase : Optional[int] ): '''simple docstring''' __a = ViTMAEModel(config=__lowercase ) model.to(__lowercase ) model.eval() __a = model(__lowercase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase_ ( self : int , __lowercase : Any , __lowercase : Union[str, Any] , __lowercase : Dict ): '''simple docstring''' __a = ViTMAEForPreTraining(__lowercase ) model.to(__lowercase ) model.eval() __a = model(__lowercase ) __a = (self.image_size // self.patch_size) ** 2 __a = self.patch_size**2 * self.num_channels self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) ) # test greyscale images __a = 1 __a = ViTMAEForPreTraining(__lowercase ) model.to(__lowercase ) model.eval() __a = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __a = model(__lowercase ) __a = self.patch_size**2 self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) ) def UpperCamelCase_ ( self : Dict ): '''simple docstring''' __a = self.prepare_config_and_inputs() __a , __a , __a = config_and_inputs __a = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE ( lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase ): __lowerCamelCase : Union[str, Any] =(ViTMAEModel, ViTMAEForPreTraining) if is_torch_available() else () __lowerCamelCase : Optional[Any] ={'feature-extraction': ViTMAEModel} if is_torch_available() else {} __lowerCamelCase : Union[str, Any] =False __lowerCamelCase : List[Any] =False __lowerCamelCase : Tuple =False __lowerCamelCase : Optional[Any] =False def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' __a = ViTMAEModelTester(self ) __a = ConfigTester(self , config_class=__lowercase , has_text_modality=__lowercase , hidden_size=37 ) def UpperCamelCase_ ( self : str ): '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason="""ViTMAE does not use inputs_embeds""" ) def UpperCamelCase_ ( self : Optional[int] ): '''simple docstring''' pass def UpperCamelCase_ ( self : Optional[int] ): '''simple docstring''' __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(__lowercase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) __a = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__lowercase , nn.Linear ) ) def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(__lowercase ) __a = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a = [*signature.parameters.keys()] __a = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , __lowercase ) def UpperCamelCase_ ( self : int ): '''simple docstring''' __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowercase ) def UpperCamelCase_ ( self : str ): '''simple docstring''' __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*__lowercase ) def UpperCamelCase_ ( self : List[Any] , __lowercase : List[str] , __lowercase : Union[str, Any] , __lowercase : List[str] ): '''simple docstring''' # make masks reproducible np.random.seed(2 ) __a = int((pt_model.config.image_size // pt_model.config.patch_size) ** 2 ) __a = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) __a = torch.from_numpy(__lowercase ) # Add `noise` argument. # PT inputs will be prepared in `super().check_pt_tf_models()` with this added `noise` argument __a = pt_noise super().check_pt_tf_models(__lowercase , __lowercase , __lowercase ) def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(__lowercase ) model.to(__lowercase ) model.eval() # make random mask reproducible torch.manual_seed(2 ) with torch.no_grad(): __a = model(**self._prepare_for_class(__lowercase , __lowercase ) ) __a = outputs[0].cpu().numpy() __a = 0 with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(__lowercase ) __a = model_class.from_pretrained(__lowercase ) model.to(__lowercase ) # make random mask reproducible torch.manual_seed(2 ) with torch.no_grad(): __a = model(**self._prepare_for_class(__lowercase , __lowercase ) ) # Make sure we don't have nans __a = after_outputs[0].cpu().numpy() __a = 0 __a = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(__lowercase , 1E-5 ) @unittest.skip( reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load to get deterministic results.""" ) def UpperCamelCase_ ( self : Any ): '''simple docstring''' pass @unittest.skip( reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load to get deterministic results.""" ) def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' pass @unittest.skip( reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load to get deterministic results.""" ) def UpperCamelCase_ ( self : Optional[int] ): '''simple docstring''' pass @unittest.skip(reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load""" ) def UpperCamelCase_ ( self : str ): '''simple docstring''' pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' pass @slow def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = ViTMAEModel.from_pretrained(__lowercase ) self.assertIsNotNone(__lowercase ) def lowerCAmelCase__ ( ): """simple docstring""" __a = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class SCREAMING_SNAKE_CASE ( unittest.TestCase ): @cached_property def UpperCamelCase_ ( self : int ): '''simple docstring''' return ViTImageProcessor.from_pretrained("""facebook/vit-mae-base""" ) if is_vision_available() else None @slow def UpperCamelCase_ ( self : Optional[int] ): '''simple docstring''' # make random mask reproducible across the PT and TF model np.random.seed(2 ) __a = ViTMAEForPreTraining.from_pretrained("""facebook/vit-mae-base""" ).to(__lowercase ) __a = self.default_image_processor __a = prepare_img() __a = image_processor(images=__lowercase , return_tensors="""pt""" ).to(__lowercase ) # prepare a noise vector that will be also used for testing the TF model # (this way we can ensure that the PT and TF models operate on the same inputs) __a = ViTMAEConfig() __a = int((vit_mae_config.image_size // vit_mae_config.patch_size) ** 2 ) __a = np.random.uniform(size=(1, num_patches) ) # forward pass with torch.no_grad(): __a = model(**__lowercase , noise=torch.from_numpy(__lowercase ).to(device=__lowercase ) ) # verify the logits __a = torch.Size((1, 196, 768) ) self.assertEqual(outputs.logits.shape , __lowercase ) __a = torch.tensor( [[-0.0548, -1.7023, -0.9325], [0.3721, -0.5670, -0.2233], [0.8235, -1.3878, -0.3524]] ) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3] , expected_slice.to(__lowercase ) , atol=1E-4 ) )
302
# 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 # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowerCamelCase__ = { """configuration_efficientnet""": [ """EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP""", """EfficientNetConfig""", """EfficientNetOnnxConfig""", ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = ["""EfficientNetImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ """EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST""", """EfficientNetForImageClassification""", """EfficientNetModel""", """EfficientNetPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_efficientnet import ( EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP, EfficientNetConfig, EfficientNetOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_efficientnet import EfficientNetImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_efficientnet import ( EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST, EfficientNetForImageClassification, EfficientNetModel, EfficientNetPreTrainedModel, ) else: import sys lowerCamelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure)
302
1
import argparse import json from pathlib import Path import torch import torchaudio from datasets import load_dataset from huggingface_hub import hf_hub_download from transformers import ASTConfig, ASTFeatureExtractor, ASTForAudioClassification from transformers.utils import logging logging.set_verbosity_info() lowerCamelCase__ = logging.get_logger(__name__) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Any ): """simple docstring""" __a = ASTConfig() if "10-10" in model_name: pass elif "speech-commands" in model_name: __a = 128 elif "12-12" in model_name: __a = 12 __a = 12 elif "14-14" in model_name: __a = 14 __a = 14 elif "16-16" in model_name: __a = 16 __a = 16 else: raise ValueError("""Model not supported""" ) __a = """huggingface/label-files""" if "speech-commands" in model_name: __a = 35 __a = """speech-commands-v2-id2label.json""" else: __a = 527 __a = """audioset-id2label.json""" __a = json.load(open(hf_hub_download(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , repo_type="""dataset""" ) , """r""" ) ) __a = {int(_SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()} __a = idalabel __a = {v: k for k, v in idalabel.items()} return config def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" if "module.v" in name: __a = name.replace("""module.v""" , """audio_spectrogram_transformer""" ) if "cls_token" in name: __a = name.replace("""cls_token""" , """embeddings.cls_token""" ) if "dist_token" in name: __a = name.replace("""dist_token""" , """embeddings.distillation_token""" ) if "pos_embed" in name: __a = name.replace("""pos_embed""" , """embeddings.position_embeddings""" ) if "patch_embed.proj" in name: __a = name.replace("""patch_embed.proj""" , """embeddings.patch_embeddings.projection""" ) # transformer blocks if "blocks" in name: __a = name.replace("""blocks""" , """encoder.layer""" ) if "attn.proj" in name: __a = name.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in name: __a = name.replace("""attn""" , """attention.self""" ) if "norm1" in name: __a = name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: __a = name.replace("""norm2""" , """layernorm_after""" ) if "mlp.fc1" in name: __a = name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: __a = name.replace("""mlp.fc2""" , """output.dense""" ) # final layernorm if "audio_spectrogram_transformer.norm" in name: __a = name.replace("""audio_spectrogram_transformer.norm""" , """audio_spectrogram_transformer.layernorm""" ) # classifier head if "module.mlp_head.0" in name: __a = name.replace("""module.mlp_head.0""" , """classifier.layernorm""" ) if "module.mlp_head.1" in name: __a = name.replace("""module.mlp_head.1""" , """classifier.dense""" ) return name def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" for key in orig_state_dict.copy().keys(): __a = orig_state_dict.pop(_SCREAMING_SNAKE_CASE ) if "qkv" in key: __a = key.split(""".""" ) __a = int(key_split[3] ) __a = config.hidden_size if "weight" in key: __a = val[:dim, :] __a = val[dim : dim * 2, :] __a = val[-dim:, :] else: __a = val[:dim] __a = val[dim : dim * 2] __a = val[-dim:] else: __a = val return orig_state_dict def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" __a = [ """module.v.head.weight""", """module.v.head.bias""", """module.v.head_dist.weight""", """module.v.head_dist.bias""", ] for k in ignore_keys: state_dict.pop(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @torch.no_grad() def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : List[str]=False ): """simple docstring""" __a = get_audio_spectrogram_transformer_config(_SCREAMING_SNAKE_CASE ) __a = { """ast-finetuned-audioset-10-10-0.4593""": ( """https://www.dropbox.com/s/ca0b1v2nlxzyeb4/audioset_10_10_0.4593.pth?dl=1""" ), """ast-finetuned-audioset-10-10-0.450""": ( """https://www.dropbox.com/s/1tv0hovue1bxupk/audioset_10_10_0.4495.pth?dl=1""" ), """ast-finetuned-audioset-10-10-0.448""": ( """https://www.dropbox.com/s/6u5sikl4b9wo4u5/audioset_10_10_0.4483.pth?dl=1""" ), """ast-finetuned-audioset-10-10-0.448-v2""": ( """https://www.dropbox.com/s/kt6i0v9fvfm1mbq/audioset_10_10_0.4475.pth?dl=1""" ), """ast-finetuned-audioset-12-12-0.447""": ( """https://www.dropbox.com/s/snfhx3tizr4nuc8/audioset_12_12_0.4467.pth?dl=1""" ), """ast-finetuned-audioset-14-14-0.443""": ( """https://www.dropbox.com/s/z18s6pemtnxm4k7/audioset_14_14_0.4431.pth?dl=1""" ), """ast-finetuned-audioset-16-16-0.442""": ( """https://www.dropbox.com/s/mdsa4t1xmcimia6/audioset_16_16_0.4422.pth?dl=1""" ), """ast-finetuned-speech-commands-v2""": ( """https://www.dropbox.com/s/q0tbqpwv44pquwy/speechcommands_10_10_0.9812.pth?dl=1""" ), } # load original state_dict __a = model_name_to_url[model_name] __a = torch.hub.load_state_dict_from_url(_SCREAMING_SNAKE_CASE , map_location="""cpu""" ) # remove some keys remove_keys(_SCREAMING_SNAKE_CASE ) # rename some keys __a = convert_state_dict(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # load 🤗 model __a = ASTForAudioClassification(_SCREAMING_SNAKE_CASE ) model.eval() model.load_state_dict(_SCREAMING_SNAKE_CASE ) # verify outputs on dummy input # source: https://github.com/YuanGongND/ast/blob/79e873b8a54d0a3b330dd522584ff2b9926cd581/src/run.py#L62 __a = -4.267_7393 if """speech-commands""" not in model_name else -6.84_5978 __a = 4.568_9974 if """speech-commands""" not in model_name else 5.565_4526 __a = 1024 if """speech-commands""" not in model_name else 128 __a = ASTFeatureExtractor(mean=_SCREAMING_SNAKE_CASE , std=_SCREAMING_SNAKE_CASE , max_length=_SCREAMING_SNAKE_CASE ) if "speech-commands" in model_name: __a = load_dataset("""speech_commands""" , """v0.02""" , split="""validation""" ) __a = dataset[0]["""audio"""]["""array"""] else: __a = hf_hub_download( repo_id="""nielsr/audio-spectogram-transformer-checkpoint""" , filename="""sample_audio.flac""" , repo_type="""dataset""" , ) __a , __a = torchaudio.load(_SCREAMING_SNAKE_CASE ) __a = waveform.squeeze().numpy() __a = feature_extractor(_SCREAMING_SNAKE_CASE , sampling_rate=1_6000 , return_tensors="""pt""" ) # forward pass __a = model(**_SCREAMING_SNAKE_CASE ) __a = outputs.logits if model_name == "ast-finetuned-audioset-10-10-0.4593": __a = torch.tensor([-0.8760, -7.0042, -8.6602] ) elif model_name == "ast-finetuned-audioset-10-10-0.450": __a = torch.tensor([-1.1986, -7.0903, -8.2718] ) elif model_name == "ast-finetuned-audioset-10-10-0.448": __a = torch.tensor([-2.6128, -8.0080, -9.4344] ) elif model_name == "ast-finetuned-audioset-10-10-0.448-v2": __a = torch.tensor([-1.5080, -7.4534, -8.8917] ) elif model_name == "ast-finetuned-audioset-12-12-0.447": __a = torch.tensor([-0.5050, -6.5833, -8.0843] ) elif model_name == "ast-finetuned-audioset-14-14-0.443": __a = torch.tensor([-0.3826, -7.0336, -8.2413] ) elif model_name == "ast-finetuned-audioset-16-16-0.442": __a = torch.tensor([-1.2113, -6.9101, -8.3470] ) elif model_name == "ast-finetuned-speech-commands-v2": __a = torch.tensor([6.1589, -8.0566, -8.7984] ) else: raise ValueError("""Unknown model name""" ) if not torch.allclose(logits[0, :3] , _SCREAMING_SNAKE_CASE , atol=1e-4 ): raise ValueError("""Logits don't match""" ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) print(f"Saving model {model_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) print(f"Saving feature extractor to {pytorch_dump_folder_path}" ) feature_extractor.save_pretrained(_SCREAMING_SNAKE_CASE ) if push_to_hub: print("""Pushing model and feature extractor to the hub...""" ) model.push_to_hub(f"MIT/{model_name}" ) feature_extractor.push_to_hub(f"MIT/{model_name}" ) if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default="""ast-finetuned-audioset-10-10-0.4593""", type=str, help="""Name of the Audio Spectrogram Transformer model you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) parser.add_argument( """--push_to_hub""", action="""store_true""", help="""Whether or not to push the converted model to the 🤗 hub.""" ) lowerCamelCase__ = parser.parse_args() convert_audio_spectrogram_transformer_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
302
import random def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : list , _SCREAMING_SNAKE_CASE : List[Any] ): """simple docstring""" __a , __a , __a = [], [], [] for element in data: if element < pivot: less.append(_SCREAMING_SNAKE_CASE ) elif element > pivot: greater.append(_SCREAMING_SNAKE_CASE ) else: equal.append(_SCREAMING_SNAKE_CASE ) return less, equal, greater def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : list , _SCREAMING_SNAKE_CASE : int ): """simple docstring""" if index >= len(_SCREAMING_SNAKE_CASE ) or index < 0: return None __a = items[random.randint(0 , len(_SCREAMING_SNAKE_CASE ) - 1 )] __a = 0 __a , __a , __a = _partition(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __a = len(_SCREAMING_SNAKE_CASE ) __a = len(_SCREAMING_SNAKE_CASE ) # index is the pivot if m <= index < m + count: return pivot # must be in smaller elif m > index: return quick_select(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # must be in larger else: return quick_select(_SCREAMING_SNAKE_CASE , index - (m + count) )
302
1
from math import ceil, sqrt def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int = 100_0000 ): """simple docstring""" __a = 0 for outer_width in range(3 , (limit // 4) + 2 ): if outer_width**2 > limit: __a = max(ceil(sqrt(outer_width**2 - limit ) ) , 1 ) else: __a = 1 if (outer_width - hole_width_lower_bound) % 2: hole_width_lower_bound += 1 answer += (outer_width - hole_width_lower_bound - 2) // 2 + 1 return answer if __name__ == "__main__": print(F"""{solution() = }""")
302
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 lowerCamelCase__ = logging.get_logger(__name__) @add_end_docstrings(lowerCamelCase__ ) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): def __init__( self : Optional[int] , **__lowercase : Dict ): '''simple docstring''' super().__init__(**__lowercase ) if self.framework != "pt": raise ValueError(F"The {self.__class__} is only available in PyTorch." ) # No specific FOR_XXX available yet def __call__( self : str , __lowercase : Union[np.ndarray, bytes, str] , **__lowercase : int ): '''simple docstring''' return super().__call__(__lowercase , **__lowercase ) def UpperCamelCase_ ( self : List[Any] , **__lowercase : Union[str, Any] ): '''simple docstring''' __a = {} if "candidate_labels" in kwargs: __a = kwargs["""candidate_labels"""] if "hypothesis_template" in kwargs: __a = kwargs["""hypothesis_template"""] return preprocess_params, {}, {} def UpperCamelCase_ ( self : int , __lowercase : Dict , __lowercase : Dict=None , __lowercase : str="This is a sound of {}." ): '''simple docstring''' if isinstance(__lowercase , __lowercase ): if audio.startswith("""http://""" ) or audio.startswith("""https://""" ): # We need to actually check for a real protocol, otherwise it's impossible to use a local file # like http_huggingface_co.png __a = requests.get(__lowercase ).content else: with open(__lowercase , """rb""" ) as f: __a = f.read() if isinstance(__lowercase , __lowercase ): __a = ffmpeg_read(__lowercase , self.feature_extractor.sampling_rate ) if not isinstance(__lowercase , np.ndarray ): raise ValueError("""We expect a numpy ndarray as input""" ) if len(audio.shape ) != 1: raise ValueError("""We expect a single channel audio input for ZeroShotAudioClassificationPipeline""" ) __a = self.feature_extractor( [audio] , sampling_rate=self.feature_extractor.sampling_rate , return_tensors="""pt""" ) __a = candidate_labels __a = [hypothesis_template.format(__lowercase ) for x in candidate_labels] __a = self.tokenizer(__lowercase , return_tensors=self.framework , padding=__lowercase ) __a = [text_inputs] return inputs def UpperCamelCase_ ( self : Any , __lowercase : Any ): '''simple docstring''' __a = model_inputs.pop("""candidate_labels""" ) __a = model_inputs.pop("""text_inputs""" ) if isinstance(text_inputs[0] , __lowercase ): __a = text_inputs[0] else: # Batching case. __a = text_inputs[0][0] __a = self.model(**__lowercase , **__lowercase ) __a = { """candidate_labels""": candidate_labels, """logits""": outputs.logits_per_audio, } return model_outputs def UpperCamelCase_ ( self : Optional[Any] , __lowercase : Dict ): '''simple docstring''' __a = model_outputs.pop("""candidate_labels""" ) __a = model_outputs["""logits"""][0] if self.framework == "pt": __a = logits.softmax(dim=0 ) __a = probs.tolist() else: raise ValueError("""`tf` framework not supported.""" ) __a = [ {"""score""": score, """label""": candidate_label} for score, candidate_label in sorted(zip(__lowercase , __lowercase ) , key=lambda __lowercase : -x[0] ) ] return result
302
1
# This model implementation is heavily inspired by https://github.com/haofanwang/ControlNet-for-Diffusers/ import gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, ControlNetModel, DDIMScheduler, StableDiffusionControlNetImgaImgPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet import MultiControlNetModel from diffusers.utils import floats_tensor, load_image, load_numpy, randn_tensor, slow, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, ) enable_full_determinism() class SCREAMING_SNAKE_CASE ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase ): __lowerCamelCase : int =StableDiffusionControlNetImgaImgPipeline __lowerCamelCase : int =TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'height', 'width'} __lowerCamelCase : str =TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS __lowerCamelCase : int =IMAGE_TO_IMAGE_IMAGE_PARAMS.union({'control_image'} ) __lowerCamelCase : Any =IMAGE_TO_IMAGE_IMAGE_PARAMS def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' torch.manual_seed(0 ) __a = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , ) torch.manual_seed(0 ) __a = ControlNetModel( block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , ) torch.manual_seed(0 ) __a = DDIMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=__lowercase , set_alpha_to_one=__lowercase , ) torch.manual_seed(0 ) __a = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) torch.manual_seed(0 ) __a = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) __a = CLIPTextModel(__lowercase ) __a = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) __a = { """unet""": unet, """controlnet""": controlnet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def UpperCamelCase_ ( self : List[str] , __lowercase : str , __lowercase : int=0 ): '''simple docstring''' if str(__lowercase ).startswith("""mps""" ): __a = torch.manual_seed(__lowercase ) else: __a = torch.Generator(device=__lowercase ).manual_seed(__lowercase ) __a = 2 __a = randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=__lowercase , device=torch.device(__lowercase ) , ) __a = floats_tensor(control_image.shape , rng=random.Random(__lowercase ) ).to(__lowercase ) __a = image.cpu().permute(0 , 2 , 3 , 1 )[0] __a = Image.fromarray(np.uinta(__lowercase ) ).convert("""RGB""" ).resize((64, 64) ) __a = { """prompt""": """A painting of a squirrel eating a burger""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", """image""": image, """control_image""": control_image, } return inputs def UpperCamelCase_ ( self : int ): '''simple docstring''' return self._test_attention_slicing_forward_pass(expected_max_diff=2E-3 ) @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2E-3 ) def UpperCamelCase_ ( self : int ): '''simple docstring''' self._test_inference_batch_single_identical(expected_max_diff=2E-3 ) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase ): __lowerCamelCase : List[Any] =StableDiffusionControlNetImgaImgPipeline __lowerCamelCase : List[Any] =TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'height', 'width'} __lowerCamelCase : Optional[int] =TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS __lowerCamelCase : List[str] =frozenset([] ) # TO_DO: add image_params once refactored VaeImageProcessor.preprocess def UpperCamelCase_ ( self : str ): '''simple docstring''' torch.manual_seed(0 ) __a = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , ) torch.manual_seed(0 ) def init_weights(__lowercase : Optional[int] ): if isinstance(__lowercase , torch.nn.Convad ): torch.nn.init.normal(m.weight ) m.bias.data.fill_(1.0 ) __a = ControlNetModel( block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , ) controlneta.controlnet_down_blocks.apply(__lowercase ) torch.manual_seed(0 ) __a = ControlNetModel( block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , ) controlneta.controlnet_down_blocks.apply(__lowercase ) torch.manual_seed(0 ) __a = DDIMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=__lowercase , set_alpha_to_one=__lowercase , ) torch.manual_seed(0 ) __a = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) torch.manual_seed(0 ) __a = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) __a = CLIPTextModel(__lowercase ) __a = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) __a = MultiControlNetModel([controlneta, controlneta] ) __a = { """unet""": unet, """controlnet""": controlnet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def UpperCamelCase_ ( self : List[str] , __lowercase : Any , __lowercase : str=0 ): '''simple docstring''' if str(__lowercase ).startswith("""mps""" ): __a = torch.manual_seed(__lowercase ) else: __a = torch.Generator(device=__lowercase ).manual_seed(__lowercase ) __a = 2 __a = [ randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=__lowercase , device=torch.device(__lowercase ) , ), randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=__lowercase , device=torch.device(__lowercase ) , ), ] __a = floats_tensor(control_image[0].shape , rng=random.Random(__lowercase ) ).to(__lowercase ) __a = image.cpu().permute(0 , 2 , 3 , 1 )[0] __a = Image.fromarray(np.uinta(__lowercase ) ).convert("""RGB""" ).resize((64, 64) ) __a = { """prompt""": """A painting of a squirrel eating a burger""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", """image""": image, """control_image""": control_image, } return inputs def UpperCamelCase_ ( self : int ): '''simple docstring''' __a = self.get_dummy_components() __a = self.pipeline_class(**__lowercase ) pipe.to(__lowercase ) __a = 10.0 __a = 4 __a = self.get_dummy_inputs(__lowercase ) __a = steps __a = scale __a = pipe(**__lowercase )[0] __a = self.get_dummy_inputs(__lowercase ) __a = steps __a = scale __a = pipe(**__lowercase , control_guidance_start=0.1 , control_guidance_end=0.2 )[0] __a = self.get_dummy_inputs(__lowercase ) __a = steps __a = scale __a = pipe(**__lowercase , control_guidance_start=[0.1, 0.3] , control_guidance_end=[0.2, 0.7] )[0] __a = self.get_dummy_inputs(__lowercase ) __a = steps __a = scale __a = pipe(**__lowercase , control_guidance_start=0.4 , control_guidance_end=[0.5, 0.8] )[0] # make sure that all outputs are different assert np.sum(np.abs(output_a - output_a ) ) > 1E-3 assert np.sum(np.abs(output_a - output_a ) ) > 1E-3 assert np.sum(np.abs(output_a - output_a ) ) > 1E-3 def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' return self._test_attention_slicing_forward_pass(expected_max_diff=2E-3 ) @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2E-3 ) def UpperCamelCase_ ( self : str ): '''simple docstring''' self._test_inference_batch_single_identical(expected_max_diff=2E-3 ) def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' __a = self.get_dummy_components() __a = self.pipeline_class(**__lowercase ) pipe.to(__lowercase ) pipe.set_progress_bar_config(disable=__lowercase ) with tempfile.TemporaryDirectory() as tmpdir: try: # save_pretrained is not implemented for Multi-ControlNet pipe.save_pretrained(__lowercase ) except NotImplementedError: pass @slow @require_torch_gpu class SCREAMING_SNAKE_CASE ( unittest.TestCase ): def UpperCamelCase_ ( self : Optional[int] ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase_ ( self : Dict ): '''simple docstring''' __a = ControlNetModel.from_pretrained("""lllyasviel/sd-controlnet-canny""" ) __a = StableDiffusionControlNetImgaImgPipeline.from_pretrained( """runwayml/stable-diffusion-v1-5""" , safety_checker=__lowercase , controlnet=__lowercase ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=__lowercase ) __a = torch.Generator(device="""cpu""" ).manual_seed(0 ) __a = """evil space-punk bird""" __a = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png""" ).resize((512, 512) ) __a = load_image( """https://huggingface.co/lllyasviel/sd-controlnet-canny/resolve/main/images/bird.png""" ).resize((512, 512) ) __a = pipe( __lowercase , __lowercase , control_image=__lowercase , generator=__lowercase , output_type="""np""" , num_inference_steps=50 , strength=0.6 , ) __a = output.images[0] assert image.shape == (512, 512, 3) __a = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/img2img.npy""" ) assert np.abs(expected_image - image ).max() < 9E-2
302
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, ChannelDimension, ImageInput, PILImageResampling, is_batched, to_numpy_array, valid_images, ) from ...utils import TensorType, logging lowerCamelCase__ = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : Dict =['pixel_values'] def __init__( self : Optional[int] , __lowercase : bool = True , __lowercase : Optional[Dict[str, int]] = None , __lowercase : PILImageResampling = PILImageResampling.BICUBIC , __lowercase : bool = True , __lowercase : bool = True , __lowercase : Union[int, float] = 1 / 255 , __lowercase : Dict[str, int] = None , __lowercase : bool = True , __lowercase : Optional[Union[float, List[float]]] = None , __lowercase : Optional[Union[float, List[float]]] = None , **__lowercase : Dict , ): '''simple docstring''' super().__init__(**__lowercase ) __a = size if size is not None else {"""height""": 224, """width""": 224} __a = get_size_dict(__lowercase ) __a = crop_size if crop_size is not None else {"""height""": 224, """width""": 224} __a = get_size_dict(__lowercase , default_to_square=__lowercase , param_name="""crop_size""" ) __a = do_resize __a = do_rescale __a = do_normalize __a = do_center_crop __a = crop_size __a = size __a = resample __a = rescale_factor __a = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN __a = image_std if image_std is not None else IMAGENET_DEFAULT_STD def UpperCamelCase_ ( self : Any , __lowercase : np.ndarray , __lowercase : Dict[str, int] , __lowercase : PILImageResampling = PILImageResampling.BILINEAR , __lowercase : Optional[Union[str, ChannelDimension]] = None , **__lowercase : Optional[Any] , ): '''simple docstring''' __a = get_size_dict(__lowercase ) if "shortest_edge" in size: __a = get_resize_output_image_size(__lowercase , size=size["""shortest_edge"""] , default_to_square=__lowercase ) # size = get_resize_output_image_size(image, size["shortest_edge"], size["longest_edge"]) elif "height" in size and "width" in size: __a = (size["""height"""], size["""width"""]) else: raise ValueError(F"Size must contain 'height' and 'width' keys or 'shortest_edge' key. Got {size.keys()}" ) return resize(__lowercase , size=__lowercase , resample=__lowercase , data_format=__lowercase , **__lowercase ) def UpperCamelCase_ ( self : str , __lowercase : np.ndarray , __lowercase : Dict[str, int] , __lowercase : Optional[Union[str, ChannelDimension]] = None , **__lowercase : List[Any] , ): '''simple docstring''' __a = get_size_dict(__lowercase ) if "height" not in size or "width" not in size: raise ValueError(F"The `size` parameter must contain the keys (height, width). Got {size.keys()}" ) return center_crop(__lowercase , size=(size["""height"""], size["""width"""]) , data_format=__lowercase , **__lowercase ) def UpperCamelCase_ ( self : Any , __lowercase : np.ndarray , __lowercase : float , __lowercase : Optional[Union[str, ChannelDimension]] = None , **__lowercase : str ): '''simple docstring''' return rescale(__lowercase , scale=__lowercase , data_format=__lowercase , **__lowercase ) def UpperCamelCase_ ( self : List[Any] , __lowercase : np.ndarray , __lowercase : Union[float, List[float]] , __lowercase : Union[float, List[float]] , __lowercase : Optional[Union[str, ChannelDimension]] = None , **__lowercase : Any , ): '''simple docstring''' return normalize(__lowercase , mean=__lowercase , std=__lowercase , data_format=__lowercase , **__lowercase ) def UpperCamelCase_ ( self : Tuple , __lowercase : ImageInput , __lowercase : Optional[bool] = None , __lowercase : Dict[str, int] = None , __lowercase : PILImageResampling = None , __lowercase : bool = None , __lowercase : int = None , __lowercase : Optional[bool] = None , __lowercase : Optional[float] = None , __lowercase : Optional[bool] = None , __lowercase : Optional[Union[float, List[float]]] = None , __lowercase : Optional[Union[float, List[float]]] = None , __lowercase : Optional[Union[str, TensorType]] = None , __lowercase : Union[str, ChannelDimension] = ChannelDimension.FIRST , **__lowercase : List[Any] , ): '''simple docstring''' __a = do_resize if do_resize is not None else self.do_resize __a = do_rescale if do_rescale is not None else self.do_rescale __a = do_normalize if do_normalize is not None else self.do_normalize __a = do_center_crop if do_center_crop is not None else self.do_center_crop __a = crop_size if crop_size is not None else self.crop_size __a = get_size_dict(__lowercase , param_name="""crop_size""" , default_to_square=__lowercase ) __a = resample if resample is not None else self.resample __a = rescale_factor if rescale_factor is not None else self.rescale_factor __a = image_mean if image_mean is not None else self.image_mean __a = image_std if image_std is not None else self.image_std __a = size if size is not None else self.size __a = get_size_dict(__lowercase ) if not is_batched(__lowercase ): __a = [images] if not valid_images(__lowercase ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None: raise ValueError("""Size must be specified if do_resize is True.""" ) if do_center_crop and crop_size is None: raise ValueError("""Crop size must be specified if do_center_crop is True.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) # All transformations expect numpy arrays. __a = [to_numpy_array(__lowercase ) for image in images] if do_resize: __a = [self.resize(image=__lowercase , size=__lowercase , resample=__lowercase ) for image in images] if do_center_crop: __a = [self.center_crop(image=__lowercase , size=__lowercase ) for image in images] if do_rescale: __a = [self.rescale(image=__lowercase , scale=__lowercase ) for image in images] if do_normalize: __a = [self.normalize(image=__lowercase , mean=__lowercase , std=__lowercase ) for image in images] __a = [to_channel_dimension_format(__lowercase , __lowercase ) for image in images] __a = {"""pixel_values""": images} return BatchFeature(data=__lowercase , tensor_type=__lowercase )
302
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tensorflow_text_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase__ = { """configuration_bert""": ["""BERT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """BertConfig""", """BertOnnxConfig"""], """tokenization_bert""": ["""BasicTokenizer""", """BertTokenizer""", """WordpieceTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = ["""BertTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ """BERT_PRETRAINED_MODEL_ARCHIVE_LIST""", """BertForMaskedLM""", """BertForMultipleChoice""", """BertForNextSentencePrediction""", """BertForPreTraining""", """BertForQuestionAnswering""", """BertForSequenceClassification""", """BertForTokenClassification""", """BertLayer""", """BertLMHeadModel""", """BertModel""", """BertPreTrainedModel""", """load_tf_weights_in_bert""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ """TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFBertEmbeddings""", """TFBertForMaskedLM""", """TFBertForMultipleChoice""", """TFBertForNextSentencePrediction""", """TFBertForPreTraining""", """TFBertForQuestionAnswering""", """TFBertForSequenceClassification""", """TFBertForTokenClassification""", """TFBertLMHeadModel""", """TFBertMainLayer""", """TFBertModel""", """TFBertPreTrainedModel""", ] try: if not is_tensorflow_text_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = ["""TFBertTokenizer"""] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ """FlaxBertForCausalLM""", """FlaxBertForMaskedLM""", """FlaxBertForMultipleChoice""", """FlaxBertForNextSentencePrediction""", """FlaxBertForPreTraining""", """FlaxBertForQuestionAnswering""", """FlaxBertForSequenceClassification""", """FlaxBertForTokenClassification""", """FlaxBertModel""", """FlaxBertPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_bert import BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BertConfig, BertOnnxConfig from .tokenization_bert import BasicTokenizer, BertTokenizer, WordpieceTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bert_fast import BertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bert import ( BERT_PRETRAINED_MODEL_ARCHIVE_LIST, BertForMaskedLM, BertForMultipleChoice, BertForNextSentencePrediction, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, BertForTokenClassification, BertLayer, BertLMHeadModel, BertModel, BertPreTrainedModel, load_tf_weights_in_bert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_bert import ( TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFBertEmbeddings, TFBertForMaskedLM, TFBertForMultipleChoice, TFBertForNextSentencePrediction, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertForTokenClassification, TFBertLMHeadModel, TFBertMainLayer, TFBertModel, TFBertPreTrainedModel, ) try: if not is_tensorflow_text_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bert_tf import TFBertTokenizer try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_bert import ( FlaxBertForCausalLM, FlaxBertForMaskedLM, FlaxBertForMultipleChoice, FlaxBertForNextSentencePrediction, FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification, FlaxBertForTokenClassification, FlaxBertModel, FlaxBertPreTrainedModel, ) else: import sys lowerCamelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
302
import tempfile import unittest from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from transformers.testing_utils import ( is_torch_available, require_optimum, require_torch, slow, ) if is_torch_available(): import torch @require_torch @require_optimum @slow class SCREAMING_SNAKE_CASE ( unittest.TestCase ): def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' __a = """hf-internal-testing/tiny-random-t5""" __a = AutoTokenizer.from_pretrained(__lowercase ) __a = AutoModelForSeqaSeqLM.from_pretrained(__lowercase ) __a = tokenizer("""This is me""" , return_tensors="""pt""" ) __a = model.to_bettertransformer() self.assertTrue(any("""BetterTransformer""" in mod.__class__.__name__ for _, mod in model.named_modules() ) ) __a = model.generate(**__lowercase ) __a = model.reverse_bettertransformer() self.assertFalse(any("""BetterTransformer""" in mod.__class__.__name__ for _, mod in model.named_modules() ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(__lowercase ) __a = AutoModelForSeqaSeqLM.from_pretrained(__lowercase ) self.assertFalse( any("""BetterTransformer""" in mod.__class__.__name__ for _, mod in model_reloaded.named_modules() ) ) __a = model_reloaded.generate(**__lowercase ) self.assertTrue(torch.allclose(__lowercase , __lowercase ) ) def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' __a = """hf-internal-testing/tiny-random-t5""" __a = AutoModelForSeqaSeqLM.from_pretrained(__lowercase ) __a = model.to_bettertransformer() with tempfile.TemporaryDirectory() as tmpdirname: with self.assertRaises(__lowercase ): model.save_pretrained(__lowercase ) __a = model.reverse_bettertransformer() model.save_pretrained(__lowercase )
302
1
import unittest from diffusers.models.unet_ad_blocks import * # noqa F403 from diffusers.utils import torch_device from .test_unet_blocks_common import UNetBlockTesterMixin class SCREAMING_SNAKE_CASE ( lowerCamelCase__ , unittest.TestCase ): __lowerCamelCase : Any =DownBlockaD # noqa F405 __lowerCamelCase : List[Any] ='down' def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' __a = [-0.0232, -0.9869, 0.8054, -0.0637, -0.1688, -1.4264, 0.4470, -1.3394, 0.0904] super().test_output(__lowercase ) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ , unittest.TestCase ): __lowerCamelCase : Optional[Any] =ResnetDownsampleBlockaD # noqa F405 __lowerCamelCase : Optional[Any] ='down' def UpperCamelCase_ ( self : Dict ): '''simple docstring''' __a = [0.0710, 0.2410, -0.7320, -1.0757, -1.1343, 0.3540, -0.0133, -0.2576, 0.0948] super().test_output(__lowercase ) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ , unittest.TestCase ): __lowerCamelCase : Any =AttnDownBlockaD # noqa F405 __lowerCamelCase : Any ='down' def UpperCamelCase_ ( self : str ): '''simple docstring''' __a = [0.0636, 0.8964, -0.6234, -1.0131, 0.0844, 0.4935, 0.3437, 0.0911, -0.2957] super().test_output(__lowercase ) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ , unittest.TestCase ): __lowerCamelCase : Optional[int] =CrossAttnDownBlockaD # noqa F405 __lowerCamelCase : Optional[int] ='down' def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' __a , __a = super().prepare_init_args_and_inputs_for_common() __a = 32 return init_dict, inputs_dict def UpperCamelCase_ ( self : Dict ): '''simple docstring''' __a = [0.2238, -0.7396, -0.2255, -0.3829, 0.1925, 1.1665, 0.0603, -0.7295, 0.1983] super().test_output(__lowercase ) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ , unittest.TestCase ): __lowerCamelCase : Any =SimpleCrossAttnDownBlockaD # noqa F405 __lowerCamelCase : Any ='down' @property def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' return super().get_dummy_input(include_encoder_hidden_states=__lowercase ) def UpperCamelCase_ ( self : Any ): '''simple docstring''' __a , __a = super().prepare_init_args_and_inputs_for_common() __a = 32 return init_dict, inputs_dict @unittest.skipIf(torch_device == """mps""" , """MPS result is not consistent""" ) def UpperCamelCase_ ( self : str ): '''simple docstring''' __a = [0.7921, -0.0992, -0.1962, -0.7695, -0.4242, 0.7804, 0.4737, 0.2765, 0.3338] super().test_output(__lowercase ) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ , unittest.TestCase ): __lowerCamelCase : Tuple =SkipDownBlockaD # noqa F405 __lowerCamelCase : List[str] ='down' @property def UpperCamelCase_ ( self : int ): '''simple docstring''' return super().get_dummy_input(include_skip_sample=__lowercase ) def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' __a = [-0.0845, -0.2087, -0.2465, 0.0971, 0.1900, -0.0484, 0.2664, 0.4179, 0.5069] super().test_output(__lowercase ) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ , unittest.TestCase ): __lowerCamelCase : str =AttnSkipDownBlockaD # noqa F405 __lowerCamelCase : str ='down' @property def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' return super().get_dummy_input(include_skip_sample=__lowercase ) def UpperCamelCase_ ( self : str ): '''simple docstring''' __a = [0.5539, 0.1609, 0.4924, 0.0537, -0.1995, 0.4050, 0.0979, -0.2721, -0.0642] super().test_output(__lowercase ) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ , unittest.TestCase ): __lowerCamelCase : List[Any] =DownEncoderBlockaD # noqa F405 __lowerCamelCase : Dict ='down' @property def UpperCamelCase_ ( self : Optional[int] ): '''simple docstring''' return super().get_dummy_input(include_temb=__lowercase ) def UpperCamelCase_ ( self : str ): '''simple docstring''' __a = { """in_channels""": 32, """out_channels""": 32, } __a = self.dummy_input return init_dict, inputs_dict def UpperCamelCase_ ( self : int ): '''simple docstring''' __a = [1.1102, 0.5302, 0.4872, -0.0023, -0.8042, 0.0483, -0.3489, -0.5632, 0.7626] super().test_output(__lowercase ) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ , unittest.TestCase ): __lowerCamelCase : Optional[Any] =AttnDownEncoderBlockaD # noqa F405 __lowerCamelCase : List[str] ='down' @property def UpperCamelCase_ ( self : Dict ): '''simple docstring''' return super().get_dummy_input(include_temb=__lowercase ) def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' __a = { """in_channels""": 32, """out_channels""": 32, } __a = self.dummy_input return init_dict, inputs_dict def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' __a = [0.8966, -0.1486, 0.8568, 0.8141, -0.9046, -0.1342, -0.0972, -0.7417, 0.1538] super().test_output(__lowercase ) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ , unittest.TestCase ): __lowerCamelCase : str =UNetMidBlockaD # noqa F405 __lowerCamelCase : Any ='mid' def UpperCamelCase_ ( self : int ): '''simple docstring''' __a = { """in_channels""": 32, """temb_channels""": 128, } __a = self.dummy_input return init_dict, inputs_dict def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' __a = [-0.1062, 1.7248, 0.3494, 1.4569, -0.0910, -1.2421, -0.9984, 0.6736, 1.0028] super().test_output(__lowercase ) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ , unittest.TestCase ): __lowerCamelCase : List[Any] =UNetMidBlockaDCrossAttn # noqa F405 __lowerCamelCase : str ='mid' def UpperCamelCase_ ( self : int ): '''simple docstring''' __a , __a = super().prepare_init_args_and_inputs_for_common() __a = 32 return init_dict, inputs_dict def UpperCamelCase_ ( self : int ): '''simple docstring''' __a = [0.0187, 2.4220, 0.4484, 1.1203, -0.6121, -1.5122, -0.8270, 0.7851, 1.8335] super().test_output(__lowercase ) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ , unittest.TestCase ): __lowerCamelCase : Any =UNetMidBlockaDSimpleCrossAttn # noqa F405 __lowerCamelCase : List[Any] ='mid' @property def UpperCamelCase_ ( self : str ): '''simple docstring''' return super().get_dummy_input(include_encoder_hidden_states=__lowercase ) def UpperCamelCase_ ( self : Optional[int] ): '''simple docstring''' __a , __a = super().prepare_init_args_and_inputs_for_common() __a = 32 return init_dict, inputs_dict def UpperCamelCase_ ( self : Any ): '''simple docstring''' __a = [0.7143, 1.9974, 0.5448, 1.3977, 0.1282, -1.1237, -1.4238, 0.5530, 0.8880] super().test_output(__lowercase ) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ , unittest.TestCase ): __lowerCamelCase : Optional[int] =UpBlockaD # noqa F405 __lowerCamelCase : int ='up' @property def UpperCamelCase_ ( self : int ): '''simple docstring''' return super().get_dummy_input(include_res_hidden_states_tuple=__lowercase ) def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' __a = [-0.2041, -0.4165, -0.3022, 0.0041, -0.6628, -0.7053, 0.1928, -0.0325, 0.0523] super().test_output(__lowercase ) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ , unittest.TestCase ): __lowerCamelCase : str =ResnetUpsampleBlockaD # noqa F405 __lowerCamelCase : Union[str, Any] ='up' @property def UpperCamelCase_ ( self : str ): '''simple docstring''' return super().get_dummy_input(include_res_hidden_states_tuple=__lowercase ) def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' __a = [0.2287, 0.3549, -0.1346, 0.4797, -0.1715, -0.9649, 0.7305, -0.5864, -0.6244] super().test_output(__lowercase ) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ , unittest.TestCase ): __lowerCamelCase : List[Any] =CrossAttnUpBlockaD # noqa F405 __lowerCamelCase : Optional[Any] ='up' @property def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' return super().get_dummy_input(include_res_hidden_states_tuple=__lowercase ) def UpperCamelCase_ ( self : int ): '''simple docstring''' __a , __a = super().prepare_init_args_and_inputs_for_common() __a = 32 return init_dict, inputs_dict def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' __a = [-0.1403, -0.3515, -0.0420, -0.1425, 0.3167, 0.5094, -0.2181, 0.5931, 0.5582] super().test_output(__lowercase ) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ , unittest.TestCase ): __lowerCamelCase : Tuple =SimpleCrossAttnUpBlockaD # noqa F405 __lowerCamelCase : Any ='up' @property def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' return super().get_dummy_input(include_res_hidden_states_tuple=__lowercase , include_encoder_hidden_states=__lowercase ) def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' __a , __a = super().prepare_init_args_and_inputs_for_common() __a = 32 return init_dict, inputs_dict def UpperCamelCase_ ( self : Any ): '''simple docstring''' __a = [0.2645, 0.1480, 0.0909, 0.8044, -0.9758, -0.9083, 0.0994, -1.1453, -0.7402] super().test_output(__lowercase ) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ , unittest.TestCase ): __lowerCamelCase : Any =AttnUpBlockaD # noqa F405 __lowerCamelCase : Any ='up' @property def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' return super().get_dummy_input(include_res_hidden_states_tuple=__lowercase ) @unittest.skipIf(torch_device == """mps""" , """MPS result is not consistent""" ) def UpperCamelCase_ ( self : str ): '''simple docstring''' __a = [0.0979, 0.1326, 0.0021, 0.0659, 0.2249, 0.0059, 0.1132, 0.5952, 0.1033] super().test_output(__lowercase ) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ , unittest.TestCase ): __lowerCamelCase : Dict =SkipUpBlockaD # noqa F405 __lowerCamelCase : List[Any] ='up' @property def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' return super().get_dummy_input(include_res_hidden_states_tuple=__lowercase ) def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' __a = [-0.0893, -0.1234, -0.1506, -0.0332, 0.0123, -0.0211, 0.0566, 0.0143, 0.0362] super().test_output(__lowercase ) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ , unittest.TestCase ): __lowerCamelCase : List[Any] =AttnSkipUpBlockaD # noqa F405 __lowerCamelCase : List[str] ='up' @property def UpperCamelCase_ ( self : int ): '''simple docstring''' return super().get_dummy_input(include_res_hidden_states_tuple=__lowercase ) def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' __a = [0.0361, 0.0617, 0.2787, -0.0350, 0.0342, 0.3421, -0.0843, 0.0913, 0.3015] super().test_output(__lowercase ) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ , unittest.TestCase ): __lowerCamelCase : Tuple =UpDecoderBlockaD # noqa F405 __lowerCamelCase : List[Any] ='up' @property def UpperCamelCase_ ( self : str ): '''simple docstring''' return super().get_dummy_input(include_temb=__lowercase ) def UpperCamelCase_ ( self : Any ): '''simple docstring''' __a = {"""in_channels""": 32, """out_channels""": 32} __a = self.dummy_input return init_dict, inputs_dict def UpperCamelCase_ ( self : str ): '''simple docstring''' __a = [0.4404, 0.1998, -0.9886, -0.3320, -0.3128, -0.7034, -0.6955, -0.2338, -0.3137] super().test_output(__lowercase ) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ , unittest.TestCase ): __lowerCamelCase : Optional[int] =AttnUpDecoderBlockaD # noqa F405 __lowerCamelCase : Optional[Any] ='up' @property def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' return super().get_dummy_input(include_temb=__lowercase ) def UpperCamelCase_ ( self : str ): '''simple docstring''' __a = {"""in_channels""": 32, """out_channels""": 32} __a = self.dummy_input return init_dict, inputs_dict def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' __a = [0.6738, 0.4491, 0.1055, 1.0710, 0.7316, 0.3339, 0.3352, 0.1023, 0.3568] super().test_output(__lowercase )
302
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig lowerCamelCase__ = { """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/config.json""", """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/config.json""", """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/config.json""", """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/config.json""", """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/config.json""", """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/config.json""", """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/config.json""", """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/config.json""", } class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : Optional[Any] ='albert' def __init__( self : Optional[Any] , __lowercase : Union[str, Any]=30000 , __lowercase : List[str]=128 , __lowercase : Optional[Any]=4096 , __lowercase : Dict=12 , __lowercase : Any=1 , __lowercase : Optional[Any]=64 , __lowercase : Any=16384 , __lowercase : Any=1 , __lowercase : Union[str, Any]="gelu_new" , __lowercase : List[str]=0 , __lowercase : int=0 , __lowercase : Dict=512 , __lowercase : str=2 , __lowercase : List[str]=0.02 , __lowercase : Union[str, Any]=1E-12 , __lowercase : int=0.1 , __lowercase : Any="absolute" , __lowercase : Optional[int]=0 , __lowercase : Dict=2 , __lowercase : Optional[Any]=3 , **__lowercase : Any , ): '''simple docstring''' super().__init__(pad_token_id=__lowercase , bos_token_id=__lowercase , eos_token_id=__lowercase , **__lowercase ) __a = vocab_size __a = embedding_size __a = hidden_size __a = num_hidden_layers __a = num_hidden_groups __a = num_attention_heads __a = inner_group_num __a = hidden_act __a = intermediate_size __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = type_vocab_size __a = initializer_range __a = layer_norm_eps __a = classifier_dropout_prob __a = position_embedding_type class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): @property def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' if self.task == "multiple-choice": __a = {0: """batch""", 1: """choice""", 2: """sequence"""} else: __a = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis), ] )
302
1
from dataclasses import asdict, dataclass from typing import Optional from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase__ = logging.get_logger(__name__) # TODO Update this lowerCamelCase__ = { """facebook/esm-1b""": """https://huggingface.co/facebook/esm-1b/resolve/main/config.json""", # See all ESM models at https://huggingface.co/models?filter=esm } class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : Optional[int] ='esm' def __init__( self : str , __lowercase : Optional[Any]=None , __lowercase : Optional[Any]=None , __lowercase : Optional[int]=None , __lowercase : Union[str, Any]=768 , __lowercase : Optional[int]=12 , __lowercase : Dict=12 , __lowercase : Optional[Any]=3072 , __lowercase : Optional[Any]=0.1 , __lowercase : Dict=0.1 , __lowercase : int=1026 , __lowercase : int=0.02 , __lowercase : List[Any]=1E-12 , __lowercase : Dict="absolute" , __lowercase : Union[str, Any]=True , __lowercase : str=None , __lowercase : Any=False , __lowercase : Dict=False , __lowercase : int=None , __lowercase : str=None , **__lowercase : str , ): '''simple docstring''' super().__init__(pad_token_id=__lowercase , mask_token_id=__lowercase , **__lowercase ) __a = vocab_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = initializer_range __a = layer_norm_eps __a = position_embedding_type __a = use_cache __a = emb_layer_norm_before __a = token_dropout __a = is_folding_model if is_folding_model: if esmfold_config is None: logger.info("""No esmfold_config supplied for folding model, using default values.""" ) __a = EsmFoldConfig() elif isinstance(__lowercase , __lowercase ): __a = EsmFoldConfig(**__lowercase ) __a = esmfold_config if vocab_list is None: logger.warning("""No vocab_list supplied for folding model, assuming the ESM-2 vocabulary!""" ) __a = get_default_vocab_list() else: __a = vocab_list else: __a = None __a = None if self.esmfold_config is not None and getattr(self.esmfold_config , """use_esm_attn_map""" , __lowercase ): raise ValueError("""The HuggingFace port of ESMFold does not support use_esm_attn_map at this time!""" ) def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' __a = super().to_dict() if isinstance(self.esmfold_config , __lowercase ): __a = self.esmfold_config.to_dict() return output @dataclass class SCREAMING_SNAKE_CASE : __lowerCamelCase : str =None __lowerCamelCase : bool =True __lowerCamelCase : bool =False __lowerCamelCase : bool =False __lowerCamelCase : bool =False __lowerCamelCase : float =0 __lowerCamelCase : bool =True __lowerCamelCase : bool =False __lowerCamelCase : int =128 __lowerCamelCase : "TrunkConfig" =None def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' if self.trunk is None: __a = TrunkConfig() elif isinstance(self.trunk , __lowercase ): __a = TrunkConfig(**self.trunk ) def UpperCamelCase_ ( self : int ): '''simple docstring''' __a = asdict(self ) __a = self.trunk.to_dict() return output @dataclass class SCREAMING_SNAKE_CASE : __lowerCamelCase : int =48 __lowerCamelCase : int =1_024 __lowerCamelCase : int =128 __lowerCamelCase : int =32 __lowerCamelCase : int =32 __lowerCamelCase : int =32 __lowerCamelCase : float =0 __lowerCamelCase : float =0 __lowerCamelCase : bool =False __lowerCamelCase : int =4 __lowerCamelCase : Optional[int] =128 __lowerCamelCase : "StructureModuleConfig" =None def UpperCamelCase_ ( self : Any ): '''simple docstring''' if self.structure_module is None: __a = StructureModuleConfig() elif isinstance(self.structure_module , __lowercase ): __a = StructureModuleConfig(**self.structure_module ) if self.max_recycles <= 0: raise ValueError(F"`max_recycles` should be positive, got {self.max_recycles}." ) if self.sequence_state_dim % self.sequence_state_dim != 0: raise ValueError( """`sequence_state_dim` should be a round multiple of `sequence_state_dim`, got""" F" {self.sequence_state_dim} and {self.sequence_state_dim}." ) if self.pairwise_state_dim % self.pairwise_state_dim != 0: raise ValueError( """`pairwise_state_dim` should be a round multiple of `pairwise_state_dim`, got""" F" {self.pairwise_state_dim} and {self.pairwise_state_dim}." ) __a = self.sequence_state_dim // self.sequence_head_width __a = self.pairwise_state_dim // self.pairwise_head_width if self.sequence_state_dim != sequence_num_heads * self.sequence_head_width: raise ValueError( """`sequence_state_dim` should be equal to `sequence_num_heads * sequence_head_width, got""" F" {self.sequence_state_dim} != {sequence_num_heads} * {self.sequence_head_width}." ) if self.pairwise_state_dim != pairwise_num_heads * self.pairwise_head_width: raise ValueError( """`pairwise_state_dim` should be equal to `pairwise_num_heads * pairwise_head_width, got""" F" {self.pairwise_state_dim} != {pairwise_num_heads} * {self.pairwise_head_width}." ) if self.pairwise_state_dim % 2 != 0: raise ValueError(F"`pairwise_state_dim` should be even, got {self.pairwise_state_dim}." ) if self.dropout >= 0.4: raise ValueError(F"`dropout` should not be greater than 0.4, got {self.dropout}." ) def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' __a = asdict(self ) __a = self.structure_module.to_dict() return output @dataclass class SCREAMING_SNAKE_CASE : __lowerCamelCase : int =384 __lowerCamelCase : int =128 __lowerCamelCase : int =16 __lowerCamelCase : int =128 __lowerCamelCase : int =12 __lowerCamelCase : int =4 __lowerCamelCase : int =8 __lowerCamelCase : float =0.1 __lowerCamelCase : int =8 __lowerCamelCase : int =1 __lowerCamelCase : int =2 __lowerCamelCase : int =7 __lowerCamelCase : int =10 __lowerCamelCase : float =1e-8 __lowerCamelCase : float =1e5 def UpperCamelCase_ ( self : Dict ): '''simple docstring''' return asdict(self ) def lowerCAmelCase__ ( ): """simple docstring""" return ( "<cls>", "<pad>", "<eos>", "<unk>", "L", "A", "G", "V", "S", "E", "R", "T", "I", "D", "P", "K", "Q", "N", "F", "Y", "M", "H", "W", "C", "X", "B", "U", "Z", "O", ".", "-", "<null_1>", "<mask>", )
302
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) lowerCamelCase__ = { """configuration_blip""": [ """BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP""", """BlipConfig""", """BlipTextConfig""", """BlipVisionConfig""", ], """processing_blip""": ["""BlipProcessor"""], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = ["""BlipImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ """BLIP_PRETRAINED_MODEL_ARCHIVE_LIST""", """BlipModel""", """BlipPreTrainedModel""", """BlipForConditionalGeneration""", """BlipForQuestionAnswering""", """BlipVisionModel""", """BlipTextModel""", """BlipForImageTextRetrieval""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ """TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFBlipModel""", """TFBlipPreTrainedModel""", """TFBlipForConditionalGeneration""", """TFBlipForQuestionAnswering""", """TFBlipVisionModel""", """TFBlipTextModel""", """TFBlipForImageTextRetrieval""", ] if TYPE_CHECKING: from .configuration_blip import BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, BlipConfig, BlipTextConfig, BlipVisionConfig from .processing_blip import BlipProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_blip import BlipImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blip import ( BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, BlipModel, BlipPreTrainedModel, BlipTextModel, BlipVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blip import ( TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFBlipForConditionalGeneration, TFBlipForImageTextRetrieval, TFBlipForQuestionAnswering, TFBlipModel, TFBlipPreTrainedModel, TFBlipTextModel, TFBlipVisionModel, ) else: import sys lowerCamelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
302
1
lowerCamelCase__ = """ # Installazione di Transformers ! pip install transformers datasets # Per installare dalla fonte invece dell'ultima versione rilasciata, commenta il comando sopra e # rimuovi la modalità commento al comando seguente. # ! pip install git+https://github.com/huggingface/transformers.git """ lowerCamelCase__ = [{"""type""": """code""", """content""": INSTALL_CONTENT}] lowerCamelCase__ = { """{processor_class}""": """FakeProcessorClass""", """{model_class}""": """FakeModelClass""", """{object_class}""": """FakeObjectClass""", }
302
class SCREAMING_SNAKE_CASE : def __init__( self : List[Any] , __lowercase : Union[str, Any] ): '''simple docstring''' __a = val __a = None __a = None def UpperCamelCase_ ( self : Union[str, Any] , __lowercase : Any ): '''simple docstring''' if self.val: if val < self.val: if self.left is None: __a = Node(__lowercase ) else: self.left.insert(__lowercase ) elif val > self.val: if self.right is None: __a = Node(__lowercase ) else: self.right.insert(__lowercase ) else: __a = val def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : Any ): """simple docstring""" if root: inorder(root.left , _SCREAMING_SNAKE_CASE ) res.append(root.val ) inorder(root.right , _SCREAMING_SNAKE_CASE ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Any ): """simple docstring""" if len(_SCREAMING_SNAKE_CASE ) == 0: return arr __a = Node(arr[0] ) for i in range(1 , len(_SCREAMING_SNAKE_CASE ) ): root.insert(arr[i] ) # Traverse BST in order. __a = [] inorder(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return res if __name__ == "__main__": print(tree_sort([10, 1, 3, 2, 9, 14, 13]))
302
1
class SCREAMING_SNAKE_CASE : def __init__( self : List[Any] , __lowercase : Union[str, Any] ): '''simple docstring''' __a = val __a = None __a = None def UpperCamelCase_ ( self : Union[str, Any] , __lowercase : Any ): '''simple docstring''' if self.val: if val < self.val: if self.left is None: __a = Node(__lowercase ) else: self.left.insert(__lowercase ) elif val > self.val: if self.right is None: __a = Node(__lowercase ) else: self.right.insert(__lowercase ) else: __a = val def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : Any ): """simple docstring""" if root: inorder(root.left , _SCREAMING_SNAKE_CASE ) res.append(root.val ) inorder(root.right , _SCREAMING_SNAKE_CASE ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Any ): """simple docstring""" if len(_SCREAMING_SNAKE_CASE ) == 0: return arr __a = Node(arr[0] ) for i in range(1 , len(_SCREAMING_SNAKE_CASE ) ): root.insert(arr[i] ) # Traverse BST in order. __a = [] inorder(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return res if __name__ == "__main__": print(tree_sort([10, 1, 3, 2, 9, 14, 13]))
302
import inspect import unittest from transformers import MobileViTVaConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, MobileViTVaModel from transformers.models.mobilevitva.modeling_mobilevitva import ( MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST, make_divisible, ) if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): def UpperCamelCase_ ( self : str ): '''simple docstring''' __a = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(__lowercase , """width_multiplier""" ) ) class SCREAMING_SNAKE_CASE : def __init__( self : Dict , __lowercase : Union[str, Any] , __lowercase : Dict=13 , __lowercase : int=64 , __lowercase : Tuple=2 , __lowercase : Tuple=3 , __lowercase : Tuple="swish" , __lowercase : List[Any]=3 , __lowercase : List[str]=32 , __lowercase : int=0.1 , __lowercase : Union[str, Any]=0.02 , __lowercase : Optional[int]=True , __lowercase : Dict=True , __lowercase : Tuple=10 , __lowercase : str=None , __lowercase : Optional[Any]=0.25 , __lowercase : str=0.0 , __lowercase : Optional[Any]=0.0 , ): '''simple docstring''' __a = parent __a = batch_size __a = image_size __a = patch_size __a = num_channels __a = make_divisible(512 * width_multiplier , divisor=8 ) __a = hidden_act __a = conv_kernel_size __a = output_stride __a = classifier_dropout_prob __a = use_labels __a = is_training __a = num_labels __a = initializer_range __a = scope __a = width_multiplier __a = ffn_dropout __a = attn_dropout def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' __a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a = None __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.num_labels ) __a = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) __a = self.get_config() return config, pixel_values, labels, pixel_labels def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' return MobileViTVaConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_act=self.hidden_act , conv_kernel_size=self.conv_kernel_size , output_stride=self.output_stride , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , width_multiplier=self.width_multiplier , ffn_dropout=self.ffn_dropout_prob , attn_dropout=self.attn_dropout_prob , ) def UpperCamelCase_ ( self : Tuple , __lowercase : Optional[Any] , __lowercase : int , __lowercase : Optional[Any] , __lowercase : Tuple ): '''simple docstring''' __a = MobileViTVaModel(config=__lowercase ) model.to(__lowercase ) model.eval() __a = model(__lowercase ) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def UpperCamelCase_ ( self : Union[str, Any] , __lowercase : List[Any] , __lowercase : str , __lowercase : Optional[int] , __lowercase : Union[str, Any] ): '''simple docstring''' __a = self.num_labels __a = MobileViTVaForImageClassification(__lowercase ) model.to(__lowercase ) model.eval() __a = model(__lowercase , labels=__lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCamelCase_ ( self : int , __lowercase : str , __lowercase : Any , __lowercase : int , __lowercase : List[str] ): '''simple docstring''' __a = self.num_labels __a = MobileViTVaForSemanticSegmentation(__lowercase ) model.to(__lowercase ) model.eval() __a = model(__lowercase ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) __a = model(__lowercase , labels=__lowercase ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def UpperCamelCase_ ( self : Dict ): '''simple docstring''' __a = self.prepare_config_and_inputs() __a , __a , __a , __a = config_and_inputs __a = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE ( lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase ): __lowerCamelCase : List[Any] =( (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation) if is_torch_available() else () ) __lowerCamelCase : Any =( { 'feature-extraction': MobileViTVaModel, 'image-classification': MobileViTVaForImageClassification, 'image-segmentation': MobileViTVaForSemanticSegmentation, } if is_torch_available() else {} ) __lowerCamelCase : Dict =False __lowerCamelCase : Optional[Any] =False __lowerCamelCase : int =False __lowerCamelCase : Any =False def UpperCamelCase_ ( self : Dict ): '''simple docstring''' __a = MobileViTVaModelTester(self ) __a = MobileViTVaConfigTester(self , config_class=__lowercase , has_text_modality=__lowercase ) def UpperCamelCase_ ( self : Dict ): '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason="""MobileViTV2 does not use inputs_embeds""" ) def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' pass @unittest.skip(reason="""MobileViTV2 does not support input and output embeddings""" ) def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' pass @unittest.skip(reason="""MobileViTV2 does not output attentions""" ) def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' pass @require_torch_multi_gpu @unittest.skip(reason="""Got `CUDA error: misaligned address` for tests after this one being run.""" ) def UpperCamelCase_ ( self : int ): '''simple docstring''' pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' pass def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(__lowercase ) __a = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a = [*signature.parameters.keys()] __a = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , __lowercase ) def UpperCamelCase_ ( self : Dict ): '''simple docstring''' __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowercase ) def UpperCamelCase_ ( self : int ): '''simple docstring''' def check_hidden_states_output(__lowercase : List[str] , __lowercase : Optional[int] , __lowercase : List[str] ): __a = model_class(__lowercase ) model.to(__lowercase ) model.eval() with torch.no_grad(): __a = model(**self._prepare_for_class(__lowercase , __lowercase ) ) __a = outputs.hidden_states __a = 5 self.assertEqual(len(__lowercase ) , __lowercase ) # MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width) # with the width and height being successively divided by 2. __a = 2 for i in range(len(__lowercase ) ): self.assertListEqual( list(hidden_states[i].shape[-2:] ) , [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor] , ) divisor *= 2 self.assertEqual(self.model_tester.output_stride , divisor // 2 ) __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = True check_hidden_states_output(__lowercase , __lowercase , __lowercase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __a = True check_hidden_states_output(__lowercase , __lowercase , __lowercase ) def UpperCamelCase_ ( self : Optional[int] ): '''simple docstring''' __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__lowercase ) def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*__lowercase ) @slow def UpperCamelCase_ ( self : Optional[int] ): '''simple docstring''' for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = MobileViTVaModel.from_pretrained(__lowercase ) self.assertIsNotNone(__lowercase ) def lowerCAmelCase__ ( ): """simple docstring""" __a = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class SCREAMING_SNAKE_CASE ( unittest.TestCase ): @cached_property def UpperCamelCase_ ( self : Dict ): '''simple docstring''' return ( MobileViTImageProcessor.from_pretrained("""apple/mobilevitv2-1.0-imagenet1k-256""" ) if is_vision_available() else None ) @slow def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' __a = MobileViTVaForImageClassification.from_pretrained("""apple/mobilevitv2-1.0-imagenet1k-256""" ).to( __lowercase ) __a = self.default_image_processor __a = prepare_img() __a = image_processor(images=__lowercase , return_tensors="""pt""" ).to(__lowercase ) # forward pass with torch.no_grad(): __a = model(**__lowercase ) # verify the logits __a = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , __lowercase ) __a = torch.tensor([-1.6336E00, -7.3204E-02, -5.1883E-01] ).to(__lowercase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __lowercase , atol=1E-4 ) ) @slow def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' __a = MobileViTVaForSemanticSegmentation.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3""" ) __a = model.to(__lowercase ) __a = MobileViTImageProcessor.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3""" ) __a = prepare_img() __a = image_processor(images=__lowercase , return_tensors="""pt""" ).to(__lowercase ) # forward pass with torch.no_grad(): __a = model(**__lowercase ) __a = outputs.logits # verify the logits __a = torch.Size((1, 21, 32, 32) ) self.assertEqual(logits.shape , __lowercase ) __a = torch.tensor( [ [[7.0863, 7.1525, 6.8201], [6.6931, 6.8770, 6.8933], [6.2978, 7.0366, 6.9636]], [[-3.7134, -3.6712, -3.6675], [-3.5825, -3.3549, -3.4777], [-3.3435, -3.3979, -3.2857]], [[-2.9329, -2.8003, -2.7369], [-3.0564, -2.4780, -2.0207], [-2.6889, -1.9298, -1.7640]], ] , device=__lowercase , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , __lowercase , atol=1E-4 ) ) @slow def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' __a = MobileViTVaForSemanticSegmentation.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3""" ) __a = model.to(__lowercase ) __a = MobileViTImageProcessor.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3""" ) __a = prepare_img() __a = image_processor(images=__lowercase , return_tensors="""pt""" ).to(__lowercase ) # forward pass with torch.no_grad(): __a = model(**__lowercase ) __a = outputs.logits.detach().cpu() __a = image_processor.post_process_semantic_segmentation(outputs=__lowercase , target_sizes=[(50, 60)] ) __a = torch.Size((50, 60) ) self.assertEqual(segmentation[0].shape , __lowercase ) __a = image_processor.post_process_semantic_segmentation(outputs=__lowercase ) __a = torch.Size((32, 32) ) self.assertEqual(segmentation[0].shape , __lowercase )
302
1
import warnings from ...utils import logging from .image_processing_deformable_detr import DeformableDetrImageProcessor lowerCamelCase__ = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): def __init__( self : List[str] , *__lowercase : int , **__lowercase : List[Any] ): '''simple docstring''' warnings.warn( """The class DeformableDetrFeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use DeformableDetrImageProcessor instead.""" , __lowercase , ) super().__init__(*__lowercase , **__lowercase )
302
from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import torch from ...utils import BaseOutput, OptionalDependencyNotAvailable, is_torch_available, is_transformers_available @dataclass class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : Union[List[np.ndarray], torch.FloatTensor] 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_text_to_video_synth import TextToVideoSDPipeline from .pipeline_text_to_video_synth_imgaimg import VideoToVideoSDPipeline # noqa: F401 from .pipeline_text_to_video_zero import TextToVideoZeroPipeline
302
1
import gc import unittest from diffusers import FlaxStableDiffusionInpaintPipeline from diffusers.utils import is_flax_available, load_image, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard @slow @require_flax class SCREAMING_SNAKE_CASE ( unittest.TestCase ): def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' # clean up the VRAM after each test super().tearDown() gc.collect() def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' __a = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) __a = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) __a = """xvjiarui/stable-diffusion-2-inpainting""" __a , __a = FlaxStableDiffusionInpaintPipeline.from_pretrained(__lowercase , safety_checker=__lowercase ) __a = """Face of a yellow cat, high resolution, sitting on a park bench""" __a = jax.random.PRNGKey(0 ) __a = 50 __a = jax.device_count() __a = num_samples * [prompt] __a = num_samples * [init_image] __a = num_samples * [mask_image] __a , __a , __a = pipeline.prepare_inputs(__lowercase , __lowercase , __lowercase ) # shard inputs and rng __a = replicate(__lowercase ) __a = jax.random.split(__lowercase , jax.device_count() ) __a = shard(__lowercase ) __a = shard(__lowercase ) __a = shard(__lowercase ) __a = pipeline( __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , jit=__lowercase ) __a = output.images.reshape(__lowercase , 512 , 512 , 3 ) __a = images[0, 253:256, 253:256, -1] __a = jnp.asarray(jax.device_get(image_slice.flatten() ) ) __a = jnp.array( [0.3611307, 0.37649736, 0.3757408, 0.38213953, 0.39295167, 0.3841631, 0.41554978, 0.4137475, 0.4217084] ) print(F"output_slice: {output_slice}" ) assert jnp.abs(output_slice - expected_slice ).max() < 1E-2
302
import string import numpy def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int ): """simple docstring""" return b if a == 0 else greatest_common_divisor(b % a , _SCREAMING_SNAKE_CASE ) class SCREAMING_SNAKE_CASE : __lowerCamelCase : List[str] =string.ascii_uppercase + string.digits # This cipher takes alphanumerics into account # i.e. a total of 36 characters # take x and return x % len(key_string) __lowerCamelCase : List[Any] =numpy.vectorize(lambda lowerCamelCase__ : x % 36 ) __lowerCamelCase : Optional[Any] =numpy.vectorize(lowerCamelCase__ ) def __init__( self : Union[str, Any] , __lowercase : numpy.ndarray ): '''simple docstring''' __a = self.modulus(__lowercase ) # mod36 calc's on the encrypt key self.check_determinant() # validate the determinant of the encryption key __a = encrypt_key.shape[0] def UpperCamelCase_ ( self : Dict , __lowercase : str ): '''simple docstring''' return self.key_string.index(__lowercase ) def UpperCamelCase_ ( self : Dict , __lowercase : int ): '''simple docstring''' return self.key_string[round(__lowercase )] def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' __a = round(numpy.linalg.det(self.encrypt_key ) ) if det < 0: __a = det % len(self.key_string ) __a = len(self.key_string ) if greatest_common_divisor(__lowercase , len(self.key_string ) ) != 1: __a = ( F"determinant modular {req_l} of encryption key({det}) " F"is not co prime w.r.t {req_l}.\nTry another key." ) raise ValueError(__lowercase ) def UpperCamelCase_ ( self : Dict , __lowercase : str ): '''simple docstring''' __a = [char for char in text.upper() if char in self.key_string] __a = chars[-1] while len(__lowercase ) % self.break_key != 0: chars.append(__lowercase ) return "".join(__lowercase ) def UpperCamelCase_ ( self : List[str] , __lowercase : str ): '''simple docstring''' __a = self.process_text(text.upper() ) __a = """""" for i in range(0 , len(__lowercase ) - self.break_key + 1 , self.break_key ): __a = text[i : i + self.break_key] __a = [self.replace_letters(__lowercase ) for char in batch] __a = numpy.array([vec] ).T __a = self.modulus(self.encrypt_key.dot(__lowercase ) ).T.tolist()[ 0 ] __a = """""".join( self.replace_digits(__lowercase ) for num in batch_encrypted ) encrypted += encrypted_batch return encrypted def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' __a = round(numpy.linalg.det(self.encrypt_key ) ) if det < 0: __a = det % len(self.key_string ) __a = None for i in range(len(self.key_string ) ): if (det * i) % len(self.key_string ) == 1: __a = i break __a = ( det_inv * numpy.linalg.det(self.encrypt_key ) * numpy.linalg.inv(self.encrypt_key ) ) return self.to_int(self.modulus(__lowercase ) ) def UpperCamelCase_ ( self : Any , __lowercase : str ): '''simple docstring''' __a = self.make_decrypt_key() __a = self.process_text(text.upper() ) __a = """""" for i in range(0 , len(__lowercase ) - self.break_key + 1 , self.break_key ): __a = text[i : i + self.break_key] __a = [self.replace_letters(__lowercase ) for char in batch] __a = numpy.array([vec] ).T __a = self.modulus(decrypt_key.dot(__lowercase ) ).T.tolist()[0] __a = """""".join( self.replace_digits(__lowercase ) for num in batch_decrypted ) decrypted += decrypted_batch return decrypted def lowerCAmelCase__ ( ): """simple docstring""" __a = int(input("""Enter the order of the encryption key: """ ) ) __a = [] print("""Enter each row of the encryption key with space separated integers""" ) for _ in range(_SCREAMING_SNAKE_CASE ): __a = [int(_SCREAMING_SNAKE_CASE ) for x in input().split()] hill_matrix.append(_SCREAMING_SNAKE_CASE ) __a = HillCipher(numpy.array(_SCREAMING_SNAKE_CASE ) ) print("""Would you like to encrypt or decrypt some text? (1 or 2)""" ) __a = input("""\n1. Encrypt\n2. Decrypt\n""" ) if option == "1": __a = input("""What text would you like to encrypt?: """ ) print("""Your encrypted text is:""" ) print(hc.encrypt(_SCREAMING_SNAKE_CASE ) ) elif option == "2": __a = input("""What text would you like to decrypt?: """ ) print("""Your decrypted text is:""" ) print(hc.decrypt(_SCREAMING_SNAKE_CASE ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
302
1
import inspect import unittest from transformers import ViTConfig from transformers.testing_utils import ( require_accelerate, require_torch, require_torch_gpu, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ViTForImageClassification, ViTForMaskedImageModeling, ViTModel from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class SCREAMING_SNAKE_CASE : def __init__( self : Tuple , __lowercase : int , __lowercase : List[Any]=13 , __lowercase : Tuple=30 , __lowercase : Dict=2 , __lowercase : Any=3 , __lowercase : Optional[Any]=True , __lowercase : Optional[int]=True , __lowercase : Any=32 , __lowercase : str=5 , __lowercase : str=4 , __lowercase : Optional[int]=37 , __lowercase : int="gelu" , __lowercase : Optional[Any]=0.1 , __lowercase : Any=0.1 , __lowercase : Optional[Any]=10 , __lowercase : List[Any]=0.02 , __lowercase : Optional[int]=None , __lowercase : List[Any]=2 , ): '''simple docstring''' __a = parent __a = batch_size __a = image_size __a = patch_size __a = num_channels __a = is_training __a = use_labels __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = type_sequence_label_size __a = initializer_range __a = scope __a = encoder_stride # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) __a = (image_size // patch_size) ** 2 __a = num_patches + 1 def UpperCamelCase_ ( self : str ): '''simple docstring''' __a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = self.get_config() return config, pixel_values, labels def UpperCamelCase_ ( self : Any ): '''simple docstring''' return ViTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=__lowercase , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def UpperCamelCase_ ( self : List[str] , __lowercase : Dict , __lowercase : str , __lowercase : List[Any] ): '''simple docstring''' __a = ViTModel(config=__lowercase ) model.to(__lowercase ) model.eval() __a = model(__lowercase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase_ ( self : Dict , __lowercase : List[str] , __lowercase : Optional[Any] , __lowercase : Union[str, Any] ): '''simple docstring''' __a = ViTForMaskedImageModeling(config=__lowercase ) model.to(__lowercase ) model.eval() __a = model(__lowercase ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images __a = 1 __a = ViTForMaskedImageModeling(__lowercase ) model.to(__lowercase ) model.eval() __a = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __a = model(__lowercase ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def UpperCamelCase_ ( self : Any , __lowercase : List[Any] , __lowercase : Any , __lowercase : str ): '''simple docstring''' __a = self.type_sequence_label_size __a = ViTForImageClassification(__lowercase ) model.to(__lowercase ) model.eval() __a = model(__lowercase , labels=__lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images __a = 1 __a = ViTForImageClassification(__lowercase ) model.to(__lowercase ) model.eval() __a = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __a = model(__lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' __a = self.prepare_config_and_inputs() ( ( __a ) , ( __a ) , ( __a ) , ) = config_and_inputs __a = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE ( lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase ): __lowerCamelCase : int =( ( ViTModel, ViTForImageClassification, ViTForMaskedImageModeling, ) if is_torch_available() else () ) __lowerCamelCase : Optional[int] =( {'feature-extraction': ViTModel, 'image-classification': ViTForImageClassification} if is_torch_available() else {} ) __lowerCamelCase : Any =True __lowerCamelCase : Tuple =False __lowerCamelCase : Any =False __lowerCamelCase : int =False def UpperCamelCase_ ( self : int ): '''simple docstring''' __a = ViTModelTester(self ) __a = ConfigTester(self , config_class=__lowercase , has_text_modality=__lowercase , hidden_size=37 ) def UpperCamelCase_ ( self : Optional[int] ): '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason="""ViT does not use inputs_embeds""" ) def UpperCamelCase_ ( self : Optional[int] ): '''simple docstring''' pass def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(__lowercase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) __a = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__lowercase , nn.Linear ) ) def UpperCamelCase_ ( self : Dict ): '''simple docstring''' __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(__lowercase ) __a = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a = [*signature.parameters.keys()] __a = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , __lowercase ) def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowercase ) def UpperCamelCase_ ( self : Optional[int] ): '''simple docstring''' __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*__lowercase ) def UpperCamelCase_ ( self : Optional[int] ): '''simple docstring''' __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__lowercase ) @slow def UpperCamelCase_ ( self : Any ): '''simple docstring''' for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = ViTModel.from_pretrained(__lowercase ) self.assertIsNotNone(__lowercase ) def lowerCAmelCase__ ( ): """simple docstring""" __a = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class SCREAMING_SNAKE_CASE ( unittest.TestCase ): @cached_property def UpperCamelCase_ ( self : Any ): '''simple docstring''' return ViTImageProcessor.from_pretrained("""google/vit-base-patch16-224""" ) if is_vision_available() else None @slow def UpperCamelCase_ ( self : int ): '''simple docstring''' __a = ViTForImageClassification.from_pretrained("""google/vit-base-patch16-224""" ).to(__lowercase ) __a = self.default_image_processor __a = prepare_img() __a = image_processor(images=__lowercase , return_tensors="""pt""" ).to(__lowercase ) # forward pass with torch.no_grad(): __a = model(**__lowercase ) # verify the logits __a = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , __lowercase ) __a = torch.tensor([-0.2744, 0.8215, -0.0836] ).to(__lowercase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __lowercase , atol=1E-4 ) ) @slow def UpperCamelCase_ ( self : Any ): '''simple docstring''' # ViT models have an `interpolate_pos_encoding` argument in their forward method, # allowing to interpolate the pre-trained position embeddings in order to use # the model on higher resolutions. The DINO model by Facebook AI leverages this # to visualize self-attention on higher resolution images. __a = ViTModel.from_pretrained("""facebook/dino-vits8""" ).to(__lowercase ) __a = ViTImageProcessor.from_pretrained("""facebook/dino-vits8""" , size=480 ) __a = prepare_img() __a = image_processor(images=__lowercase , return_tensors="""pt""" ) __a = inputs.pixel_values.to(__lowercase ) # forward pass with torch.no_grad(): __a = model(__lowercase , interpolate_pos_encoding=__lowercase ) # verify the logits __a = torch.Size((1, 3601, 384) ) self.assertEqual(outputs.last_hidden_state.shape , __lowercase ) __a = torch.tensor( [[4.2340, 4.3906, -6.6692], [4.5463, 1.8928, -6.7257], [4.4429, 0.8496, -5.8585]] ).to(__lowercase ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3] , __lowercase , atol=1E-4 ) ) @slow @require_accelerate @require_torch_gpu def UpperCamelCase_ ( self : str ): '''simple docstring''' __a = ViTModel.from_pretrained("""facebook/dino-vits8""" , torch_dtype=torch.floataa , device_map="""auto""" ) __a = self.default_image_processor __a = prepare_img() __a = image_processor(images=__lowercase , return_tensors="""pt""" ) __a = inputs.pixel_values.to(__lowercase ) # forward pass to make sure inference works in fp16 with torch.no_grad(): __a = model(__lowercase )
302
from typing import List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { """huggingface/autoformer-tourism-monthly""": """https://huggingface.co/huggingface/autoformer-tourism-monthly/resolve/main/config.json""", } class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : List[Any] ='autoformer' __lowerCamelCase : str ={ 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', 'num_hidden_layers': 'encoder_layers', } def __init__( self : List[Any] , __lowercase : Optional[int] = None , __lowercase : Optional[int] = None , __lowercase : str = "student_t" , __lowercase : str = "nll" , __lowercase : int = 1 , __lowercase : List[int] = [1, 2, 3, 4, 5, 6, 7] , __lowercase : bool = True , __lowercase : int = 0 , __lowercase : int = 0 , __lowercase : int = 0 , __lowercase : int = 0 , __lowercase : Optional[List[int]] = None , __lowercase : Optional[List[int]] = None , __lowercase : int = 64 , __lowercase : int = 2 , __lowercase : int = 2 , __lowercase : int = 2 , __lowercase : int = 2 , __lowercase : int = 32 , __lowercase : int = 32 , __lowercase : str = "gelu" , __lowercase : float = 0.1 , __lowercase : float = 0.1 , __lowercase : float = 0.1 , __lowercase : float = 0.1 , __lowercase : float = 0.1 , __lowercase : int = 100 , __lowercase : float = 0.02 , __lowercase : bool = True , __lowercase : List[Any]=True , __lowercase : int = 10 , __lowercase : int = 25 , __lowercase : int = 3 , **__lowercase : Optional[int] , ): '''simple docstring''' # time series specific configuration __a = prediction_length __a = context_length if context_length is not None else prediction_length __a = distribution_output __a = loss __a = input_size __a = num_time_features __a = lags_sequence __a = scaling __a = num_dynamic_real_features __a = num_static_real_features __a = num_static_categorical_features if cardinality is not None and num_static_categorical_features > 0: if len(__lowercase ) != num_static_categorical_features: raise ValueError( """The cardinality should be a list of the same length as `num_static_categorical_features`""" ) __a = cardinality else: __a = [0] if embedding_dimension is not None and num_static_categorical_features > 0: if len(__lowercase ) != num_static_categorical_features: raise ValueError( """The embedding dimension should be a list of the same length as `num_static_categorical_features`""" ) __a = embedding_dimension else: __a = [min(50 , (cat + 1) // 2 ) for cat in self.cardinality] __a = num_parallel_samples # Transformer architecture configuration __a = input_size * len(self.lags_sequence ) + self._number_of_features __a = d_model __a = encoder_attention_heads __a = decoder_attention_heads __a = encoder_ffn_dim __a = decoder_ffn_dim __a = encoder_layers __a = decoder_layers __a = dropout __a = attention_dropout __a = activation_dropout __a = encoder_layerdrop __a = decoder_layerdrop __a = activation_function __a = init_std __a = use_cache # Autoformer __a = label_length __a = moving_average __a = autocorrelation_factor super().__init__(is_encoder_decoder=__lowercase , **__lowercase ) @property def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' return ( sum(self.embedding_dimension ) + self.num_dynamic_real_features + self.num_time_features + self.num_static_real_features + self.input_size * 2 # the log1p(abs(loc)) and log(scale) features )
302
1
import argparse import struct import unittest class SCREAMING_SNAKE_CASE : def __init__( self : str , __lowercase : bytes ): '''simple docstring''' __a = data # Initialize hash values __a = [ 0X6a_09_e6_67, 0Xbb_67_ae_85, 0X3c_6e_f3_72, 0Xa5_4f_f5_3a, 0X51_0e_52_7f, 0X9b_05_68_8c, 0X1f_83_d9_ab, 0X5b_e0_cd_19, ] # Initialize round constants __a = [ 0X42_8a_2f_98, 0X71_37_44_91, 0Xb5_c0_fb_cf, 0Xe9_b5_db_a5, 0X39_56_c2_5b, 0X59_f1_11_f1, 0X92_3f_82_a4, 0Xab_1c_5e_d5, 0Xd8_07_aa_98, 0X12_83_5b_01, 0X24_31_85_be, 0X55_0c_7d_c3, 0X72_be_5d_74, 0X80_de_b1_fe, 0X9b_dc_06_a7, 0Xc1_9b_f1_74, 0Xe4_9b_69_c1, 0Xef_be_47_86, 0X0f_c1_9d_c6, 0X24_0c_a1_cc, 0X2d_e9_2c_6f, 0X4a_74_84_aa, 0X5c_b0_a9_dc, 0X76_f9_88_da, 0X98_3e_51_52, 0Xa8_31_c6_6d, 0Xb0_03_27_c8, 0Xbf_59_7f_c7, 0Xc6_e0_0b_f3, 0Xd5_a7_91_47, 0X06_ca_63_51, 0X14_29_29_67, 0X27_b7_0a_85, 0X2e_1b_21_38, 0X4d_2c_6d_fc, 0X53_38_0d_13, 0X65_0a_73_54, 0X76_6a_0a_bb, 0X81_c2_c9_2e, 0X92_72_2c_85, 0Xa2_bf_e8_a1, 0Xa8_1a_66_4b, 0Xc2_4b_8b_70, 0Xc7_6c_51_a3, 0Xd1_92_e8_19, 0Xd6_99_06_24, 0Xf4_0e_35_85, 0X10_6a_a0_70, 0X19_a4_c1_16, 0X1e_37_6c_08, 0X27_48_77_4c, 0X34_b0_bc_b5, 0X39_1c_0c_b3, 0X4e_d8_aa_4a, 0X5b_9c_ca_4f, 0X68_2e_6f_f3, 0X74_8f_82_ee, 0X78_a5_63_6f, 0X84_c8_78_14, 0X8c_c7_02_08, 0X90_be_ff_fa, 0Xa4_50_6c_eb, 0Xbe_f9_a3_f7, 0Xc6_71_78_f2, ] __a = self.preprocessing(self.data ) self.final_hash() @staticmethod def UpperCamelCase_ ( __lowercase : bytes ): '''simple docstring''' __a = b"""\x80""" + (b"""\x00""" * (63 - (len(__lowercase ) + 8) % 64)) __a = struct.pack(""">Q""" , (len(__lowercase ) * 8) ) return data + padding + big_endian_integer def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' # Convert into blocks of 64 bytes __a = [ self.preprocessed_data[x : x + 64] for x in range(0 , len(self.preprocessed_data ) , 64 ) ] for block in self.blocks: # Convert the given block into a list of 4 byte integers __a = list(struct.unpack(""">16L""" , __lowercase ) ) # add 48 0-ed integers words += [0] * 48 __a , __a , __a , __a , __a , __a , __a , __a = self.hashes for index in range(0 , 64 ): if index > 15: # modify the zero-ed indexes at the end of the array __a = ( self.ror(words[index - 15] , 7 ) ^ self.ror(words[index - 15] , 18 ) ^ (words[index - 15] >> 3) ) __a = ( self.ror(words[index - 2] , 17 ) ^ self.ror(words[index - 2] , 19 ) ^ (words[index - 2] >> 10) ) __a = ( words[index - 16] + sa + words[index - 7] + sa ) % 0X1_00_00_00_00 # Compression __a = self.ror(__lowercase , 6 ) ^ self.ror(__lowercase , 11 ) ^ self.ror(__lowercase , 25 ) __a = (e & f) ^ ((~e & 0Xff_ff_ff_ff) & g) __a = ( h + sa + ch + self.round_constants[index] + words[index] ) % 0X1_00_00_00_00 __a = self.ror(__lowercase , 2 ) ^ self.ror(__lowercase , 13 ) ^ self.ror(__lowercase , 22 ) __a = (a & b) ^ (a & c) ^ (b & c) __a = (sa + maj) % 0X1_00_00_00_00 __a , __a , __a , __a , __a , __a , __a , __a = ( g, f, e, ((d + tempa) % 0X1_00_00_00_00), c, b, a, ((tempa + tempa) % 0X1_00_00_00_00), ) __a = [a, b, c, d, e, f, g, h] # Modify final values __a = [ ((element + mutated_hash_values[index]) % 0X1_00_00_00_00) for index, element in enumerate(self.hashes ) ] __a = """""".join([hex(__lowercase )[2:].zfill(8 ) for value in self.hashes] ) def UpperCamelCase_ ( self : Tuple , __lowercase : int , __lowercase : int ): '''simple docstring''' return 0Xff_ff_ff_ff & (value << (32 - rotations)) | (value >> rotations) class SCREAMING_SNAKE_CASE ( unittest.TestCase ): def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' import hashlib __a = bytes("""Test String""" , """utf-8""" ) self.assertEqual(SHAaaa(__lowercase ).hash , hashlib.shaaaa(__lowercase ).hexdigest() ) def lowerCAmelCase__ ( ): """simple docstring""" import doctest doctest.testmod() __a = argparse.ArgumentParser() parser.add_argument( """-s""" , """--string""" , dest="""input_string""" , default="""Hello World!! Welcome to Cryptography""" , help="""Hash the string""" , ) parser.add_argument( """-f""" , """--file""" , dest="""input_file""" , help="""Hash contents of a file""" ) __a = parser.parse_args() __a = args.input_string # hash input should be a bytestring if args.input_file: with open(args.input_file , """rb""" ) as f: __a = f.read() else: __a = bytes(_SCREAMING_SNAKE_CASE , """utf-8""" ) print(SHAaaa(_SCREAMING_SNAKE_CASE ).hash ) if __name__ == "__main__": main()
302
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase__ = { """configuration_electra""": ["""ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ElectraConfig""", """ElectraOnnxConfig"""], """tokenization_electra""": ["""ElectraTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = ["""ElectraTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ """ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST""", """ElectraForCausalLM""", """ElectraForMaskedLM""", """ElectraForMultipleChoice""", """ElectraForPreTraining""", """ElectraForQuestionAnswering""", """ElectraForSequenceClassification""", """ElectraForTokenClassification""", """ElectraModel""", """ElectraPreTrainedModel""", """load_tf_weights_in_electra""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ """TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFElectraForMaskedLM""", """TFElectraForMultipleChoice""", """TFElectraForPreTraining""", """TFElectraForQuestionAnswering""", """TFElectraForSequenceClassification""", """TFElectraForTokenClassification""", """TFElectraModel""", """TFElectraPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ """FlaxElectraForCausalLM""", """FlaxElectraForMaskedLM""", """FlaxElectraForMultipleChoice""", """FlaxElectraForPreTraining""", """FlaxElectraForQuestionAnswering""", """FlaxElectraForSequenceClassification""", """FlaxElectraForTokenClassification""", """FlaxElectraModel""", """FlaxElectraPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_electra import ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ElectraConfig, ElectraOnnxConfig from .tokenization_electra import ElectraTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_electra_fast import ElectraTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_electra import ( ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST, ElectraForCausalLM, ElectraForMaskedLM, ElectraForMultipleChoice, ElectraForPreTraining, ElectraForQuestionAnswering, ElectraForSequenceClassification, ElectraForTokenClassification, ElectraModel, ElectraPreTrainedModel, load_tf_weights_in_electra, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_electra import ( TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST, TFElectraForMaskedLM, TFElectraForMultipleChoice, TFElectraForPreTraining, TFElectraForQuestionAnswering, TFElectraForSequenceClassification, TFElectraForTokenClassification, TFElectraModel, TFElectraPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_electra import ( FlaxElectraForCausalLM, FlaxElectraForMaskedLM, FlaxElectraForMultipleChoice, FlaxElectraForPreTraining, FlaxElectraForQuestionAnswering, FlaxElectraForSequenceClassification, FlaxElectraForTokenClassification, FlaxElectraModel, FlaxElectraPreTrainedModel, ) else: import sys lowerCamelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
302
1
import contextlib import csv import json import os import sqlitea import tarfile import textwrap import zipfile import pyarrow as pa import pyarrow.parquet as pq import pytest import datasets import datasets.config @pytest.fixture(scope="""session""" ) def lowerCAmelCase__ ( ): """simple docstring""" __a = 10 __a = datasets.Features( { """tokens""": datasets.Sequence(datasets.Value("""string""" ) ), """labels""": datasets.Sequence(datasets.ClassLabel(names=["""negative""", """positive"""] ) ), """answers""": datasets.Sequence( { """text""": datasets.Value("""string""" ), """answer_start""": datasets.Value("""int32""" ), } ), """id""": datasets.Value("""int64""" ), } ) __a = datasets.Dataset.from_dict( { """tokens""": [["""foo"""] * 5] * n, """labels""": [[1] * 5] * n, """answers""": [{"""answer_start""": [97], """text""": ["""1976"""]}] * 10, """id""": list(range(_SCREAMING_SNAKE_CASE ) ), } , features=_SCREAMING_SNAKE_CASE , ) return dataset @pytest.fixture(scope="""session""" ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Optional[int] ): """simple docstring""" __a = str(tmp_path_factory.mktemp("""data""" ) / """file.arrow""" ) dataset.map(cache_file_name=_SCREAMING_SNAKE_CASE ) return filename # FILE_CONTENT + files lowerCamelCase__ = """\ Text data. Second line of data.""" @pytest.fixture(scope="""session""" ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Any ): """simple docstring""" __a = tmp_path_factory.mktemp("""data""" ) / """file.txt""" __a = FILE_CONTENT with open(_SCREAMING_SNAKE_CASE , """w""" ) as f: f.write(_SCREAMING_SNAKE_CASE ) return filename @pytest.fixture(scope="""session""" ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Optional[int] ): """simple docstring""" import bza __a = tmp_path_factory.mktemp("""data""" ) / """file.txt.bz2""" __a = bytes(_SCREAMING_SNAKE_CASE , """utf-8""" ) with bza.open(_SCREAMING_SNAKE_CASE , """wb""" ) as f: f.write(_SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope="""session""" ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" import gzip __a = str(tmp_path_factory.mktemp("""data""" ) / """file.txt.gz""" ) __a = bytes(_SCREAMING_SNAKE_CASE , """utf-8""" ) with gzip.open(_SCREAMING_SNAKE_CASE , """wb""" ) as f: f.write(_SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope="""session""" ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Optional[int] ): """simple docstring""" if datasets.config.LZ4_AVAILABLE: import lza.frame __a = tmp_path_factory.mktemp("""data""" ) / """file.txt.lz4""" __a = bytes(_SCREAMING_SNAKE_CASE , """utf-8""" ) with lza.frame.open(_SCREAMING_SNAKE_CASE , """wb""" ) as f: f.write(_SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope="""session""" ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : List[Any] ): """simple docstring""" if datasets.config.PY7ZR_AVAILABLE: import pyazr __a = tmp_path_factory.mktemp("""data""" ) / """file.txt.7z""" with pyazr.SevenZipFile(_SCREAMING_SNAKE_CASE , """w""" ) as archive: archive.write(_SCREAMING_SNAKE_CASE , arcname=os.path.basename(_SCREAMING_SNAKE_CASE ) ) return path @pytest.fixture(scope="""session""" ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Any ): """simple docstring""" import tarfile __a = tmp_path_factory.mktemp("""data""" ) / """file.txt.tar""" with tarfile.TarFile(_SCREAMING_SNAKE_CASE , """w""" ) as f: f.add(_SCREAMING_SNAKE_CASE , arcname=os.path.basename(_SCREAMING_SNAKE_CASE ) ) return path @pytest.fixture(scope="""session""" ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" import lzma __a = tmp_path_factory.mktemp("""data""" ) / """file.txt.xz""" __a = bytes(_SCREAMING_SNAKE_CASE , """utf-8""" ) with lzma.open(_SCREAMING_SNAKE_CASE , """wb""" ) as f: f.write(_SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope="""session""" ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" import zipfile __a = tmp_path_factory.mktemp("""data""" ) / """file.txt.zip""" with zipfile.ZipFile(_SCREAMING_SNAKE_CASE , """w""" ) as f: f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.basename(_SCREAMING_SNAKE_CASE ) ) return path @pytest.fixture(scope="""session""" ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" if datasets.config.ZSTANDARD_AVAILABLE: import zstandard as zstd __a = tmp_path_factory.mktemp("""data""" ) / """file.txt.zst""" __a = bytes(_SCREAMING_SNAKE_CASE , """utf-8""" ) with zstd.open(_SCREAMING_SNAKE_CASE , """wb""" ) as f: f.write(_SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope="""session""" ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int ): """simple docstring""" __a = tmp_path_factory.mktemp("""data""" ) / """file.xml""" __a = textwrap.dedent( """\ <?xml version=\"1.0\" encoding=\"UTF-8\" ?> <tmx version=\"1.4\"> <header segtype=\"sentence\" srclang=\"ca\" /> <body> <tu> <tuv xml:lang=\"ca\"><seg>Contingut 1</seg></tuv> <tuv xml:lang=\"en\"><seg>Content 1</seg></tuv> </tu> <tu> <tuv xml:lang=\"ca\"><seg>Contingut 2</seg></tuv> <tuv xml:lang=\"en\"><seg>Content 2</seg></tuv> </tu> <tu> <tuv xml:lang=\"ca\"><seg>Contingut 3</seg></tuv> <tuv xml:lang=\"en\"><seg>Content 3</seg></tuv> </tu> <tu> <tuv xml:lang=\"ca\"><seg>Contingut 4</seg></tuv> <tuv xml:lang=\"en\"><seg>Content 4</seg></tuv> </tu> <tu> <tuv xml:lang=\"ca\"><seg>Contingut 5</seg></tuv> <tuv xml:lang=\"en\"><seg>Content 5</seg></tuv> </tu> </body> </tmx>""" ) with open(_SCREAMING_SNAKE_CASE , """w""" ) as f: f.write(_SCREAMING_SNAKE_CASE ) return filename lowerCamelCase__ = [ {"""col_1""": """0""", """col_2""": 0, """col_3""": 0.0}, {"""col_1""": """1""", """col_2""": 1, """col_3""": 1.0}, {"""col_1""": """2""", """col_2""": 2, """col_3""": 2.0}, {"""col_1""": """3""", """col_2""": 3, """col_3""": 3.0}, ] lowerCamelCase__ = [ {"""col_1""": """4""", """col_2""": 4, """col_3""": 4.0}, {"""col_1""": """5""", """col_2""": 5, """col_3""": 5.0}, ] lowerCamelCase__ = { """col_1""": ["""0""", """1""", """2""", """3"""], """col_2""": [0, 1, 2, 3], """col_3""": [0.0, 1.0, 2.0, 3.0], } lowerCamelCase__ = [ {"""col_3""": 0.0, """col_1""": """0""", """col_2""": 0}, {"""col_3""": 1.0, """col_1""": """1""", """col_2""": 1}, ] lowerCamelCase__ = [ {"""col_1""": """s0""", """col_2""": 0, """col_3""": 0.0}, {"""col_1""": """s1""", """col_2""": 1, """col_3""": 1.0}, {"""col_1""": """s2""", """col_2""": 2, """col_3""": 2.0}, {"""col_1""": """s3""", """col_2""": 3, """col_3""": 3.0}, ] @pytest.fixture(scope="""session""" ) def lowerCAmelCase__ ( ): """simple docstring""" return DATA_DICT_OF_LISTS @pytest.fixture(scope="""session""" ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : str ): """simple docstring""" __a = datasets.Dataset.from_dict(_SCREAMING_SNAKE_CASE ) __a = str(tmp_path_factory.mktemp("""data""" ) / """dataset.arrow""" ) dataset.map(cache_file_name=_SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope="""session""" ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : List[Any] ): """simple docstring""" __a = str(tmp_path_factory.mktemp("""data""" ) / """dataset.sqlite""" ) with contextlib.closing(sqlitea.connect(_SCREAMING_SNAKE_CASE ) ) as con: __a = con.cursor() cur.execute("""CREATE TABLE dataset(col_1 text, col_2 int, col_3 real)""" ) for item in DATA: cur.execute("""INSERT INTO dataset(col_1, col_2, col_3) VALUES (?, ?, ?)""" , tuple(item.values() ) ) con.commit() return path @pytest.fixture(scope="""session""" ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" __a = str(tmp_path_factory.mktemp("""data""" ) / """dataset.csv""" ) with open(_SCREAMING_SNAKE_CASE , """w""" , newline="""""" ) as f: __a = csv.DictWriter(_SCREAMING_SNAKE_CASE , fieldnames=["""col_1""", """col_2""", """col_3"""] ) writer.writeheader() for item in DATA: writer.writerow(_SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope="""session""" ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" __a = str(tmp_path_factory.mktemp("""data""" ) / """dataset2.csv""" ) with open(_SCREAMING_SNAKE_CASE , """w""" , newline="""""" ) as f: __a = csv.DictWriter(_SCREAMING_SNAKE_CASE , fieldnames=["""col_1""", """col_2""", """col_3"""] ) writer.writeheader() for item in DATA: writer.writerow(_SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope="""session""" ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" import bza __a = tmp_path_factory.mktemp("""data""" ) / """dataset.csv.bz2""" with open(_SCREAMING_SNAKE_CASE , """rb""" ) as f: __a = f.read() # data = bytes(FILE_CONTENT, "utf-8") with bza.open(_SCREAMING_SNAKE_CASE , """wb""" ) as f: f.write(_SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope="""session""" ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" __a = tmp_path_factory.mktemp("""data""" ) / """dataset.csv.zip""" with zipfile.ZipFile(_SCREAMING_SNAKE_CASE , """w""" ) as f: f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.basename(_SCREAMING_SNAKE_CASE ) ) f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.basename(_SCREAMING_SNAKE_CASE ) ) return path @pytest.fixture(scope="""session""" ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" __a = tmp_path_factory.mktemp("""data""" ) / """dataset.csv.zip""" with zipfile.ZipFile(_SCREAMING_SNAKE_CASE , """w""" ) as f: f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.basename(csv_path.replace(""".csv""" , """.CSV""" ) ) ) f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.basename(csva_path.replace(""".csv""" , """.CSV""" ) ) ) return path @pytest.fixture(scope="""session""" ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" __a = tmp_path_factory.mktemp("""data""" ) / """dataset_with_dir.csv.zip""" with zipfile.ZipFile(_SCREAMING_SNAKE_CASE , """w""" ) as f: f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.join("""main_dir""" , os.path.basename(_SCREAMING_SNAKE_CASE ) ) ) f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.join("""main_dir""" , os.path.basename(_SCREAMING_SNAKE_CASE ) ) ) return path @pytest.fixture(scope="""session""" ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Optional[int] ): """simple docstring""" __a = str(tmp_path_factory.mktemp("""data""" ) / """dataset.parquet""" ) __a = pa.schema( { """col_1""": pa.string(), """col_2""": pa.intaa(), """col_3""": pa.floataa(), } ) with open(_SCREAMING_SNAKE_CASE , """wb""" ) as f: __a = pq.ParquetWriter(_SCREAMING_SNAKE_CASE , schema=_SCREAMING_SNAKE_CASE ) __a = pa.Table.from_pydict({k: [DATA[i][k] for i in range(len(_SCREAMING_SNAKE_CASE ) )] for k in DATA[0]} , schema=_SCREAMING_SNAKE_CASE ) writer.write_table(_SCREAMING_SNAKE_CASE ) writer.close() return path @pytest.fixture(scope="""session""" ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Any ): """simple docstring""" __a = str(tmp_path_factory.mktemp("""data""" ) / """dataset.json""" ) __a = {"""data""": DATA} with open(_SCREAMING_SNAKE_CASE , """w""" ) as f: json.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope="""session""" ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Optional[int] ): """simple docstring""" __a = str(tmp_path_factory.mktemp("""data""" ) / """dataset.json""" ) __a = {"""data""": DATA_DICT_OF_LISTS} with open(_SCREAMING_SNAKE_CASE , """w""" ) as f: json.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope="""session""" ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" __a = str(tmp_path_factory.mktemp("""data""" ) / """dataset.jsonl""" ) with open(_SCREAMING_SNAKE_CASE , """w""" ) as f: for item in DATA: f.write(json.dumps(_SCREAMING_SNAKE_CASE ) + """\n""" ) return path @pytest.fixture(scope="""session""" ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" __a = str(tmp_path_factory.mktemp("""data""" ) / """dataset2.jsonl""" ) with open(_SCREAMING_SNAKE_CASE , """w""" ) as f: for item in DATA: f.write(json.dumps(_SCREAMING_SNAKE_CASE ) + """\n""" ) return path @pytest.fixture(scope="""session""" ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" __a = str(tmp_path_factory.mktemp("""data""" ) / """dataset_312.jsonl""" ) with open(_SCREAMING_SNAKE_CASE , """w""" ) as f: for item in DATA_312: f.write(json.dumps(_SCREAMING_SNAKE_CASE ) + """\n""" ) return path @pytest.fixture(scope="""session""" ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" __a = str(tmp_path_factory.mktemp("""data""" ) / """dataset-str.jsonl""" ) with open(_SCREAMING_SNAKE_CASE , """w""" ) as f: for item in DATA_STR: f.write(json.dumps(_SCREAMING_SNAKE_CASE ) + """\n""" ) return path @pytest.fixture(scope="""session""" ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : str ): """simple docstring""" import gzip __a = str(tmp_path_factory.mktemp("""data""" ) / """dataset.txt.gz""" ) with open(_SCREAMING_SNAKE_CASE , """rb""" ) as orig_file: with gzip.open(_SCREAMING_SNAKE_CASE , """wb""" ) as zipped_file: zipped_file.writelines(_SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope="""session""" ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" import gzip __a = str(tmp_path_factory.mktemp("""data""" ) / """dataset.jsonl.gz""" ) with open(_SCREAMING_SNAKE_CASE , """rb""" ) as orig_file: with gzip.open(_SCREAMING_SNAKE_CASE , """wb""" ) as zipped_file: zipped_file.writelines(_SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope="""session""" ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" __a = tmp_path_factory.mktemp("""data""" ) / """dataset.jsonl.zip""" with zipfile.ZipFile(_SCREAMING_SNAKE_CASE , """w""" ) as f: f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.basename(_SCREAMING_SNAKE_CASE ) ) f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.basename(_SCREAMING_SNAKE_CASE ) ) return path @pytest.fixture(scope="""session""" ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : int ): """simple docstring""" __a = tmp_path_factory.mktemp("""data""" ) / """dataset_nested.jsonl.zip""" with zipfile.ZipFile(_SCREAMING_SNAKE_CASE , """w""" ) as f: f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.join("""nested""" , os.path.basename(_SCREAMING_SNAKE_CASE ) ) ) return path @pytest.fixture(scope="""session""" ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : List[Any] ): """simple docstring""" __a = tmp_path_factory.mktemp("""data""" ) / """dataset_with_dir.jsonl.zip""" with zipfile.ZipFile(_SCREAMING_SNAKE_CASE , """w""" ) as f: f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.join("""main_dir""" , os.path.basename(_SCREAMING_SNAKE_CASE ) ) ) f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.join("""main_dir""" , os.path.basename(_SCREAMING_SNAKE_CASE ) ) ) return path @pytest.fixture(scope="""session""" ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : str ): """simple docstring""" __a = tmp_path_factory.mktemp("""data""" ) / """dataset.jsonl.tar""" with tarfile.TarFile(_SCREAMING_SNAKE_CASE , """w""" ) as f: f.add(_SCREAMING_SNAKE_CASE , arcname=os.path.basename(_SCREAMING_SNAKE_CASE ) ) f.add(_SCREAMING_SNAKE_CASE , arcname=os.path.basename(_SCREAMING_SNAKE_CASE ) ) return path @pytest.fixture(scope="""session""" ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" __a = tmp_path_factory.mktemp("""data""" ) / """dataset_nested.jsonl.tar""" with tarfile.TarFile(_SCREAMING_SNAKE_CASE , """w""" ) as f: f.add(_SCREAMING_SNAKE_CASE , arcname=os.path.join("""nested""" , os.path.basename(_SCREAMING_SNAKE_CASE ) ) ) return path @pytest.fixture(scope="""session""" ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : List[Any] ): """simple docstring""" __a = ["""0""", """1""", """2""", """3"""] __a = str(tmp_path_factory.mktemp("""data""" ) / """dataset.txt""" ) with open(_SCREAMING_SNAKE_CASE , """w""" ) as f: for item in data: f.write(item + """\n""" ) return path @pytest.fixture(scope="""session""" ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" __a = ["""0""", """1""", """2""", """3"""] __a = str(tmp_path_factory.mktemp("""data""" ) / """dataset2.txt""" ) with open(_SCREAMING_SNAKE_CASE , """w""" ) as f: for item in data: f.write(item + """\n""" ) return path @pytest.fixture(scope="""session""" ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Any ): """simple docstring""" __a = ["""0""", """1""", """2""", """3"""] __a = tmp_path_factory.mktemp("""data""" ) / """dataset.abc""" with open(_SCREAMING_SNAKE_CASE , """w""" ) as f: for item in data: f.write(item + """\n""" ) return path @pytest.fixture(scope="""session""" ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int ): """simple docstring""" __a = tmp_path_factory.mktemp("""data""" ) / """dataset.text.zip""" with zipfile.ZipFile(_SCREAMING_SNAKE_CASE , """w""" ) as f: f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.basename(_SCREAMING_SNAKE_CASE ) ) f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.basename(_SCREAMING_SNAKE_CASE ) ) return path @pytest.fixture(scope="""session""" ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : int ): """simple docstring""" __a = tmp_path_factory.mktemp("""data""" ) / """dataset_with_dir.text.zip""" with zipfile.ZipFile(_SCREAMING_SNAKE_CASE , """w""" ) as f: f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.join("""main_dir""" , os.path.basename(_SCREAMING_SNAKE_CASE ) ) ) f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.join("""main_dir""" , os.path.basename(_SCREAMING_SNAKE_CASE ) ) ) return path @pytest.fixture(scope="""session""" ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" __a = tmp_path_factory.mktemp("""data""" ) / """dataset.ext.zip""" with zipfile.ZipFile(_SCREAMING_SNAKE_CASE , """w""" ) as f: f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.basename("""unsupported.ext""" ) ) f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.basename("""unsupported_2.ext""" ) ) return path @pytest.fixture(scope="""session""" ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : str ): """simple docstring""" __a = """\n""".join(["""First""", """Second\u2029with Unicode new line""", """Third"""] ) __a = str(tmp_path_factory.mktemp("""data""" ) / """dataset_with_unicode_new_lines.txt""" ) with open(_SCREAMING_SNAKE_CASE , """w""" , encoding="""utf-8""" ) as f: f.write(_SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope="""session""" ) def lowerCAmelCase__ ( ): """simple docstring""" return os.path.join("""tests""" , """features""" , """data""" , """test_image_rgb.jpg""" ) @pytest.fixture(scope="""session""" ) def lowerCAmelCase__ ( ): """simple docstring""" return os.path.join("""tests""" , """features""" , """data""" , """test_audio_44100.wav""" ) @pytest.fixture(scope="""session""" ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : int ): """simple docstring""" __a = tmp_path_factory.mktemp("""data""" ) / """dataset.img.zip""" with zipfile.ZipFile(_SCREAMING_SNAKE_CASE , """w""" ) as f: f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.basename(_SCREAMING_SNAKE_CASE ) ) f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.basename(_SCREAMING_SNAKE_CASE ).replace(""".jpg""" , """2.jpg""" ) ) return path @pytest.fixture(scope="""session""" ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : str ): """simple docstring""" __a = tmp_path_factory.mktemp("""data_dir""" ) (data_dir / "subdir").mkdir() with open(data_dir / """subdir""" / """train.txt""" , """w""" ) as f: f.write("""foo\n""" * 10 ) with open(data_dir / """subdir""" / """test.txt""" , """w""" ) as f: f.write("""bar\n""" * 10 ) # hidden file with open(data_dir / """subdir""" / """.test.txt""" , """w""" ) as f: f.write("""bar\n""" * 10 ) # hidden directory (data_dir / ".subdir").mkdir() with open(data_dir / """.subdir""" / """train.txt""" , """w""" ) as f: f.write("""foo\n""" * 10 ) with open(data_dir / """.subdir""" / """test.txt""" , """w""" ) as f: f.write("""bar\n""" * 10 ) return data_dir
302
from __future__ import annotations lowerCamelCase__ = """#""" class SCREAMING_SNAKE_CASE : def __init__( self : Optional[Any] ): '''simple docstring''' __a = {} def UpperCamelCase_ ( self : Optional[Any] , __lowercase : str ): '''simple docstring''' __a = self._trie for char in text: if char not in trie: __a = {} __a = trie[char] __a = True def UpperCamelCase_ ( self : Tuple , __lowercase : str ): '''simple docstring''' __a = self._trie for char in prefix: if char in trie: __a = trie[char] else: return [] return self._elements(__lowercase ) def UpperCamelCase_ ( self : Optional[int] , __lowercase : dict ): '''simple docstring''' __a = [] for c, v in d.items(): __a = [""" """] if c == END else [(c + s) for s in self._elements(__lowercase )] result.extend(__lowercase ) return tuple(__lowercase ) lowerCamelCase__ = Trie() lowerCamelCase__ = ("""depart""", """detergent""", """daring""", """dog""", """deer""", """deal""") for word in words: trie.insert_word(word) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : str ): """simple docstring""" __a = trie.find_word(_SCREAMING_SNAKE_CASE ) return tuple(string + word for word in suffixes ) def lowerCAmelCase__ ( ): """simple docstring""" print(autocomplete_using_trie("""de""" ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
302
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCamelCase__ = { """configuration_upernet""": ["""UperNetConfig"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ """UperNetForSemanticSegmentation""", """UperNetPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_upernet import UperNetConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_upernet import UperNetForSemanticSegmentation, UperNetPreTrainedModel else: import sys lowerCamelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
302
from dataclasses import dataclass from typing import Dict, Optional, Union import torch import torch.nn.functional as F from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .attention import BasicTransformerBlock from .attention_processor import AttentionProcessor, AttnProcessor from .embeddings import TimestepEmbedding, Timesteps from .modeling_utils import ModelMixin @dataclass class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : torch.FloatTensor class SCREAMING_SNAKE_CASE ( lowerCamelCase__ , lowerCamelCase__ ): @register_to_config def __init__( self : Dict , __lowercase : int = 32 , __lowercase : int = 64 , __lowercase : int = 20 , __lowercase : int = 768 , __lowercase : Any=77 , __lowercase : Optional[int]=4 , __lowercase : float = 0.0 , __lowercase : str = "silu" , __lowercase : Optional[str] = None , __lowercase : Optional[str] = None , __lowercase : Optional[str] = "linear" , __lowercase : Optional[str] = "prd" , __lowercase : Optional[int] = None , __lowercase : Optional[int] = None , __lowercase : Optional[int] = None , ): '''simple docstring''' super().__init__() __a = num_attention_heads __a = attention_head_dim __a = num_attention_heads * attention_head_dim __a = additional_embeddings __a = time_embed_dim or inner_dim __a = embedding_proj_dim or embedding_dim __a = clip_embed_dim or embedding_dim __a = Timesteps(__lowercase , __lowercase , 0 ) __a = TimestepEmbedding(__lowercase , __lowercase , out_dim=__lowercase , act_fn=__lowercase ) __a = nn.Linear(__lowercase , __lowercase ) if embedding_proj_norm_type is None: __a = None elif embedding_proj_norm_type == "layer": __a = nn.LayerNorm(__lowercase ) else: raise ValueError(F"unsupported embedding_proj_norm_type: {embedding_proj_norm_type}" ) __a = nn.Linear(__lowercase , __lowercase ) if encoder_hid_proj_type is None: __a = None elif encoder_hid_proj_type == "linear": __a = nn.Linear(__lowercase , __lowercase ) else: raise ValueError(F"unsupported encoder_hid_proj_type: {encoder_hid_proj_type}" ) __a = nn.Parameter(torch.zeros(1 , num_embeddings + additional_embeddings , __lowercase ) ) if added_emb_type == "prd": __a = nn.Parameter(torch.zeros(1 , 1 , __lowercase ) ) elif added_emb_type is None: __a = None else: raise ValueError( F"`added_emb_type`: {added_emb_type} is not supported. Make sure to choose one of `'prd'` or `None`." ) __a = nn.ModuleList( [ BasicTransformerBlock( __lowercase , __lowercase , __lowercase , dropout=__lowercase , activation_fn="""gelu""" , attention_bias=__lowercase , ) for d in range(__lowercase ) ] ) if norm_in_type == "layer": __a = nn.LayerNorm(__lowercase ) elif norm_in_type is None: __a = None else: raise ValueError(F"Unsupported norm_in_type: {norm_in_type}." ) __a = nn.LayerNorm(__lowercase ) __a = nn.Linear(__lowercase , __lowercase ) __a = torch.full( [num_embeddings + additional_embeddings, num_embeddings + additional_embeddings] , -10000.0 ) causal_attention_mask.triu_(1 ) __a = causal_attention_mask[None, ...] self.register_buffer("""causal_attention_mask""" , __lowercase , persistent=__lowercase ) __a = nn.Parameter(torch.zeros(1 , __lowercase ) ) __a = nn.Parameter(torch.zeros(1 , __lowercase ) ) @property # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' __a = {} def fn_recursive_add_processors(__lowercase : str , __lowercase : torch.nn.Module , __lowercase : Dict[str, AttentionProcessor] ): if hasattr(__lowercase , """set_processor""" ): __a = module.processor for sub_name, child in module.named_children(): fn_recursive_add_processors(F"{name}.{sub_name}" , __lowercase , __lowercase ) return processors for name, module in self.named_children(): fn_recursive_add_processors(__lowercase , __lowercase , __lowercase ) return processors def UpperCamelCase_ ( self : List[str] , __lowercase : Union[AttentionProcessor, Dict[str, AttentionProcessor]] ): '''simple docstring''' __a = len(self.attn_processors.keys() ) if isinstance(__lowercase , __lowercase ) and len(__lowercase ) != count: raise ValueError( F"A dict of processors was passed, but the number of processors {len(__lowercase )} does not match the" F" number of attention layers: {count}. Please make sure to pass {count} processor classes." ) def fn_recursive_attn_processor(__lowercase : str , __lowercase : torch.nn.Module , __lowercase : Dict ): if hasattr(__lowercase , """set_processor""" ): if not isinstance(__lowercase , __lowercase ): module.set_processor(__lowercase ) else: module.set_processor(processor.pop(F"{name}.processor" ) ) for sub_name, child in module.named_children(): fn_recursive_attn_processor(F"{name}.{sub_name}" , __lowercase , __lowercase ) for name, module in self.named_children(): fn_recursive_attn_processor(__lowercase , __lowercase , __lowercase ) def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' self.set_attn_processor(AttnProcessor() ) def UpperCamelCase_ ( self : Union[str, Any] , __lowercase : Optional[int] , __lowercase : Union[torch.Tensor, float, int] , __lowercase : torch.FloatTensor , __lowercase : Optional[torch.FloatTensor] = None , __lowercase : Optional[torch.BoolTensor] = None , __lowercase : bool = True , ): '''simple docstring''' __a = hidden_states.shape[0] __a = timestep if not torch.is_tensor(__lowercase ): __a = torch.tensor([timesteps] , dtype=torch.long , device=hidden_states.device ) elif torch.is_tensor(__lowercase ) and len(timesteps.shape ) == 0: __a = timesteps[None].to(hidden_states.device ) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML __a = timesteps * torch.ones(__lowercase , dtype=timesteps.dtype , device=timesteps.device ) __a = self.time_proj(__lowercase ) # timesteps does not contain any weights and will always return f32 tensors # but time_embedding might be fp16, so we need to cast here. __a = timesteps_projected.to(dtype=self.dtype ) __a = self.time_embedding(__lowercase ) if self.embedding_proj_norm is not None: __a = self.embedding_proj_norm(__lowercase ) __a = self.embedding_proj(__lowercase ) if self.encoder_hidden_states_proj is not None and encoder_hidden_states is not None: __a = self.encoder_hidden_states_proj(__lowercase ) elif self.encoder_hidden_states_proj is not None and encoder_hidden_states is None: raise ValueError("""`encoder_hidden_states_proj` requires `encoder_hidden_states` to be set""" ) __a = self.proj_in(__lowercase ) __a = self.positional_embedding.to(hidden_states.dtype ) __a = [] __a = 0 if encoder_hidden_states is not None: additional_embeds.append(__lowercase ) additional_embeddings_len += encoder_hidden_states.shape[1] if len(proj_embeddings.shape ) == 2: __a = proj_embeddings[:, None, :] if len(hidden_states.shape ) == 2: __a = hidden_states[:, None, :] __a = additional_embeds + [ proj_embeddings, time_embeddings[:, None, :], hidden_states, ] if self.prd_embedding is not None: __a = self.prd_embedding.to(hidden_states.dtype ).expand(__lowercase , -1 , -1 ) additional_embeds.append(__lowercase ) __a = torch.cat( __lowercase , dim=1 , ) # Allow positional_embedding to not include the `addtional_embeddings` and instead pad it with zeros for these additional tokens __a = additional_embeddings_len + proj_embeddings.shape[1] + 1 if positional_embeddings.shape[1] < hidden_states.shape[1]: __a = F.pad( __lowercase , ( 0, 0, additional_embeddings_len, self.prd_embedding.shape[1] if self.prd_embedding is not None else 0, ) , value=0.0 , ) __a = hidden_states + positional_embeddings if attention_mask is not None: __a = (1 - attention_mask.to(hidden_states.dtype )) * -10000.0 __a = F.pad(__lowercase , (0, self.additional_embeddings) , value=0.0 ) __a = (attention_mask[:, None, :] + self.causal_attention_mask).to(hidden_states.dtype ) __a = attention_mask.repeat_interleave(self.config.num_attention_heads , dim=0 ) if self.norm_in is not None: __a = self.norm_in(__lowercase ) for block in self.transformer_blocks: __a = block(__lowercase , attention_mask=__lowercase ) __a = self.norm_out(__lowercase ) if self.prd_embedding is not None: __a = hidden_states[:, -1] else: __a = hidden_states[:, additional_embeddings_len:] __a = self.proj_to_clip_embeddings(__lowercase ) if not return_dict: return (predicted_image_embedding,) return PriorTransformerOutput(predicted_image_embedding=__lowercase ) def UpperCamelCase_ ( self : Any , __lowercase : Tuple ): '''simple docstring''' __a = (prior_latents * self.clip_std) + self.clip_mean return prior_latents
302
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available lowerCamelCase__ = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = ["""GPTSw3Tokenizer"""] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_swa import GPTSwaTokenizer else: import sys lowerCamelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
302
from functools import lru_cache def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int ): """simple docstring""" __a = 2 __a = set() while i * i <= n: if n % i: i += 1 else: n //= i factors.add(_SCREAMING_SNAKE_CASE ) if n > 1: factors.add(_SCREAMING_SNAKE_CASE ) return factors @lru_cache def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int ): """simple docstring""" return len(unique_prime_factors(_SCREAMING_SNAKE_CASE ) ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : list ): """simple docstring""" return len(set(_SCREAMING_SNAKE_CASE ) ) in (0, 1) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int ): """simple docstring""" __a = 2 while True: # Increment each value of a generated range __a = [base + i for i in range(_SCREAMING_SNAKE_CASE )] # Run elements through out unique_prime_factors function # Append our target number to the end. __a = [upf_len(_SCREAMING_SNAKE_CASE ) for x in group] checker.append(_SCREAMING_SNAKE_CASE ) # If all numbers in the list are equal, return the group variable. if equality(_SCREAMING_SNAKE_CASE ): return group # Increment our base variable by 1 base += 1 def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int = 4 ): """simple docstring""" __a = run(_SCREAMING_SNAKE_CASE ) return results[0] if len(_SCREAMING_SNAKE_CASE ) else None if __name__ == "__main__": print(solution())
302
1
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { """google/pix2struct-textcaps-base""": ( """https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json""" ), } class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : List[Any] ='pix2struct_text_model' __lowerCamelCase : Union[str, Any] =['past_key_values'] __lowerCamelCase : List[str] ={ 'hidden_size': 'hidden_size', 'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers', } def __init__( self : int , __lowercase : Dict=50244 , __lowercase : List[str]=768 , __lowercase : int=64 , __lowercase : str=2048 , __lowercase : str=12 , __lowercase : Union[str, Any]=12 , __lowercase : Tuple=32 , __lowercase : Tuple=128 , __lowercase : str=0.1 , __lowercase : int=1E-6 , __lowercase : List[str]=1.0 , __lowercase : List[Any]="gelu_new" , __lowercase : List[Any]=0 , __lowercase : Optional[int]=False , __lowercase : Any=0 , __lowercase : str=1 , __lowercase : Any=False , __lowercase : Optional[int]=True , **__lowercase : List[str] , ): '''simple docstring''' __a = vocab_size __a = hidden_size __a = d_kv __a = d_ff __a = num_layers __a = num_heads __a = relative_attention_num_buckets __a = relative_attention_max_distance __a = dropout_rate __a = layer_norm_epsilon __a = initializer_factor __a = use_cache __a = eos_token_id __a = decoder_start_token_id # for backwards compatibility __a = dense_act_fn super().__init__( pad_token_id=__lowercase , eos_token_id=__lowercase , decoder_start_token_id=__lowercase , tie_word_embeddings=__lowercase , is_decoder=__lowercase , **__lowercase , ) @classmethod def UpperCamelCase_ ( cls : Any , __lowercase : Union[str, os.PathLike] , **__lowercase : Union[str, Any] ): '''simple docstring''' cls._set_token_in_kwargs(__lowercase ) __a , __a = cls.get_config_dict(__lowercase , **__lowercase ) # get the text config dict if we are loading from Pix2StructConfig if config_dict.get("""model_type""" ) == "pix2struct": __a = config_dict["""text_config"""] if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( F"You are using a model of type {config_dict['model_type']} to instantiate a model of type " F"{cls.model_type}. This is not supported for all configurations of models and can yield errors." ) return cls.from_dict(__lowercase , **__lowercase ) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : Union[str, Any] ='pix2struct_vision_model' def __init__( self : Optional[Any] , __lowercase : Optional[Any]=768 , __lowercase : Tuple=768 , __lowercase : Union[str, Any]=2048 , __lowercase : Any=64 , __lowercase : Dict=12 , __lowercase : Optional[int]=12 , __lowercase : Dict="gelu_new" , __lowercase : Optional[int]=1E-6 , __lowercase : List[Any]=0.0 , __lowercase : Any=0.0 , __lowercase : List[Any]=1E-10 , __lowercase : str=1.0 , __lowercase : Optional[int]=4096 , __lowercase : Dict=32 , __lowercase : Optional[int]=128 , **__lowercase : Optional[Any] , ): '''simple docstring''' super().__init__(**__lowercase ) __a = hidden_size __a = patch_embed_hidden_size __a = d_ff __a = dropout_rate __a = num_hidden_layers __a = num_attention_heads __a = initializer_range __a = initializer_factor __a = attention_dropout __a = layer_norm_eps __a = dense_act_fn __a = seq_len __a = relative_attention_num_buckets __a = relative_attention_max_distance __a = d_kv @classmethod def UpperCamelCase_ ( cls : int , __lowercase : Union[str, os.PathLike] , **__lowercase : Tuple ): '''simple docstring''' cls._set_token_in_kwargs(__lowercase ) __a , __a = cls.get_config_dict(__lowercase , **__lowercase ) # get the vision config dict if we are loading from Pix2StructConfig if config_dict.get("""model_type""" ) == "pix2struct": __a = config_dict["""vision_config"""] if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( F"You are using a model of type {config_dict['model_type']} to instantiate a model of type " F"{cls.model_type}. This is not supported for all configurations of models and can yield errors." ) return cls.from_dict(__lowercase , **__lowercase ) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : Optional[int] ='pix2struct' __lowerCamelCase : Optional[Any] =True def __init__( self : Tuple , __lowercase : Optional[int]=None , __lowercase : Optional[Any]=None , __lowercase : Dict=1.0 , __lowercase : str=0.02 , __lowercase : Optional[Any]=False , __lowercase : List[Any]=False , __lowercase : List[str]=True , **__lowercase : List[str] , ): '''simple docstring''' super().__init__(tie_word_embeddings=__lowercase , is_encoder_decoder=__lowercase , **__lowercase ) if text_config is None: __a = {} logger.info("""text_config is None. Initializing the Pix2StructTextConfig with default values.""" ) if vision_config is None: __a = {} logger.info("""vision_config is None. Initializing the Pix2StructVisionConfig with default values.""" ) __a = PixaStructTextConfig(**__lowercase ) __a = PixaStructVisionConfig(**__lowercase ) __a = self.text_config.decoder_start_token_id __a = self.text_config.pad_token_id __a = self.text_config.eos_token_id __a = initializer_factor __a = initializer_range __a = self.initializer_range __a = self.initializer_range __a = is_vqa @classmethod def UpperCamelCase_ ( cls : Optional[Any] , __lowercase : PixaStructTextConfig , __lowercase : PixaStructVisionConfig , **__lowercase : Optional[int] ): '''simple docstring''' return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **__lowercase ) def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' __a = copy.deepcopy(self.__dict__ ) __a = self.text_config.to_dict() __a = self.vision_config.to_dict() __a = self.__class__.model_type return output
302
import argparse import json from pathlib import Path import torch import torchaudio from datasets import load_dataset from huggingface_hub import hf_hub_download from transformers import ASTConfig, ASTFeatureExtractor, ASTForAudioClassification from transformers.utils import logging logging.set_verbosity_info() lowerCamelCase__ = logging.get_logger(__name__) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Any ): """simple docstring""" __a = ASTConfig() if "10-10" in model_name: pass elif "speech-commands" in model_name: __a = 128 elif "12-12" in model_name: __a = 12 __a = 12 elif "14-14" in model_name: __a = 14 __a = 14 elif "16-16" in model_name: __a = 16 __a = 16 else: raise ValueError("""Model not supported""" ) __a = """huggingface/label-files""" if "speech-commands" in model_name: __a = 35 __a = """speech-commands-v2-id2label.json""" else: __a = 527 __a = """audioset-id2label.json""" __a = json.load(open(hf_hub_download(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , repo_type="""dataset""" ) , """r""" ) ) __a = {int(_SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()} __a = idalabel __a = {v: k for k, v in idalabel.items()} return config def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" if "module.v" in name: __a = name.replace("""module.v""" , """audio_spectrogram_transformer""" ) if "cls_token" in name: __a = name.replace("""cls_token""" , """embeddings.cls_token""" ) if "dist_token" in name: __a = name.replace("""dist_token""" , """embeddings.distillation_token""" ) if "pos_embed" in name: __a = name.replace("""pos_embed""" , """embeddings.position_embeddings""" ) if "patch_embed.proj" in name: __a = name.replace("""patch_embed.proj""" , """embeddings.patch_embeddings.projection""" ) # transformer blocks if "blocks" in name: __a = name.replace("""blocks""" , """encoder.layer""" ) if "attn.proj" in name: __a = name.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in name: __a = name.replace("""attn""" , """attention.self""" ) if "norm1" in name: __a = name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: __a = name.replace("""norm2""" , """layernorm_after""" ) if "mlp.fc1" in name: __a = name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: __a = name.replace("""mlp.fc2""" , """output.dense""" ) # final layernorm if "audio_spectrogram_transformer.norm" in name: __a = name.replace("""audio_spectrogram_transformer.norm""" , """audio_spectrogram_transformer.layernorm""" ) # classifier head if "module.mlp_head.0" in name: __a = name.replace("""module.mlp_head.0""" , """classifier.layernorm""" ) if "module.mlp_head.1" in name: __a = name.replace("""module.mlp_head.1""" , """classifier.dense""" ) return name def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" for key in orig_state_dict.copy().keys(): __a = orig_state_dict.pop(_SCREAMING_SNAKE_CASE ) if "qkv" in key: __a = key.split(""".""" ) __a = int(key_split[3] ) __a = config.hidden_size if "weight" in key: __a = val[:dim, :] __a = val[dim : dim * 2, :] __a = val[-dim:, :] else: __a = val[:dim] __a = val[dim : dim * 2] __a = val[-dim:] else: __a = val return orig_state_dict def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" __a = [ """module.v.head.weight""", """module.v.head.bias""", """module.v.head_dist.weight""", """module.v.head_dist.bias""", ] for k in ignore_keys: state_dict.pop(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @torch.no_grad() def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : List[str]=False ): """simple docstring""" __a = get_audio_spectrogram_transformer_config(_SCREAMING_SNAKE_CASE ) __a = { """ast-finetuned-audioset-10-10-0.4593""": ( """https://www.dropbox.com/s/ca0b1v2nlxzyeb4/audioset_10_10_0.4593.pth?dl=1""" ), """ast-finetuned-audioset-10-10-0.450""": ( """https://www.dropbox.com/s/1tv0hovue1bxupk/audioset_10_10_0.4495.pth?dl=1""" ), """ast-finetuned-audioset-10-10-0.448""": ( """https://www.dropbox.com/s/6u5sikl4b9wo4u5/audioset_10_10_0.4483.pth?dl=1""" ), """ast-finetuned-audioset-10-10-0.448-v2""": ( """https://www.dropbox.com/s/kt6i0v9fvfm1mbq/audioset_10_10_0.4475.pth?dl=1""" ), """ast-finetuned-audioset-12-12-0.447""": ( """https://www.dropbox.com/s/snfhx3tizr4nuc8/audioset_12_12_0.4467.pth?dl=1""" ), """ast-finetuned-audioset-14-14-0.443""": ( """https://www.dropbox.com/s/z18s6pemtnxm4k7/audioset_14_14_0.4431.pth?dl=1""" ), """ast-finetuned-audioset-16-16-0.442""": ( """https://www.dropbox.com/s/mdsa4t1xmcimia6/audioset_16_16_0.4422.pth?dl=1""" ), """ast-finetuned-speech-commands-v2""": ( """https://www.dropbox.com/s/q0tbqpwv44pquwy/speechcommands_10_10_0.9812.pth?dl=1""" ), } # load original state_dict __a = model_name_to_url[model_name] __a = torch.hub.load_state_dict_from_url(_SCREAMING_SNAKE_CASE , map_location="""cpu""" ) # remove some keys remove_keys(_SCREAMING_SNAKE_CASE ) # rename some keys __a = convert_state_dict(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # load 🤗 model __a = ASTForAudioClassification(_SCREAMING_SNAKE_CASE ) model.eval() model.load_state_dict(_SCREAMING_SNAKE_CASE ) # verify outputs on dummy input # source: https://github.com/YuanGongND/ast/blob/79e873b8a54d0a3b330dd522584ff2b9926cd581/src/run.py#L62 __a = -4.267_7393 if """speech-commands""" not in model_name else -6.84_5978 __a = 4.568_9974 if """speech-commands""" not in model_name else 5.565_4526 __a = 1024 if """speech-commands""" not in model_name else 128 __a = ASTFeatureExtractor(mean=_SCREAMING_SNAKE_CASE , std=_SCREAMING_SNAKE_CASE , max_length=_SCREAMING_SNAKE_CASE ) if "speech-commands" in model_name: __a = load_dataset("""speech_commands""" , """v0.02""" , split="""validation""" ) __a = dataset[0]["""audio"""]["""array"""] else: __a = hf_hub_download( repo_id="""nielsr/audio-spectogram-transformer-checkpoint""" , filename="""sample_audio.flac""" , repo_type="""dataset""" , ) __a , __a = torchaudio.load(_SCREAMING_SNAKE_CASE ) __a = waveform.squeeze().numpy() __a = feature_extractor(_SCREAMING_SNAKE_CASE , sampling_rate=1_6000 , return_tensors="""pt""" ) # forward pass __a = model(**_SCREAMING_SNAKE_CASE ) __a = outputs.logits if model_name == "ast-finetuned-audioset-10-10-0.4593": __a = torch.tensor([-0.8760, -7.0042, -8.6602] ) elif model_name == "ast-finetuned-audioset-10-10-0.450": __a = torch.tensor([-1.1986, -7.0903, -8.2718] ) elif model_name == "ast-finetuned-audioset-10-10-0.448": __a = torch.tensor([-2.6128, -8.0080, -9.4344] ) elif model_name == "ast-finetuned-audioset-10-10-0.448-v2": __a = torch.tensor([-1.5080, -7.4534, -8.8917] ) elif model_name == "ast-finetuned-audioset-12-12-0.447": __a = torch.tensor([-0.5050, -6.5833, -8.0843] ) elif model_name == "ast-finetuned-audioset-14-14-0.443": __a = torch.tensor([-0.3826, -7.0336, -8.2413] ) elif model_name == "ast-finetuned-audioset-16-16-0.442": __a = torch.tensor([-1.2113, -6.9101, -8.3470] ) elif model_name == "ast-finetuned-speech-commands-v2": __a = torch.tensor([6.1589, -8.0566, -8.7984] ) else: raise ValueError("""Unknown model name""" ) if not torch.allclose(logits[0, :3] , _SCREAMING_SNAKE_CASE , atol=1e-4 ): raise ValueError("""Logits don't match""" ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) print(f"Saving model {model_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) print(f"Saving feature extractor to {pytorch_dump_folder_path}" ) feature_extractor.save_pretrained(_SCREAMING_SNAKE_CASE ) if push_to_hub: print("""Pushing model and feature extractor to the hub...""" ) model.push_to_hub(f"MIT/{model_name}" ) feature_extractor.push_to_hub(f"MIT/{model_name}" ) if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default="""ast-finetuned-audioset-10-10-0.4593""", type=str, help="""Name of the Audio Spectrogram Transformer model you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) parser.add_argument( """--push_to_hub""", action="""store_true""", help="""Whether or not to push the converted model to the 🤗 hub.""" ) lowerCamelCase__ = parser.parse_args() convert_audio_spectrogram_transformer_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
302
1
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { """google/realm-cc-news-pretrained-embedder""": ( """https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/config.json""" ), """google/realm-cc-news-pretrained-encoder""": ( """https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/config.json""" ), """google/realm-cc-news-pretrained-scorer""": ( """https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/config.json""" ), """google/realm-cc-news-pretrained-openqa""": ( """https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/config.json""" ), """google/realm-orqa-nq-openqa""": """https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/config.json""", """google/realm-orqa-nq-reader""": """https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/config.json""", """google/realm-orqa-wq-openqa""": """https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/config.json""", """google/realm-orqa-wq-reader""": """https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/config.json""", # See all REALM models at https://huggingface.co/models?filter=realm } class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : Union[str, Any] ='realm' def __init__( self : int , __lowercase : Union[str, Any]=30522 , __lowercase : List[str]=768 , __lowercase : Optional[int]=128 , __lowercase : Optional[int]=12 , __lowercase : List[Any]=12 , __lowercase : List[str]=8 , __lowercase : List[Any]=3072 , __lowercase : Union[str, Any]="gelu_new" , __lowercase : Union[str, Any]=0.1 , __lowercase : int=0.1 , __lowercase : str=512 , __lowercase : Optional[Any]=2 , __lowercase : List[Any]=0.02 , __lowercase : Optional[Any]=1E-12 , __lowercase : Dict=256 , __lowercase : str=10 , __lowercase : List[Any]=1E-3 , __lowercase : int=5 , __lowercase : Any=320 , __lowercase : List[Any]=13353718 , __lowercase : List[Any]=5000 , __lowercase : str=1 , __lowercase : List[Any]=0 , __lowercase : Tuple=2 , **__lowercase : Optional[Any] , ): '''simple docstring''' super().__init__(pad_token_id=__lowercase , bos_token_id=__lowercase , eos_token_id=__lowercase , **__lowercase ) # Common config __a = vocab_size __a = max_position_embeddings __a = hidden_size __a = retriever_proj_size __a = num_hidden_layers __a = num_attention_heads __a = num_candidates __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = initializer_range __a = type_vocab_size __a = layer_norm_eps # Reader config __a = span_hidden_size __a = max_span_width __a = reader_layer_norm_eps __a = reader_beam_size __a = reader_seq_len # Retrieval config __a = num_block_records __a = searcher_beam_size
302
import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_albert import AlbertTokenizer else: lowerCamelCase__ = None lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = {"""vocab_file""": """spiece.model""", """tokenizer_file""": """tokenizer.json"""} lowerCamelCase__ = { """vocab_file""": { """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/spiece.model""", """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/spiece.model""", """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model""", """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model""", """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/spiece.model""", """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/spiece.model""", """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model""", """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model""", }, """tokenizer_file""": { """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/tokenizer.json""", """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/tokenizer.json""", """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/tokenizer.json""", """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/tokenizer.json""", """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/tokenizer.json""", """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/tokenizer.json""", """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/tokenizer.json""", """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/tokenizer.json""", }, } lowerCamelCase__ = { """albert-base-v1""": 512, """albert-large-v1""": 512, """albert-xlarge-v1""": 512, """albert-xxlarge-v1""": 512, """albert-base-v2""": 512, """albert-large-v2""": 512, """albert-xlarge-v2""": 512, """albert-xxlarge-v2""": 512, } lowerCamelCase__ = """▁""" class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : List[Any] =VOCAB_FILES_NAMES __lowerCamelCase : Union[str, Any] =PRETRAINED_VOCAB_FILES_MAP __lowerCamelCase : List[str] =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCamelCase : Any =AlbertTokenizer def __init__( self : Tuple , __lowercase : Union[str, Any]=None , __lowercase : Optional[int]=None , __lowercase : int=True , __lowercase : Dict=True , __lowercase : str=False , __lowercase : str="[CLS]" , __lowercase : List[Any]="[SEP]" , __lowercase : Any="<unk>" , __lowercase : List[Any]="[SEP]" , __lowercase : List[Any]="<pad>" , __lowercase : Optional[Any]="[CLS]" , __lowercase : List[str]="[MASK]" , **__lowercase : str , ): '''simple docstring''' # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. __a = ( AddedToken(__lowercase , lstrip=__lowercase , rstrip=__lowercase , normalized=__lowercase ) if isinstance(__lowercase , __lowercase ) else mask_token ) super().__init__( __lowercase , tokenizer_file=__lowercase , do_lower_case=__lowercase , remove_space=__lowercase , keep_accents=__lowercase , bos_token=__lowercase , eos_token=__lowercase , unk_token=__lowercase , sep_token=__lowercase , pad_token=__lowercase , cls_token=__lowercase , mask_token=__lowercase , **__lowercase , ) __a = do_lower_case __a = remove_space __a = keep_accents __a = vocab_file __a = False if not self.vocab_file else True def UpperCamelCase_ ( self : Dict , __lowercase : List[int] , __lowercase : Optional[List[int]] = None ): '''simple docstring''' __a = [self.sep_token_id] __a = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def UpperCamelCase_ ( self : str , __lowercase : List[int] , __lowercase : Optional[List[int]] = None ): '''simple docstring''' __a = [self.sep_token_id] __a = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCamelCase_ ( self : Tuple , __lowercase : str , __lowercase : Optional[str] = None ): '''simple docstring''' if not self.can_save_slow_tokenizer: raise ValueError( """Your fast tokenizer does not have the necessary information to save the vocabulary for a slow """ """tokenizer.""" ) if not os.path.isdir(__lowercase ): logger.error(F"Vocabulary path ({save_directory}) should be a directory" ) return __a = os.path.join( __lowercase , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__lowercase ): copyfile(self.vocab_file , __lowercase ) return (out_vocab_file,)
302
1
import logging import torch from accelerate import Accelerator from arguments import EvaluationArguments from datasets import load_dataset from torch.utils.data import IterableDataset from torch.utils.data.dataloader import DataLoader from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, set_seed class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): def __init__( self : List[str] , __lowercase : str , __lowercase : Union[str, Any] , __lowercase : Any=1024 , __lowercase : Optional[Any]=1024 , __lowercase : Any=3.6 ): '''simple docstring''' __a = tokenizer __a = tokenizer.bos_token_id __a = dataset __a = seq_length __a = seq_length * chars_per_token * num_of_sequences def __iter__( self : Union[str, Any] ): '''simple docstring''' __a = iter(self.dataset ) __a = True while more_examples: __a , __a = [], 0 while True: if buffer_len >= self.input_characters: break try: buffer.append(next(__lowercase )["""content"""] ) buffer_len += len(buffer[-1] ) except StopIteration: __a = False break __a = tokenizer(__lowercase , truncation=__lowercase )["""input_ids"""] __a = [] for tokenized_input in tokenized_inputs: all_token_ids.extend(tokenized_input + [self.concat_token_id] ) for i in range(0 , len(__lowercase ) , self.seq_length ): __a = all_token_ids[i : i + self.seq_length] if len(__lowercase ) == self.seq_length: yield torch.tensor(__lowercase ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" __a = {"""streaming""": True} __a = load_dataset(args.dataset_name , split="""train""" , **_SCREAMING_SNAKE_CASE ) __a = ConstantLengthDataset(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , seq_length=args.seq_length ) __a = DataLoader(_SCREAMING_SNAKE_CASE , batch_size=args.batch_size ) return eval_dataloader def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : List[Any] ): """simple docstring""" model.eval() __a = [] for step, batch in enumerate(_SCREAMING_SNAKE_CASE ): with torch.no_grad(): __a = model(_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE ) __a = outputs.loss.repeat(args.batch_size ) losses.append(accelerator.gather(_SCREAMING_SNAKE_CASE ) ) if args.max_eval_steps > 0 and step >= args.max_eval_steps: break __a = torch.mean(torch.cat(_SCREAMING_SNAKE_CASE ) ) try: __a = torch.exp(_SCREAMING_SNAKE_CASE ) except OverflowError: __a = float("""inf""" ) return loss.item(), perplexity.item() # Setup Accelerator lowerCamelCase__ = Accelerator() # Parse configuration lowerCamelCase__ = HfArgumentParser(EvaluationArguments) lowerCamelCase__ = parser.parse_args() set_seed(args.seed) # Logging lowerCamelCase__ = logging.getLogger(__name__) logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""", datefmt="""%m/%d/%Y %H:%M:%S""", level=logging.INFO ) # Load model and tokenizer lowerCamelCase__ = AutoModelForCausalLM.from_pretrained(args.model_ckpt) lowerCamelCase__ = AutoTokenizer.from_pretrained(args.model_ckpt) # Load dataset and dataloader lowerCamelCase__ = create_dataloader(args) # Prepare everything with our `accelerator`. lowerCamelCase__ , lowerCamelCase__ = accelerator.prepare(model, eval_dataloader) # Evaluate and save the last checkpoint logger.info("""Evaluating and saving model after training""") lowerCamelCase__ , lowerCamelCase__ = evaluate(args) logger.info(F"""loss/eval: {eval_loss}, perplexity: {perplexity}""")
302
import tempfile import torch from diffusers import IPNDMScheduler from .test_schedulers import SchedulerCommonTest class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : Optional[int] =(IPNDMScheduler,) __lowerCamelCase : int =(('num_inference_steps', 50),) def UpperCamelCase_ ( self : str , **__lowercase : Dict ): '''simple docstring''' __a = {"""num_train_timesteps""": 1000} config.update(**__lowercase ) return config def UpperCamelCase_ ( self : Any , __lowercase : Tuple=0 , **__lowercase : Dict ): '''simple docstring''' __a = dict(self.forward_default_kwargs ) __a = kwargs.pop("""num_inference_steps""" , __lowercase ) __a = self.dummy_sample __a = 0.1 * sample __a = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: __a = self.get_scheduler_config(**__lowercase ) __a = scheduler_class(**__lowercase ) scheduler.set_timesteps(__lowercase ) # copy over dummy past residuals __a = dummy_past_residuals[:] if time_step is None: __a = scheduler.timesteps[len(scheduler.timesteps ) // 2] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(__lowercase ) __a = scheduler_class.from_pretrained(__lowercase ) new_scheduler.set_timesteps(__lowercase ) # copy over dummy past residuals __a = dummy_past_residuals[:] __a = scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample __a = new_scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" __a = scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample __a = new_scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def UpperCamelCase_ ( self : str ): '''simple docstring''' pass def UpperCamelCase_ ( self : str , __lowercase : int=0 , **__lowercase : Dict ): '''simple docstring''' __a = dict(self.forward_default_kwargs ) __a = kwargs.pop("""num_inference_steps""" , __lowercase ) __a = self.dummy_sample __a = 0.1 * sample __a = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: __a = self.get_scheduler_config() __a = scheduler_class(**__lowercase ) scheduler.set_timesteps(__lowercase ) # copy over dummy past residuals (must be after setting timesteps) __a = dummy_past_residuals[:] if time_step is None: __a = scheduler.timesteps[len(scheduler.timesteps ) // 2] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(__lowercase ) __a = scheduler_class.from_pretrained(__lowercase ) # copy over dummy past residuals new_scheduler.set_timesteps(__lowercase ) # copy over dummy past residual (must be after setting timesteps) __a = dummy_past_residuals[:] __a = scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample __a = new_scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" __a = scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample __a = new_scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def UpperCamelCase_ ( self : List[str] , **__lowercase : Dict ): '''simple docstring''' __a = self.scheduler_classes[0] __a = self.get_scheduler_config(**__lowercase ) __a = scheduler_class(**__lowercase ) __a = 10 __a = self.dummy_model() __a = self.dummy_sample_deter scheduler.set_timesteps(__lowercase ) for i, t in enumerate(scheduler.timesteps ): __a = model(__lowercase , __lowercase ) __a = scheduler.step(__lowercase , __lowercase , __lowercase ).prev_sample for i, t in enumerate(scheduler.timesteps ): __a = model(__lowercase , __lowercase ) __a = scheduler.step(__lowercase , __lowercase , __lowercase ).prev_sample return sample def UpperCamelCase_ ( self : str ): '''simple docstring''' __a = dict(self.forward_default_kwargs ) __a = kwargs.pop("""num_inference_steps""" , __lowercase ) for scheduler_class in self.scheduler_classes: __a = self.get_scheduler_config() __a = scheduler_class(**__lowercase ) __a = self.dummy_sample __a = 0.1 * sample if num_inference_steps is not None and hasattr(__lowercase , """set_timesteps""" ): scheduler.set_timesteps(__lowercase ) elif num_inference_steps is not None and not hasattr(__lowercase , """set_timesteps""" ): __a = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) __a = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] __a = dummy_past_residuals[:] __a = scheduler.timesteps[5] __a = scheduler.timesteps[6] __a = scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample __a = scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) __a = scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample __a = scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' for timesteps in [100, 1000]: self.check_over_configs(num_train_timesteps=__lowercase , time_step=__lowercase ) def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' for t, num_inference_steps in zip([1, 5, 10] , [10, 50, 100] ): self.check_over_forward(num_inference_steps=__lowercase , time_step=__lowercase ) def UpperCamelCase_ ( self : int ): '''simple docstring''' __a = self.full_loop() __a = torch.mean(torch.abs(__lowercase ) ) assert abs(result_mean.item() - 2540529 ) < 10
302
1
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig lowerCamelCase__ = { """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/config.json""", """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/config.json""", """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/config.json""", """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/config.json""", """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/config.json""", """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/config.json""", """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/config.json""", """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/config.json""", } class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : Optional[Any] ='albert' def __init__( self : Optional[Any] , __lowercase : Union[str, Any]=30000 , __lowercase : List[str]=128 , __lowercase : Optional[Any]=4096 , __lowercase : Dict=12 , __lowercase : Any=1 , __lowercase : Optional[Any]=64 , __lowercase : Any=16384 , __lowercase : Any=1 , __lowercase : Union[str, Any]="gelu_new" , __lowercase : List[str]=0 , __lowercase : int=0 , __lowercase : Dict=512 , __lowercase : str=2 , __lowercase : List[str]=0.02 , __lowercase : Union[str, Any]=1E-12 , __lowercase : int=0.1 , __lowercase : Any="absolute" , __lowercase : Optional[int]=0 , __lowercase : Dict=2 , __lowercase : Optional[Any]=3 , **__lowercase : Any , ): '''simple docstring''' super().__init__(pad_token_id=__lowercase , bos_token_id=__lowercase , eos_token_id=__lowercase , **__lowercase ) __a = vocab_size __a = embedding_size __a = hidden_size __a = num_hidden_layers __a = num_hidden_groups __a = num_attention_heads __a = inner_group_num __a = hidden_act __a = intermediate_size __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = type_vocab_size __a = initializer_range __a = layer_norm_eps __a = classifier_dropout_prob __a = position_embedding_type class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): @property def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' if self.task == "multiple-choice": __a = {0: """batch""", 1: """choice""", 2: """sequence"""} else: __a = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis), ] )
302
from __future__ import annotations lowerCamelCase__ = { """A""": ["""B""", """C""", """E"""], """B""": ["""A""", """D""", """E"""], """C""": ["""A""", """F""", """G"""], """D""": ["""B"""], """E""": ["""A""", """B""", """D"""], """F""": ["""C"""], """G""": ["""C"""], } class SCREAMING_SNAKE_CASE : def __init__( self : Tuple , __lowercase : dict[str, list[str]] , __lowercase : str ): '''simple docstring''' __a = graph # mapping node to its parent in resulting breadth first tree __a = {} __a = source_vertex def UpperCamelCase_ ( self : Any ): '''simple docstring''' __a = {self.source_vertex} __a = None __a = [self.source_vertex] # first in first out queue while queue: __a = queue.pop(0 ) for adjacent_vertex in self.graph[vertex]: if adjacent_vertex not in visited: visited.add(__lowercase ) __a = vertex queue.append(__lowercase ) def UpperCamelCase_ ( self : Optional[int] , __lowercase : str ): '''simple docstring''' if target_vertex == self.source_vertex: return self.source_vertex __a = self.parent.get(__lowercase ) if target_vertex_parent is None: __a = ( F"No path from vertex: {self.source_vertex} to vertex: {target_vertex}" ) raise ValueError(__lowercase ) return self.shortest_path(__lowercase ) + F"->{target_vertex}" if __name__ == "__main__": lowerCamelCase__ = Graph(graph, """G""") g.breath_first_search() print(g.shortest_path("""D""")) print(g.shortest_path("""G""")) print(g.shortest_path("""Foo"""))
302
1
from __future__ import annotations lowerCamelCase__ = { """A""": ["""B""", """C""", """E"""], """B""": ["""A""", """D""", """E"""], """C""": ["""A""", """F""", """G"""], """D""": ["""B"""], """E""": ["""A""", """B""", """D"""], """F""": ["""C"""], """G""": ["""C"""], } class SCREAMING_SNAKE_CASE : def __init__( self : Tuple , __lowercase : dict[str, list[str]] , __lowercase : str ): '''simple docstring''' __a = graph # mapping node to its parent in resulting breadth first tree __a = {} __a = source_vertex def UpperCamelCase_ ( self : Any ): '''simple docstring''' __a = {self.source_vertex} __a = None __a = [self.source_vertex] # first in first out queue while queue: __a = queue.pop(0 ) for adjacent_vertex in self.graph[vertex]: if adjacent_vertex not in visited: visited.add(__lowercase ) __a = vertex queue.append(__lowercase ) def UpperCamelCase_ ( self : Optional[int] , __lowercase : str ): '''simple docstring''' if target_vertex == self.source_vertex: return self.source_vertex __a = self.parent.get(__lowercase ) if target_vertex_parent is None: __a = ( F"No path from vertex: {self.source_vertex} to vertex: {target_vertex}" ) raise ValueError(__lowercase ) return self.shortest_path(__lowercase ) + F"->{target_vertex}" if __name__ == "__main__": lowerCamelCase__ = Graph(graph, """G""") g.breath_first_search() print(g.shortest_path("""D""")) print(g.shortest_path("""G""")) print(g.shortest_path("""Foo"""))
302
import unittest import numpy as np import torch from torch import nn from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import KandinskyVaaPriorPipeline, PriorTransformer, UnCLIPScheduler from diffusers.utils import torch_device from diffusers.utils.testing_utils import enable_full_determinism, skip_mps from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class SCREAMING_SNAKE_CASE ( lowerCamelCase__ , unittest.TestCase ): __lowerCamelCase : Tuple =KandinskyVaaPriorPipeline __lowerCamelCase : Union[str, Any] =['prompt'] __lowerCamelCase : Any =['prompt', 'negative_prompt'] __lowerCamelCase : List[str] =[ 'num_images_per_prompt', 'generator', 'num_inference_steps', 'latents', 'negative_prompt', 'guidance_scale', 'output_type', 'return_dict', ] __lowerCamelCase : List[Any] =False @property def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' return 32 @property def UpperCamelCase_ ( self : Any ): '''simple docstring''' return 32 @property def UpperCamelCase_ ( self : str ): '''simple docstring''' return self.time_input_dim @property def UpperCamelCase_ ( self : str ): '''simple docstring''' return self.time_input_dim * 4 @property def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' return 100 @property def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' __a = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) return tokenizer @property def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' torch.manual_seed(0 ) __a = 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-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(__lowercase ) @property def UpperCamelCase_ ( self : int ): '''simple docstring''' torch.manual_seed(0 ) __a = { """num_attention_heads""": 2, """attention_head_dim""": 12, """embedding_dim""": self.text_embedder_hidden_size, """num_layers""": 1, } __a = PriorTransformer(**__lowercase ) # clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0 __a = nn.Parameter(torch.ones(model.clip_std.shape ) ) return model @property def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' torch.manual_seed(0 ) __a = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=224 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=14 , ) __a = CLIPVisionModelWithProjection(__lowercase ) return model @property def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' __a = CLIPImageProcessor( crop_size=224 , do_center_crop=__lowercase , do_normalize=__lowercase , do_resize=__lowercase , image_mean=[0.48145466, 0.4578275, 0.40821073] , image_std=[0.26862954, 0.26130258, 0.27577711] , resample=3 , size=224 , ) return image_processor def UpperCamelCase_ ( self : str ): '''simple docstring''' __a = self.dummy_prior __a = self.dummy_image_encoder __a = self.dummy_text_encoder __a = self.dummy_tokenizer __a = self.dummy_image_processor __a = UnCLIPScheduler( variance_type="""fixed_small_log""" , prediction_type="""sample""" , num_train_timesteps=1000 , clip_sample=__lowercase , clip_sample_range=10.0 , ) __a = { """prior""": prior, """image_encoder""": image_encoder, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """scheduler""": scheduler, """image_processor""": image_processor, } return components def UpperCamelCase_ ( self : Optional[int] , __lowercase : List[str] , __lowercase : Any=0 ): '''simple docstring''' if str(__lowercase ).startswith("""mps""" ): __a = torch.manual_seed(__lowercase ) else: __a = torch.Generator(device=__lowercase ).manual_seed(__lowercase ) __a = { """prompt""": """horse""", """generator""": generator, """guidance_scale""": 4.0, """num_inference_steps""": 2, """output_type""": """np""", } return inputs def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' __a = """cpu""" __a = self.get_dummy_components() __a = self.pipeline_class(**__lowercase ) __a = pipe.to(__lowercase ) pipe.set_progress_bar_config(disable=__lowercase ) __a = pipe(**self.get_dummy_inputs(__lowercase ) ) __a = output.image_embeds __a = pipe( **self.get_dummy_inputs(__lowercase ) , return_dict=__lowercase , )[0] __a = image[0, -10:] __a = image_from_tuple[0, -10:] assert image.shape == (1, 32) __a = np.array( [-0.0532, 1.7120, 0.3656, -1.0852, -0.8946, -1.1756, 0.4348, 0.2482, 0.5146, -0.1156] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 @skip_mps def UpperCamelCase_ ( self : Dict ): '''simple docstring''' __a = torch_device == """cpu""" __a = True __a = False self._test_inference_batch_single_identical( test_max_difference=__lowercase , relax_max_difference=__lowercase , test_mean_pixel_difference=__lowercase , ) @skip_mps def UpperCamelCase_ ( self : Any ): '''simple docstring''' __a = torch_device == """cpu""" __a = False self._test_attention_slicing_forward_pass( test_max_difference=__lowercase , test_mean_pixel_difference=__lowercase , )
302
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, is_vision_available, ) lowerCamelCase__ = {"""processing_layoutxlm""": ["""LayoutXLMProcessor"""]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = ["""LayoutXLMTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = ["""LayoutXLMTokenizerFast"""] if TYPE_CHECKING: from .processing_layoutxlm import LayoutXLMProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutxlm import LayoutXLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutxlm_fast import LayoutXLMTokenizerFast else: import sys lowerCamelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
302
from typing import Any, Dict, List, Union from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from ..image_utils import load_image if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_OBJECT_DETECTION_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = Dict[str, Any] lowerCamelCase__ = List[Prediction] @add_end_docstrings(lowerCamelCase__ ) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): def __init__( self : Tuple , *__lowercase : Tuple , **__lowercase : Optional[int] ): '''simple docstring''' super().__init__(*__lowercase , **__lowercase ) if self.framework == "tf": raise ValueError(F"The {self.__class__} is only available in PyTorch." ) requires_backends(self , """vision""" ) self.check_model_type( dict(MODEL_FOR_OBJECT_DETECTION_MAPPING.items() + MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING.items() ) ) def UpperCamelCase_ ( self : Optional[int] , **__lowercase : List[str] ): '''simple docstring''' __a = {} if "threshold" in kwargs: __a = kwargs["""threshold"""] return {}, {}, postprocess_kwargs def __call__( self : List[Any] , *__lowercase : Any , **__lowercase : Tuple ): '''simple docstring''' return super().__call__(*__lowercase , **__lowercase ) def UpperCamelCase_ ( self : str , __lowercase : Tuple ): '''simple docstring''' __a = load_image(__lowercase ) __a = torch.IntTensor([[image.height, image.width]] ) __a = self.image_processor(images=[image] , return_tensors="""pt""" ) if self.tokenizer is not None: __a = self.tokenizer(text=inputs["""words"""] , boxes=inputs["""boxes"""] , return_tensors="""pt""" ) __a = target_size return inputs def UpperCamelCase_ ( self : Dict , __lowercase : List[str] ): '''simple docstring''' __a = model_inputs.pop("""target_size""" ) __a = self.model(**__lowercase ) __a = outputs.__class__({"""target_size""": target_size, **outputs} ) if self.tokenizer is not None: __a = model_inputs["""bbox"""] return model_outputs def UpperCamelCase_ ( self : Optional[int] , __lowercase : List[Any] , __lowercase : List[Any]=0.9 ): '''simple docstring''' __a = model_outputs["""target_size"""] if self.tokenizer is not None: # This is a LayoutLMForTokenClassification variant. # The OCR got the boxes and the model classified the words. __a , __a = target_size[0].tolist() def unnormalize(__lowercase : Optional[Any] ): return self._get_bounding_box( torch.Tensor( [ (width * bbox[0] / 1000), (height * bbox[1] / 1000), (width * bbox[2] / 1000), (height * bbox[3] / 1000), ] ) ) __a , __a = model_outputs["""logits"""].squeeze(0 ).softmax(dim=-1 ).max(dim=-1 ) __a = [self.model.config.idalabel[prediction] for prediction in classes.tolist()] __a = [unnormalize(__lowercase ) for bbox in model_outputs["""bbox"""].squeeze(0 )] __a = ["""score""", """label""", """box"""] __a = [dict(zip(__lowercase , __lowercase ) ) for vals in zip(scores.tolist() , __lowercase , __lowercase ) if vals[0] > threshold] else: # This is a regular ForObjectDetectionModel __a = self.image_processor.post_process_object_detection(__lowercase , __lowercase , __lowercase ) __a = raw_annotations[0] __a = raw_annotation["""scores"""] __a = raw_annotation["""labels"""] __a = raw_annotation["""boxes"""] __a = scores.tolist() __a = [self.model.config.idalabel[label.item()] for label in labels] __a = [self._get_bounding_box(__lowercase ) for box in boxes] # {"scores": [...], ...} --> [{"score":x, ...}, ...] __a = ["""score""", """label""", """box"""] __a = [ dict(zip(__lowercase , __lowercase ) ) for vals in zip(raw_annotation["""scores"""] , raw_annotation["""labels"""] , raw_annotation["""boxes"""] ) ] return annotation def UpperCamelCase_ ( self : Optional[int] , __lowercase : "torch.Tensor" ): '''simple docstring''' if self.framework != "pt": raise ValueError("""The ObjectDetectionPipeline is only available in PyTorch.""" ) __a , __a , __a , __a = box.int().tolist() __a = { """xmin""": xmin, """ymin""": ymin, """xmax""": xmax, """ymax""": ymax, } return bbox
302
1
import argparse import os.path as osp import re import torch from safetensors.torch import load_file, save_file # =================# # UNet Conversion # # =================# lowerCamelCase__ = [ # (stable-diffusion, HF Diffusers) ("""time_embed.0.weight""", """time_embedding.linear_1.weight"""), ("""time_embed.0.bias""", """time_embedding.linear_1.bias"""), ("""time_embed.2.weight""", """time_embedding.linear_2.weight"""), ("""time_embed.2.bias""", """time_embedding.linear_2.bias"""), ("""input_blocks.0.0.weight""", """conv_in.weight"""), ("""input_blocks.0.0.bias""", """conv_in.bias"""), ("""out.0.weight""", """conv_norm_out.weight"""), ("""out.0.bias""", """conv_norm_out.bias"""), ("""out.2.weight""", """conv_out.weight"""), ("""out.2.bias""", """conv_out.bias"""), ] lowerCamelCase__ = [ # (stable-diffusion, HF Diffusers) ("""in_layers.0""", """norm1"""), ("""in_layers.2""", """conv1"""), ("""out_layers.0""", """norm2"""), ("""out_layers.3""", """conv2"""), ("""emb_layers.1""", """time_emb_proj"""), ("""skip_connection""", """conv_shortcut"""), ] lowerCamelCase__ = [] # hardcoded number of downblocks and resnets/attentions... # would need smarter logic for other networks. for i in range(4): # loop over downblocks/upblocks for j in range(2): # loop over resnets/attentions for downblocks lowerCamelCase__ = F"""down_blocks.{i}.resnets.{j}.""" lowerCamelCase__ = F"""input_blocks.{3*i + j + 1}.0.""" unet_conversion_map_layer.append((sd_down_res_prefix, hf_down_res_prefix)) if i < 3: # no attention layers in down_blocks.3 lowerCamelCase__ = F"""down_blocks.{i}.attentions.{j}.""" lowerCamelCase__ = F"""input_blocks.{3*i + j + 1}.1.""" unet_conversion_map_layer.append((sd_down_atn_prefix, hf_down_atn_prefix)) for j in range(3): # loop over resnets/attentions for upblocks lowerCamelCase__ = F"""up_blocks.{i}.resnets.{j}.""" lowerCamelCase__ = F"""output_blocks.{3*i + j}.0.""" unet_conversion_map_layer.append((sd_up_res_prefix, hf_up_res_prefix)) if i > 0: # no attention layers in up_blocks.0 lowerCamelCase__ = F"""up_blocks.{i}.attentions.{j}.""" lowerCamelCase__ = F"""output_blocks.{3*i + j}.1.""" unet_conversion_map_layer.append((sd_up_atn_prefix, hf_up_atn_prefix)) if i < 3: # no downsample in down_blocks.3 lowerCamelCase__ = F"""down_blocks.{i}.downsamplers.0.conv.""" lowerCamelCase__ = F"""input_blocks.{3*(i+1)}.0.op.""" unet_conversion_map_layer.append((sd_downsample_prefix, hf_downsample_prefix)) # no upsample in up_blocks.3 lowerCamelCase__ = F"""up_blocks.{i}.upsamplers.0.""" lowerCamelCase__ = F"""output_blocks.{3*i + 2}.{1 if i == 0 else 2}.""" unet_conversion_map_layer.append((sd_upsample_prefix, hf_upsample_prefix)) lowerCamelCase__ = """mid_block.attentions.0.""" lowerCamelCase__ = """middle_block.1.""" unet_conversion_map_layer.append((sd_mid_atn_prefix, hf_mid_atn_prefix)) for j in range(2): lowerCamelCase__ = F"""mid_block.resnets.{j}.""" lowerCamelCase__ = F"""middle_block.{2*j}.""" unet_conversion_map_layer.append((sd_mid_res_prefix, hf_mid_res_prefix)) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Any ): """simple docstring""" __a = {k: k for k in unet_state_dict.keys()} for sd_name, hf_name in unet_conversion_map: __a = sd_name for k, v in mapping.items(): if "resnets" in k: for sd_part, hf_part in unet_conversion_map_resnet: __a = v.replace(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __a = v for k, v in mapping.items(): for sd_part, hf_part in unet_conversion_map_layer: __a = v.replace(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __a = v __a = {v: unet_state_dict[k] for k, v in mapping.items()} return new_state_dict # ================# # VAE Conversion # # ================# lowerCamelCase__ = [ # (stable-diffusion, HF Diffusers) ("""nin_shortcut""", """conv_shortcut"""), ("""norm_out""", """conv_norm_out"""), ("""mid.attn_1.""", """mid_block.attentions.0."""), ] for i in range(4): # down_blocks have two resnets for j in range(2): lowerCamelCase__ = F"""encoder.down_blocks.{i}.resnets.{j}.""" lowerCamelCase__ = F"""encoder.down.{i}.block.{j}.""" vae_conversion_map.append((sd_down_prefix, hf_down_prefix)) if i < 3: lowerCamelCase__ = F"""down_blocks.{i}.downsamplers.0.""" lowerCamelCase__ = F"""down.{i}.downsample.""" vae_conversion_map.append((sd_downsample_prefix, hf_downsample_prefix)) lowerCamelCase__ = F"""up_blocks.{i}.upsamplers.0.""" lowerCamelCase__ = F"""up.{3-i}.upsample.""" vae_conversion_map.append((sd_upsample_prefix, hf_upsample_prefix)) # up_blocks have three resnets # also, up blocks in hf are numbered in reverse from sd for j in range(3): lowerCamelCase__ = F"""decoder.up_blocks.{i}.resnets.{j}.""" lowerCamelCase__ = F"""decoder.up.{3-i}.block.{j}.""" vae_conversion_map.append((sd_up_prefix, hf_up_prefix)) # this part accounts for mid blocks in both the encoder and the decoder for i in range(2): lowerCamelCase__ = F"""mid_block.resnets.{i}.""" lowerCamelCase__ = F"""mid.block_{i+1}.""" vae_conversion_map.append((sd_mid_res_prefix, hf_mid_res_prefix)) lowerCamelCase__ = [ # (stable-diffusion, HF Diffusers) ("""norm.""", """group_norm."""), ("""q.""", """query."""), ("""k.""", """key."""), ("""v.""", """value."""), ("""proj_out.""", """proj_attn."""), ] def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" return w.reshape(*w.shape , 1 , 1 ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Any ): """simple docstring""" __a = {k: k for k in vae_state_dict.keys()} for k, v in mapping.items(): for sd_part, hf_part in vae_conversion_map: __a = v.replace(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __a = v for k, v in mapping.items(): if "attentions" in k: for sd_part, hf_part in vae_conversion_map_attn: __a = v.replace(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __a = v __a = {v: vae_state_dict[k] for k, v in mapping.items()} __a = ["""q""", """k""", """v""", """proj_out"""] for k, v in new_state_dict.items(): for weight_name in weights_to_convert: if f"mid.attn_1.{weight_name}.weight" in k: print(f"Reshaping {k} for SD format" ) __a = reshape_weight_for_sd(_SCREAMING_SNAKE_CASE ) return new_state_dict # =========================# # Text Encoder Conversion # # =========================# lowerCamelCase__ = [ # (stable-diffusion, HF Diffusers) ("""resblocks.""", """text_model.encoder.layers."""), ("""ln_1""", """layer_norm1"""), ("""ln_2""", """layer_norm2"""), (""".c_fc.""", """.fc1."""), (""".c_proj.""", """.fc2."""), (""".attn""", """.self_attn"""), ("""ln_final.""", """transformer.text_model.final_layer_norm."""), ("""token_embedding.weight""", """transformer.text_model.embeddings.token_embedding.weight"""), ("""positional_embedding""", """transformer.text_model.embeddings.position_embedding.weight"""), ] lowerCamelCase__ = {re.escape(x[1]): x[0] for x in textenc_conversion_lst} lowerCamelCase__ = re.compile("""|""".join(protected.keys())) # Ordering is from https://github.com/pytorch/pytorch/blob/master/test/cpp/api/modules.cpp lowerCamelCase__ = {"""q""": 0, """k""": 1, """v""": 2} def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int ): """simple docstring""" __a = {} __a = {} __a = {} for k, v in text_enc_dict.items(): if ( k.endswith(""".self_attn.q_proj.weight""" ) or k.endswith(""".self_attn.k_proj.weight""" ) or k.endswith(""".self_attn.v_proj.weight""" ) ): __a = k[: -len(""".q_proj.weight""" )] __a = k[-len("""q_proj.weight""" )] if k_pre not in capture_qkv_weight: __a = [None, None, None] __a = v continue if ( k.endswith(""".self_attn.q_proj.bias""" ) or k.endswith(""".self_attn.k_proj.bias""" ) or k.endswith(""".self_attn.v_proj.bias""" ) ): __a = k[: -len(""".q_proj.bias""" )] __a = k[-len("""q_proj.bias""" )] if k_pre not in capture_qkv_bias: __a = [None, None, None] __a = v continue __a = textenc_pattern.sub(lambda _SCREAMING_SNAKE_CASE : protected[re.escape(m.group(0 ) )] , _SCREAMING_SNAKE_CASE ) __a = v for k_pre, tensors in capture_qkv_weight.items(): if None in tensors: raise Exception("""CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing""" ) __a = textenc_pattern.sub(lambda _SCREAMING_SNAKE_CASE : protected[re.escape(m.group(0 ) )] , _SCREAMING_SNAKE_CASE ) __a = torch.cat(_SCREAMING_SNAKE_CASE ) for k_pre, tensors in capture_qkv_bias.items(): if None in tensors: raise Exception("""CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing""" ) __a = textenc_pattern.sub(lambda _SCREAMING_SNAKE_CASE : protected[re.escape(m.group(0 ) )] , _SCREAMING_SNAKE_CASE ) __a = torch.cat(_SCREAMING_SNAKE_CASE ) return new_state_dict def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int ): """simple docstring""" return text_enc_dict if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() parser.add_argument("""--model_path""", default=None, type=str, required=True, help="""Path to the model to convert.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, required=True, help="""Path to the output model.""") parser.add_argument("""--half""", action="""store_true""", help="""Save weights in half precision.""") parser.add_argument( """--use_safetensors""", action="""store_true""", help="""Save weights use safetensors, default is ckpt.""" ) lowerCamelCase__ = parser.parse_args() assert args.model_path is not None, "Must provide a model path!" assert args.checkpoint_path is not None, "Must provide a checkpoint path!" # Path for safetensors lowerCamelCase__ = osp.join(args.model_path, """unet""", """diffusion_pytorch_model.safetensors""") lowerCamelCase__ = osp.join(args.model_path, """vae""", """diffusion_pytorch_model.safetensors""") lowerCamelCase__ = osp.join(args.model_path, """text_encoder""", """model.safetensors""") # Load models from safetensors if it exists, if it doesn't pytorch if osp.exists(unet_path): lowerCamelCase__ = load_file(unet_path, device="""cpu""") else: lowerCamelCase__ = osp.join(args.model_path, """unet""", """diffusion_pytorch_model.bin""") lowerCamelCase__ = torch.load(unet_path, map_location="""cpu""") if osp.exists(vae_path): lowerCamelCase__ = load_file(vae_path, device="""cpu""") else: lowerCamelCase__ = osp.join(args.model_path, """vae""", """diffusion_pytorch_model.bin""") lowerCamelCase__ = torch.load(vae_path, map_location="""cpu""") if osp.exists(text_enc_path): lowerCamelCase__ = load_file(text_enc_path, device="""cpu""") else: lowerCamelCase__ = osp.join(args.model_path, """text_encoder""", """pytorch_model.bin""") lowerCamelCase__ = torch.load(text_enc_path, map_location="""cpu""") # Convert the UNet model lowerCamelCase__ = convert_unet_state_dict(unet_state_dict) lowerCamelCase__ = {"""model.diffusion_model.""" + k: v for k, v in unet_state_dict.items()} # Convert the VAE model lowerCamelCase__ = convert_vae_state_dict(vae_state_dict) lowerCamelCase__ = {"""first_stage_model.""" + k: v for k, v in vae_state_dict.items()} # Easiest way to identify v2.0 model seems to be that the text encoder (OpenCLIP) is deeper lowerCamelCase__ = """text_model.encoder.layers.22.layer_norm2.bias""" in text_enc_dict if is_vaa_model: # Need to add the tag 'transformer' in advance so we can knock it out from the final layer-norm lowerCamelCase__ = {"""transformer.""" + k: v for k, v in text_enc_dict.items()} lowerCamelCase__ = convert_text_enc_state_dict_vaa(text_enc_dict) lowerCamelCase__ = {"""cond_stage_model.model.""" + k: v for k, v in text_enc_dict.items()} else: lowerCamelCase__ = convert_text_enc_state_dict(text_enc_dict) lowerCamelCase__ = {"""cond_stage_model.transformer.""" + k: v for k, v in text_enc_dict.items()} # Put together new checkpoint lowerCamelCase__ = {**unet_state_dict, **vae_state_dict, **text_enc_dict} if args.half: lowerCamelCase__ = {k: v.half() for k, v in state_dict.items()} if args.use_safetensors: save_file(state_dict, args.checkpoint_path) else: lowerCamelCase__ = {"""state_dict""": state_dict} torch.save(state_dict, args.checkpoint_path)
302
# 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 # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowerCamelCase__ = { """configuration_efficientnet""": [ """EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP""", """EfficientNetConfig""", """EfficientNetOnnxConfig""", ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = ["""EfficientNetImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ """EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST""", """EfficientNetForImageClassification""", """EfficientNetModel""", """EfficientNetPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_efficientnet import ( EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP, EfficientNetConfig, EfficientNetOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_efficientnet import EfficientNetImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_efficientnet import ( EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST, EfficientNetForImageClassification, EfficientNetModel, EfficientNetPreTrainedModel, ) else: import sys lowerCamelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure)
302
1
from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer from ...configuration_utils import PretrainedConfig from ...file_utils import TensorType, is_torch_available from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast from ...onnx.utils import compute_effective_axis_dimension from ...utils import logging lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { """facebook/blenderbot_small-90M""": """https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/config.json""", # See all BlenderbotSmall models at https://huggingface.co/models?filter=blenderbot_small } class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : Union[str, Any] ='blenderbot-small' __lowerCamelCase : int =['past_key_values'] __lowerCamelCase : int ={'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self : List[Any] , __lowercase : List[Any]=50265 , __lowercase : Optional[int]=512 , __lowercase : Union[str, Any]=8 , __lowercase : Optional[int]=2048 , __lowercase : Optional[int]=16 , __lowercase : List[str]=8 , __lowercase : Optional[Any]=2048 , __lowercase : int=16 , __lowercase : str=0.0 , __lowercase : Optional[Any]=0.0 , __lowercase : str=True , __lowercase : Tuple=True , __lowercase : Optional[int]="gelu" , __lowercase : List[Any]=512 , __lowercase : Optional[int]=0.1 , __lowercase : Optional[Any]=0.0 , __lowercase : Optional[int]=0.0 , __lowercase : Any=0.02 , __lowercase : List[str]=1 , __lowercase : Optional[Any]=False , __lowercase : Union[str, Any]=0 , __lowercase : Optional[Any]=1 , __lowercase : str=2 , __lowercase : str=2 , **__lowercase : Any , ): '''simple docstring''' __a = vocab_size __a = max_position_embeddings __a = d_model __a = encoder_ffn_dim __a = encoder_layers __a = encoder_attention_heads __a = decoder_ffn_dim __a = decoder_layers __a = decoder_attention_heads __a = dropout __a = attention_dropout __a = activation_dropout __a = activation_function __a = init_std __a = encoder_layerdrop __a = decoder_layerdrop __a = use_cache __a = encoder_layers __a = scale_embedding # scale factor will be sqrt(d_model) if True super().__init__( pad_token_id=__lowercase , bos_token_id=__lowercase , eos_token_id=__lowercase , is_encoder_decoder=__lowercase , decoder_start_token_id=__lowercase , forced_eos_token_id=__lowercase , **__lowercase , ) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): @property def UpperCamelCase_ ( self : str ): '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: __a = OrderedDict( [ ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}), ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}), ] ) if self.use_past: __a = {0: """batch"""} __a = {0: """batch""", 1: """past_decoder_sequence + sequence"""} else: __a = {0: """batch""", 1: """decoder_sequence"""} __a = {0: """batch""", 1: """decoder_sequence"""} if self.use_past: self.fill_with_past_key_values_(__lowercase , direction="""inputs""" ) elif self.task == "causal-lm": # TODO: figure this case out. __a = OrderedDict( [ ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}), ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}), ] ) if self.use_past: __a , __a = self.num_layers for i in range(__lowercase ): __a = {0: """batch""", 2: """past_sequence + sequence"""} __a = {0: """batch""", 2: """past_sequence + sequence"""} else: __a = OrderedDict( [ ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}), ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}), ("""decoder_input_ids""", {0: """batch""", 1: """decoder_sequence"""}), ("""decoder_attention_mask""", {0: """batch""", 1: """decoder_sequence"""}), ] ) return common_inputs @property def UpperCamelCase_ ( self : Optional[int] ): '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: __a = super().outputs else: __a = super(__lowercase , self ).outputs if self.use_past: __a , __a = self.num_layers for i in range(__lowercase ): __a = {0: """batch""", 2: """past_sequence + sequence"""} __a = {0: """batch""", 2: """past_sequence + sequence"""} return common_outputs def UpperCamelCase_ ( self : Dict , __lowercase : PreTrainedTokenizer , __lowercase : int = -1 , __lowercase : int = -1 , __lowercase : bool = False , __lowercase : Optional[TensorType] = None , ): '''simple docstring''' __a = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( __lowercase , __lowercase , __lowercase , __lowercase , __lowercase ) # Generate decoder inputs __a = seq_length if not self.use_past else 1 __a = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( __lowercase , __lowercase , __lowercase , __lowercase , __lowercase ) __a = {F"decoder_{name}": tensor for name, tensor in decoder_inputs.items()} __a = dict(**__lowercase , **__lowercase ) if self.use_past: if not is_torch_available(): raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed.""" ) else: import torch __a , __a = common_inputs["""input_ids"""].shape __a = common_inputs["""decoder_input_ids"""].shape[1] __a , __a = self.num_attention_heads __a = ( batch, num_encoder_attention_heads, encoder_seq_length, self._config.hidden_size // num_encoder_attention_heads, ) __a = decoder_seq_length + 3 __a = ( batch, num_decoder_attention_heads, decoder_past_length, self._config.hidden_size // num_decoder_attention_heads, ) __a = torch.cat( [common_inputs["""decoder_attention_mask"""], torch.ones(__lowercase , __lowercase )] , dim=1 ) __a = [] # If the number of encoder and decoder layers are present in the model configuration, both are considered __a , __a = self.num_layers __a = min(__lowercase , __lowercase ) __a = max(__lowercase , __lowercase ) - min_num_layers __a = """encoder""" if num_encoder_layers > num_decoder_layers else """decoder""" for _ in range(__lowercase ): common_inputs["past_key_values"].append( ( torch.zeros(__lowercase ), torch.zeros(__lowercase ), torch.zeros(__lowercase ), torch.zeros(__lowercase ), ) ) # TODO: test this. __a = encoder_shape if remaining_side_name == """encoder""" else decoder_shape for _ in range(__lowercase , __lowercase ): common_inputs["past_key_values"].append((torch.zeros(__lowercase ), torch.zeros(__lowercase )) ) return common_inputs def UpperCamelCase_ ( self : List[Any] , __lowercase : PreTrainedTokenizer , __lowercase : int = -1 , __lowercase : int = -1 , __lowercase : bool = False , __lowercase : Optional[TensorType] = None , ): '''simple docstring''' __a = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( __lowercase , __lowercase , __lowercase , __lowercase , __lowercase ) if self.use_past: if not is_torch_available(): raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed.""" ) else: import torch __a , __a = common_inputs["""input_ids"""].shape # Not using the same length for past_key_values __a = seqlen + 2 __a , __a = self.num_layers __a , __a = self.num_attention_heads __a = ( batch, num_encoder_attention_heads, past_key_values_length, self._config.hidden_size // num_encoder_attention_heads, ) __a = common_inputs["""attention_mask"""].dtype __a = torch.cat( [common_inputs["""attention_mask"""], torch.ones(__lowercase , __lowercase , dtype=__lowercase )] , dim=1 ) __a = [ (torch.zeros(__lowercase ), torch.zeros(__lowercase )) for _ in range(__lowercase ) ] return common_inputs def UpperCamelCase_ ( self : int , __lowercase : PreTrainedTokenizer , __lowercase : int = -1 , __lowercase : int = -1 , __lowercase : bool = False , __lowercase : Optional[TensorType] = None , ): '''simple docstring''' # Copied from OnnxConfig.generate_dummy_inputs # Did not use super(OnnxConfigWithPast, self).generate_dummy_inputs for code clarity. # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX __a = compute_effective_axis_dimension( __lowercase , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX __a = tokenizer.num_special_tokens_to_add(__lowercase ) __a = compute_effective_axis_dimension( __lowercase , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=__lowercase ) # Generate dummy inputs according to compute batch and sequence __a = [""" """.join([tokenizer.unk_token] ) * seq_length] * batch_size __a = dict(tokenizer(__lowercase , return_tensors=__lowercase ) ) return common_inputs def UpperCamelCase_ ( self : str , __lowercase : PreTrainedTokenizer , __lowercase : int = -1 , __lowercase : int = -1 , __lowercase : bool = False , __lowercase : Optional[TensorType] = None , ): '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: __a = self._generate_dummy_inputs_for_default_and_seqaseq_lm( __lowercase , batch_size=__lowercase , seq_length=__lowercase , is_pair=__lowercase , framework=__lowercase ) elif self.task == "causal-lm": __a = self._generate_dummy_inputs_for_causal_lm( __lowercase , batch_size=__lowercase , seq_length=__lowercase , is_pair=__lowercase , framework=__lowercase ) else: __a = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( __lowercase , batch_size=__lowercase , seq_length=__lowercase , is_pair=__lowercase , framework=__lowercase ) return common_inputs def UpperCamelCase_ ( self : Union[str, Any] , __lowercase : Dict , __lowercase : List[str] , __lowercase : Any , __lowercase : Dict ): '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: __a = super()._flatten_past_key_values_(__lowercase , __lowercase , __lowercase , __lowercase ) else: __a = super(__lowercase , self )._flatten_past_key_values_( __lowercase , __lowercase , __lowercase , __lowercase )
302
import random def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : list , _SCREAMING_SNAKE_CASE : List[Any] ): """simple docstring""" __a , __a , __a = [], [], [] for element in data: if element < pivot: less.append(_SCREAMING_SNAKE_CASE ) elif element > pivot: greater.append(_SCREAMING_SNAKE_CASE ) else: equal.append(_SCREAMING_SNAKE_CASE ) return less, equal, greater def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : list , _SCREAMING_SNAKE_CASE : int ): """simple docstring""" if index >= len(_SCREAMING_SNAKE_CASE ) or index < 0: return None __a = items[random.randint(0 , len(_SCREAMING_SNAKE_CASE ) - 1 )] __a = 0 __a , __a , __a = _partition(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __a = len(_SCREAMING_SNAKE_CASE ) __a = len(_SCREAMING_SNAKE_CASE ) # index is the pivot if m <= index < m + count: return pivot # must be in smaller elif m > index: return quick_select(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # must be in larger else: return quick_select(_SCREAMING_SNAKE_CASE , index - (m + count) )
302
1
from math import loga def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int ): """simple docstring""" if a < 0: raise ValueError("""Input value must be a positive integer""" ) elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): raise TypeError("""Input value must be a 'int' type""" ) return 0 if (a == 0) else int(loga(a & -a ) ) if __name__ == "__main__": import doctest doctest.testmod()
302
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 lowerCamelCase__ = logging.get_logger(__name__) @add_end_docstrings(lowerCamelCase__ ) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): def __init__( self : Optional[int] , **__lowercase : Dict ): '''simple docstring''' super().__init__(**__lowercase ) if self.framework != "pt": raise ValueError(F"The {self.__class__} is only available in PyTorch." ) # No specific FOR_XXX available yet def __call__( self : str , __lowercase : Union[np.ndarray, bytes, str] , **__lowercase : int ): '''simple docstring''' return super().__call__(__lowercase , **__lowercase ) def UpperCamelCase_ ( self : List[Any] , **__lowercase : Union[str, Any] ): '''simple docstring''' __a = {} if "candidate_labels" in kwargs: __a = kwargs["""candidate_labels"""] if "hypothesis_template" in kwargs: __a = kwargs["""hypothesis_template"""] return preprocess_params, {}, {} def UpperCamelCase_ ( self : int , __lowercase : Dict , __lowercase : Dict=None , __lowercase : str="This is a sound of {}." ): '''simple docstring''' if isinstance(__lowercase , __lowercase ): if audio.startswith("""http://""" ) or audio.startswith("""https://""" ): # We need to actually check for a real protocol, otherwise it's impossible to use a local file # like http_huggingface_co.png __a = requests.get(__lowercase ).content else: with open(__lowercase , """rb""" ) as f: __a = f.read() if isinstance(__lowercase , __lowercase ): __a = ffmpeg_read(__lowercase , self.feature_extractor.sampling_rate ) if not isinstance(__lowercase , np.ndarray ): raise ValueError("""We expect a numpy ndarray as input""" ) if len(audio.shape ) != 1: raise ValueError("""We expect a single channel audio input for ZeroShotAudioClassificationPipeline""" ) __a = self.feature_extractor( [audio] , sampling_rate=self.feature_extractor.sampling_rate , return_tensors="""pt""" ) __a = candidate_labels __a = [hypothesis_template.format(__lowercase ) for x in candidate_labels] __a = self.tokenizer(__lowercase , return_tensors=self.framework , padding=__lowercase ) __a = [text_inputs] return inputs def UpperCamelCase_ ( self : Any , __lowercase : Any ): '''simple docstring''' __a = model_inputs.pop("""candidate_labels""" ) __a = model_inputs.pop("""text_inputs""" ) if isinstance(text_inputs[0] , __lowercase ): __a = text_inputs[0] else: # Batching case. __a = text_inputs[0][0] __a = self.model(**__lowercase , **__lowercase ) __a = { """candidate_labels""": candidate_labels, """logits""": outputs.logits_per_audio, } return model_outputs def UpperCamelCase_ ( self : Optional[Any] , __lowercase : Dict ): '''simple docstring''' __a = model_outputs.pop("""candidate_labels""" ) __a = model_outputs["""logits"""][0] if self.framework == "pt": __a = logits.softmax(dim=0 ) __a = probs.tolist() else: raise ValueError("""`tf` framework not supported.""" ) __a = [ {"""score""": score, """label""": candidate_label} for score, candidate_label in sorted(zip(__lowercase , __lowercase ) , key=lambda __lowercase : -x[0] ) ] return result
302
1
def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : list[int] , _SCREAMING_SNAKE_CASE : int ): """simple docstring""" def count_of_possible_combinations(_SCREAMING_SNAKE_CASE : int ) -> int: if target < 0: return 0 if target == 0: return 1 return sum(count_of_possible_combinations(target - item ) for item in array ) return count_of_possible_combinations(_SCREAMING_SNAKE_CASE ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : list[int] , _SCREAMING_SNAKE_CASE : int ): """simple docstring""" def count_of_possible_combinations_with_dp_array( _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : list[int] ) -> int: if target < 0: return 0 if target == 0: return 1 if dp_array[target] != -1: return dp_array[target] __a = sum( count_of_possible_combinations_with_dp_array(target - item , _SCREAMING_SNAKE_CASE ) for item in array ) __a = answer return answer __a = [-1] * (target + 1) return count_of_possible_combinations_with_dp_array(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : list[int] , _SCREAMING_SNAKE_CASE : int ): """simple docstring""" __a = [0] * (target + 1) __a = 1 for i in range(1 , target + 1 ): for j in range(_SCREAMING_SNAKE_CASE ): if i - array[j] >= 0: dp_array[i] += dp_array[i - array[j]] return dp_array[target] if __name__ == "__main__": import doctest doctest.testmod() lowerCamelCase__ = 3 lowerCamelCase__ = 5 lowerCamelCase__ = [1, 2, 5] print(combination_sum_iv(n, array, target))
302
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, ChannelDimension, ImageInput, PILImageResampling, is_batched, to_numpy_array, valid_images, ) from ...utils import TensorType, logging lowerCamelCase__ = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : Dict =['pixel_values'] def __init__( self : Optional[int] , __lowercase : bool = True , __lowercase : Optional[Dict[str, int]] = None , __lowercase : PILImageResampling = PILImageResampling.BICUBIC , __lowercase : bool = True , __lowercase : bool = True , __lowercase : Union[int, float] = 1 / 255 , __lowercase : Dict[str, int] = None , __lowercase : bool = True , __lowercase : Optional[Union[float, List[float]]] = None , __lowercase : Optional[Union[float, List[float]]] = None , **__lowercase : Dict , ): '''simple docstring''' super().__init__(**__lowercase ) __a = size if size is not None else {"""height""": 224, """width""": 224} __a = get_size_dict(__lowercase ) __a = crop_size if crop_size is not None else {"""height""": 224, """width""": 224} __a = get_size_dict(__lowercase , default_to_square=__lowercase , param_name="""crop_size""" ) __a = do_resize __a = do_rescale __a = do_normalize __a = do_center_crop __a = crop_size __a = size __a = resample __a = rescale_factor __a = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN __a = image_std if image_std is not None else IMAGENET_DEFAULT_STD def UpperCamelCase_ ( self : Any , __lowercase : np.ndarray , __lowercase : Dict[str, int] , __lowercase : PILImageResampling = PILImageResampling.BILINEAR , __lowercase : Optional[Union[str, ChannelDimension]] = None , **__lowercase : Optional[Any] , ): '''simple docstring''' __a = get_size_dict(__lowercase ) if "shortest_edge" in size: __a = get_resize_output_image_size(__lowercase , size=size["""shortest_edge"""] , default_to_square=__lowercase ) # size = get_resize_output_image_size(image, size["shortest_edge"], size["longest_edge"]) elif "height" in size and "width" in size: __a = (size["""height"""], size["""width"""]) else: raise ValueError(F"Size must contain 'height' and 'width' keys or 'shortest_edge' key. Got {size.keys()}" ) return resize(__lowercase , size=__lowercase , resample=__lowercase , data_format=__lowercase , **__lowercase ) def UpperCamelCase_ ( self : str , __lowercase : np.ndarray , __lowercase : Dict[str, int] , __lowercase : Optional[Union[str, ChannelDimension]] = None , **__lowercase : List[Any] , ): '''simple docstring''' __a = get_size_dict(__lowercase ) if "height" not in size or "width" not in size: raise ValueError(F"The `size` parameter must contain the keys (height, width). Got {size.keys()}" ) return center_crop(__lowercase , size=(size["""height"""], size["""width"""]) , data_format=__lowercase , **__lowercase ) def UpperCamelCase_ ( self : Any , __lowercase : np.ndarray , __lowercase : float , __lowercase : Optional[Union[str, ChannelDimension]] = None , **__lowercase : str ): '''simple docstring''' return rescale(__lowercase , scale=__lowercase , data_format=__lowercase , **__lowercase ) def UpperCamelCase_ ( self : List[Any] , __lowercase : np.ndarray , __lowercase : Union[float, List[float]] , __lowercase : Union[float, List[float]] , __lowercase : Optional[Union[str, ChannelDimension]] = None , **__lowercase : Any , ): '''simple docstring''' return normalize(__lowercase , mean=__lowercase , std=__lowercase , data_format=__lowercase , **__lowercase ) def UpperCamelCase_ ( self : Tuple , __lowercase : ImageInput , __lowercase : Optional[bool] = None , __lowercase : Dict[str, int] = None , __lowercase : PILImageResampling = None , __lowercase : bool = None , __lowercase : int = None , __lowercase : Optional[bool] = None , __lowercase : Optional[float] = None , __lowercase : Optional[bool] = None , __lowercase : Optional[Union[float, List[float]]] = None , __lowercase : Optional[Union[float, List[float]]] = None , __lowercase : Optional[Union[str, TensorType]] = None , __lowercase : Union[str, ChannelDimension] = ChannelDimension.FIRST , **__lowercase : List[Any] , ): '''simple docstring''' __a = do_resize if do_resize is not None else self.do_resize __a = do_rescale if do_rescale is not None else self.do_rescale __a = do_normalize if do_normalize is not None else self.do_normalize __a = do_center_crop if do_center_crop is not None else self.do_center_crop __a = crop_size if crop_size is not None else self.crop_size __a = get_size_dict(__lowercase , param_name="""crop_size""" , default_to_square=__lowercase ) __a = resample if resample is not None else self.resample __a = rescale_factor if rescale_factor is not None else self.rescale_factor __a = image_mean if image_mean is not None else self.image_mean __a = image_std if image_std is not None else self.image_std __a = size if size is not None else self.size __a = get_size_dict(__lowercase ) if not is_batched(__lowercase ): __a = [images] if not valid_images(__lowercase ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None: raise ValueError("""Size must be specified if do_resize is True.""" ) if do_center_crop and crop_size is None: raise ValueError("""Crop size must be specified if do_center_crop is True.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) # All transformations expect numpy arrays. __a = [to_numpy_array(__lowercase ) for image in images] if do_resize: __a = [self.resize(image=__lowercase , size=__lowercase , resample=__lowercase ) for image in images] if do_center_crop: __a = [self.center_crop(image=__lowercase , size=__lowercase ) for image in images] if do_rescale: __a = [self.rescale(image=__lowercase , scale=__lowercase ) for image in images] if do_normalize: __a = [self.normalize(image=__lowercase , mean=__lowercase , std=__lowercase ) for image in images] __a = [to_channel_dimension_format(__lowercase , __lowercase ) for image in images] __a = {"""pixel_values""": images} return BatchFeature(data=__lowercase , tensor_type=__lowercase )
302
1
from __future__ import annotations from decimal import Decimal from numpy import array def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : list[list[float]] ): """simple docstring""" __a = Decimal # Check if the provided matrix has 2 rows and 2 columns # since this implementation only works for 2x2 matrices if len(_SCREAMING_SNAKE_CASE ) == 2 and len(matrix[0] ) == 2 and len(matrix[1] ) == 2: # Calculate the determinant of the matrix __a = float( d(matrix[0][0] ) * d(matrix[1][1] ) - d(matrix[1][0] ) * d(matrix[0][1] ) ) if determinant == 0: raise ValueError("""This matrix has no inverse.""" ) # Creates a copy of the matrix with swapped positions of the elements __a = [[0.0, 0.0], [0.0, 0.0]] __a , __a = matrix[1][1], matrix[0][0] __a , __a = -matrix[1][0], -matrix[0][1] # Calculate the inverse of the matrix return [ [(float(d(_SCREAMING_SNAKE_CASE ) ) / determinant) or 0.0 for n in row] for row in swapped_matrix ] elif ( len(_SCREAMING_SNAKE_CASE ) == 3 and len(matrix[0] ) == 3 and len(matrix[1] ) == 3 and len(matrix[2] ) == 3 ): # Calculate the determinant of the matrix using Sarrus rule __a = float( ( (d(matrix[0][0] ) * d(matrix[1][1] ) * d(matrix[2][2] )) + (d(matrix[0][1] ) * d(matrix[1][2] ) * d(matrix[2][0] )) + (d(matrix[0][2] ) * d(matrix[1][0] ) * d(matrix[2][1] )) ) - ( (d(matrix[0][2] ) * d(matrix[1][1] ) * d(matrix[2][0] )) + (d(matrix[0][1] ) * d(matrix[1][0] ) * d(matrix[2][2] )) + (d(matrix[0][0] ) * d(matrix[1][2] ) * d(matrix[2][1] )) ) ) if determinant == 0: raise ValueError("""This matrix has no inverse.""" ) # Creating cofactor matrix __a = [ [d(0.0 ), d(0.0 ), d(0.0 )], [d(0.0 ), d(0.0 ), d(0.0 )], [d(0.0 ), d(0.0 ), d(0.0 )], ] __a = (d(matrix[1][1] ) * d(matrix[2][2] )) - ( d(matrix[1][2] ) * d(matrix[2][1] ) ) __a = -( (d(matrix[1][0] ) * d(matrix[2][2] )) - (d(matrix[1][2] ) * d(matrix[2][0] )) ) __a = (d(matrix[1][0] ) * d(matrix[2][1] )) - ( d(matrix[1][1] ) * d(matrix[2][0] ) ) __a = -( (d(matrix[0][1] ) * d(matrix[2][2] )) - (d(matrix[0][2] ) * d(matrix[2][1] )) ) __a = (d(matrix[0][0] ) * d(matrix[2][2] )) - ( d(matrix[0][2] ) * d(matrix[2][0] ) ) __a = -( (d(matrix[0][0] ) * d(matrix[2][1] )) - (d(matrix[0][1] ) * d(matrix[2][0] )) ) __a = (d(matrix[0][1] ) * d(matrix[1][2] )) - ( d(matrix[0][2] ) * d(matrix[1][1] ) ) __a = -( (d(matrix[0][0] ) * d(matrix[1][2] )) - (d(matrix[0][2] ) * d(matrix[1][0] )) ) __a = (d(matrix[0][0] ) * d(matrix[1][1] )) - ( d(matrix[0][1] ) * d(matrix[1][0] ) ) # Transpose the cofactor matrix (Adjoint matrix) __a = array(_SCREAMING_SNAKE_CASE ) for i in range(3 ): for j in range(3 ): __a = cofactor_matrix[j][i] # Inverse of the matrix using the formula (1/determinant) * adjoint matrix __a = array(_SCREAMING_SNAKE_CASE ) for i in range(3 ): for j in range(3 ): inverse_matrix[i][j] /= d(_SCREAMING_SNAKE_CASE ) # Calculate the inverse of the matrix return [[float(d(_SCREAMING_SNAKE_CASE ) ) or 0.0 for n in row] for row in inverse_matrix] raise ValueError("""Please provide a matrix of size 2x2 or 3x3.""" )
302
import tempfile import unittest from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from transformers.testing_utils import ( is_torch_available, require_optimum, require_torch, slow, ) if is_torch_available(): import torch @require_torch @require_optimum @slow class SCREAMING_SNAKE_CASE ( unittest.TestCase ): def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' __a = """hf-internal-testing/tiny-random-t5""" __a = AutoTokenizer.from_pretrained(__lowercase ) __a = AutoModelForSeqaSeqLM.from_pretrained(__lowercase ) __a = tokenizer("""This is me""" , return_tensors="""pt""" ) __a = model.to_bettertransformer() self.assertTrue(any("""BetterTransformer""" in mod.__class__.__name__ for _, mod in model.named_modules() ) ) __a = model.generate(**__lowercase ) __a = model.reverse_bettertransformer() self.assertFalse(any("""BetterTransformer""" in mod.__class__.__name__ for _, mod in model.named_modules() ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(__lowercase ) __a = AutoModelForSeqaSeqLM.from_pretrained(__lowercase ) self.assertFalse( any("""BetterTransformer""" in mod.__class__.__name__ for _, mod in model_reloaded.named_modules() ) ) __a = model_reloaded.generate(**__lowercase ) self.assertTrue(torch.allclose(__lowercase , __lowercase ) ) def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' __a = """hf-internal-testing/tiny-random-t5""" __a = AutoModelForSeqaSeqLM.from_pretrained(__lowercase ) __a = model.to_bettertransformer() with tempfile.TemporaryDirectory() as tmpdirname: with self.assertRaises(__lowercase ): model.save_pretrained(__lowercase ) __a = model.reverse_bettertransformer() model.save_pretrained(__lowercase )
302
1
from __future__ import annotations lowerCamelCase__ = """#""" class SCREAMING_SNAKE_CASE : def __init__( self : Optional[Any] ): '''simple docstring''' __a = {} def UpperCamelCase_ ( self : Optional[Any] , __lowercase : str ): '''simple docstring''' __a = self._trie for char in text: if char not in trie: __a = {} __a = trie[char] __a = True def UpperCamelCase_ ( self : Tuple , __lowercase : str ): '''simple docstring''' __a = self._trie for char in prefix: if char in trie: __a = trie[char] else: return [] return self._elements(__lowercase ) def UpperCamelCase_ ( self : Optional[int] , __lowercase : dict ): '''simple docstring''' __a = [] for c, v in d.items(): __a = [""" """] if c == END else [(c + s) for s in self._elements(__lowercase )] result.extend(__lowercase ) return tuple(__lowercase ) lowerCamelCase__ = Trie() lowerCamelCase__ = ("""depart""", """detergent""", """daring""", """dog""", """deer""", """deal""") for word in words: trie.insert_word(word) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : str ): """simple docstring""" __a = trie.find_word(_SCREAMING_SNAKE_CASE ) return tuple(string + word for word in suffixes ) def lowerCAmelCase__ ( ): """simple docstring""" print(autocomplete_using_trie("""de""" ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
302
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig lowerCamelCase__ = { """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/config.json""", """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/config.json""", """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/config.json""", """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/config.json""", """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/config.json""", """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/config.json""", """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/config.json""", """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/config.json""", } class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : Optional[Any] ='albert' def __init__( self : Optional[Any] , __lowercase : Union[str, Any]=30000 , __lowercase : List[str]=128 , __lowercase : Optional[Any]=4096 , __lowercase : Dict=12 , __lowercase : Any=1 , __lowercase : Optional[Any]=64 , __lowercase : Any=16384 , __lowercase : Any=1 , __lowercase : Union[str, Any]="gelu_new" , __lowercase : List[str]=0 , __lowercase : int=0 , __lowercase : Dict=512 , __lowercase : str=2 , __lowercase : List[str]=0.02 , __lowercase : Union[str, Any]=1E-12 , __lowercase : int=0.1 , __lowercase : Any="absolute" , __lowercase : Optional[int]=0 , __lowercase : Dict=2 , __lowercase : Optional[Any]=3 , **__lowercase : Any , ): '''simple docstring''' super().__init__(pad_token_id=__lowercase , bos_token_id=__lowercase , eos_token_id=__lowercase , **__lowercase ) __a = vocab_size __a = embedding_size __a = hidden_size __a = num_hidden_layers __a = num_hidden_groups __a = num_attention_heads __a = inner_group_num __a = hidden_act __a = intermediate_size __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = type_vocab_size __a = initializer_range __a = layer_norm_eps __a = classifier_dropout_prob __a = position_embedding_type class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): @property def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' if self.task == "multiple-choice": __a = {0: """batch""", 1: """choice""", 2: """sequence"""} else: __a = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis), ] )
302
1
import random def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : list , _SCREAMING_SNAKE_CASE : List[Any] ): """simple docstring""" __a , __a , __a = [], [], [] for element in data: if element < pivot: less.append(_SCREAMING_SNAKE_CASE ) elif element > pivot: greater.append(_SCREAMING_SNAKE_CASE ) else: equal.append(_SCREAMING_SNAKE_CASE ) return less, equal, greater def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : list , _SCREAMING_SNAKE_CASE : int ): """simple docstring""" if index >= len(_SCREAMING_SNAKE_CASE ) or index < 0: return None __a = items[random.randint(0 , len(_SCREAMING_SNAKE_CASE ) - 1 )] __a = 0 __a , __a , __a = _partition(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __a = len(_SCREAMING_SNAKE_CASE ) __a = len(_SCREAMING_SNAKE_CASE ) # index is the pivot if m <= index < m + count: return pivot # must be in smaller elif m > index: return quick_select(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # must be in larger else: return quick_select(_SCREAMING_SNAKE_CASE , index - (m + count) )
302
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) lowerCamelCase__ = { """configuration_blip""": [ """BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP""", """BlipConfig""", """BlipTextConfig""", """BlipVisionConfig""", ], """processing_blip""": ["""BlipProcessor"""], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = ["""BlipImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ """BLIP_PRETRAINED_MODEL_ARCHIVE_LIST""", """BlipModel""", """BlipPreTrainedModel""", """BlipForConditionalGeneration""", """BlipForQuestionAnswering""", """BlipVisionModel""", """BlipTextModel""", """BlipForImageTextRetrieval""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ """TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFBlipModel""", """TFBlipPreTrainedModel""", """TFBlipForConditionalGeneration""", """TFBlipForQuestionAnswering""", """TFBlipVisionModel""", """TFBlipTextModel""", """TFBlipForImageTextRetrieval""", ] if TYPE_CHECKING: from .configuration_blip import BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, BlipConfig, BlipTextConfig, BlipVisionConfig from .processing_blip import BlipProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_blip import BlipImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blip import ( BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, BlipModel, BlipPreTrainedModel, BlipTextModel, BlipVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blip import ( TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFBlipForConditionalGeneration, TFBlipForImageTextRetrieval, TFBlipForQuestionAnswering, TFBlipModel, TFBlipPreTrainedModel, TFBlipTextModel, TFBlipVisionModel, ) else: import sys lowerCamelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
302
1
import io import json import fsspec import pytest from datasets import Dataset, DatasetDict, Features, NamedSplit, Value from datasets.io.json import JsonDatasetReader, JsonDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : str ): """simple docstring""" assert isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("""keep_in_memory""" , [False, True] ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" __a = tmp_path / """cache""" __a = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): __a = JsonDatasetReader(_SCREAMING_SNAKE_CASE , cache_dir=_SCREAMING_SNAKE_CASE , keep_in_memory=_SCREAMING_SNAKE_CASE ).read() _check_json_dataset(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( """features""" , [ None, {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}, {"""col_1""": """string""", """col_2""": """string""", """col_3""": """string"""}, {"""col_1""": """int32""", """col_2""": """int32""", """col_3""": """int32"""}, {"""col_1""": """float32""", """col_2""": """float32""", """col_3""": """float32"""}, ] , ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" __a = tmp_path / """cache""" __a = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} __a = features.copy() if features else default_expected_features __a = ( Features({feature: Value(_SCREAMING_SNAKE_CASE ) for feature, dtype in features.items()} ) if features is not None else None ) __a = JsonDatasetReader(_SCREAMING_SNAKE_CASE , features=_SCREAMING_SNAKE_CASE , cache_dir=_SCREAMING_SNAKE_CASE ).read() _check_json_dataset(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( """features""" , [ None, {"""col_3""": """float64""", """col_1""": """string""", """col_2""": """int64"""}, ] , ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : str ): """simple docstring""" __a = tmp_path / """cache""" __a = {"""col_3""": """float64""", """col_1""": """string""", """col_2""": """int64"""} __a = features.copy() if features else default_expected_features __a = ( Features({feature: Value(_SCREAMING_SNAKE_CASE ) for feature, dtype in features.items()} ) if features is not None else None ) __a = JsonDatasetReader(_SCREAMING_SNAKE_CASE , features=_SCREAMING_SNAKE_CASE , cache_dir=_SCREAMING_SNAKE_CASE ).read() assert isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_3", "col_1", "col_2"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : int ): """simple docstring""" __a = {"""col_2""": """int64""", """col_3""": """float64""", """col_1""": """string"""} __a = features.copy() __a = ( Features({feature: Value(_SCREAMING_SNAKE_CASE ) for feature, dtype in features.items()} ) if features is not None else None ) __a = tmp_path / """cache""" __a = JsonDatasetReader(_SCREAMING_SNAKE_CASE , features=_SCREAMING_SNAKE_CASE , cache_dir=_SCREAMING_SNAKE_CASE ).read() assert isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_2", "col_3", "col_1"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("""split""" , [None, NamedSplit("""train""" ), """train""", """test"""] ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" __a = tmp_path / """cache""" __a = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} __a = JsonDatasetReader(_SCREAMING_SNAKE_CASE , cache_dir=_SCREAMING_SNAKE_CASE , split=_SCREAMING_SNAKE_CASE ).read() _check_json_dataset(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) assert dataset.split == split if split else "train" @pytest.mark.parametrize("""path_type""" , [str, list] ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : Any ): """simple docstring""" if issubclass(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __a = jsonl_path elif issubclass(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __a = [jsonl_path] __a = tmp_path / """cache""" __a = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} __a = JsonDatasetReader(_SCREAMING_SNAKE_CASE , cache_dir=_SCREAMING_SNAKE_CASE ).read() _check_json_dataset(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Dict=("train",) ): """simple docstring""" assert isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for split in splits: __a = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("""keep_in_memory""" , [False, True] ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" __a = tmp_path / """cache""" __a = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): __a = JsonDatasetReader({"""train""": jsonl_path} , cache_dir=_SCREAMING_SNAKE_CASE , keep_in_memory=_SCREAMING_SNAKE_CASE ).read() _check_json_datasetdict(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( """features""" , [ None, {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}, {"""col_1""": """string""", """col_2""": """string""", """col_3""": """string"""}, {"""col_1""": """int32""", """col_2""": """int32""", """col_3""": """int32"""}, {"""col_1""": """float32""", """col_2""": """float32""", """col_3""": """float32"""}, ] , ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" __a = tmp_path / """cache""" __a = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} __a = features.copy() if features else default_expected_features __a = ( Features({feature: Value(_SCREAMING_SNAKE_CASE ) for feature, dtype in features.items()} ) if features is not None else None ) __a = JsonDatasetReader({"""train""": jsonl_path} , features=_SCREAMING_SNAKE_CASE , cache_dir=_SCREAMING_SNAKE_CASE ).read() _check_json_datasetdict(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize("""split""" , [None, NamedSplit("""train""" ), """train""", """test"""] ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" if split: __a = {split: jsonl_path} else: __a = """train""" __a = {"""train""": jsonl_path, """test""": jsonl_path} __a = tmp_path / """cache""" __a = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} __a = JsonDatasetReader(_SCREAMING_SNAKE_CASE , cache_dir=_SCREAMING_SNAKE_CASE ).read() _check_json_datasetdict(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" return json.load(_SCREAMING_SNAKE_CASE ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int ): """simple docstring""" return [json.loads(_SCREAMING_SNAKE_CASE ) for line in buffer] class SCREAMING_SNAKE_CASE : @pytest.mark.parametrize("""lines, load_json_function""" , [(True, load_json_lines), (False, load_json)] ) def UpperCamelCase_ ( self : str , __lowercase : Optional[int] , __lowercase : int , __lowercase : Any ): '''simple docstring''' with io.BytesIO() as buffer: JsonDatasetWriter(__lowercase , __lowercase , lines=__lowercase ).write() buffer.seek(0 ) __a = load_json_function(__lowercase ) assert isinstance(__lowercase , __lowercase ) assert isinstance(exported_content[0] , __lowercase ) assert len(__lowercase ) == 10 @pytest.mark.parametrize( """orient, container, keys, len_at""" , [ ("""records""", list, {"""tokens""", """labels""", """answers""", """id"""}, None), ("""split""", dict, {"""columns""", """data"""}, """data"""), ("""index""", dict, set("""0123456789""" ), None), ("""columns""", dict, {"""tokens""", """labels""", """answers""", """id"""}, """tokens"""), ("""values""", list, None, None), ("""table""", dict, {"""schema""", """data"""}, """data"""), ] , ) def UpperCamelCase_ ( self : Union[str, Any] , __lowercase : Union[str, Any] , __lowercase : List[Any] , __lowercase : Union[str, Any] , __lowercase : Optional[int] , __lowercase : Tuple ): '''simple docstring''' with io.BytesIO() as buffer: JsonDatasetWriter(__lowercase , __lowercase , lines=__lowercase , orient=__lowercase ).write() buffer.seek(0 ) __a = load_json(__lowercase ) assert isinstance(__lowercase , __lowercase ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(__lowercase , """keys""" ) and not hasattr(exported_content[0] , """keys""" ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(__lowercase ) == 10 @pytest.mark.parametrize("""lines, load_json_function""" , [(True, load_json_lines), (False, load_json)] ) def UpperCamelCase_ ( self : Tuple , __lowercase : List[str] , __lowercase : List[Any] , __lowercase : Any ): '''simple docstring''' with io.BytesIO() as buffer: JsonDatasetWriter(__lowercase , __lowercase , lines=__lowercase , num_proc=2 ).write() buffer.seek(0 ) __a = load_json_function(__lowercase ) assert isinstance(__lowercase , __lowercase ) assert isinstance(exported_content[0] , __lowercase ) assert len(__lowercase ) == 10 @pytest.mark.parametrize( """orient, container, keys, len_at""" , [ ("""records""", list, {"""tokens""", """labels""", """answers""", """id"""}, None), ("""split""", dict, {"""columns""", """data"""}, """data"""), ("""index""", dict, set("""0123456789""" ), None), ("""columns""", dict, {"""tokens""", """labels""", """answers""", """id"""}, """tokens"""), ("""values""", list, None, None), ("""table""", dict, {"""schema""", """data"""}, """data"""), ] , ) def UpperCamelCase_ ( self : str , __lowercase : int , __lowercase : Any , __lowercase : int , __lowercase : Optional[Any] , __lowercase : Optional[int] ): '''simple docstring''' with io.BytesIO() as buffer: JsonDatasetWriter(__lowercase , __lowercase , lines=__lowercase , orient=__lowercase , num_proc=2 ).write() buffer.seek(0 ) __a = load_json(__lowercase ) assert isinstance(__lowercase , __lowercase ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(__lowercase , """keys""" ) and not hasattr(exported_content[0] , """keys""" ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(__lowercase ) == 10 def UpperCamelCase_ ( self : Any , __lowercase : Union[str, Any] ): '''simple docstring''' with pytest.raises(__lowercase ): with io.BytesIO() as buffer: JsonDatasetWriter(__lowercase , __lowercase , num_proc=0 ) @pytest.mark.parametrize("""compression, extension""" , [("""gzip""", """gz"""), ("""bz2""", """bz2"""), ("""xz""", """xz""")] ) def UpperCamelCase_ ( self : str , __lowercase : Optional[Any] , __lowercase : Union[str, Any] , __lowercase : int , __lowercase : Tuple , __lowercase : str ): '''simple docstring''' __a = tmp_path_factory.mktemp("""data""" ) / F"test.json.{extension}" __a = str(shared_datadir / F"test_file.json.{extension}" ) JsonDatasetWriter(__lowercase , __lowercase , compression=__lowercase ).write() with fsspec.open(__lowercase , """rb""" , compression="""infer""" ) as f: __a = f.read() with fsspec.open(__lowercase , """rb""" , compression="""infer""" ) as f: __a = f.read() assert exported_content == original_content
302
class SCREAMING_SNAKE_CASE : def __init__( self : List[Any] , __lowercase : Union[str, Any] ): '''simple docstring''' __a = val __a = None __a = None def UpperCamelCase_ ( self : Union[str, Any] , __lowercase : Any ): '''simple docstring''' if self.val: if val < self.val: if self.left is None: __a = Node(__lowercase ) else: self.left.insert(__lowercase ) elif val > self.val: if self.right is None: __a = Node(__lowercase ) else: self.right.insert(__lowercase ) else: __a = val def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : Any ): """simple docstring""" if root: inorder(root.left , _SCREAMING_SNAKE_CASE ) res.append(root.val ) inorder(root.right , _SCREAMING_SNAKE_CASE ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Any ): """simple docstring""" if len(_SCREAMING_SNAKE_CASE ) == 0: return arr __a = Node(arr[0] ) for i in range(1 , len(_SCREAMING_SNAKE_CASE ) ): root.insert(arr[i] ) # Traverse BST in order. __a = [] inorder(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return res if __name__ == "__main__": print(tree_sort([10, 1, 3, 2, 9, 14, 13]))
302
1
import numpy as np def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : np.array ): """simple docstring""" return 1 / (1 + np.exp(-vector )) if __name__ == "__main__": import doctest doctest.testmod()
302
import inspect import unittest from transformers import MobileViTVaConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, MobileViTVaModel from transformers.models.mobilevitva.modeling_mobilevitva import ( MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST, make_divisible, ) if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): def UpperCamelCase_ ( self : str ): '''simple docstring''' __a = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(__lowercase , """width_multiplier""" ) ) class SCREAMING_SNAKE_CASE : def __init__( self : Dict , __lowercase : Union[str, Any] , __lowercase : Dict=13 , __lowercase : int=64 , __lowercase : Tuple=2 , __lowercase : Tuple=3 , __lowercase : Tuple="swish" , __lowercase : List[Any]=3 , __lowercase : List[str]=32 , __lowercase : int=0.1 , __lowercase : Union[str, Any]=0.02 , __lowercase : Optional[int]=True , __lowercase : Dict=True , __lowercase : Tuple=10 , __lowercase : str=None , __lowercase : Optional[Any]=0.25 , __lowercase : str=0.0 , __lowercase : Optional[Any]=0.0 , ): '''simple docstring''' __a = parent __a = batch_size __a = image_size __a = patch_size __a = num_channels __a = make_divisible(512 * width_multiplier , divisor=8 ) __a = hidden_act __a = conv_kernel_size __a = output_stride __a = classifier_dropout_prob __a = use_labels __a = is_training __a = num_labels __a = initializer_range __a = scope __a = width_multiplier __a = ffn_dropout __a = attn_dropout def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' __a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a = None __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.num_labels ) __a = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) __a = self.get_config() return config, pixel_values, labels, pixel_labels def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' return MobileViTVaConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_act=self.hidden_act , conv_kernel_size=self.conv_kernel_size , output_stride=self.output_stride , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , width_multiplier=self.width_multiplier , ffn_dropout=self.ffn_dropout_prob , attn_dropout=self.attn_dropout_prob , ) def UpperCamelCase_ ( self : Tuple , __lowercase : Optional[Any] , __lowercase : int , __lowercase : Optional[Any] , __lowercase : Tuple ): '''simple docstring''' __a = MobileViTVaModel(config=__lowercase ) model.to(__lowercase ) model.eval() __a = model(__lowercase ) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def UpperCamelCase_ ( self : Union[str, Any] , __lowercase : List[Any] , __lowercase : str , __lowercase : Optional[int] , __lowercase : Union[str, Any] ): '''simple docstring''' __a = self.num_labels __a = MobileViTVaForImageClassification(__lowercase ) model.to(__lowercase ) model.eval() __a = model(__lowercase , labels=__lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCamelCase_ ( self : int , __lowercase : str , __lowercase : Any , __lowercase : int , __lowercase : List[str] ): '''simple docstring''' __a = self.num_labels __a = MobileViTVaForSemanticSegmentation(__lowercase ) model.to(__lowercase ) model.eval() __a = model(__lowercase ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) __a = model(__lowercase , labels=__lowercase ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def UpperCamelCase_ ( self : Dict ): '''simple docstring''' __a = self.prepare_config_and_inputs() __a , __a , __a , __a = config_and_inputs __a = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE ( lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase ): __lowerCamelCase : List[Any] =( (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation) if is_torch_available() else () ) __lowerCamelCase : Any =( { 'feature-extraction': MobileViTVaModel, 'image-classification': MobileViTVaForImageClassification, 'image-segmentation': MobileViTVaForSemanticSegmentation, } if is_torch_available() else {} ) __lowerCamelCase : Dict =False __lowerCamelCase : Optional[Any] =False __lowerCamelCase : int =False __lowerCamelCase : Any =False def UpperCamelCase_ ( self : Dict ): '''simple docstring''' __a = MobileViTVaModelTester(self ) __a = MobileViTVaConfigTester(self , config_class=__lowercase , has_text_modality=__lowercase ) def UpperCamelCase_ ( self : Dict ): '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason="""MobileViTV2 does not use inputs_embeds""" ) def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' pass @unittest.skip(reason="""MobileViTV2 does not support input and output embeddings""" ) def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' pass @unittest.skip(reason="""MobileViTV2 does not output attentions""" ) def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' pass @require_torch_multi_gpu @unittest.skip(reason="""Got `CUDA error: misaligned address` for tests after this one being run.""" ) def UpperCamelCase_ ( self : int ): '''simple docstring''' pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' pass def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(__lowercase ) __a = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a = [*signature.parameters.keys()] __a = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , __lowercase ) def UpperCamelCase_ ( self : Dict ): '''simple docstring''' __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowercase ) def UpperCamelCase_ ( self : int ): '''simple docstring''' def check_hidden_states_output(__lowercase : List[str] , __lowercase : Optional[int] , __lowercase : List[str] ): __a = model_class(__lowercase ) model.to(__lowercase ) model.eval() with torch.no_grad(): __a = model(**self._prepare_for_class(__lowercase , __lowercase ) ) __a = outputs.hidden_states __a = 5 self.assertEqual(len(__lowercase ) , __lowercase ) # MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width) # with the width and height being successively divided by 2. __a = 2 for i in range(len(__lowercase ) ): self.assertListEqual( list(hidden_states[i].shape[-2:] ) , [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor] , ) divisor *= 2 self.assertEqual(self.model_tester.output_stride , divisor // 2 ) __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = True check_hidden_states_output(__lowercase , __lowercase , __lowercase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __a = True check_hidden_states_output(__lowercase , __lowercase , __lowercase ) def UpperCamelCase_ ( self : Optional[int] ): '''simple docstring''' __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__lowercase ) def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*__lowercase ) @slow def UpperCamelCase_ ( self : Optional[int] ): '''simple docstring''' for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = MobileViTVaModel.from_pretrained(__lowercase ) self.assertIsNotNone(__lowercase ) def lowerCAmelCase__ ( ): """simple docstring""" __a = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class SCREAMING_SNAKE_CASE ( unittest.TestCase ): @cached_property def UpperCamelCase_ ( self : Dict ): '''simple docstring''' return ( MobileViTImageProcessor.from_pretrained("""apple/mobilevitv2-1.0-imagenet1k-256""" ) if is_vision_available() else None ) @slow def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' __a = MobileViTVaForImageClassification.from_pretrained("""apple/mobilevitv2-1.0-imagenet1k-256""" ).to( __lowercase ) __a = self.default_image_processor __a = prepare_img() __a = image_processor(images=__lowercase , return_tensors="""pt""" ).to(__lowercase ) # forward pass with torch.no_grad(): __a = model(**__lowercase ) # verify the logits __a = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , __lowercase ) __a = torch.tensor([-1.6336E00, -7.3204E-02, -5.1883E-01] ).to(__lowercase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __lowercase , atol=1E-4 ) ) @slow def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' __a = MobileViTVaForSemanticSegmentation.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3""" ) __a = model.to(__lowercase ) __a = MobileViTImageProcessor.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3""" ) __a = prepare_img() __a = image_processor(images=__lowercase , return_tensors="""pt""" ).to(__lowercase ) # forward pass with torch.no_grad(): __a = model(**__lowercase ) __a = outputs.logits # verify the logits __a = torch.Size((1, 21, 32, 32) ) self.assertEqual(logits.shape , __lowercase ) __a = torch.tensor( [ [[7.0863, 7.1525, 6.8201], [6.6931, 6.8770, 6.8933], [6.2978, 7.0366, 6.9636]], [[-3.7134, -3.6712, -3.6675], [-3.5825, -3.3549, -3.4777], [-3.3435, -3.3979, -3.2857]], [[-2.9329, -2.8003, -2.7369], [-3.0564, -2.4780, -2.0207], [-2.6889, -1.9298, -1.7640]], ] , device=__lowercase , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , __lowercase , atol=1E-4 ) ) @slow def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' __a = MobileViTVaForSemanticSegmentation.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3""" ) __a = model.to(__lowercase ) __a = MobileViTImageProcessor.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3""" ) __a = prepare_img() __a = image_processor(images=__lowercase , return_tensors="""pt""" ).to(__lowercase ) # forward pass with torch.no_grad(): __a = model(**__lowercase ) __a = outputs.logits.detach().cpu() __a = image_processor.post_process_semantic_segmentation(outputs=__lowercase , target_sizes=[(50, 60)] ) __a = torch.Size((50, 60) ) self.assertEqual(segmentation[0].shape , __lowercase ) __a = image_processor.post_process_semantic_segmentation(outputs=__lowercase ) __a = torch.Size((32, 32) ) self.assertEqual(segmentation[0].shape , __lowercase )
302
1
import argparse from pathlib import Path import requests import torch from PIL import Image from transformers import ( RobertaTokenizer, TrOCRConfig, TrOCRForCausalLM, TrOCRProcessor, VisionEncoderDecoderModel, ViTConfig, ViTImageProcessor, ViTModel, ) from transformers.utils import logging logging.set_verbosity_info() lowerCamelCase__ = logging.get_logger(__name__) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : Optional[int] ): """simple docstring""" __a = [] for i in range(encoder_config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append( (f"encoder.deit.blocks.{i}.norm1.weight", f"encoder.encoder.layer.{i}.layernorm_before.weight") ) rename_keys.append((f"encoder.deit.blocks.{i}.norm1.bias", f"encoder.encoder.layer.{i}.layernorm_before.bias") ) rename_keys.append( (f"encoder.deit.blocks.{i}.attn.proj.weight", f"encoder.encoder.layer.{i}.attention.output.dense.weight") ) rename_keys.append( (f"encoder.deit.blocks.{i}.attn.proj.bias", f"encoder.encoder.layer.{i}.attention.output.dense.bias") ) rename_keys.append( (f"encoder.deit.blocks.{i}.norm2.weight", f"encoder.encoder.layer.{i}.layernorm_after.weight") ) rename_keys.append((f"encoder.deit.blocks.{i}.norm2.bias", f"encoder.encoder.layer.{i}.layernorm_after.bias") ) rename_keys.append( (f"encoder.deit.blocks.{i}.mlp.fc1.weight", f"encoder.encoder.layer.{i}.intermediate.dense.weight") ) rename_keys.append( (f"encoder.deit.blocks.{i}.mlp.fc1.bias", f"encoder.encoder.layer.{i}.intermediate.dense.bias") ) rename_keys.append( (f"encoder.deit.blocks.{i}.mlp.fc2.weight", f"encoder.encoder.layer.{i}.output.dense.weight") ) rename_keys.append((f"encoder.deit.blocks.{i}.mlp.fc2.bias", f"encoder.encoder.layer.{i}.output.dense.bias") ) # cls token, position embeddings and patch embeddings of encoder rename_keys.extend( [ ("""encoder.deit.cls_token""", """encoder.embeddings.cls_token"""), ("""encoder.deit.pos_embed""", """encoder.embeddings.position_embeddings"""), ("""encoder.deit.patch_embed.proj.weight""", """encoder.embeddings.patch_embeddings.projection.weight"""), ("""encoder.deit.patch_embed.proj.bias""", """encoder.embeddings.patch_embeddings.projection.bias"""), ("""encoder.deit.norm.weight""", """encoder.layernorm.weight"""), ("""encoder.deit.norm.bias""", """encoder.layernorm.bias"""), ] ) return rename_keys def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : int ): """simple docstring""" for i in range(encoder_config.num_hidden_layers ): # queries, keys and values (only weights, no biases) __a = state_dict.pop(f"encoder.deit.blocks.{i}.attn.qkv.weight" ) __a = in_proj_weight[ : encoder_config.hidden_size, : ] __a = in_proj_weight[ encoder_config.hidden_size : encoder_config.hidden_size * 2, : ] __a = in_proj_weight[ -encoder_config.hidden_size :, : ] def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : str ): """simple docstring""" __a = dct.pop(_SCREAMING_SNAKE_CASE ) __a = val def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : List[Any] ): """simple docstring""" if "handwritten" in checkpoint_url: __a = """https://fki.tic.heia-fr.ch/static/img/a01-122-02-00.jpg""" # industry # url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02-12.jpg" # have # url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02-10.jpg" # let # url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02.jpg" # # url = "https://fki.tic.heia-fr.ch/static/img/a01-122.jpg" elif "printed" in checkpoint_url or "stage1" in checkpoint_url: __a = """https://www.researchgate.net/profile/Dinh-Sang/publication/338099565/figure/fig8/AS:840413229350922@1577381536857/An-receipt-example-in-the-SROIE-2019-dataset_Q640.jpg""" __a = Image.open(requests.get(_SCREAMING_SNAKE_CASE , stream=_SCREAMING_SNAKE_CASE ).raw ).convert("""RGB""" ) return im @torch.no_grad() def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" __a = ViTConfig(image_size=384 , qkv_bias=_SCREAMING_SNAKE_CASE ) __a = TrOCRConfig() # size of the architecture if "base" in checkpoint_url: __a = 768 elif "large" in checkpoint_url: # use ViT-large encoder __a = 1024 __a = 4096 __a = 24 __a = 16 __a = 1024 else: raise ValueError("""Should either find 'base' or 'large' in checkpoint URL""" ) # the large-printed + stage1 checkpoints uses sinusoidal position embeddings, no layernorm afterwards if "large-printed" in checkpoint_url or "stage1" in checkpoint_url: __a = False __a = """relu""" __a = 1024 __a = True __a = False __a = False # load HuggingFace model __a = ViTModel(_SCREAMING_SNAKE_CASE , add_pooling_layer=_SCREAMING_SNAKE_CASE ) __a = TrOCRForCausalLM(_SCREAMING_SNAKE_CASE ) __a = VisionEncoderDecoderModel(encoder=_SCREAMING_SNAKE_CASE , decoder=_SCREAMING_SNAKE_CASE ) model.eval() # load state_dict of original model, rename some keys __a = torch.hub.load_state_dict_from_url(_SCREAMING_SNAKE_CASE , map_location="""cpu""" , check_hash=_SCREAMING_SNAKE_CASE )["""model"""] __a = create_rename_keys(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for src, dest in rename_keys: rename_key(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) read_in_q_k_v(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # remove parameters we don't need del state_dict["encoder.deit.head.weight"] del state_dict["encoder.deit.head.bias"] del state_dict["decoder.version"] # add prefix to decoder keys for key, val in state_dict.copy().items(): __a = state_dict.pop(_SCREAMING_SNAKE_CASE ) if key.startswith("""decoder""" ) and "output_projection" not in key: __a = val else: __a = val # load state dict model.load_state_dict(_SCREAMING_SNAKE_CASE ) # Check outputs on an image __a = ViTImageProcessor(size=encoder_config.image_size ) __a = RobertaTokenizer.from_pretrained("""roberta-large""" ) __a = TrOCRProcessor(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __a = processor(images=prepare_img(_SCREAMING_SNAKE_CASE ) , return_tensors="""pt""" ).pixel_values # verify logits __a = torch.tensor([[model.config.decoder.decoder_start_token_id]] ) __a = model(pixel_values=_SCREAMING_SNAKE_CASE , decoder_input_ids=_SCREAMING_SNAKE_CASE ) __a = outputs.logits __a = torch.Size([1, 1, 5_0265] ) if "trocr-base-handwritten" in checkpoint_url: __a = torch.tensor( [-1.4502, -4.6683, -0.5347, -2.9291, 9.1435, -3.0571, 8.9764, 1.7560, 8.7358, -1.5311] ) elif "trocr-large-handwritten" in checkpoint_url: __a = torch.tensor( [-2.6437, -1.3129, -2.2596, -5.3455, 6.3539, 1.7604, 5.4991, 1.4702, 5.6113, 2.0170] ) elif "trocr-base-printed" in checkpoint_url: __a = torch.tensor( [-5.6816, -5.8388, 1.1398, -6.9034, 6.8505, -2.4393, 1.2284, -1.0232, -1.9661, -3.9210] ) elif "trocr-large-printed" in checkpoint_url: __a = torch.tensor( [-6.0162, -7.0959, 4.4155, -5.1063, 7.0468, -3.1631, 2.6466, -0.3081, -0.8106, -1.7535] ) if "stage1" not in checkpoint_url: assert logits.shape == expected_shape, "Shape of logits not as expected" assert torch.allclose(logits[0, 0, :10] , _SCREAMING_SNAKE_CASE , atol=1e-3 ), "First elements of logits not as expected" Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) print(f"Saving model to {pytorch_dump_folder_path}" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) print(f"Saving processor to {pytorch_dump_folder_path}" ) processor.save_pretrained(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() parser.add_argument( """--checkpoint_url""", default="""https://layoutlm.blob.core.windows.net/trocr/model_zoo/fairseq/trocr-base-handwritten.pt""", type=str, help="""URL to the original PyTorch checkpoint (.pth file).""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the folder to output PyTorch model.""" ) lowerCamelCase__ = parser.parse_args() convert_tr_ocr_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
302
from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import torch from ...utils import BaseOutput, OptionalDependencyNotAvailable, is_torch_available, is_transformers_available @dataclass class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : Union[List[np.ndarray], torch.FloatTensor] 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_text_to_video_synth import TextToVideoSDPipeline from .pipeline_text_to_video_synth_imgaimg import VideoToVideoSDPipeline # noqa: F401 from .pipeline_text_to_video_zero import TextToVideoZeroPipeline
302
1
import itertools from dataclasses import dataclass from typing import List, Optional import pyarrow as pa import pyarrow.parquet as pq import datasets from datasets.table import table_cast lowerCamelCase__ = datasets.utils.logging.get_logger(__name__) @dataclass class SCREAMING_SNAKE_CASE ( datasets.BuilderConfig ): __lowerCamelCase : int =10_000 __lowerCamelCase : Optional[List[str]] =None __lowerCamelCase : Optional[datasets.Features] =None class SCREAMING_SNAKE_CASE ( datasets.ArrowBasedBuilder ): __lowerCamelCase : str =ParquetConfig def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' return datasets.DatasetInfo(features=self.config.features ) def UpperCamelCase_ ( self : Any , __lowercase : Optional[Any] ): '''simple docstring''' if not self.config.data_files: raise ValueError(F"At least one data file must be specified, but got data_files={self.config.data_files}" ) __a = dl_manager.download_and_extract(self.config.data_files ) if isinstance(__lowercase , (str, list, tuple) ): __a = data_files if isinstance(__lowercase , __lowercase ): __a = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive __a = [dl_manager.iter_files(__lowercase ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"""files""": files} )] __a = [] for split_name, files in data_files.items(): if isinstance(__lowercase , __lowercase ): __a = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive __a = [dl_manager.iter_files(__lowercase ) for file in files] # Infer features is they are stoed in the arrow schema if self.info.features is None: for file in itertools.chain.from_iterable(__lowercase ): with open(__lowercase , """rb""" ) as f: __a = datasets.Features.from_arrow_schema(pq.read_schema(__lowercase ) ) break splits.append(datasets.SplitGenerator(name=__lowercase , gen_kwargs={"""files""": files} ) ) return splits def UpperCamelCase_ ( self : Union[str, Any] , __lowercase : pa.Table ): '''simple docstring''' if self.info.features is not None: # more expensive cast to support nested features with keys in a different order # allows str <-> int/float or str to Audio for example __a = table_cast(__lowercase , self.info.features.arrow_schema ) return pa_table def UpperCamelCase_ ( self : Tuple , __lowercase : str ): '''simple docstring''' __a = self.info.features.arrow_schema if self.info.features is not None else None if self.info.features is not None and self.config.columns is not None: if sorted(field.name for field in schema ) != sorted(self.config.columns ): raise ValueError( F"Tried to load parquet data with columns '{self.config.columns}' with mismatching features '{self.info.features}'" ) for file_idx, file in enumerate(itertools.chain.from_iterable(__lowercase ) ): with open(__lowercase , """rb""" ) as f: __a = pq.ParquetFile(__lowercase ) try: for batch_idx, record_batch in enumerate( parquet_file.iter_batches(batch_size=self.config.batch_size , columns=self.config.columns ) ): __a = pa.Table.from_batches([record_batch] ) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield F"{file_idx}_{batch_idx}", self._cast_table(__lowercase ) except ValueError as e: logger.error(F"Failed to read file '{file}' with error {type(__lowercase )}: {e}" ) raise
302
import string import numpy def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int ): """simple docstring""" return b if a == 0 else greatest_common_divisor(b % a , _SCREAMING_SNAKE_CASE ) class SCREAMING_SNAKE_CASE : __lowerCamelCase : List[str] =string.ascii_uppercase + string.digits # This cipher takes alphanumerics into account # i.e. a total of 36 characters # take x and return x % len(key_string) __lowerCamelCase : List[Any] =numpy.vectorize(lambda lowerCamelCase__ : x % 36 ) __lowerCamelCase : Optional[Any] =numpy.vectorize(lowerCamelCase__ ) def __init__( self : Union[str, Any] , __lowercase : numpy.ndarray ): '''simple docstring''' __a = self.modulus(__lowercase ) # mod36 calc's on the encrypt key self.check_determinant() # validate the determinant of the encryption key __a = encrypt_key.shape[0] def UpperCamelCase_ ( self : Dict , __lowercase : str ): '''simple docstring''' return self.key_string.index(__lowercase ) def UpperCamelCase_ ( self : Dict , __lowercase : int ): '''simple docstring''' return self.key_string[round(__lowercase )] def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' __a = round(numpy.linalg.det(self.encrypt_key ) ) if det < 0: __a = det % len(self.key_string ) __a = len(self.key_string ) if greatest_common_divisor(__lowercase , len(self.key_string ) ) != 1: __a = ( F"determinant modular {req_l} of encryption key({det}) " F"is not co prime w.r.t {req_l}.\nTry another key." ) raise ValueError(__lowercase ) def UpperCamelCase_ ( self : Dict , __lowercase : str ): '''simple docstring''' __a = [char for char in text.upper() if char in self.key_string] __a = chars[-1] while len(__lowercase ) % self.break_key != 0: chars.append(__lowercase ) return "".join(__lowercase ) def UpperCamelCase_ ( self : List[str] , __lowercase : str ): '''simple docstring''' __a = self.process_text(text.upper() ) __a = """""" for i in range(0 , len(__lowercase ) - self.break_key + 1 , self.break_key ): __a = text[i : i + self.break_key] __a = [self.replace_letters(__lowercase ) for char in batch] __a = numpy.array([vec] ).T __a = self.modulus(self.encrypt_key.dot(__lowercase ) ).T.tolist()[ 0 ] __a = """""".join( self.replace_digits(__lowercase ) for num in batch_encrypted ) encrypted += encrypted_batch return encrypted def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' __a = round(numpy.linalg.det(self.encrypt_key ) ) if det < 0: __a = det % len(self.key_string ) __a = None for i in range(len(self.key_string ) ): if (det * i) % len(self.key_string ) == 1: __a = i break __a = ( det_inv * numpy.linalg.det(self.encrypt_key ) * numpy.linalg.inv(self.encrypt_key ) ) return self.to_int(self.modulus(__lowercase ) ) def UpperCamelCase_ ( self : Any , __lowercase : str ): '''simple docstring''' __a = self.make_decrypt_key() __a = self.process_text(text.upper() ) __a = """""" for i in range(0 , len(__lowercase ) - self.break_key + 1 , self.break_key ): __a = text[i : i + self.break_key] __a = [self.replace_letters(__lowercase ) for char in batch] __a = numpy.array([vec] ).T __a = self.modulus(decrypt_key.dot(__lowercase ) ).T.tolist()[0] __a = """""".join( self.replace_digits(__lowercase ) for num in batch_decrypted ) decrypted += decrypted_batch return decrypted def lowerCAmelCase__ ( ): """simple docstring""" __a = int(input("""Enter the order of the encryption key: """ ) ) __a = [] print("""Enter each row of the encryption key with space separated integers""" ) for _ in range(_SCREAMING_SNAKE_CASE ): __a = [int(_SCREAMING_SNAKE_CASE ) for x in input().split()] hill_matrix.append(_SCREAMING_SNAKE_CASE ) __a = HillCipher(numpy.array(_SCREAMING_SNAKE_CASE ) ) print("""Would you like to encrypt or decrypt some text? (1 or 2)""" ) __a = input("""\n1. Encrypt\n2. Decrypt\n""" ) if option == "1": __a = input("""What text would you like to encrypt?: """ ) print("""Your encrypted text is:""" ) print(hc.encrypt(_SCREAMING_SNAKE_CASE ) ) elif option == "2": __a = input("""What text would you like to decrypt?: """ ) print("""Your decrypted text is:""" ) print(hc.decrypt(_SCREAMING_SNAKE_CASE ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
302
1
from typing import Optional import torch import torch.utils.checkpoint from torch import Tensor, nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_outputs import ( BaseModelOutputWithNoAttention, BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention, ) from ...modeling_utils import PreTrainedModel from ...utils import logging from .configuration_regnet import RegNetConfig lowerCamelCase__ = logging.get_logger(__name__) # General docstring lowerCamelCase__ = """RegNetConfig""" # Base docstring lowerCamelCase__ = """facebook/regnet-y-040""" lowerCamelCase__ = [1, 1088, 7, 7] # Image classification docstring lowerCamelCase__ = """facebook/regnet-y-040""" lowerCamelCase__ = """tabby, tabby cat""" lowerCamelCase__ = [ """facebook/regnet-y-040""", # See all regnet models at https://huggingface.co/models?filter=regnet ] class SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : List[str] , __lowercase : int , __lowercase : int , __lowercase : int = 3 , __lowercase : int = 1 , __lowercase : int = 1 , __lowercase : Optional[str] = "relu" , ): '''simple docstring''' super().__init__() __a = nn.Convad( __lowercase , __lowercase , kernel_size=__lowercase , stride=__lowercase , padding=kernel_size // 2 , groups=__lowercase , bias=__lowercase , ) __a = nn.BatchNormad(__lowercase ) __a = ACTaFN[activation] if activation is not None else nn.Identity() def UpperCamelCase_ ( self : Dict , __lowercase : int ): '''simple docstring''' __a = self.convolution(__lowercase ) __a = self.normalization(__lowercase ) __a = self.activation(__lowercase ) return hidden_state class SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : Optional[Any] , __lowercase : RegNetConfig ): '''simple docstring''' super().__init__() __a = RegNetConvLayer( config.num_channels , config.embedding_size , kernel_size=3 , stride=2 , activation=config.hidden_act ) __a = config.num_channels def UpperCamelCase_ ( self : List[Any] , __lowercase : List[str] ): '''simple docstring''' __a = pixel_values.shape[1] if num_channels != self.num_channels: raise ValueError( """Make sure that the channel dimension of the pixel values match with the one set in the configuration.""" ) __a = self.embedder(__lowercase ) return hidden_state class SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : Tuple , __lowercase : int , __lowercase : int , __lowercase : int = 2 ): '''simple docstring''' super().__init__() __a = nn.Convad(__lowercase , __lowercase , kernel_size=1 , stride=__lowercase , bias=__lowercase ) __a = nn.BatchNormad(__lowercase ) def UpperCamelCase_ ( self : str , __lowercase : Tensor ): '''simple docstring''' __a = self.convolution(__lowercase ) __a = self.normalization(__lowercase ) return hidden_state class SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : int , __lowercase : int , __lowercase : int ): '''simple docstring''' super().__init__() __a = nn.AdaptiveAvgPoolad((1, 1) ) __a = nn.Sequential( nn.Convad(__lowercase , __lowercase , kernel_size=1 ) , nn.ReLU() , nn.Convad(__lowercase , __lowercase , kernel_size=1 ) , nn.Sigmoid() , ) def UpperCamelCase_ ( self : Any , __lowercase : str ): '''simple docstring''' # b c h w -> b c 1 1 __a = self.pooler(__lowercase ) __a = self.attention(__lowercase ) __a = hidden_state * attention return hidden_state class SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : Tuple , __lowercase : RegNetConfig , __lowercase : int , __lowercase : int , __lowercase : int = 1 ): '''simple docstring''' super().__init__() __a = in_channels != out_channels or stride != 1 __a = max(1 , out_channels // config.groups_width ) __a = ( RegNetShortCut(__lowercase , __lowercase , stride=__lowercase ) if should_apply_shortcut else nn.Identity() ) __a = nn.Sequential( RegNetConvLayer(__lowercase , __lowercase , kernel_size=1 , activation=config.hidden_act ) , RegNetConvLayer(__lowercase , __lowercase , stride=__lowercase , groups=__lowercase , activation=config.hidden_act ) , RegNetConvLayer(__lowercase , __lowercase , kernel_size=1 , activation=__lowercase ) , ) __a = ACTaFN[config.hidden_act] def UpperCamelCase_ ( self : List[Any] , __lowercase : Optional[int] ): '''simple docstring''' __a = hidden_state __a = self.layer(__lowercase ) __a = self.shortcut(__lowercase ) hidden_state += residual __a = self.activation(__lowercase ) return hidden_state class SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : Optional[int] , __lowercase : RegNetConfig , __lowercase : int , __lowercase : int , __lowercase : int = 1 ): '''simple docstring''' super().__init__() __a = in_channels != out_channels or stride != 1 __a = max(1 , out_channels // config.groups_width ) __a = ( RegNetShortCut(__lowercase , __lowercase , stride=__lowercase ) if should_apply_shortcut else nn.Identity() ) __a = nn.Sequential( RegNetConvLayer(__lowercase , __lowercase , kernel_size=1 , activation=config.hidden_act ) , RegNetConvLayer(__lowercase , __lowercase , stride=__lowercase , groups=__lowercase , activation=config.hidden_act ) , RegNetSELayer(__lowercase , reduced_channels=int(round(in_channels / 4 ) ) ) , RegNetConvLayer(__lowercase , __lowercase , kernel_size=1 , activation=__lowercase ) , ) __a = ACTaFN[config.hidden_act] def UpperCamelCase_ ( self : Optional[int] , __lowercase : List[Any] ): '''simple docstring''' __a = hidden_state __a = self.layer(__lowercase ) __a = self.shortcut(__lowercase ) hidden_state += residual __a = self.activation(__lowercase ) return hidden_state class SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : Optional[Any] , __lowercase : RegNetConfig , __lowercase : int , __lowercase : int , __lowercase : int = 2 , __lowercase : int = 2 , ): '''simple docstring''' super().__init__() __a = RegNetXLayer if config.layer_type == """x""" else RegNetYLayer __a = nn.Sequential( # downsampling is done in the first layer with stride of 2 layer( __lowercase , __lowercase , __lowercase , stride=__lowercase , ) , *[layer(__lowercase , __lowercase , __lowercase ) for _ in range(depth - 1 )] , ) def UpperCamelCase_ ( self : Dict , __lowercase : Any ): '''simple docstring''' __a = self.layers(__lowercase ) return hidden_state class SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : int , __lowercase : RegNetConfig ): '''simple docstring''' super().__init__() __a = nn.ModuleList([] ) # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( RegNetStage( __lowercase , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , ) ) __a = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for (in_channels, out_channels), depth in zip(__lowercase , config.depths[1:] ): self.stages.append(RegNetStage(__lowercase , __lowercase , __lowercase , depth=__lowercase ) ) def UpperCamelCase_ ( self : Optional[int] , __lowercase : Tensor , __lowercase : bool = False , __lowercase : bool = True ): '''simple docstring''' __a = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: __a = hidden_states + (hidden_state,) __a = stage_module(__lowercase ) if output_hidden_states: __a = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return BaseModelOutputWithNoAttention(last_hidden_state=__lowercase , hidden_states=__lowercase ) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : Tuple =RegNetConfig __lowerCamelCase : List[str] ='regnet' __lowerCamelCase : Tuple ='pixel_values' __lowerCamelCase : str =True def UpperCamelCase_ ( self : Dict , __lowercase : Optional[Any] ): '''simple docstring''' if isinstance(__lowercase , nn.Convad ): nn.init.kaiming_normal_(module.weight , mode="""fan_out""" , nonlinearity="""relu""" ) elif isinstance(__lowercase , (nn.BatchNormad, nn.GroupNorm) ): nn.init.constant_(module.weight , 1 ) nn.init.constant_(module.bias , 0 ) def UpperCamelCase_ ( self : str , __lowercase : List[str] , __lowercase : Optional[int]=False ): '''simple docstring''' if isinstance(__lowercase , __lowercase ): __a = value lowerCamelCase__ = r""" This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`RegNetConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. """ lowerCamelCase__ = r""" Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`ConvNextImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple. """ @add_start_docstrings( 'The bare RegNet model outputting raw features without any specific head on top.' , lowerCamelCase__ , ) # Copied from transformers.models.resnet.modeling_resnet.ResNetModel with RESNET->REGNET,ResNet->RegNet class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): def __init__( self : int , __lowercase : Dict ): '''simple docstring''' super().__init__(__lowercase ) __a = config __a = RegNetEmbeddings(__lowercase ) __a = RegNetEncoder(__lowercase ) __a = nn.AdaptiveAvgPoolad((1, 1) ) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(__lowercase ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=__lowercase , config_class=_CONFIG_FOR_DOC , modality="""vision""" , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def UpperCamelCase_ ( self : int , __lowercase : Tensor , __lowercase : Optional[bool] = None , __lowercase : Optional[bool] = None ): '''simple docstring''' __a = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __a = return_dict if return_dict is not None else self.config.use_return_dict __a = self.embedder(__lowercase ) __a = self.encoder( __lowercase , output_hidden_states=__lowercase , return_dict=__lowercase ) __a = encoder_outputs[0] __a = self.pooler(__lowercase ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return BaseModelOutputWithPoolingAndNoAttention( last_hidden_state=__lowercase , pooler_output=__lowercase , hidden_states=encoder_outputs.hidden_states , ) @add_start_docstrings( '\n RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n ' , lowerCamelCase__ , ) # Copied from transformers.models.resnet.modeling_resnet.ResNetForImageClassification with RESNET->REGNET,ResNet->RegNet,resnet->regnet class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): def __init__( self : Optional[Any] , __lowercase : List[Any] ): '''simple docstring''' super().__init__(__lowercase ) __a = config.num_labels __a = RegNetModel(__lowercase ) # classification head __a = nn.Sequential( nn.Flatten() , nn.Linear(config.hidden_sizes[-1] , config.num_labels ) if config.num_labels > 0 else nn.Identity() , ) # initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(__lowercase ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=__lowercase , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def UpperCamelCase_ ( self : List[Any] , __lowercase : Optional[torch.FloatTensor] = None , __lowercase : Optional[torch.LongTensor] = None , __lowercase : Optional[bool] = None , __lowercase : Optional[bool] = None , ): '''simple docstring''' __a = return_dict if return_dict is not None else self.config.use_return_dict __a = self.regnet(__lowercase , output_hidden_states=__lowercase , return_dict=__lowercase ) __a = outputs.pooler_output if return_dict else outputs[1] __a = self.classifier(__lowercase ) __a = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: __a = """regression""" elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): __a = """single_label_classification""" else: __a = """multi_label_classification""" if self.config.problem_type == "regression": __a = MSELoss() if self.num_labels == 1: __a = loss_fct(logits.squeeze() , labels.squeeze() ) else: __a = loss_fct(__lowercase , __lowercase ) elif self.config.problem_type == "single_label_classification": __a = CrossEntropyLoss() __a = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": __a = BCEWithLogitsLoss() __a = loss_fct(__lowercase , __lowercase ) if not return_dict: __a = (logits,) + outputs[2:] return (loss,) + output if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=__lowercase , logits=__lowercase , hidden_states=outputs.hidden_states )
302
from typing import List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { """huggingface/autoformer-tourism-monthly""": """https://huggingface.co/huggingface/autoformer-tourism-monthly/resolve/main/config.json""", } class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : List[Any] ='autoformer' __lowerCamelCase : str ={ 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', 'num_hidden_layers': 'encoder_layers', } def __init__( self : List[Any] , __lowercase : Optional[int] = None , __lowercase : Optional[int] = None , __lowercase : str = "student_t" , __lowercase : str = "nll" , __lowercase : int = 1 , __lowercase : List[int] = [1, 2, 3, 4, 5, 6, 7] , __lowercase : bool = True , __lowercase : int = 0 , __lowercase : int = 0 , __lowercase : int = 0 , __lowercase : int = 0 , __lowercase : Optional[List[int]] = None , __lowercase : Optional[List[int]] = None , __lowercase : int = 64 , __lowercase : int = 2 , __lowercase : int = 2 , __lowercase : int = 2 , __lowercase : int = 2 , __lowercase : int = 32 , __lowercase : int = 32 , __lowercase : str = "gelu" , __lowercase : float = 0.1 , __lowercase : float = 0.1 , __lowercase : float = 0.1 , __lowercase : float = 0.1 , __lowercase : float = 0.1 , __lowercase : int = 100 , __lowercase : float = 0.02 , __lowercase : bool = True , __lowercase : List[Any]=True , __lowercase : int = 10 , __lowercase : int = 25 , __lowercase : int = 3 , **__lowercase : Optional[int] , ): '''simple docstring''' # time series specific configuration __a = prediction_length __a = context_length if context_length is not None else prediction_length __a = distribution_output __a = loss __a = input_size __a = num_time_features __a = lags_sequence __a = scaling __a = num_dynamic_real_features __a = num_static_real_features __a = num_static_categorical_features if cardinality is not None and num_static_categorical_features > 0: if len(__lowercase ) != num_static_categorical_features: raise ValueError( """The cardinality should be a list of the same length as `num_static_categorical_features`""" ) __a = cardinality else: __a = [0] if embedding_dimension is not None and num_static_categorical_features > 0: if len(__lowercase ) != num_static_categorical_features: raise ValueError( """The embedding dimension should be a list of the same length as `num_static_categorical_features`""" ) __a = embedding_dimension else: __a = [min(50 , (cat + 1) // 2 ) for cat in self.cardinality] __a = num_parallel_samples # Transformer architecture configuration __a = input_size * len(self.lags_sequence ) + self._number_of_features __a = d_model __a = encoder_attention_heads __a = decoder_attention_heads __a = encoder_ffn_dim __a = decoder_ffn_dim __a = encoder_layers __a = decoder_layers __a = dropout __a = attention_dropout __a = activation_dropout __a = encoder_layerdrop __a = decoder_layerdrop __a = activation_function __a = init_std __a = use_cache # Autoformer __a = label_length __a = moving_average __a = autocorrelation_factor super().__init__(is_encoder_decoder=__lowercase , **__lowercase ) @property def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' return ( sum(self.embedding_dimension ) + self.num_dynamic_real_features + self.num_time_features + self.num_static_real_features + self.input_size * 2 # the log1p(abs(loc)) and log(scale) features )
302
1
def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int ): """simple docstring""" __a = 1 __a = 2 while i * i <= n: __a = 0 while n % i == 0: n //= i multiplicity += 1 n_divisors *= multiplicity + 1 i += 1 if n > 1: n_divisors *= 2 return n_divisors def lowerCAmelCase__ ( ): """simple docstring""" __a = 1 __a = 1 while True: i += 1 t_num += i if count_divisors(_SCREAMING_SNAKE_CASE ) > 500: break return t_num if __name__ == "__main__": print(solution())
302
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase__ = { """configuration_electra""": ["""ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ElectraConfig""", """ElectraOnnxConfig"""], """tokenization_electra""": ["""ElectraTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = ["""ElectraTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ """ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST""", """ElectraForCausalLM""", """ElectraForMaskedLM""", """ElectraForMultipleChoice""", """ElectraForPreTraining""", """ElectraForQuestionAnswering""", """ElectraForSequenceClassification""", """ElectraForTokenClassification""", """ElectraModel""", """ElectraPreTrainedModel""", """load_tf_weights_in_electra""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ """TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFElectraForMaskedLM""", """TFElectraForMultipleChoice""", """TFElectraForPreTraining""", """TFElectraForQuestionAnswering""", """TFElectraForSequenceClassification""", """TFElectraForTokenClassification""", """TFElectraModel""", """TFElectraPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ """FlaxElectraForCausalLM""", """FlaxElectraForMaskedLM""", """FlaxElectraForMultipleChoice""", """FlaxElectraForPreTraining""", """FlaxElectraForQuestionAnswering""", """FlaxElectraForSequenceClassification""", """FlaxElectraForTokenClassification""", """FlaxElectraModel""", """FlaxElectraPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_electra import ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ElectraConfig, ElectraOnnxConfig from .tokenization_electra import ElectraTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_electra_fast import ElectraTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_electra import ( ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST, ElectraForCausalLM, ElectraForMaskedLM, ElectraForMultipleChoice, ElectraForPreTraining, ElectraForQuestionAnswering, ElectraForSequenceClassification, ElectraForTokenClassification, ElectraModel, ElectraPreTrainedModel, load_tf_weights_in_electra, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_electra import ( TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST, TFElectraForMaskedLM, TFElectraForMultipleChoice, TFElectraForPreTraining, TFElectraForQuestionAnswering, TFElectraForSequenceClassification, TFElectraForTokenClassification, TFElectraModel, TFElectraPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_electra import ( FlaxElectraForCausalLM, FlaxElectraForMaskedLM, FlaxElectraForMultipleChoice, FlaxElectraForPreTraining, FlaxElectraForQuestionAnswering, FlaxElectraForSequenceClassification, FlaxElectraForTokenClassification, FlaxElectraModel, FlaxElectraPreTrainedModel, ) else: import sys lowerCamelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
302
1
import warnings from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : Optional[int] =['image_processor', 'tokenizer'] __lowerCamelCase : Tuple ='LayoutLMv2ImageProcessor' __lowerCamelCase : Union[str, Any] =('LayoutXLMTokenizer', 'LayoutXLMTokenizerFast') def __init__( self : Any , __lowercase : Tuple=None , __lowercase : Tuple=None , **__lowercase : List[str] ): '''simple docstring''' if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""" , __lowercase , ) __a = kwargs.pop("""feature_extractor""" ) __a = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("""You need to specify an `image_processor`.""" ) if tokenizer is None: raise ValueError("""You need to specify a `tokenizer`.""" ) super().__init__(__lowercase , __lowercase ) def __call__( self : Union[str, Any] , __lowercase : int , __lowercase : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , __lowercase : Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None , __lowercase : Union[List[List[int]], List[List[List[int]]]] = None , __lowercase : Optional[Union[List[int], List[List[int]]]] = None , __lowercase : bool = True , __lowercase : Union[bool, str, PaddingStrategy] = False , __lowercase : Union[bool, str, TruncationStrategy] = None , __lowercase : Optional[int] = None , __lowercase : int = 0 , __lowercase : Optional[int] = None , __lowercase : Optional[bool] = None , __lowercase : Optional[bool] = None , __lowercase : bool = False , __lowercase : bool = False , __lowercase : bool = False , __lowercase : bool = False , __lowercase : bool = True , __lowercase : Optional[Union[str, TensorType]] = None , **__lowercase : Union[str, Any] , ): '''simple docstring''' # verify input if self.image_processor.apply_ocr and (boxes is not None): raise ValueError( """You cannot provide bounding boxes """ """if you initialized the image processor with apply_ocr set to True.""" ) if self.image_processor.apply_ocr and (word_labels is not None): raise ValueError( """You cannot provide word labels if you initialized the image processor with apply_ocr set to True.""" ) if return_overflowing_tokens is True and return_offsets_mapping is False: raise ValueError("""You cannot return overflowing tokens without returning the offsets mapping.""" ) # first, apply the image processor __a = self.image_processor(images=__lowercase , return_tensors=__lowercase ) # second, apply the tokenizer if text is not None and self.image_processor.apply_ocr and text_pair is None: if isinstance(__lowercase , __lowercase ): __a = [text] # add batch dimension (as the image processor always adds a batch dimension) __a = features["""words"""] __a = self.tokenizer( text=text if text is not None else features["""words"""] , text_pair=text_pair if text_pair is not None else None , boxes=boxes if boxes is not None else features["""boxes"""] , word_labels=__lowercase , add_special_tokens=__lowercase , padding=__lowercase , truncation=__lowercase , max_length=__lowercase , stride=__lowercase , pad_to_multiple_of=__lowercase , return_token_type_ids=__lowercase , return_attention_mask=__lowercase , return_overflowing_tokens=__lowercase , return_special_tokens_mask=__lowercase , return_offsets_mapping=__lowercase , return_length=__lowercase , verbose=__lowercase , return_tensors=__lowercase , **__lowercase , ) # add pixel values __a = features.pop("""pixel_values""" ) if return_overflowing_tokens is True: __a = self.get_overflowing_images(__lowercase , encoded_inputs["""overflow_to_sample_mapping"""] ) __a = images return encoded_inputs def UpperCamelCase_ ( self : Optional[int] , __lowercase : Tuple , __lowercase : List[Any] ): '''simple docstring''' # in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image __a = [] for sample_idx in overflow_to_sample_mapping: images_with_overflow.append(images[sample_idx] ) if len(__lowercase ) != len(__lowercase ): raise ValueError( """Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got""" F" {len(__lowercase )} and {len(__lowercase )}" ) return images_with_overflow def UpperCamelCase_ ( self : Tuple , *__lowercase : Dict , **__lowercase : Dict ): '''simple docstring''' return self.tokenizer.batch_decode(*__lowercase , **__lowercase ) def UpperCamelCase_ ( self : Union[str, Any] , *__lowercase : List[Any] , **__lowercase : str ): '''simple docstring''' return self.tokenizer.decode(*__lowercase , **__lowercase ) @property def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' return ["input_ids", "bbox", "attention_mask", "image"] @property def UpperCamelCase_ ( self : Any ): '''simple docstring''' warnings.warn( """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.""" , __lowercase , ) return self.image_processor_class @property def UpperCamelCase_ ( self : str ): '''simple docstring''' warnings.warn( """`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.""" , __lowercase , ) return self.image_processor
302
from __future__ import annotations lowerCamelCase__ = """#""" class SCREAMING_SNAKE_CASE : def __init__( self : Optional[Any] ): '''simple docstring''' __a = {} def UpperCamelCase_ ( self : Optional[Any] , __lowercase : str ): '''simple docstring''' __a = self._trie for char in text: if char not in trie: __a = {} __a = trie[char] __a = True def UpperCamelCase_ ( self : Tuple , __lowercase : str ): '''simple docstring''' __a = self._trie for char in prefix: if char in trie: __a = trie[char] else: return [] return self._elements(__lowercase ) def UpperCamelCase_ ( self : Optional[int] , __lowercase : dict ): '''simple docstring''' __a = [] for c, v in d.items(): __a = [""" """] if c == END else [(c + s) for s in self._elements(__lowercase )] result.extend(__lowercase ) return tuple(__lowercase ) lowerCamelCase__ = Trie() lowerCamelCase__ = ("""depart""", """detergent""", """daring""", """dog""", """deer""", """deal""") for word in words: trie.insert_word(word) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : str ): """simple docstring""" __a = trie.find_word(_SCREAMING_SNAKE_CASE ) return tuple(string + word for word in suffixes ) def lowerCAmelCase__ ( ): """simple docstring""" print(autocomplete_using_trie("""de""" ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
302
1
import argparse from copy import deepcopy import numpy as np from datasets import ClassLabel, DatasetDict, load_dataset from evaluate import load from transformers import ( AutoModelForSequenceClassification, AutoTokenizer, DataCollatorWithPadding, Trainer, TrainerCallback, TrainingArguments, set_seed, ) def lowerCAmelCase__ ( ): """simple docstring""" __a = argparse.ArgumentParser() parser.add_argument("""--model_ckpt""" , type=_SCREAMING_SNAKE_CASE , default="""microsoft/unixcoder-base-nine""" ) parser.add_argument("""--num_epochs""" , type=_SCREAMING_SNAKE_CASE , default=5 ) parser.add_argument("""--batch_size""" , type=_SCREAMING_SNAKE_CASE , default=6 ) parser.add_argument("""--gradient_accumulation_steps""" , type=_SCREAMING_SNAKE_CASE , default=1 ) parser.add_argument("""--freeze""" , type=_SCREAMING_SNAKE_CASE , default=_SCREAMING_SNAKE_CASE ) parser.add_argument("""--learning_rate""" , type=_SCREAMING_SNAKE_CASE , default=5e-4 ) parser.add_argument("""--seed""" , type=_SCREAMING_SNAKE_CASE , default=0 ) parser.add_argument("""--lr_scheduler_type""" , type=_SCREAMING_SNAKE_CASE , default="""cosine""" ) parser.add_argument("""--num_warmup_steps""" , type=_SCREAMING_SNAKE_CASE , default=10 ) parser.add_argument("""--weight_decay""" , type=_SCREAMING_SNAKE_CASE , default=0.01 ) parser.add_argument("""--output_dir""" , type=_SCREAMING_SNAKE_CASE , default="""./results""" ) return parser.parse_args() lowerCamelCase__ = load("""accuracy""") def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" __a , __a = eval_pred __a = np.argmax(_SCREAMING_SNAKE_CASE , axis=1 ) return metric.compute(predictions=_SCREAMING_SNAKE_CASE , references=_SCREAMING_SNAKE_CASE ) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): def __init__( self : int , __lowercase : int ): '''simple docstring''' super().__init__() __a = trainer def UpperCamelCase_ ( self : List[Any] , __lowercase : Any , __lowercase : int , __lowercase : Optional[int] , **__lowercase : int ): '''simple docstring''' if control.should_evaluate: __a = deepcopy(__lowercase ) self._trainer.evaluate(eval_dataset=self._trainer.train_dataset , metric_key_prefix="""train""" ) return control_copy def lowerCAmelCase__ ( ): """simple docstring""" __a = get_args() set_seed(args.seed ) __a = load_dataset("""codeparrot/codecomplex""" , split="""train""" ) __a = dataset.train_test_split(test_size=0.2 ) __a = train_test["""test"""].train_test_split(test_size=0.5 ) __a = DatasetDict( { """train""": train_test["""train"""], """test""": test_validation["""train"""], """valid""": test_validation["""test"""], } ) print("""Loading tokenizer and model""" ) __a = AutoTokenizer.from_pretrained(args.model_ckpt ) __a = tokenizer.eos_token __a = AutoModelForSequenceClassification.from_pretrained(args.model_ckpt , num_labels=7 ) __a = model.config.eos_token_id if args.freeze: for param in model.roberta.parameters(): __a = False __a = ClassLabel(num_classes=7 , names=list(set(train_test_validation["""train"""]["""complexity"""] ) ) ) def tokenize(_SCREAMING_SNAKE_CASE : List[str] ): __a = tokenizer(example["""src"""] , truncation=_SCREAMING_SNAKE_CASE , max_length=1024 ) __a = labels.straint(example["""complexity"""] ) return { "input_ids": inputs["input_ids"], "attention_mask": inputs["attention_mask"], "label": label, } __a = train_test_validation.map( _SCREAMING_SNAKE_CASE , batched=_SCREAMING_SNAKE_CASE , remove_columns=train_test_validation["""train"""].column_names , ) __a = DataCollatorWithPadding(tokenizer=_SCREAMING_SNAKE_CASE ) __a = TrainingArguments( output_dir=args.output_dir , learning_rate=args.learning_rate , lr_scheduler_type=args.lr_scheduler_type , evaluation_strategy="""epoch""" , save_strategy="""epoch""" , logging_strategy="""epoch""" , per_device_train_batch_size=args.batch_size , per_device_eval_batch_size=args.batch_size , num_train_epochs=args.num_epochs , gradient_accumulation_steps=args.gradient_accumulation_steps , weight_decay=0.01 , metric_for_best_model="""accuracy""" , run_name="""complexity-java""" , report_to="""wandb""" , ) __a = Trainer( model=_SCREAMING_SNAKE_CASE , args=_SCREAMING_SNAKE_CASE , train_dataset=tokenized_datasets["""train"""] , eval_dataset=tokenized_datasets["""valid"""] , tokenizer=_SCREAMING_SNAKE_CASE , data_collator=_SCREAMING_SNAKE_CASE , compute_metrics=_SCREAMING_SNAKE_CASE , ) print("""Training...""" ) trainer.add_callback(CustomCallback(_SCREAMING_SNAKE_CASE ) ) trainer.train() if __name__ == "__main__": main()
302
from dataclasses import dataclass from typing import Dict, Optional, Union import torch import torch.nn.functional as F from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .attention import BasicTransformerBlock from .attention_processor import AttentionProcessor, AttnProcessor from .embeddings import TimestepEmbedding, Timesteps from .modeling_utils import ModelMixin @dataclass class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : torch.FloatTensor class SCREAMING_SNAKE_CASE ( lowerCamelCase__ , lowerCamelCase__ ): @register_to_config def __init__( self : Dict , __lowercase : int = 32 , __lowercase : int = 64 , __lowercase : int = 20 , __lowercase : int = 768 , __lowercase : Any=77 , __lowercase : Optional[int]=4 , __lowercase : float = 0.0 , __lowercase : str = "silu" , __lowercase : Optional[str] = None , __lowercase : Optional[str] = None , __lowercase : Optional[str] = "linear" , __lowercase : Optional[str] = "prd" , __lowercase : Optional[int] = None , __lowercase : Optional[int] = None , __lowercase : Optional[int] = None , ): '''simple docstring''' super().__init__() __a = num_attention_heads __a = attention_head_dim __a = num_attention_heads * attention_head_dim __a = additional_embeddings __a = time_embed_dim or inner_dim __a = embedding_proj_dim or embedding_dim __a = clip_embed_dim or embedding_dim __a = Timesteps(__lowercase , __lowercase , 0 ) __a = TimestepEmbedding(__lowercase , __lowercase , out_dim=__lowercase , act_fn=__lowercase ) __a = nn.Linear(__lowercase , __lowercase ) if embedding_proj_norm_type is None: __a = None elif embedding_proj_norm_type == "layer": __a = nn.LayerNorm(__lowercase ) else: raise ValueError(F"unsupported embedding_proj_norm_type: {embedding_proj_norm_type}" ) __a = nn.Linear(__lowercase , __lowercase ) if encoder_hid_proj_type is None: __a = None elif encoder_hid_proj_type == "linear": __a = nn.Linear(__lowercase , __lowercase ) else: raise ValueError(F"unsupported encoder_hid_proj_type: {encoder_hid_proj_type}" ) __a = nn.Parameter(torch.zeros(1 , num_embeddings + additional_embeddings , __lowercase ) ) if added_emb_type == "prd": __a = nn.Parameter(torch.zeros(1 , 1 , __lowercase ) ) elif added_emb_type is None: __a = None else: raise ValueError( F"`added_emb_type`: {added_emb_type} is not supported. Make sure to choose one of `'prd'` or `None`." ) __a = nn.ModuleList( [ BasicTransformerBlock( __lowercase , __lowercase , __lowercase , dropout=__lowercase , activation_fn="""gelu""" , attention_bias=__lowercase , ) for d in range(__lowercase ) ] ) if norm_in_type == "layer": __a = nn.LayerNorm(__lowercase ) elif norm_in_type is None: __a = None else: raise ValueError(F"Unsupported norm_in_type: {norm_in_type}." ) __a = nn.LayerNorm(__lowercase ) __a = nn.Linear(__lowercase , __lowercase ) __a = torch.full( [num_embeddings + additional_embeddings, num_embeddings + additional_embeddings] , -10000.0 ) causal_attention_mask.triu_(1 ) __a = causal_attention_mask[None, ...] self.register_buffer("""causal_attention_mask""" , __lowercase , persistent=__lowercase ) __a = nn.Parameter(torch.zeros(1 , __lowercase ) ) __a = nn.Parameter(torch.zeros(1 , __lowercase ) ) @property # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' __a = {} def fn_recursive_add_processors(__lowercase : str , __lowercase : torch.nn.Module , __lowercase : Dict[str, AttentionProcessor] ): if hasattr(__lowercase , """set_processor""" ): __a = module.processor for sub_name, child in module.named_children(): fn_recursive_add_processors(F"{name}.{sub_name}" , __lowercase , __lowercase ) return processors for name, module in self.named_children(): fn_recursive_add_processors(__lowercase , __lowercase , __lowercase ) return processors def UpperCamelCase_ ( self : List[str] , __lowercase : Union[AttentionProcessor, Dict[str, AttentionProcessor]] ): '''simple docstring''' __a = len(self.attn_processors.keys() ) if isinstance(__lowercase , __lowercase ) and len(__lowercase ) != count: raise ValueError( F"A dict of processors was passed, but the number of processors {len(__lowercase )} does not match the" F" number of attention layers: {count}. Please make sure to pass {count} processor classes." ) def fn_recursive_attn_processor(__lowercase : str , __lowercase : torch.nn.Module , __lowercase : Dict ): if hasattr(__lowercase , """set_processor""" ): if not isinstance(__lowercase , __lowercase ): module.set_processor(__lowercase ) else: module.set_processor(processor.pop(F"{name}.processor" ) ) for sub_name, child in module.named_children(): fn_recursive_attn_processor(F"{name}.{sub_name}" , __lowercase , __lowercase ) for name, module in self.named_children(): fn_recursive_attn_processor(__lowercase , __lowercase , __lowercase ) def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' self.set_attn_processor(AttnProcessor() ) def UpperCamelCase_ ( self : Union[str, Any] , __lowercase : Optional[int] , __lowercase : Union[torch.Tensor, float, int] , __lowercase : torch.FloatTensor , __lowercase : Optional[torch.FloatTensor] = None , __lowercase : Optional[torch.BoolTensor] = None , __lowercase : bool = True , ): '''simple docstring''' __a = hidden_states.shape[0] __a = timestep if not torch.is_tensor(__lowercase ): __a = torch.tensor([timesteps] , dtype=torch.long , device=hidden_states.device ) elif torch.is_tensor(__lowercase ) and len(timesteps.shape ) == 0: __a = timesteps[None].to(hidden_states.device ) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML __a = timesteps * torch.ones(__lowercase , dtype=timesteps.dtype , device=timesteps.device ) __a = self.time_proj(__lowercase ) # timesteps does not contain any weights and will always return f32 tensors # but time_embedding might be fp16, so we need to cast here. __a = timesteps_projected.to(dtype=self.dtype ) __a = self.time_embedding(__lowercase ) if self.embedding_proj_norm is not None: __a = self.embedding_proj_norm(__lowercase ) __a = self.embedding_proj(__lowercase ) if self.encoder_hidden_states_proj is not None and encoder_hidden_states is not None: __a = self.encoder_hidden_states_proj(__lowercase ) elif self.encoder_hidden_states_proj is not None and encoder_hidden_states is None: raise ValueError("""`encoder_hidden_states_proj` requires `encoder_hidden_states` to be set""" ) __a = self.proj_in(__lowercase ) __a = self.positional_embedding.to(hidden_states.dtype ) __a = [] __a = 0 if encoder_hidden_states is not None: additional_embeds.append(__lowercase ) additional_embeddings_len += encoder_hidden_states.shape[1] if len(proj_embeddings.shape ) == 2: __a = proj_embeddings[:, None, :] if len(hidden_states.shape ) == 2: __a = hidden_states[:, None, :] __a = additional_embeds + [ proj_embeddings, time_embeddings[:, None, :], hidden_states, ] if self.prd_embedding is not None: __a = self.prd_embedding.to(hidden_states.dtype ).expand(__lowercase , -1 , -1 ) additional_embeds.append(__lowercase ) __a = torch.cat( __lowercase , dim=1 , ) # Allow positional_embedding to not include the `addtional_embeddings` and instead pad it with zeros for these additional tokens __a = additional_embeddings_len + proj_embeddings.shape[1] + 1 if positional_embeddings.shape[1] < hidden_states.shape[1]: __a = F.pad( __lowercase , ( 0, 0, additional_embeddings_len, self.prd_embedding.shape[1] if self.prd_embedding is not None else 0, ) , value=0.0 , ) __a = hidden_states + positional_embeddings if attention_mask is not None: __a = (1 - attention_mask.to(hidden_states.dtype )) * -10000.0 __a = F.pad(__lowercase , (0, self.additional_embeddings) , value=0.0 ) __a = (attention_mask[:, None, :] + self.causal_attention_mask).to(hidden_states.dtype ) __a = attention_mask.repeat_interleave(self.config.num_attention_heads , dim=0 ) if self.norm_in is not None: __a = self.norm_in(__lowercase ) for block in self.transformer_blocks: __a = block(__lowercase , attention_mask=__lowercase ) __a = self.norm_out(__lowercase ) if self.prd_embedding is not None: __a = hidden_states[:, -1] else: __a = hidden_states[:, additional_embeddings_len:] __a = self.proj_to_clip_embeddings(__lowercase ) if not return_dict: return (predicted_image_embedding,) return PriorTransformerOutput(predicted_image_embedding=__lowercase ) def UpperCamelCase_ ( self : Any , __lowercase : Tuple ): '''simple docstring''' __a = (prior_latents * self.clip_std) + self.clip_mean return prior_latents
302
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowerCamelCase__ = { """configuration_mask2former""": [ """MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Mask2FormerConfig""", ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = ["""Mask2FormerImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ """MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """Mask2FormerForUniversalSegmentation""", """Mask2FormerModel""", """Mask2FormerPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_maskaformer import MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskaFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_maskaformer import MaskaFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskaformer import ( MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskaFormerForUniversalSegmentation, MaskaFormerModel, MaskaFormerPreTrainedModel, ) else: import sys lowerCamelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure)
302
from functools import lru_cache def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int ): """simple docstring""" __a = 2 __a = set() while i * i <= n: if n % i: i += 1 else: n //= i factors.add(_SCREAMING_SNAKE_CASE ) if n > 1: factors.add(_SCREAMING_SNAKE_CASE ) return factors @lru_cache def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int ): """simple docstring""" return len(unique_prime_factors(_SCREAMING_SNAKE_CASE ) ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : list ): """simple docstring""" return len(set(_SCREAMING_SNAKE_CASE ) ) in (0, 1) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int ): """simple docstring""" __a = 2 while True: # Increment each value of a generated range __a = [base + i for i in range(_SCREAMING_SNAKE_CASE )] # Run elements through out unique_prime_factors function # Append our target number to the end. __a = [upf_len(_SCREAMING_SNAKE_CASE ) for x in group] checker.append(_SCREAMING_SNAKE_CASE ) # If all numbers in the list are equal, return the group variable. if equality(_SCREAMING_SNAKE_CASE ): return group # Increment our base variable by 1 base += 1 def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int = 4 ): """simple docstring""" __a = run(_SCREAMING_SNAKE_CASE ) return results[0] if len(_SCREAMING_SNAKE_CASE ) else None if __name__ == "__main__": print(solution())
302
1
import argparse import re from pathlib import Path import requests import torch from PIL import Image from torchvision.transforms import CenterCrop, Compose, Normalize, Resize, ToTensor from transformers import ( EfficientFormerConfig, EfficientFormerForImageClassificationWithTeacher, EfficientFormerImageProcessor, ) from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, PILImageResampling def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Optional[int] ): """simple docstring""" __a = old_name if "patch_embed" in old_name: __a , __a , __a = old_name.split(""".""" ) if layer == "0": __a = old_name.replace("""0""" , """convolution1""" ) elif layer == "1": __a = old_name.replace("""1""" , """batchnorm_before""" ) elif layer == "3": __a = old_name.replace("""3""" , """convolution2""" ) else: __a = old_name.replace("""4""" , """batchnorm_after""" ) if "network" in old_name and re.search(r"""\d\.\d""" , _SCREAMING_SNAKE_CASE ): __a = r"""\b\d{2}\b""" if bool(re.search(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ): __a = re.search(r"""\d\.\d\d.""" , _SCREAMING_SNAKE_CASE ).group() else: __a = re.search(r"""\d\.\d.""" , _SCREAMING_SNAKE_CASE ).group() if int(match[0] ) < 6: __a = old_name.replace(_SCREAMING_SNAKE_CASE , """""" ) __a = trimmed_name.replace("""network""" , match[0] + """.meta4D_layers.blocks.""" + match[2:-1] ) __a = """intermediate_stages.""" + trimmed_name else: __a = old_name.replace(_SCREAMING_SNAKE_CASE , """""" ) if int(match[2] ) < num_meta4D_last_stage: __a = trimmed_name.replace("""network""" , """meta4D_layers.blocks.""" + match[2] ) else: __a = str(int(match[2] ) - num_meta4D_last_stage ) __a = trimmed_name.replace("""network""" , """meta3D_layers.blocks.""" + layer_index ) if "norm1" in old_name: __a = trimmed_name.replace("""norm1""" , """layernorm1""" ) elif "norm2" in old_name: __a = trimmed_name.replace("""norm2""" , """layernorm2""" ) elif "fc1" in old_name: __a = trimmed_name.replace("""fc1""" , """linear_in""" ) elif "fc2" in old_name: __a = trimmed_name.replace("""fc2""" , """linear_out""" ) __a = """last_stage.""" + trimmed_name elif "network" in old_name and re.search(r""".\d.""" , _SCREAMING_SNAKE_CASE ): __a = old_name.replace("""network""" , """intermediate_stages""" ) if "fc" in new_name: __a = new_name.replace("""fc""" , """convolution""" ) elif ("norm1" in new_name) and ("layernorm1" not in new_name): __a = new_name.replace("""norm1""" , """batchnorm_before""" ) elif ("norm2" in new_name) and ("layernorm2" not in new_name): __a = new_name.replace("""norm2""" , """batchnorm_after""" ) if "proj" in new_name: __a = new_name.replace("""proj""" , """projection""" ) if "dist_head" in new_name: __a = new_name.replace("""dist_head""" , """distillation_classifier""" ) elif "head" in new_name: __a = new_name.replace("""head""" , """classifier""" ) elif "patch_embed" in new_name: __a = """efficientformer.""" + new_name elif new_name == "norm.weight" or new_name == "norm.bias": __a = new_name.replace("""norm""" , """layernorm""" ) __a = """efficientformer.""" + new_name else: __a = """efficientformer.encoder.""" + new_name return new_name def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" for key in checkpoint.copy().keys(): __a = checkpoint.pop(_SCREAMING_SNAKE_CASE ) __a = val return checkpoint def lowerCAmelCase__ ( ): """simple docstring""" __a = """http://images.cocodataset.org/val2017/000000039769.jpg""" __a = Image.open(requests.get(_SCREAMING_SNAKE_CASE , stream=_SCREAMING_SNAKE_CASE ).raw ) return image def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Path , _SCREAMING_SNAKE_CASE : Path , _SCREAMING_SNAKE_CASE : Path , _SCREAMING_SNAKE_CASE : bool ): """simple docstring""" __a = torch.load(_SCREAMING_SNAKE_CASE , map_location="""cpu""" )["""model"""] __a = EfficientFormerConfig.from_json_file(_SCREAMING_SNAKE_CASE ) __a = EfficientFormerForImageClassificationWithTeacher(_SCREAMING_SNAKE_CASE ) __a = """_""".join(checkpoint_path.split("""/""" )[-1].split(""".""" )[0].split("""_""" )[:-1] ) __a = config.depths[-1] - config.num_metaad_blocks + 1 __a = convert_torch_checkpoint(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) model.load_state_dict(_SCREAMING_SNAKE_CASE ) model.eval() __a = { """bilinear""": PILImageResampling.BILINEAR, """bicubic""": PILImageResampling.BICUBIC, """nearest""": PILImageResampling.NEAREST, } # prepare image __a = prepare_img() __a = 256 __a = 224 __a = EfficientFormerImageProcessor( size={"""shortest_edge""": image_size} , crop_size={"""height""": crop_size, """width""": crop_size} , resample=pillow_resamplings["""bicubic"""] , ) __a = processor(images=_SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).pixel_values # original processing pipeline __a = Compose( [ Resize(_SCREAMING_SNAKE_CASE , interpolation=pillow_resamplings["""bicubic"""] ), CenterCrop(_SCREAMING_SNAKE_CASE ), ToTensor(), Normalize(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ), ] ) __a = image_transforms(_SCREAMING_SNAKE_CASE ).unsqueeze(0 ) assert torch.allclose(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __a = model(_SCREAMING_SNAKE_CASE ) __a = outputs.logits __a = (1, 1000) if "l1" in model_name: __a = torch.Tensor( [-0.1312, 0.4353, -1.0499, -0.5124, 0.4183, -0.6793, -1.3777, -0.0893, -0.7358, -2.4328] ) assert torch.allclose(logits[0, :10] , _SCREAMING_SNAKE_CASE , atol=1e-3 ) assert logits.shape == expected_shape elif "l3" in model_name: __a = torch.Tensor( [-1.3150, -1.5456, -1.2556, -0.8496, -0.7127, -0.7897, -0.9728, -0.3052, 0.3751, -0.3127] ) assert torch.allclose(logits[0, :10] , _SCREAMING_SNAKE_CASE , atol=1e-3 ) assert logits.shape == expected_shape elif "l7" in model_name: __a = torch.Tensor( [-1.0283, -1.4131, -0.5644, -1.3115, -0.5785, -1.2049, -0.7528, 0.1992, -0.3822, -0.0878] ) assert logits.shape == expected_shape else: raise ValueError( f"Unknown model checkpoint: {checkpoint_path}. Supported version of efficientformer are l1, l3 and l7" ) # Save Checkpoints Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) print(f"Checkpoint successfuly converted. Model saved at {pytorch_dump_path}" ) processor.save_pretrained(_SCREAMING_SNAKE_CASE ) print(f"Processor successfuly saved at {pytorch_dump_path}" ) if push_to_hub: print("""Pushing model to the hub...""" ) model.push_to_hub( repo_id=f"Bearnardd/{pytorch_dump_path}" , commit_message="""Add model""" , use_temp_dir=_SCREAMING_SNAKE_CASE , ) processor.push_to_hub( repo_id=f"Bearnardd/{pytorch_dump_path}" , commit_message="""Add image processor""" , use_temp_dir=_SCREAMING_SNAKE_CASE , ) if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--pytorch_model_path""", default=None, type=str, required=True, help="""Path to EfficientFormer pytorch checkpoint.""", ) parser.add_argument( """--config_file""", default=None, type=str, required=True, help="""The json file for EfficientFormer model config.""", ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) parser.add_argument("""--push_to_hub""", action="""store_true""", help="""Push model and image processor to the hub""") parser.add_argument( """--no-push_to_hub""", dest="""push_to_hub""", action="""store_false""", help="""Do not push model and image processor to the hub""", ) parser.set_defaults(push_to_hub=True) lowerCamelCase__ = parser.parse_args() convert_efficientformer_checkpoint( checkpoint_path=args.pytorch_model_path, efficientformer_config_file=args.config_file, pytorch_dump_path=args.pytorch_dump_path, push_to_hub=args.push_to_hub, )
302
import argparse import json from pathlib import Path import torch import torchaudio from datasets import load_dataset from huggingface_hub import hf_hub_download from transformers import ASTConfig, ASTFeatureExtractor, ASTForAudioClassification from transformers.utils import logging logging.set_verbosity_info() lowerCamelCase__ = logging.get_logger(__name__) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Any ): """simple docstring""" __a = ASTConfig() if "10-10" in model_name: pass elif "speech-commands" in model_name: __a = 128 elif "12-12" in model_name: __a = 12 __a = 12 elif "14-14" in model_name: __a = 14 __a = 14 elif "16-16" in model_name: __a = 16 __a = 16 else: raise ValueError("""Model not supported""" ) __a = """huggingface/label-files""" if "speech-commands" in model_name: __a = 35 __a = """speech-commands-v2-id2label.json""" else: __a = 527 __a = """audioset-id2label.json""" __a = json.load(open(hf_hub_download(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , repo_type="""dataset""" ) , """r""" ) ) __a = {int(_SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()} __a = idalabel __a = {v: k for k, v in idalabel.items()} return config def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" if "module.v" in name: __a = name.replace("""module.v""" , """audio_spectrogram_transformer""" ) if "cls_token" in name: __a = name.replace("""cls_token""" , """embeddings.cls_token""" ) if "dist_token" in name: __a = name.replace("""dist_token""" , """embeddings.distillation_token""" ) if "pos_embed" in name: __a = name.replace("""pos_embed""" , """embeddings.position_embeddings""" ) if "patch_embed.proj" in name: __a = name.replace("""patch_embed.proj""" , """embeddings.patch_embeddings.projection""" ) # transformer blocks if "blocks" in name: __a = name.replace("""blocks""" , """encoder.layer""" ) if "attn.proj" in name: __a = name.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in name: __a = name.replace("""attn""" , """attention.self""" ) if "norm1" in name: __a = name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: __a = name.replace("""norm2""" , """layernorm_after""" ) if "mlp.fc1" in name: __a = name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: __a = name.replace("""mlp.fc2""" , """output.dense""" ) # final layernorm if "audio_spectrogram_transformer.norm" in name: __a = name.replace("""audio_spectrogram_transformer.norm""" , """audio_spectrogram_transformer.layernorm""" ) # classifier head if "module.mlp_head.0" in name: __a = name.replace("""module.mlp_head.0""" , """classifier.layernorm""" ) if "module.mlp_head.1" in name: __a = name.replace("""module.mlp_head.1""" , """classifier.dense""" ) return name def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" for key in orig_state_dict.copy().keys(): __a = orig_state_dict.pop(_SCREAMING_SNAKE_CASE ) if "qkv" in key: __a = key.split(""".""" ) __a = int(key_split[3] ) __a = config.hidden_size if "weight" in key: __a = val[:dim, :] __a = val[dim : dim * 2, :] __a = val[-dim:, :] else: __a = val[:dim] __a = val[dim : dim * 2] __a = val[-dim:] else: __a = val return orig_state_dict def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" __a = [ """module.v.head.weight""", """module.v.head.bias""", """module.v.head_dist.weight""", """module.v.head_dist.bias""", ] for k in ignore_keys: state_dict.pop(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @torch.no_grad() def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : List[str]=False ): """simple docstring""" __a = get_audio_spectrogram_transformer_config(_SCREAMING_SNAKE_CASE ) __a = { """ast-finetuned-audioset-10-10-0.4593""": ( """https://www.dropbox.com/s/ca0b1v2nlxzyeb4/audioset_10_10_0.4593.pth?dl=1""" ), """ast-finetuned-audioset-10-10-0.450""": ( """https://www.dropbox.com/s/1tv0hovue1bxupk/audioset_10_10_0.4495.pth?dl=1""" ), """ast-finetuned-audioset-10-10-0.448""": ( """https://www.dropbox.com/s/6u5sikl4b9wo4u5/audioset_10_10_0.4483.pth?dl=1""" ), """ast-finetuned-audioset-10-10-0.448-v2""": ( """https://www.dropbox.com/s/kt6i0v9fvfm1mbq/audioset_10_10_0.4475.pth?dl=1""" ), """ast-finetuned-audioset-12-12-0.447""": ( """https://www.dropbox.com/s/snfhx3tizr4nuc8/audioset_12_12_0.4467.pth?dl=1""" ), """ast-finetuned-audioset-14-14-0.443""": ( """https://www.dropbox.com/s/z18s6pemtnxm4k7/audioset_14_14_0.4431.pth?dl=1""" ), """ast-finetuned-audioset-16-16-0.442""": ( """https://www.dropbox.com/s/mdsa4t1xmcimia6/audioset_16_16_0.4422.pth?dl=1""" ), """ast-finetuned-speech-commands-v2""": ( """https://www.dropbox.com/s/q0tbqpwv44pquwy/speechcommands_10_10_0.9812.pth?dl=1""" ), } # load original state_dict __a = model_name_to_url[model_name] __a = torch.hub.load_state_dict_from_url(_SCREAMING_SNAKE_CASE , map_location="""cpu""" ) # remove some keys remove_keys(_SCREAMING_SNAKE_CASE ) # rename some keys __a = convert_state_dict(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # load 🤗 model __a = ASTForAudioClassification(_SCREAMING_SNAKE_CASE ) model.eval() model.load_state_dict(_SCREAMING_SNAKE_CASE ) # verify outputs on dummy input # source: https://github.com/YuanGongND/ast/blob/79e873b8a54d0a3b330dd522584ff2b9926cd581/src/run.py#L62 __a = -4.267_7393 if """speech-commands""" not in model_name else -6.84_5978 __a = 4.568_9974 if """speech-commands""" not in model_name else 5.565_4526 __a = 1024 if """speech-commands""" not in model_name else 128 __a = ASTFeatureExtractor(mean=_SCREAMING_SNAKE_CASE , std=_SCREAMING_SNAKE_CASE , max_length=_SCREAMING_SNAKE_CASE ) if "speech-commands" in model_name: __a = load_dataset("""speech_commands""" , """v0.02""" , split="""validation""" ) __a = dataset[0]["""audio"""]["""array"""] else: __a = hf_hub_download( repo_id="""nielsr/audio-spectogram-transformer-checkpoint""" , filename="""sample_audio.flac""" , repo_type="""dataset""" , ) __a , __a = torchaudio.load(_SCREAMING_SNAKE_CASE ) __a = waveform.squeeze().numpy() __a = feature_extractor(_SCREAMING_SNAKE_CASE , sampling_rate=1_6000 , return_tensors="""pt""" ) # forward pass __a = model(**_SCREAMING_SNAKE_CASE ) __a = outputs.logits if model_name == "ast-finetuned-audioset-10-10-0.4593": __a = torch.tensor([-0.8760, -7.0042, -8.6602] ) elif model_name == "ast-finetuned-audioset-10-10-0.450": __a = torch.tensor([-1.1986, -7.0903, -8.2718] ) elif model_name == "ast-finetuned-audioset-10-10-0.448": __a = torch.tensor([-2.6128, -8.0080, -9.4344] ) elif model_name == "ast-finetuned-audioset-10-10-0.448-v2": __a = torch.tensor([-1.5080, -7.4534, -8.8917] ) elif model_name == "ast-finetuned-audioset-12-12-0.447": __a = torch.tensor([-0.5050, -6.5833, -8.0843] ) elif model_name == "ast-finetuned-audioset-14-14-0.443": __a = torch.tensor([-0.3826, -7.0336, -8.2413] ) elif model_name == "ast-finetuned-audioset-16-16-0.442": __a = torch.tensor([-1.2113, -6.9101, -8.3470] ) elif model_name == "ast-finetuned-speech-commands-v2": __a = torch.tensor([6.1589, -8.0566, -8.7984] ) else: raise ValueError("""Unknown model name""" ) if not torch.allclose(logits[0, :3] , _SCREAMING_SNAKE_CASE , atol=1e-4 ): raise ValueError("""Logits don't match""" ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) print(f"Saving model {model_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) print(f"Saving feature extractor to {pytorch_dump_folder_path}" ) feature_extractor.save_pretrained(_SCREAMING_SNAKE_CASE ) if push_to_hub: print("""Pushing model and feature extractor to the hub...""" ) model.push_to_hub(f"MIT/{model_name}" ) feature_extractor.push_to_hub(f"MIT/{model_name}" ) if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default="""ast-finetuned-audioset-10-10-0.4593""", type=str, help="""Name of the Audio Spectrogram Transformer model you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) parser.add_argument( """--push_to_hub""", action="""store_true""", help="""Whether or not to push the converted model to the 🤗 hub.""" ) lowerCamelCase__ = parser.parse_args() convert_audio_spectrogram_transformer_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
302
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase__ = { """configuration_electra""": ["""ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ElectraConfig""", """ElectraOnnxConfig"""], """tokenization_electra""": ["""ElectraTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = ["""ElectraTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ """ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST""", """ElectraForCausalLM""", """ElectraForMaskedLM""", """ElectraForMultipleChoice""", """ElectraForPreTraining""", """ElectraForQuestionAnswering""", """ElectraForSequenceClassification""", """ElectraForTokenClassification""", """ElectraModel""", """ElectraPreTrainedModel""", """load_tf_weights_in_electra""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ """TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFElectraForMaskedLM""", """TFElectraForMultipleChoice""", """TFElectraForPreTraining""", """TFElectraForQuestionAnswering""", """TFElectraForSequenceClassification""", """TFElectraForTokenClassification""", """TFElectraModel""", """TFElectraPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ """FlaxElectraForCausalLM""", """FlaxElectraForMaskedLM""", """FlaxElectraForMultipleChoice""", """FlaxElectraForPreTraining""", """FlaxElectraForQuestionAnswering""", """FlaxElectraForSequenceClassification""", """FlaxElectraForTokenClassification""", """FlaxElectraModel""", """FlaxElectraPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_electra import ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ElectraConfig, ElectraOnnxConfig from .tokenization_electra import ElectraTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_electra_fast import ElectraTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_electra import ( ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST, ElectraForCausalLM, ElectraForMaskedLM, ElectraForMultipleChoice, ElectraForPreTraining, ElectraForQuestionAnswering, ElectraForSequenceClassification, ElectraForTokenClassification, ElectraModel, ElectraPreTrainedModel, load_tf_weights_in_electra, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_electra import ( TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST, TFElectraForMaskedLM, TFElectraForMultipleChoice, TFElectraForPreTraining, TFElectraForQuestionAnswering, TFElectraForSequenceClassification, TFElectraForTokenClassification, TFElectraModel, TFElectraPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_electra import ( FlaxElectraForCausalLM, FlaxElectraForMaskedLM, FlaxElectraForMultipleChoice, FlaxElectraForPreTraining, FlaxElectraForQuestionAnswering, FlaxElectraForSequenceClassification, FlaxElectraForTokenClassification, FlaxElectraModel, FlaxElectraPreTrainedModel, ) else: import sys lowerCamelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
302
import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_albert import AlbertTokenizer else: lowerCamelCase__ = None lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = {"""vocab_file""": """spiece.model""", """tokenizer_file""": """tokenizer.json"""} lowerCamelCase__ = { """vocab_file""": { """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/spiece.model""", """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/spiece.model""", """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model""", """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model""", """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/spiece.model""", """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/spiece.model""", """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model""", """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model""", }, """tokenizer_file""": { """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/tokenizer.json""", """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/tokenizer.json""", """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/tokenizer.json""", """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/tokenizer.json""", """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/tokenizer.json""", """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/tokenizer.json""", """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/tokenizer.json""", """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/tokenizer.json""", }, } lowerCamelCase__ = { """albert-base-v1""": 512, """albert-large-v1""": 512, """albert-xlarge-v1""": 512, """albert-xxlarge-v1""": 512, """albert-base-v2""": 512, """albert-large-v2""": 512, """albert-xlarge-v2""": 512, """albert-xxlarge-v2""": 512, } lowerCamelCase__ = """▁""" class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : List[Any] =VOCAB_FILES_NAMES __lowerCamelCase : Union[str, Any] =PRETRAINED_VOCAB_FILES_MAP __lowerCamelCase : List[str] =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCamelCase : Any =AlbertTokenizer def __init__( self : Tuple , __lowercase : Union[str, Any]=None , __lowercase : Optional[int]=None , __lowercase : int=True , __lowercase : Dict=True , __lowercase : str=False , __lowercase : str="[CLS]" , __lowercase : List[Any]="[SEP]" , __lowercase : Any="<unk>" , __lowercase : List[Any]="[SEP]" , __lowercase : List[Any]="<pad>" , __lowercase : Optional[Any]="[CLS]" , __lowercase : List[str]="[MASK]" , **__lowercase : str , ): '''simple docstring''' # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. __a = ( AddedToken(__lowercase , lstrip=__lowercase , rstrip=__lowercase , normalized=__lowercase ) if isinstance(__lowercase , __lowercase ) else mask_token ) super().__init__( __lowercase , tokenizer_file=__lowercase , do_lower_case=__lowercase , remove_space=__lowercase , keep_accents=__lowercase , bos_token=__lowercase , eos_token=__lowercase , unk_token=__lowercase , sep_token=__lowercase , pad_token=__lowercase , cls_token=__lowercase , mask_token=__lowercase , **__lowercase , ) __a = do_lower_case __a = remove_space __a = keep_accents __a = vocab_file __a = False if not self.vocab_file else True def UpperCamelCase_ ( self : Dict , __lowercase : List[int] , __lowercase : Optional[List[int]] = None ): '''simple docstring''' __a = [self.sep_token_id] __a = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def UpperCamelCase_ ( self : str , __lowercase : List[int] , __lowercase : Optional[List[int]] = None ): '''simple docstring''' __a = [self.sep_token_id] __a = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCamelCase_ ( self : Tuple , __lowercase : str , __lowercase : Optional[str] = None ): '''simple docstring''' if not self.can_save_slow_tokenizer: raise ValueError( """Your fast tokenizer does not have the necessary information to save the vocabulary for a slow """ """tokenizer.""" ) if not os.path.isdir(__lowercase ): logger.error(F"Vocabulary path ({save_directory}) should be a directory" ) return __a = os.path.join( __lowercase , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__lowercase ): copyfile(self.vocab_file , __lowercase ) return (out_vocab_file,)
302
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 SCREAMING_SNAKE_CASE ( unittest.TestCase ): def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' __a = """laion/clap-htsat-unfused""" __a = tempfile.mkdtemp() def UpperCamelCase_ ( self : Dict , **__lowercase : List[str] ): '''simple docstring''' return RobertaTokenizer.from_pretrained(self.checkpoint , **__lowercase ) def UpperCamelCase_ ( self : Any , **__lowercase : Tuple ): '''simple docstring''' return ClapFeatureExtractor.from_pretrained(self.checkpoint , **__lowercase ) def UpperCamelCase_ ( self : Any ): '''simple docstring''' shutil.rmtree(self.tmpdirname ) def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' __a = self.get_tokenizer() __a = self.get_feature_extractor() __a = ClapProcessor(tokenizer=__lowercase , feature_extractor=__lowercase ) processor.save_pretrained(self.tmpdirname ) __a = ClapProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , __lowercase ) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor.to_json_string() ) self.assertIsInstance(processor.feature_extractor , __lowercase ) def UpperCamelCase_ ( self : str ): '''simple docstring''' __a = ClapProcessor(tokenizer=self.get_tokenizer() , feature_extractor=self.get_feature_extractor() ) processor.save_pretrained(self.tmpdirname ) __a = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) __a = self.get_feature_extractor(do_normalize=__lowercase , padding_value=1.0 ) __a = ClapProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=__lowercase , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __lowercase ) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.feature_extractor , __lowercase ) def UpperCamelCase_ ( self : Any ): '''simple docstring''' __a = self.get_feature_extractor() __a = self.get_tokenizer() __a = ClapProcessor(tokenizer=__lowercase , feature_extractor=__lowercase ) __a = floats_list((3, 1000) ) __a = feature_extractor(__lowercase , return_tensors="""np""" ) __a = processor(audios=__lowercase , 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 : List[Any] ): '''simple docstring''' __a = self.get_feature_extractor() __a = self.get_tokenizer() __a = ClapProcessor(tokenizer=__lowercase , feature_extractor=__lowercase ) __a = """This is a test string""" __a = processor(text=__lowercase ) __a = tokenizer(__lowercase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def UpperCamelCase_ ( self : Optional[int] ): '''simple docstring''' __a = self.get_feature_extractor() __a = self.get_tokenizer() __a = ClapProcessor(tokenizer=__lowercase , feature_extractor=__lowercase ) __a = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __a = processor.batch_decode(__lowercase ) __a = tokenizer.batch_decode(__lowercase ) self.assertListEqual(__lowercase , __lowercase ) def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' __a = self.get_feature_extractor() __a = self.get_tokenizer() __a = ClapProcessor(tokenizer=__lowercase , feature_extractor=__lowercase ) self.assertListEqual( processor.model_input_names[2:] , feature_extractor.model_input_names , msg="""`processor` and `feature_extractor` model input names do not match""" , )
302
import tempfile import torch from diffusers import IPNDMScheduler from .test_schedulers import SchedulerCommonTest class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : Optional[int] =(IPNDMScheduler,) __lowerCamelCase : int =(('num_inference_steps', 50),) def UpperCamelCase_ ( self : str , **__lowercase : Dict ): '''simple docstring''' __a = {"""num_train_timesteps""": 1000} config.update(**__lowercase ) return config def UpperCamelCase_ ( self : Any , __lowercase : Tuple=0 , **__lowercase : Dict ): '''simple docstring''' __a = dict(self.forward_default_kwargs ) __a = kwargs.pop("""num_inference_steps""" , __lowercase ) __a = self.dummy_sample __a = 0.1 * sample __a = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: __a = self.get_scheduler_config(**__lowercase ) __a = scheduler_class(**__lowercase ) scheduler.set_timesteps(__lowercase ) # copy over dummy past residuals __a = dummy_past_residuals[:] if time_step is None: __a = scheduler.timesteps[len(scheduler.timesteps ) // 2] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(__lowercase ) __a = scheduler_class.from_pretrained(__lowercase ) new_scheduler.set_timesteps(__lowercase ) # copy over dummy past residuals __a = dummy_past_residuals[:] __a = scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample __a = new_scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" __a = scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample __a = new_scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def UpperCamelCase_ ( self : str ): '''simple docstring''' pass def UpperCamelCase_ ( self : str , __lowercase : int=0 , **__lowercase : Dict ): '''simple docstring''' __a = dict(self.forward_default_kwargs ) __a = kwargs.pop("""num_inference_steps""" , __lowercase ) __a = self.dummy_sample __a = 0.1 * sample __a = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: __a = self.get_scheduler_config() __a = scheduler_class(**__lowercase ) scheduler.set_timesteps(__lowercase ) # copy over dummy past residuals (must be after setting timesteps) __a = dummy_past_residuals[:] if time_step is None: __a = scheduler.timesteps[len(scheduler.timesteps ) // 2] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(__lowercase ) __a = scheduler_class.from_pretrained(__lowercase ) # copy over dummy past residuals new_scheduler.set_timesteps(__lowercase ) # copy over dummy past residual (must be after setting timesteps) __a = dummy_past_residuals[:] __a = scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample __a = new_scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" __a = scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample __a = new_scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def UpperCamelCase_ ( self : List[str] , **__lowercase : Dict ): '''simple docstring''' __a = self.scheduler_classes[0] __a = self.get_scheduler_config(**__lowercase ) __a = scheduler_class(**__lowercase ) __a = 10 __a = self.dummy_model() __a = self.dummy_sample_deter scheduler.set_timesteps(__lowercase ) for i, t in enumerate(scheduler.timesteps ): __a = model(__lowercase , __lowercase ) __a = scheduler.step(__lowercase , __lowercase , __lowercase ).prev_sample for i, t in enumerate(scheduler.timesteps ): __a = model(__lowercase , __lowercase ) __a = scheduler.step(__lowercase , __lowercase , __lowercase ).prev_sample return sample def UpperCamelCase_ ( self : str ): '''simple docstring''' __a = dict(self.forward_default_kwargs ) __a = kwargs.pop("""num_inference_steps""" , __lowercase ) for scheduler_class in self.scheduler_classes: __a = self.get_scheduler_config() __a = scheduler_class(**__lowercase ) __a = self.dummy_sample __a = 0.1 * sample if num_inference_steps is not None and hasattr(__lowercase , """set_timesteps""" ): scheduler.set_timesteps(__lowercase ) elif num_inference_steps is not None and not hasattr(__lowercase , """set_timesteps""" ): __a = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) __a = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] __a = dummy_past_residuals[:] __a = scheduler.timesteps[5] __a = scheduler.timesteps[6] __a = scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample __a = scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) __a = scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample __a = scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' for timesteps in [100, 1000]: self.check_over_configs(num_train_timesteps=__lowercase , time_step=__lowercase ) def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' for t, num_inference_steps in zip([1, 5, 10] , [10, 50, 100] ): self.check_over_forward(num_inference_steps=__lowercase , time_step=__lowercase ) def UpperCamelCase_ ( self : int ): '''simple docstring''' __a = self.full_loop() __a = torch.mean(torch.abs(__lowercase ) ) assert abs(result_mean.item() - 2540529 ) < 10
302
1
import inspect import unittest from transformers import MobileViTVaConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, MobileViTVaModel from transformers.models.mobilevitva.modeling_mobilevitva import ( MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST, make_divisible, ) if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): def UpperCamelCase_ ( self : str ): '''simple docstring''' __a = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(__lowercase , """width_multiplier""" ) ) class SCREAMING_SNAKE_CASE : def __init__( self : Dict , __lowercase : Union[str, Any] , __lowercase : Dict=13 , __lowercase : int=64 , __lowercase : Tuple=2 , __lowercase : Tuple=3 , __lowercase : Tuple="swish" , __lowercase : List[Any]=3 , __lowercase : List[str]=32 , __lowercase : int=0.1 , __lowercase : Union[str, Any]=0.02 , __lowercase : Optional[int]=True , __lowercase : Dict=True , __lowercase : Tuple=10 , __lowercase : str=None , __lowercase : Optional[Any]=0.25 , __lowercase : str=0.0 , __lowercase : Optional[Any]=0.0 , ): '''simple docstring''' __a = parent __a = batch_size __a = image_size __a = patch_size __a = num_channels __a = make_divisible(512 * width_multiplier , divisor=8 ) __a = hidden_act __a = conv_kernel_size __a = output_stride __a = classifier_dropout_prob __a = use_labels __a = is_training __a = num_labels __a = initializer_range __a = scope __a = width_multiplier __a = ffn_dropout __a = attn_dropout def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' __a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a = None __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.num_labels ) __a = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) __a = self.get_config() return config, pixel_values, labels, pixel_labels def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' return MobileViTVaConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_act=self.hidden_act , conv_kernel_size=self.conv_kernel_size , output_stride=self.output_stride , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , width_multiplier=self.width_multiplier , ffn_dropout=self.ffn_dropout_prob , attn_dropout=self.attn_dropout_prob , ) def UpperCamelCase_ ( self : Tuple , __lowercase : Optional[Any] , __lowercase : int , __lowercase : Optional[Any] , __lowercase : Tuple ): '''simple docstring''' __a = MobileViTVaModel(config=__lowercase ) model.to(__lowercase ) model.eval() __a = model(__lowercase ) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def UpperCamelCase_ ( self : Union[str, Any] , __lowercase : List[Any] , __lowercase : str , __lowercase : Optional[int] , __lowercase : Union[str, Any] ): '''simple docstring''' __a = self.num_labels __a = MobileViTVaForImageClassification(__lowercase ) model.to(__lowercase ) model.eval() __a = model(__lowercase , labels=__lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCamelCase_ ( self : int , __lowercase : str , __lowercase : Any , __lowercase : int , __lowercase : List[str] ): '''simple docstring''' __a = self.num_labels __a = MobileViTVaForSemanticSegmentation(__lowercase ) model.to(__lowercase ) model.eval() __a = model(__lowercase ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) __a = model(__lowercase , labels=__lowercase ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def UpperCamelCase_ ( self : Dict ): '''simple docstring''' __a = self.prepare_config_and_inputs() __a , __a , __a , __a = config_and_inputs __a = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE ( lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase ): __lowerCamelCase : List[Any] =( (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation) if is_torch_available() else () ) __lowerCamelCase : Any =( { 'feature-extraction': MobileViTVaModel, 'image-classification': MobileViTVaForImageClassification, 'image-segmentation': MobileViTVaForSemanticSegmentation, } if is_torch_available() else {} ) __lowerCamelCase : Dict =False __lowerCamelCase : Optional[Any] =False __lowerCamelCase : int =False __lowerCamelCase : Any =False def UpperCamelCase_ ( self : Dict ): '''simple docstring''' __a = MobileViTVaModelTester(self ) __a = MobileViTVaConfigTester(self , config_class=__lowercase , has_text_modality=__lowercase ) def UpperCamelCase_ ( self : Dict ): '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason="""MobileViTV2 does not use inputs_embeds""" ) def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' pass @unittest.skip(reason="""MobileViTV2 does not support input and output embeddings""" ) def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' pass @unittest.skip(reason="""MobileViTV2 does not output attentions""" ) def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' pass @require_torch_multi_gpu @unittest.skip(reason="""Got `CUDA error: misaligned address` for tests after this one being run.""" ) def UpperCamelCase_ ( self : int ): '''simple docstring''' pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' pass def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(__lowercase ) __a = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a = [*signature.parameters.keys()] __a = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , __lowercase ) def UpperCamelCase_ ( self : Dict ): '''simple docstring''' __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowercase ) def UpperCamelCase_ ( self : int ): '''simple docstring''' def check_hidden_states_output(__lowercase : List[str] , __lowercase : Optional[int] , __lowercase : List[str] ): __a = model_class(__lowercase ) model.to(__lowercase ) model.eval() with torch.no_grad(): __a = model(**self._prepare_for_class(__lowercase , __lowercase ) ) __a = outputs.hidden_states __a = 5 self.assertEqual(len(__lowercase ) , __lowercase ) # MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width) # with the width and height being successively divided by 2. __a = 2 for i in range(len(__lowercase ) ): self.assertListEqual( list(hidden_states[i].shape[-2:] ) , [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor] , ) divisor *= 2 self.assertEqual(self.model_tester.output_stride , divisor // 2 ) __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = True check_hidden_states_output(__lowercase , __lowercase , __lowercase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __a = True check_hidden_states_output(__lowercase , __lowercase , __lowercase ) def UpperCamelCase_ ( self : Optional[int] ): '''simple docstring''' __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__lowercase ) def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*__lowercase ) @slow def UpperCamelCase_ ( self : Optional[int] ): '''simple docstring''' for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = MobileViTVaModel.from_pretrained(__lowercase ) self.assertIsNotNone(__lowercase ) def lowerCAmelCase__ ( ): """simple docstring""" __a = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class SCREAMING_SNAKE_CASE ( unittest.TestCase ): @cached_property def UpperCamelCase_ ( self : Dict ): '''simple docstring''' return ( MobileViTImageProcessor.from_pretrained("""apple/mobilevitv2-1.0-imagenet1k-256""" ) if is_vision_available() else None ) @slow def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' __a = MobileViTVaForImageClassification.from_pretrained("""apple/mobilevitv2-1.0-imagenet1k-256""" ).to( __lowercase ) __a = self.default_image_processor __a = prepare_img() __a = image_processor(images=__lowercase , return_tensors="""pt""" ).to(__lowercase ) # forward pass with torch.no_grad(): __a = model(**__lowercase ) # verify the logits __a = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , __lowercase ) __a = torch.tensor([-1.6336E00, -7.3204E-02, -5.1883E-01] ).to(__lowercase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __lowercase , atol=1E-4 ) ) @slow def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' __a = MobileViTVaForSemanticSegmentation.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3""" ) __a = model.to(__lowercase ) __a = MobileViTImageProcessor.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3""" ) __a = prepare_img() __a = image_processor(images=__lowercase , return_tensors="""pt""" ).to(__lowercase ) # forward pass with torch.no_grad(): __a = model(**__lowercase ) __a = outputs.logits # verify the logits __a = torch.Size((1, 21, 32, 32) ) self.assertEqual(logits.shape , __lowercase ) __a = torch.tensor( [ [[7.0863, 7.1525, 6.8201], [6.6931, 6.8770, 6.8933], [6.2978, 7.0366, 6.9636]], [[-3.7134, -3.6712, -3.6675], [-3.5825, -3.3549, -3.4777], [-3.3435, -3.3979, -3.2857]], [[-2.9329, -2.8003, -2.7369], [-3.0564, -2.4780, -2.0207], [-2.6889, -1.9298, -1.7640]], ] , device=__lowercase , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , __lowercase , atol=1E-4 ) ) @slow def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' __a = MobileViTVaForSemanticSegmentation.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3""" ) __a = model.to(__lowercase ) __a = MobileViTImageProcessor.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3""" ) __a = prepare_img() __a = image_processor(images=__lowercase , return_tensors="""pt""" ).to(__lowercase ) # forward pass with torch.no_grad(): __a = model(**__lowercase ) __a = outputs.logits.detach().cpu() __a = image_processor.post_process_semantic_segmentation(outputs=__lowercase , target_sizes=[(50, 60)] ) __a = torch.Size((50, 60) ) self.assertEqual(segmentation[0].shape , __lowercase ) __a = image_processor.post_process_semantic_segmentation(outputs=__lowercase ) __a = torch.Size((32, 32) ) self.assertEqual(segmentation[0].shape , __lowercase )
302
from __future__ import annotations lowerCamelCase__ = { """A""": ["""B""", """C""", """E"""], """B""": ["""A""", """D""", """E"""], """C""": ["""A""", """F""", """G"""], """D""": ["""B"""], """E""": ["""A""", """B""", """D"""], """F""": ["""C"""], """G""": ["""C"""], } class SCREAMING_SNAKE_CASE : def __init__( self : Tuple , __lowercase : dict[str, list[str]] , __lowercase : str ): '''simple docstring''' __a = graph # mapping node to its parent in resulting breadth first tree __a = {} __a = source_vertex def UpperCamelCase_ ( self : Any ): '''simple docstring''' __a = {self.source_vertex} __a = None __a = [self.source_vertex] # first in first out queue while queue: __a = queue.pop(0 ) for adjacent_vertex in self.graph[vertex]: if adjacent_vertex not in visited: visited.add(__lowercase ) __a = vertex queue.append(__lowercase ) def UpperCamelCase_ ( self : Optional[int] , __lowercase : str ): '''simple docstring''' if target_vertex == self.source_vertex: return self.source_vertex __a = self.parent.get(__lowercase ) if target_vertex_parent is None: __a = ( F"No path from vertex: {self.source_vertex} to vertex: {target_vertex}" ) raise ValueError(__lowercase ) return self.shortest_path(__lowercase ) + F"->{target_vertex}" if __name__ == "__main__": lowerCamelCase__ = Graph(graph, """G""") g.breath_first_search() print(g.shortest_path("""D""")) print(g.shortest_path("""G""")) print(g.shortest_path("""Foo"""))
302
1
from typing import List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { """huggingface/autoformer-tourism-monthly""": """https://huggingface.co/huggingface/autoformer-tourism-monthly/resolve/main/config.json""", } class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : List[Any] ='autoformer' __lowerCamelCase : str ={ 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', 'num_hidden_layers': 'encoder_layers', } def __init__( self : List[Any] , __lowercase : Optional[int] = None , __lowercase : Optional[int] = None , __lowercase : str = "student_t" , __lowercase : str = "nll" , __lowercase : int = 1 , __lowercase : List[int] = [1, 2, 3, 4, 5, 6, 7] , __lowercase : bool = True , __lowercase : int = 0 , __lowercase : int = 0 , __lowercase : int = 0 , __lowercase : int = 0 , __lowercase : Optional[List[int]] = None , __lowercase : Optional[List[int]] = None , __lowercase : int = 64 , __lowercase : int = 2 , __lowercase : int = 2 , __lowercase : int = 2 , __lowercase : int = 2 , __lowercase : int = 32 , __lowercase : int = 32 , __lowercase : str = "gelu" , __lowercase : float = 0.1 , __lowercase : float = 0.1 , __lowercase : float = 0.1 , __lowercase : float = 0.1 , __lowercase : float = 0.1 , __lowercase : int = 100 , __lowercase : float = 0.02 , __lowercase : bool = True , __lowercase : List[Any]=True , __lowercase : int = 10 , __lowercase : int = 25 , __lowercase : int = 3 , **__lowercase : Optional[int] , ): '''simple docstring''' # time series specific configuration __a = prediction_length __a = context_length if context_length is not None else prediction_length __a = distribution_output __a = loss __a = input_size __a = num_time_features __a = lags_sequence __a = scaling __a = num_dynamic_real_features __a = num_static_real_features __a = num_static_categorical_features if cardinality is not None and num_static_categorical_features > 0: if len(__lowercase ) != num_static_categorical_features: raise ValueError( """The cardinality should be a list of the same length as `num_static_categorical_features`""" ) __a = cardinality else: __a = [0] if embedding_dimension is not None and num_static_categorical_features > 0: if len(__lowercase ) != num_static_categorical_features: raise ValueError( """The embedding dimension should be a list of the same length as `num_static_categorical_features`""" ) __a = embedding_dimension else: __a = [min(50 , (cat + 1) // 2 ) for cat in self.cardinality] __a = num_parallel_samples # Transformer architecture configuration __a = input_size * len(self.lags_sequence ) + self._number_of_features __a = d_model __a = encoder_attention_heads __a = decoder_attention_heads __a = encoder_ffn_dim __a = decoder_ffn_dim __a = encoder_layers __a = decoder_layers __a = dropout __a = attention_dropout __a = activation_dropout __a = encoder_layerdrop __a = decoder_layerdrop __a = activation_function __a = init_std __a = use_cache # Autoformer __a = label_length __a = moving_average __a = autocorrelation_factor super().__init__(is_encoder_decoder=__lowercase , **__lowercase ) @property def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' return ( sum(self.embedding_dimension ) + self.num_dynamic_real_features + self.num_time_features + self.num_static_real_features + self.input_size * 2 # the log1p(abs(loc)) and log(scale) features )
302
import unittest import numpy as np import torch from torch import nn from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import KandinskyVaaPriorPipeline, PriorTransformer, UnCLIPScheduler from diffusers.utils import torch_device from diffusers.utils.testing_utils import enable_full_determinism, skip_mps from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class SCREAMING_SNAKE_CASE ( lowerCamelCase__ , unittest.TestCase ): __lowerCamelCase : Tuple =KandinskyVaaPriorPipeline __lowerCamelCase : Union[str, Any] =['prompt'] __lowerCamelCase : Any =['prompt', 'negative_prompt'] __lowerCamelCase : List[str] =[ 'num_images_per_prompt', 'generator', 'num_inference_steps', 'latents', 'negative_prompt', 'guidance_scale', 'output_type', 'return_dict', ] __lowerCamelCase : List[Any] =False @property def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' return 32 @property def UpperCamelCase_ ( self : Any ): '''simple docstring''' return 32 @property def UpperCamelCase_ ( self : str ): '''simple docstring''' return self.time_input_dim @property def UpperCamelCase_ ( self : str ): '''simple docstring''' return self.time_input_dim * 4 @property def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' return 100 @property def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' __a = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) return tokenizer @property def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' torch.manual_seed(0 ) __a = 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-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(__lowercase ) @property def UpperCamelCase_ ( self : int ): '''simple docstring''' torch.manual_seed(0 ) __a = { """num_attention_heads""": 2, """attention_head_dim""": 12, """embedding_dim""": self.text_embedder_hidden_size, """num_layers""": 1, } __a = PriorTransformer(**__lowercase ) # clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0 __a = nn.Parameter(torch.ones(model.clip_std.shape ) ) return model @property def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' torch.manual_seed(0 ) __a = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=224 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=14 , ) __a = CLIPVisionModelWithProjection(__lowercase ) return model @property def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' __a = CLIPImageProcessor( crop_size=224 , do_center_crop=__lowercase , do_normalize=__lowercase , do_resize=__lowercase , image_mean=[0.48145466, 0.4578275, 0.40821073] , image_std=[0.26862954, 0.26130258, 0.27577711] , resample=3 , size=224 , ) return image_processor def UpperCamelCase_ ( self : str ): '''simple docstring''' __a = self.dummy_prior __a = self.dummy_image_encoder __a = self.dummy_text_encoder __a = self.dummy_tokenizer __a = self.dummy_image_processor __a = UnCLIPScheduler( variance_type="""fixed_small_log""" , prediction_type="""sample""" , num_train_timesteps=1000 , clip_sample=__lowercase , clip_sample_range=10.0 , ) __a = { """prior""": prior, """image_encoder""": image_encoder, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """scheduler""": scheduler, """image_processor""": image_processor, } return components def UpperCamelCase_ ( self : Optional[int] , __lowercase : List[str] , __lowercase : Any=0 ): '''simple docstring''' if str(__lowercase ).startswith("""mps""" ): __a = torch.manual_seed(__lowercase ) else: __a = torch.Generator(device=__lowercase ).manual_seed(__lowercase ) __a = { """prompt""": """horse""", """generator""": generator, """guidance_scale""": 4.0, """num_inference_steps""": 2, """output_type""": """np""", } return inputs def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' __a = """cpu""" __a = self.get_dummy_components() __a = self.pipeline_class(**__lowercase ) __a = pipe.to(__lowercase ) pipe.set_progress_bar_config(disable=__lowercase ) __a = pipe(**self.get_dummy_inputs(__lowercase ) ) __a = output.image_embeds __a = pipe( **self.get_dummy_inputs(__lowercase ) , return_dict=__lowercase , )[0] __a = image[0, -10:] __a = image_from_tuple[0, -10:] assert image.shape == (1, 32) __a = np.array( [-0.0532, 1.7120, 0.3656, -1.0852, -0.8946, -1.1756, 0.4348, 0.2482, 0.5146, -0.1156] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 @skip_mps def UpperCamelCase_ ( self : Dict ): '''simple docstring''' __a = torch_device == """cpu""" __a = True __a = False self._test_inference_batch_single_identical( test_max_difference=__lowercase , relax_max_difference=__lowercase , test_mean_pixel_difference=__lowercase , ) @skip_mps def UpperCamelCase_ ( self : Any ): '''simple docstring''' __a = torch_device == """cpu""" __a = False self._test_attention_slicing_forward_pass( test_max_difference=__lowercase , test_mean_pixel_difference=__lowercase , )
302
1
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { """MIT/ast-finetuned-audioset-10-10-0.4593""": ( """https://huggingface.co/MIT/ast-finetuned-audioset-10-10-0.4593/resolve/main/config.json""" ), } class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : List[Any] ='audio-spectrogram-transformer' def __init__( self : int , __lowercase : List[Any]=768 , __lowercase : Dict=12 , __lowercase : List[str]=12 , __lowercase : Dict=3072 , __lowercase : Optional[int]="gelu" , __lowercase : Optional[int]=0.0 , __lowercase : List[str]=0.0 , __lowercase : List[Any]=0.02 , __lowercase : List[Any]=1E-12 , __lowercase : Dict=16 , __lowercase : Dict=True , __lowercase : int=10 , __lowercase : str=10 , __lowercase : List[Any]=1024 , __lowercase : List[str]=128 , **__lowercase : Union[str, Any] , ): '''simple docstring''' super().__init__(**__lowercase ) __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = initializer_range __a = layer_norm_eps __a = patch_size __a = qkv_bias __a = frequency_stride __a = time_stride __a = max_length __a = num_mel_bins
302
from typing import Any, Dict, List, Union from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from ..image_utils import load_image if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_OBJECT_DETECTION_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = Dict[str, Any] lowerCamelCase__ = List[Prediction] @add_end_docstrings(lowerCamelCase__ ) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): def __init__( self : Tuple , *__lowercase : Tuple , **__lowercase : Optional[int] ): '''simple docstring''' super().__init__(*__lowercase , **__lowercase ) if self.framework == "tf": raise ValueError(F"The {self.__class__} is only available in PyTorch." ) requires_backends(self , """vision""" ) self.check_model_type( dict(MODEL_FOR_OBJECT_DETECTION_MAPPING.items() + MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING.items() ) ) def UpperCamelCase_ ( self : Optional[int] , **__lowercase : List[str] ): '''simple docstring''' __a = {} if "threshold" in kwargs: __a = kwargs["""threshold"""] return {}, {}, postprocess_kwargs def __call__( self : List[Any] , *__lowercase : Any , **__lowercase : Tuple ): '''simple docstring''' return super().__call__(*__lowercase , **__lowercase ) def UpperCamelCase_ ( self : str , __lowercase : Tuple ): '''simple docstring''' __a = load_image(__lowercase ) __a = torch.IntTensor([[image.height, image.width]] ) __a = self.image_processor(images=[image] , return_tensors="""pt""" ) if self.tokenizer is not None: __a = self.tokenizer(text=inputs["""words"""] , boxes=inputs["""boxes"""] , return_tensors="""pt""" ) __a = target_size return inputs def UpperCamelCase_ ( self : Dict , __lowercase : List[str] ): '''simple docstring''' __a = model_inputs.pop("""target_size""" ) __a = self.model(**__lowercase ) __a = outputs.__class__({"""target_size""": target_size, **outputs} ) if self.tokenizer is not None: __a = model_inputs["""bbox"""] return model_outputs def UpperCamelCase_ ( self : Optional[int] , __lowercase : List[Any] , __lowercase : List[Any]=0.9 ): '''simple docstring''' __a = model_outputs["""target_size"""] if self.tokenizer is not None: # This is a LayoutLMForTokenClassification variant. # The OCR got the boxes and the model classified the words. __a , __a = target_size[0].tolist() def unnormalize(__lowercase : Optional[Any] ): return self._get_bounding_box( torch.Tensor( [ (width * bbox[0] / 1000), (height * bbox[1] / 1000), (width * bbox[2] / 1000), (height * bbox[3] / 1000), ] ) ) __a , __a = model_outputs["""logits"""].squeeze(0 ).softmax(dim=-1 ).max(dim=-1 ) __a = [self.model.config.idalabel[prediction] for prediction in classes.tolist()] __a = [unnormalize(__lowercase ) for bbox in model_outputs["""bbox"""].squeeze(0 )] __a = ["""score""", """label""", """box"""] __a = [dict(zip(__lowercase , __lowercase ) ) for vals in zip(scores.tolist() , __lowercase , __lowercase ) if vals[0] > threshold] else: # This is a regular ForObjectDetectionModel __a = self.image_processor.post_process_object_detection(__lowercase , __lowercase , __lowercase ) __a = raw_annotations[0] __a = raw_annotation["""scores"""] __a = raw_annotation["""labels"""] __a = raw_annotation["""boxes"""] __a = scores.tolist() __a = [self.model.config.idalabel[label.item()] for label in labels] __a = [self._get_bounding_box(__lowercase ) for box in boxes] # {"scores": [...], ...} --> [{"score":x, ...}, ...] __a = ["""score""", """label""", """box"""] __a = [ dict(zip(__lowercase , __lowercase ) ) for vals in zip(raw_annotation["""scores"""] , raw_annotation["""labels"""] , raw_annotation["""boxes"""] ) ] return annotation def UpperCamelCase_ ( self : Optional[int] , __lowercase : "torch.Tensor" ): '''simple docstring''' if self.framework != "pt": raise ValueError("""The ObjectDetectionPipeline is only available in PyTorch.""" ) __a , __a , __a , __a = box.int().tolist() __a = { """xmin""": xmin, """ymin""": ymin, """xmax""": xmax, """ymax""": ymax, } return bbox
302
1
from __future__ import annotations import unittest from transformers import is_tf_available, is_torch_available from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, is_pt_tf_cross_test, slow if is_tf_available(): from transformers import ( AutoConfig, BertConfig, GPTaConfig, TaConfig, TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSeqaSeqLM, TFAutoModelForSequenceClassification, TFAutoModelWithLMHead, TFBertForMaskedLM, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertModel, TFGPTaLMHeadModel, TFRobertaForMaskedLM, TFTaForConditionalGeneration, ) from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST if is_torch_available(): from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForPreTraining, AutoModelForQuestionAnswering, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoModelWithLMHead, BertForMaskedLM, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, BertModel, GPTaLMHeadModel, RobertaForMaskedLM, TaForConditionalGeneration, ) @is_pt_tf_cross_test class SCREAMING_SNAKE_CASE ( unittest.TestCase ): @slow def UpperCamelCase_ ( self : Any ): '''simple docstring''' # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __a = AutoConfig.from_pretrained(__lowercase ) self.assertIsNotNone(__lowercase ) self.assertIsInstance(__lowercase , __lowercase ) __a = TFAutoModel.from_pretrained(__lowercase , from_pt=__lowercase ) self.assertIsNotNone(__lowercase ) self.assertIsInstance(__lowercase , __lowercase ) __a = AutoModel.from_pretrained(__lowercase , from_tf=__lowercase ) self.assertIsNotNone(__lowercase ) self.assertIsInstance(__lowercase , __lowercase ) @slow def UpperCamelCase_ ( self : Any ): '''simple docstring''' # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __a = AutoConfig.from_pretrained(__lowercase ) self.assertIsNotNone(__lowercase ) self.assertIsInstance(__lowercase , __lowercase ) __a = TFAutoModelForPreTraining.from_pretrained(__lowercase , from_pt=__lowercase ) self.assertIsNotNone(__lowercase ) self.assertIsInstance(__lowercase , __lowercase ) __a = AutoModelForPreTraining.from_pretrained(__lowercase , from_tf=__lowercase ) self.assertIsNotNone(__lowercase ) self.assertIsInstance(__lowercase , __lowercase ) @slow def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = AutoConfig.from_pretrained(__lowercase ) self.assertIsNotNone(__lowercase ) self.assertIsInstance(__lowercase , __lowercase ) __a = TFAutoModelForCausalLM.from_pretrained(__lowercase , from_pt=__lowercase ) __a , __a = TFAutoModelForCausalLM.from_pretrained( __lowercase , output_loading_info=__lowercase , from_pt=__lowercase ) self.assertIsNotNone(__lowercase ) self.assertIsInstance(__lowercase , __lowercase ) __a = AutoModelForCausalLM.from_pretrained(__lowercase , from_tf=__lowercase ) __a , __a = AutoModelForCausalLM.from_pretrained( __lowercase , output_loading_info=__lowercase , from_tf=__lowercase ) self.assertIsNotNone(__lowercase ) self.assertIsInstance(__lowercase , __lowercase ) @slow def UpperCamelCase_ ( self : str ): '''simple docstring''' for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = AutoConfig.from_pretrained(__lowercase ) self.assertIsNotNone(__lowercase ) self.assertIsInstance(__lowercase , __lowercase ) __a = TFAutoModelWithLMHead.from_pretrained(__lowercase , from_pt=__lowercase ) self.assertIsNotNone(__lowercase ) self.assertIsInstance(__lowercase , __lowercase ) __a = AutoModelWithLMHead.from_pretrained(__lowercase , from_tf=__lowercase ) self.assertIsNotNone(__lowercase ) self.assertIsInstance(__lowercase , __lowercase ) @slow def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = AutoConfig.from_pretrained(__lowercase ) self.assertIsNotNone(__lowercase ) self.assertIsInstance(__lowercase , __lowercase ) __a = TFAutoModelForMaskedLM.from_pretrained(__lowercase , from_pt=__lowercase ) __a , __a = TFAutoModelForMaskedLM.from_pretrained( __lowercase , output_loading_info=__lowercase , from_pt=__lowercase ) self.assertIsNotNone(__lowercase ) self.assertIsInstance(__lowercase , __lowercase ) __a = AutoModelForMaskedLM.from_pretrained(__lowercase , from_tf=__lowercase ) __a , __a = AutoModelForMaskedLM.from_pretrained( __lowercase , output_loading_info=__lowercase , from_tf=__lowercase ) self.assertIsNotNone(__lowercase ) self.assertIsInstance(__lowercase , __lowercase ) @slow def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = AutoConfig.from_pretrained(__lowercase ) self.assertIsNotNone(__lowercase ) self.assertIsInstance(__lowercase , __lowercase ) __a = TFAutoModelForSeqaSeqLM.from_pretrained(__lowercase , from_pt=__lowercase ) __a , __a = TFAutoModelForSeqaSeqLM.from_pretrained( __lowercase , output_loading_info=__lowercase , from_pt=__lowercase ) self.assertIsNotNone(__lowercase ) self.assertIsInstance(__lowercase , __lowercase ) __a = AutoModelForSeqaSeqLM.from_pretrained(__lowercase , from_tf=__lowercase ) __a , __a = AutoModelForSeqaSeqLM.from_pretrained( __lowercase , output_loading_info=__lowercase , from_tf=__lowercase ) self.assertIsNotNone(__lowercase ) self.assertIsInstance(__lowercase , __lowercase ) @slow def UpperCamelCase_ ( self : Optional[int] ): '''simple docstring''' # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __a = AutoConfig.from_pretrained(__lowercase ) self.assertIsNotNone(__lowercase ) self.assertIsInstance(__lowercase , __lowercase ) __a = TFAutoModelForSequenceClassification.from_pretrained(__lowercase , from_pt=__lowercase ) self.assertIsNotNone(__lowercase ) self.assertIsInstance(__lowercase , __lowercase ) __a = AutoModelForSequenceClassification.from_pretrained(__lowercase , from_tf=__lowercase ) self.assertIsNotNone(__lowercase ) self.assertIsInstance(__lowercase , __lowercase ) @slow def UpperCamelCase_ ( self : int ): '''simple docstring''' # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __a = AutoConfig.from_pretrained(__lowercase ) self.assertIsNotNone(__lowercase ) self.assertIsInstance(__lowercase , __lowercase ) __a = TFAutoModelForQuestionAnswering.from_pretrained(__lowercase , from_pt=__lowercase ) self.assertIsNotNone(__lowercase ) self.assertIsInstance(__lowercase , __lowercase ) __a = AutoModelForQuestionAnswering.from_pretrained(__lowercase , from_tf=__lowercase ) self.assertIsNotNone(__lowercase ) self.assertIsInstance(__lowercase , __lowercase ) def UpperCamelCase_ ( self : Dict ): '''simple docstring''' __a = TFAutoModelWithLMHead.from_pretrained(__lowercase , from_pt=__lowercase ) self.assertIsInstance(__lowercase , __lowercase ) self.assertEqual(model.num_parameters() , 14410 ) self.assertEqual(model.num_parameters(only_trainable=__lowercase ) , 14410 ) __a = AutoModelWithLMHead.from_pretrained(__lowercase , from_tf=__lowercase ) self.assertIsInstance(__lowercase , __lowercase ) self.assertEqual(model.num_parameters() , 14410 ) self.assertEqual(model.num_parameters(only_trainable=__lowercase ) , 14410 ) def UpperCamelCase_ ( self : int ): '''simple docstring''' __a = TFAutoModelWithLMHead.from_pretrained(__lowercase , from_pt=__lowercase ) self.assertIsInstance(__lowercase , __lowercase ) self.assertEqual(model.num_parameters() , 14410 ) self.assertEqual(model.num_parameters(only_trainable=__lowercase ) , 14410 ) __a = AutoModelWithLMHead.from_pretrained(__lowercase , from_tf=__lowercase ) self.assertIsInstance(__lowercase , __lowercase ) self.assertEqual(model.num_parameters() , 14410 ) self.assertEqual(model.num_parameters(only_trainable=__lowercase ) , 14410 )
302
# 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 # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowerCamelCase__ = { """configuration_efficientnet""": [ """EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP""", """EfficientNetConfig""", """EfficientNetOnnxConfig""", ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = ["""EfficientNetImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ """EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST""", """EfficientNetForImageClassification""", """EfficientNetModel""", """EfficientNetPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_efficientnet import ( EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP, EfficientNetConfig, EfficientNetOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_efficientnet import EfficientNetImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_efficientnet import ( EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST, EfficientNetForImageClassification, EfficientNetModel, EfficientNetPreTrainedModel, ) else: import sys lowerCamelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure)
302
1
import tempfile import torch from diffusers import IPNDMScheduler from .test_schedulers import SchedulerCommonTest class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : Optional[int] =(IPNDMScheduler,) __lowerCamelCase : int =(('num_inference_steps', 50),) def UpperCamelCase_ ( self : str , **__lowercase : Dict ): '''simple docstring''' __a = {"""num_train_timesteps""": 1000} config.update(**__lowercase ) return config def UpperCamelCase_ ( self : Any , __lowercase : Tuple=0 , **__lowercase : Dict ): '''simple docstring''' __a = dict(self.forward_default_kwargs ) __a = kwargs.pop("""num_inference_steps""" , __lowercase ) __a = self.dummy_sample __a = 0.1 * sample __a = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: __a = self.get_scheduler_config(**__lowercase ) __a = scheduler_class(**__lowercase ) scheduler.set_timesteps(__lowercase ) # copy over dummy past residuals __a = dummy_past_residuals[:] if time_step is None: __a = scheduler.timesteps[len(scheduler.timesteps ) // 2] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(__lowercase ) __a = scheduler_class.from_pretrained(__lowercase ) new_scheduler.set_timesteps(__lowercase ) # copy over dummy past residuals __a = dummy_past_residuals[:] __a = scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample __a = new_scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" __a = scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample __a = new_scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def UpperCamelCase_ ( self : str ): '''simple docstring''' pass def UpperCamelCase_ ( self : str , __lowercase : int=0 , **__lowercase : Dict ): '''simple docstring''' __a = dict(self.forward_default_kwargs ) __a = kwargs.pop("""num_inference_steps""" , __lowercase ) __a = self.dummy_sample __a = 0.1 * sample __a = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: __a = self.get_scheduler_config() __a = scheduler_class(**__lowercase ) scheduler.set_timesteps(__lowercase ) # copy over dummy past residuals (must be after setting timesteps) __a = dummy_past_residuals[:] if time_step is None: __a = scheduler.timesteps[len(scheduler.timesteps ) // 2] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(__lowercase ) __a = scheduler_class.from_pretrained(__lowercase ) # copy over dummy past residuals new_scheduler.set_timesteps(__lowercase ) # copy over dummy past residual (must be after setting timesteps) __a = dummy_past_residuals[:] __a = scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample __a = new_scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" __a = scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample __a = new_scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def UpperCamelCase_ ( self : List[str] , **__lowercase : Dict ): '''simple docstring''' __a = self.scheduler_classes[0] __a = self.get_scheduler_config(**__lowercase ) __a = scheduler_class(**__lowercase ) __a = 10 __a = self.dummy_model() __a = self.dummy_sample_deter scheduler.set_timesteps(__lowercase ) for i, t in enumerate(scheduler.timesteps ): __a = model(__lowercase , __lowercase ) __a = scheduler.step(__lowercase , __lowercase , __lowercase ).prev_sample for i, t in enumerate(scheduler.timesteps ): __a = model(__lowercase , __lowercase ) __a = scheduler.step(__lowercase , __lowercase , __lowercase ).prev_sample return sample def UpperCamelCase_ ( self : str ): '''simple docstring''' __a = dict(self.forward_default_kwargs ) __a = kwargs.pop("""num_inference_steps""" , __lowercase ) for scheduler_class in self.scheduler_classes: __a = self.get_scheduler_config() __a = scheduler_class(**__lowercase ) __a = self.dummy_sample __a = 0.1 * sample if num_inference_steps is not None and hasattr(__lowercase , """set_timesteps""" ): scheduler.set_timesteps(__lowercase ) elif num_inference_steps is not None and not hasattr(__lowercase , """set_timesteps""" ): __a = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) __a = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] __a = dummy_past_residuals[:] __a = scheduler.timesteps[5] __a = scheduler.timesteps[6] __a = scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample __a = scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) __a = scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample __a = scheduler.step(__lowercase , __lowercase , __lowercase , **__lowercase ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' for timesteps in [100, 1000]: self.check_over_configs(num_train_timesteps=__lowercase , time_step=__lowercase ) def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' for t, num_inference_steps in zip([1, 5, 10] , [10, 50, 100] ): self.check_over_forward(num_inference_steps=__lowercase , time_step=__lowercase ) def UpperCamelCase_ ( self : int ): '''simple docstring''' __a = self.full_loop() __a = torch.mean(torch.abs(__lowercase ) ) assert abs(result_mean.item() - 2540529 ) < 10
302
import random def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : list , _SCREAMING_SNAKE_CASE : List[Any] ): """simple docstring""" __a , __a , __a = [], [], [] for element in data: if element < pivot: less.append(_SCREAMING_SNAKE_CASE ) elif element > pivot: greater.append(_SCREAMING_SNAKE_CASE ) else: equal.append(_SCREAMING_SNAKE_CASE ) return less, equal, greater def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : list , _SCREAMING_SNAKE_CASE : int ): """simple docstring""" if index >= len(_SCREAMING_SNAKE_CASE ) or index < 0: return None __a = items[random.randint(0 , len(_SCREAMING_SNAKE_CASE ) - 1 )] __a = 0 __a , __a , __a = _partition(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __a = len(_SCREAMING_SNAKE_CASE ) __a = len(_SCREAMING_SNAKE_CASE ) # index is the pivot if m <= index < m + count: return pivot # must be in smaller elif m > index: return quick_select(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # must be in larger else: return quick_select(_SCREAMING_SNAKE_CASE , index - (m + count) )
302
1
from ...utils import logging from ..ta.modeling_tf_ta import TFTaEncoderModel, TFTaForConditionalGeneration, TFTaModel from .configuration_mta import MTaConfig lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = """T5Config""" class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : Any ='mt5' __lowerCamelCase : Dict =MTaConfig class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : Optional[int] ='mt5' __lowerCamelCase : str =MTaConfig class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : List[Any] ='mt5' __lowerCamelCase : Optional[int] =MTaConfig
302
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 lowerCamelCase__ = logging.get_logger(__name__) @add_end_docstrings(lowerCamelCase__ ) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): def __init__( self : Optional[int] , **__lowercase : Dict ): '''simple docstring''' super().__init__(**__lowercase ) if self.framework != "pt": raise ValueError(F"The {self.__class__} is only available in PyTorch." ) # No specific FOR_XXX available yet def __call__( self : str , __lowercase : Union[np.ndarray, bytes, str] , **__lowercase : int ): '''simple docstring''' return super().__call__(__lowercase , **__lowercase ) def UpperCamelCase_ ( self : List[Any] , **__lowercase : Union[str, Any] ): '''simple docstring''' __a = {} if "candidate_labels" in kwargs: __a = kwargs["""candidate_labels"""] if "hypothesis_template" in kwargs: __a = kwargs["""hypothesis_template"""] return preprocess_params, {}, {} def UpperCamelCase_ ( self : int , __lowercase : Dict , __lowercase : Dict=None , __lowercase : str="This is a sound of {}." ): '''simple docstring''' if isinstance(__lowercase , __lowercase ): if audio.startswith("""http://""" ) or audio.startswith("""https://""" ): # We need to actually check for a real protocol, otherwise it's impossible to use a local file # like http_huggingface_co.png __a = requests.get(__lowercase ).content else: with open(__lowercase , """rb""" ) as f: __a = f.read() if isinstance(__lowercase , __lowercase ): __a = ffmpeg_read(__lowercase , self.feature_extractor.sampling_rate ) if not isinstance(__lowercase , np.ndarray ): raise ValueError("""We expect a numpy ndarray as input""" ) if len(audio.shape ) != 1: raise ValueError("""We expect a single channel audio input for ZeroShotAudioClassificationPipeline""" ) __a = self.feature_extractor( [audio] , sampling_rate=self.feature_extractor.sampling_rate , return_tensors="""pt""" ) __a = candidate_labels __a = [hypothesis_template.format(__lowercase ) for x in candidate_labels] __a = self.tokenizer(__lowercase , return_tensors=self.framework , padding=__lowercase ) __a = [text_inputs] return inputs def UpperCamelCase_ ( self : Any , __lowercase : Any ): '''simple docstring''' __a = model_inputs.pop("""candidate_labels""" ) __a = model_inputs.pop("""text_inputs""" ) if isinstance(text_inputs[0] , __lowercase ): __a = text_inputs[0] else: # Batching case. __a = text_inputs[0][0] __a = self.model(**__lowercase , **__lowercase ) __a = { """candidate_labels""": candidate_labels, """logits""": outputs.logits_per_audio, } return model_outputs def UpperCamelCase_ ( self : Optional[Any] , __lowercase : Dict ): '''simple docstring''' __a = model_outputs.pop("""candidate_labels""" ) __a = model_outputs["""logits"""][0] if self.framework == "pt": __a = logits.softmax(dim=0 ) __a = probs.tolist() else: raise ValueError("""`tf` framework not supported.""" ) __a = [ {"""score""": score, """label""": candidate_label} for score, candidate_label in sorted(zip(__lowercase , __lowercase ) , key=lambda __lowercase : -x[0] ) ] return result
302
1
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary # Register SEW's fairseq modules from sew_asapp import tasks # noqa: F401 from transformers import ( SEWConfig, SEWForCTC, SEWModel, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { """post_extract_proj""": """feature_projection""", """encoder.pos_conv.0""": """encoder.pos_conv_embed.conv""", """self_attn.k_proj""": """encoder.layers.*.attention.k_proj""", """self_attn.v_proj""": """encoder.layers.*.attention.v_proj""", """self_attn.q_proj""": """encoder.layers.*.attention.q_proj""", """self_attn.out_proj""": """encoder.layers.*.attention.out_proj""", """self_attn_layer_norm""": """encoder.layers.*.layer_norm""", """fc1""": """encoder.layers.*.feed_forward.intermediate_dense""", """fc2""": """encoder.layers.*.feed_forward.output_dense""", """final_layer_norm""": """encoder.layers.*.final_layer_norm""", """encoder.upsample.0""": """encoder.upsample.projection""", """encoder.layer_norm""": """encoder.layer_norm""", """w2v_model.layer_norm""": """layer_norm""", """w2v_encoder.proj""": """lm_head""", """mask_emb""": """masked_spec_embed""", } def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" for attribute in key.split(""".""" ): __a = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if weight_type is not None: __a = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).shape else: __a = hf_pointer.shape assert hf_shape == value.shape, ( f"Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be" f" {value.shape} for {full_name}" ) if weight_type == "weight": __a = value elif weight_type == "weight_g": __a = value elif weight_type == "weight_v": __a = value elif weight_type == "bias": __a = value else: __a = value logger.info(f"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}." ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" __a = [] __a = fairseq_model.state_dict() __a = hf_model.sew.feature_extractor if is_finetuned else hf_model.feature_extractor for name, value in fairseq_dict.items(): __a = False if "conv_layers" in name: load_conv_layer( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , hf_model.config.feat_extract_norm == """group""" , ) __a = True else: for key, mapped_key in MAPPING.items(): __a = """sew.""" + mapped_key if (is_finetuned and mapped_key != """lm_head""") else mapped_key if key in name or key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0]: __a = True if "*" in mapped_key: __a = name.split(_SCREAMING_SNAKE_CASE )[0].split(""".""" )[-2] __a = mapped_key.replace("""*""" , _SCREAMING_SNAKE_CASE ) if "weight_g" in name: __a = """weight_g""" elif "weight_v" in name: __a = """weight_v""" elif "weight" in name: __a = """weight""" elif "bias" in name: __a = """bias""" else: __a = None set_recursively(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) continue if not is_used: unused_weights.append(_SCREAMING_SNAKE_CASE ) logger.warning(f"Unused weights: {unused_weights}" ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" __a = full_name.split("""conv_layers.""" )[-1] __a = name.split(""".""" ) __a = int(items[0] ) __a = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( f"{full_name} has size {value.shape}, but" f" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found." ) __a = value logger.info(f"Feat extract conv layer {layer_id} was initialized from {full_name}." ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( f"{full_name} has size {value.shape}, but" f" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found." ) __a = value logger.info(f"Feat extract conv layer {layer_id} was initialized from {full_name}." ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( f"{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was" " found." ) __a = value logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( f"{full_name} has size {value.shape}, but" f" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found." ) __a = value logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) else: unused_weights.append(_SCREAMING_SNAKE_CASE ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" __a = SEWConfig() if is_finetuned: __a = model.wav_encoder.wav_model.cfg else: __a = model.cfg __a = fs_config.conv_bias __a = eval(fs_config.conv_feature_layers ) __a = [x[0] for x in conv_layers] __a = [x[1] for x in conv_layers] __a = [x[2] for x in conv_layers] __a = """gelu""" __a = """layer""" if fs_config.extractor_mode == """layer_norm""" else """group""" __a = 0.0 __a = fs_config.activation_fn.name __a = fs_config.encoder_embed_dim __a = 0.02 __a = fs_config.encoder_ffn_embed_dim __a = 1e-5 __a = fs_config.encoder_layerdrop __a = fs_config.encoder_attention_heads __a = fs_config.conv_pos_groups __a = fs_config.conv_pos __a = len(_SCREAMING_SNAKE_CASE ) __a = fs_config.encoder_layers __a = fs_config.squeeze_factor # take care of any params that are overridden by the Wav2VecCtc model if is_finetuned: __a = model.cfg __a = fs_config.final_dropout __a = fs_config.layerdrop __a = fs_config.activation_dropout __a = fs_config.mask_prob > 0 or fs_config.mask_channel_prob > 0 __a = fs_config.attention_dropout __a = fs_config.dropout_input __a = fs_config.dropout __a = fs_config.mask_channel_length __a = fs_config.mask_channel_prob __a = fs_config.mask_length __a = fs_config.mask_prob __a = """Wav2Vec2FeatureExtractor""" __a = """Wav2Vec2CTCTokenizer""" return config @torch.no_grad() def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : Optional[Any]=None , _SCREAMING_SNAKE_CASE : List[Any]=None , _SCREAMING_SNAKE_CASE : Any=True ): """simple docstring""" if is_finetuned: __a , __a , __a = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"""data""": """/""".join(dict_path.split("""/""" )[:-1] )} ) else: __a , __a , __a = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ) if config_path is not None: __a = SEWConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) else: __a = convert_config(model[0] , _SCREAMING_SNAKE_CASE ) __a = model[0].eval() __a = True if config.feat_extract_norm == """layer""" else False __a = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6000 , padding_value=0 , do_normalize=_SCREAMING_SNAKE_CASE , return_attention_mask=_SCREAMING_SNAKE_CASE , ) if is_finetuned: if dict_path: __a = Dictionary.load(_SCREAMING_SNAKE_CASE ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq __a = target_dict.pad_index __a = target_dict.bos_index __a = target_dict.pad_index __a = target_dict.bos_index __a = target_dict.eos_index __a = len(target_dict.symbols ) __a = os.path.join(_SCREAMING_SNAKE_CASE , """vocab.json""" ) if not os.path.isdir(_SCREAMING_SNAKE_CASE ): logger.error("""--pytorch_dump_folder_path ({}) should be a directory""".format(_SCREAMING_SNAKE_CASE ) ) return os.makedirs(_SCREAMING_SNAKE_CASE , exist_ok=_SCREAMING_SNAKE_CASE ) with open(_SCREAMING_SNAKE_CASE , """w""" , encoding="""utf-8""" ) as vocab_handle: json.dump(target_dict.indices , _SCREAMING_SNAKE_CASE ) __a = WavaVecaCTCTokenizer( _SCREAMING_SNAKE_CASE , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token="""|""" , do_lower_case=_SCREAMING_SNAKE_CASE , ) __a = WavaVecaProcessor(feature_extractor=_SCREAMING_SNAKE_CASE , tokenizer=_SCREAMING_SNAKE_CASE ) processor.save_pretrained(_SCREAMING_SNAKE_CASE ) __a = SEWForCTC(_SCREAMING_SNAKE_CASE ) else: __a = SEWModel(_SCREAMING_SNAKE_CASE ) feature_extractor.save_pretrained(_SCREAMING_SNAKE_CASE ) recursively_load_weights(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) hf_model.save_pretrained(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to fairseq checkpoint""") parser.add_argument("""--dict_path""", default=None, type=str, help="""Path to dict of fine-tuned model""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") parser.add_argument( """--is_finetuned""", action="""store_true""", help="""Whether the model to convert is a fine-tuned model or not""" ) lowerCamelCase__ = parser.parse_args() convert_sew_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, args.is_finetuned )
302
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, ChannelDimension, ImageInput, PILImageResampling, is_batched, to_numpy_array, valid_images, ) from ...utils import TensorType, logging lowerCamelCase__ = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : Dict =['pixel_values'] def __init__( self : Optional[int] , __lowercase : bool = True , __lowercase : Optional[Dict[str, int]] = None , __lowercase : PILImageResampling = PILImageResampling.BICUBIC , __lowercase : bool = True , __lowercase : bool = True , __lowercase : Union[int, float] = 1 / 255 , __lowercase : Dict[str, int] = None , __lowercase : bool = True , __lowercase : Optional[Union[float, List[float]]] = None , __lowercase : Optional[Union[float, List[float]]] = None , **__lowercase : Dict , ): '''simple docstring''' super().__init__(**__lowercase ) __a = size if size is not None else {"""height""": 224, """width""": 224} __a = get_size_dict(__lowercase ) __a = crop_size if crop_size is not None else {"""height""": 224, """width""": 224} __a = get_size_dict(__lowercase , default_to_square=__lowercase , param_name="""crop_size""" ) __a = do_resize __a = do_rescale __a = do_normalize __a = do_center_crop __a = crop_size __a = size __a = resample __a = rescale_factor __a = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN __a = image_std if image_std is not None else IMAGENET_DEFAULT_STD def UpperCamelCase_ ( self : Any , __lowercase : np.ndarray , __lowercase : Dict[str, int] , __lowercase : PILImageResampling = PILImageResampling.BILINEAR , __lowercase : Optional[Union[str, ChannelDimension]] = None , **__lowercase : Optional[Any] , ): '''simple docstring''' __a = get_size_dict(__lowercase ) if "shortest_edge" in size: __a = get_resize_output_image_size(__lowercase , size=size["""shortest_edge"""] , default_to_square=__lowercase ) # size = get_resize_output_image_size(image, size["shortest_edge"], size["longest_edge"]) elif "height" in size and "width" in size: __a = (size["""height"""], size["""width"""]) else: raise ValueError(F"Size must contain 'height' and 'width' keys or 'shortest_edge' key. Got {size.keys()}" ) return resize(__lowercase , size=__lowercase , resample=__lowercase , data_format=__lowercase , **__lowercase ) def UpperCamelCase_ ( self : str , __lowercase : np.ndarray , __lowercase : Dict[str, int] , __lowercase : Optional[Union[str, ChannelDimension]] = None , **__lowercase : List[Any] , ): '''simple docstring''' __a = get_size_dict(__lowercase ) if "height" not in size or "width" not in size: raise ValueError(F"The `size` parameter must contain the keys (height, width). Got {size.keys()}" ) return center_crop(__lowercase , size=(size["""height"""], size["""width"""]) , data_format=__lowercase , **__lowercase ) def UpperCamelCase_ ( self : Any , __lowercase : np.ndarray , __lowercase : float , __lowercase : Optional[Union[str, ChannelDimension]] = None , **__lowercase : str ): '''simple docstring''' return rescale(__lowercase , scale=__lowercase , data_format=__lowercase , **__lowercase ) def UpperCamelCase_ ( self : List[Any] , __lowercase : np.ndarray , __lowercase : Union[float, List[float]] , __lowercase : Union[float, List[float]] , __lowercase : Optional[Union[str, ChannelDimension]] = None , **__lowercase : Any , ): '''simple docstring''' return normalize(__lowercase , mean=__lowercase , std=__lowercase , data_format=__lowercase , **__lowercase ) def UpperCamelCase_ ( self : Tuple , __lowercase : ImageInput , __lowercase : Optional[bool] = None , __lowercase : Dict[str, int] = None , __lowercase : PILImageResampling = None , __lowercase : bool = None , __lowercase : int = None , __lowercase : Optional[bool] = None , __lowercase : Optional[float] = None , __lowercase : Optional[bool] = None , __lowercase : Optional[Union[float, List[float]]] = None , __lowercase : Optional[Union[float, List[float]]] = None , __lowercase : Optional[Union[str, TensorType]] = None , __lowercase : Union[str, ChannelDimension] = ChannelDimension.FIRST , **__lowercase : List[Any] , ): '''simple docstring''' __a = do_resize if do_resize is not None else self.do_resize __a = do_rescale if do_rescale is not None else self.do_rescale __a = do_normalize if do_normalize is not None else self.do_normalize __a = do_center_crop if do_center_crop is not None else self.do_center_crop __a = crop_size if crop_size is not None else self.crop_size __a = get_size_dict(__lowercase , param_name="""crop_size""" , default_to_square=__lowercase ) __a = resample if resample is not None else self.resample __a = rescale_factor if rescale_factor is not None else self.rescale_factor __a = image_mean if image_mean is not None else self.image_mean __a = image_std if image_std is not None else self.image_std __a = size if size is not None else self.size __a = get_size_dict(__lowercase ) if not is_batched(__lowercase ): __a = [images] if not valid_images(__lowercase ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None: raise ValueError("""Size must be specified if do_resize is True.""" ) if do_center_crop and crop_size is None: raise ValueError("""Crop size must be specified if do_center_crop is True.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) # All transformations expect numpy arrays. __a = [to_numpy_array(__lowercase ) for image in images] if do_resize: __a = [self.resize(image=__lowercase , size=__lowercase , resample=__lowercase ) for image in images] if do_center_crop: __a = [self.center_crop(image=__lowercase , size=__lowercase ) for image in images] if do_rescale: __a = [self.rescale(image=__lowercase , scale=__lowercase ) for image in images] if do_normalize: __a = [self.normalize(image=__lowercase , mean=__lowercase , std=__lowercase ) for image in images] __a = [to_channel_dimension_format(__lowercase , __lowercase ) for image in images] __a = {"""pixel_values""": images} return BatchFeature(data=__lowercase , tensor_type=__lowercase )
302
1
import string import numpy def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int ): """simple docstring""" return b if a == 0 else greatest_common_divisor(b % a , _SCREAMING_SNAKE_CASE ) class SCREAMING_SNAKE_CASE : __lowerCamelCase : List[str] =string.ascii_uppercase + string.digits # This cipher takes alphanumerics into account # i.e. a total of 36 characters # take x and return x % len(key_string) __lowerCamelCase : List[Any] =numpy.vectorize(lambda lowerCamelCase__ : x % 36 ) __lowerCamelCase : Optional[Any] =numpy.vectorize(lowerCamelCase__ ) def __init__( self : Union[str, Any] , __lowercase : numpy.ndarray ): '''simple docstring''' __a = self.modulus(__lowercase ) # mod36 calc's on the encrypt key self.check_determinant() # validate the determinant of the encryption key __a = encrypt_key.shape[0] def UpperCamelCase_ ( self : Dict , __lowercase : str ): '''simple docstring''' return self.key_string.index(__lowercase ) def UpperCamelCase_ ( self : Dict , __lowercase : int ): '''simple docstring''' return self.key_string[round(__lowercase )] def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' __a = round(numpy.linalg.det(self.encrypt_key ) ) if det < 0: __a = det % len(self.key_string ) __a = len(self.key_string ) if greatest_common_divisor(__lowercase , len(self.key_string ) ) != 1: __a = ( F"determinant modular {req_l} of encryption key({det}) " F"is not co prime w.r.t {req_l}.\nTry another key." ) raise ValueError(__lowercase ) def UpperCamelCase_ ( self : Dict , __lowercase : str ): '''simple docstring''' __a = [char for char in text.upper() if char in self.key_string] __a = chars[-1] while len(__lowercase ) % self.break_key != 0: chars.append(__lowercase ) return "".join(__lowercase ) def UpperCamelCase_ ( self : List[str] , __lowercase : str ): '''simple docstring''' __a = self.process_text(text.upper() ) __a = """""" for i in range(0 , len(__lowercase ) - self.break_key + 1 , self.break_key ): __a = text[i : i + self.break_key] __a = [self.replace_letters(__lowercase ) for char in batch] __a = numpy.array([vec] ).T __a = self.modulus(self.encrypt_key.dot(__lowercase ) ).T.tolist()[ 0 ] __a = """""".join( self.replace_digits(__lowercase ) for num in batch_encrypted ) encrypted += encrypted_batch return encrypted def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' __a = round(numpy.linalg.det(self.encrypt_key ) ) if det < 0: __a = det % len(self.key_string ) __a = None for i in range(len(self.key_string ) ): if (det * i) % len(self.key_string ) == 1: __a = i break __a = ( det_inv * numpy.linalg.det(self.encrypt_key ) * numpy.linalg.inv(self.encrypt_key ) ) return self.to_int(self.modulus(__lowercase ) ) def UpperCamelCase_ ( self : Any , __lowercase : str ): '''simple docstring''' __a = self.make_decrypt_key() __a = self.process_text(text.upper() ) __a = """""" for i in range(0 , len(__lowercase ) - self.break_key + 1 , self.break_key ): __a = text[i : i + self.break_key] __a = [self.replace_letters(__lowercase ) for char in batch] __a = numpy.array([vec] ).T __a = self.modulus(decrypt_key.dot(__lowercase ) ).T.tolist()[0] __a = """""".join( self.replace_digits(__lowercase ) for num in batch_decrypted ) decrypted += decrypted_batch return decrypted def lowerCAmelCase__ ( ): """simple docstring""" __a = int(input("""Enter the order of the encryption key: """ ) ) __a = [] print("""Enter each row of the encryption key with space separated integers""" ) for _ in range(_SCREAMING_SNAKE_CASE ): __a = [int(_SCREAMING_SNAKE_CASE ) for x in input().split()] hill_matrix.append(_SCREAMING_SNAKE_CASE ) __a = HillCipher(numpy.array(_SCREAMING_SNAKE_CASE ) ) print("""Would you like to encrypt or decrypt some text? (1 or 2)""" ) __a = input("""\n1. Encrypt\n2. Decrypt\n""" ) if option == "1": __a = input("""What text would you like to encrypt?: """ ) print("""Your encrypted text is:""" ) print(hc.encrypt(_SCREAMING_SNAKE_CASE ) ) elif option == "2": __a = input("""What text would you like to decrypt?: """ ) print("""Your decrypted text is:""" ) print(hc.decrypt(_SCREAMING_SNAKE_CASE ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
302
import tempfile import unittest from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from transformers.testing_utils import ( is_torch_available, require_optimum, require_torch, slow, ) if is_torch_available(): import torch @require_torch @require_optimum @slow class SCREAMING_SNAKE_CASE ( unittest.TestCase ): def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' __a = """hf-internal-testing/tiny-random-t5""" __a = AutoTokenizer.from_pretrained(__lowercase ) __a = AutoModelForSeqaSeqLM.from_pretrained(__lowercase ) __a = tokenizer("""This is me""" , return_tensors="""pt""" ) __a = model.to_bettertransformer() self.assertTrue(any("""BetterTransformer""" in mod.__class__.__name__ for _, mod in model.named_modules() ) ) __a = model.generate(**__lowercase ) __a = model.reverse_bettertransformer() self.assertFalse(any("""BetterTransformer""" in mod.__class__.__name__ for _, mod in model.named_modules() ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(__lowercase ) __a = AutoModelForSeqaSeqLM.from_pretrained(__lowercase ) self.assertFalse( any("""BetterTransformer""" in mod.__class__.__name__ for _, mod in model_reloaded.named_modules() ) ) __a = model_reloaded.generate(**__lowercase ) self.assertTrue(torch.allclose(__lowercase , __lowercase ) ) def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' __a = """hf-internal-testing/tiny-random-t5""" __a = AutoModelForSeqaSeqLM.from_pretrained(__lowercase ) __a = model.to_bettertransformer() with tempfile.TemporaryDirectory() as tmpdirname: with self.assertRaises(__lowercase ): model.save_pretrained(__lowercase ) __a = model.reverse_bettertransformer() model.save_pretrained(__lowercase )
302
1
import numpy as np import torch import tqdm from ...models.unet_ad import UNetaDModel from ...pipelines import DiffusionPipeline from ...utils import randn_tensor from ...utils.dummy_pt_objects import DDPMScheduler class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): def __init__( self : List[str] , __lowercase : UNetaDModel , __lowercase : UNetaDModel , __lowercase : DDPMScheduler , __lowercase : Tuple , ): '''simple docstring''' super().__init__() __a = value_function __a = unet __a = scheduler __a = env __a = env.get_dataset() __a = {} for key in self.data.keys(): try: __a = self.data[key].mean() except: # noqa: E722 pass __a = {} for key in self.data.keys(): try: __a = self.data[key].std() except: # noqa: E722 pass __a = env.observation_space.shape[0] __a = env.action_space.shape[0] def UpperCamelCase_ ( self : int , __lowercase : Any , __lowercase : Optional[Any] ): '''simple docstring''' return (x_in - self.means[key]) / self.stds[key] def UpperCamelCase_ ( self : Dict , __lowercase : Dict , __lowercase : Tuple ): '''simple docstring''' return x_in * self.stds[key] + self.means[key] def UpperCamelCase_ ( self : str , __lowercase : int ): '''simple docstring''' if type(__lowercase ) is dict: return {k: self.to_torch(__lowercase ) for k, v in x_in.items()} elif torch.is_tensor(__lowercase ): return x_in.to(self.unet.device ) return torch.tensor(__lowercase , device=self.unet.device ) def UpperCamelCase_ ( self : Optional[int] , __lowercase : Tuple , __lowercase : Optional[Any] , __lowercase : Optional[int] ): '''simple docstring''' for key, val in cond.items(): __a = val.clone() return x_in def UpperCamelCase_ ( self : Tuple , __lowercase : Optional[int] , __lowercase : Union[str, Any] , __lowercase : Union[str, Any] , __lowercase : int ): '''simple docstring''' __a = x.shape[0] __a = None for i in tqdm.tqdm(self.scheduler.timesteps ): # create batch of timesteps to pass into model __a = torch.full((batch_size,) , __lowercase , device=self.unet.device , dtype=torch.long ) for _ in range(__lowercase ): with torch.enable_grad(): x.requires_grad_() # permute to match dimension for pre-trained models __a = self.value_function(x.permute(0 , 2 , 1 ) , __lowercase ).sample __a = torch.autograd.grad([y.sum()] , [x] )[0] __a = self.scheduler._get_variance(__lowercase ) __a = torch.exp(0.5 * posterior_variance ) __a = model_std * grad __a = 0 __a = x.detach() __a = x + scale * grad __a = self.reset_xa(__lowercase , __lowercase , self.action_dim ) __a = self.unet(x.permute(0 , 2 , 1 ) , __lowercase ).sample.permute(0 , 2 , 1 ) # TODO: verify deprecation of this kwarg __a = self.scheduler.step(__lowercase , __lowercase , __lowercase , predict_epsilon=__lowercase )["""prev_sample"""] # apply conditions to the trajectory (set the initial state) __a = self.reset_xa(__lowercase , __lowercase , self.action_dim ) __a = self.to_torch(__lowercase ) return x, y def __call__( self : int , __lowercase : Optional[int] , __lowercase : List[str]=64 , __lowercase : Optional[int]=32 , __lowercase : Union[str, Any]=2 , __lowercase : Any=0.1 ): '''simple docstring''' # normalize the observations and create batch dimension __a = self.normalize(__lowercase , """observations""" ) __a = obs[None].repeat(__lowercase , axis=0 ) __a = {0: self.to_torch(__lowercase )} __a = (batch_size, planning_horizon, self.state_dim + self.action_dim) # generate initial noise and apply our conditions (to make the trajectories start at current state) __a = randn_tensor(__lowercase , device=self.unet.device ) __a = self.reset_xa(__lowercase , __lowercase , self.action_dim ) __a = self.to_torch(__lowercase ) # run the diffusion process __a , __a = self.run_diffusion(__lowercase , __lowercase , __lowercase , __lowercase ) # sort output trajectories by value __a = y.argsort(0 , descending=__lowercase ).squeeze() __a = x[sorted_idx] __a = sorted_values[:, :, : self.action_dim] __a = actions.detach().cpu().numpy() __a = self.de_normalize(__lowercase , key="""actions""" ) # select the action with the highest value if y is not None: __a = 0 else: # if we didn't run value guiding, select a random action __a = np.random.randint(0 , __lowercase ) __a = denorm_actions[selected_index, 0] return denorm_actions
302
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig lowerCamelCase__ = { """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/config.json""", """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/config.json""", """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/config.json""", """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/config.json""", """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/config.json""", """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/config.json""", """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/config.json""", """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/config.json""", } class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : Optional[Any] ='albert' def __init__( self : Optional[Any] , __lowercase : Union[str, Any]=30000 , __lowercase : List[str]=128 , __lowercase : Optional[Any]=4096 , __lowercase : Dict=12 , __lowercase : Any=1 , __lowercase : Optional[Any]=64 , __lowercase : Any=16384 , __lowercase : Any=1 , __lowercase : Union[str, Any]="gelu_new" , __lowercase : List[str]=0 , __lowercase : int=0 , __lowercase : Dict=512 , __lowercase : str=2 , __lowercase : List[str]=0.02 , __lowercase : Union[str, Any]=1E-12 , __lowercase : int=0.1 , __lowercase : Any="absolute" , __lowercase : Optional[int]=0 , __lowercase : Dict=2 , __lowercase : Optional[Any]=3 , **__lowercase : Any , ): '''simple docstring''' super().__init__(pad_token_id=__lowercase , bos_token_id=__lowercase , eos_token_id=__lowercase , **__lowercase ) __a = vocab_size __a = embedding_size __a = hidden_size __a = num_hidden_layers __a = num_hidden_groups __a = num_attention_heads __a = inner_group_num __a = hidden_act __a = intermediate_size __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = type_vocab_size __a = initializer_range __a = layer_norm_eps __a = classifier_dropout_prob __a = position_embedding_type class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): @property def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' if self.task == "multiple-choice": __a = {0: """batch""", 1: """choice""", 2: """sequence"""} else: __a = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis), ] )
302
1
import argparse import os import torch from transformers import FlavaImageCodebook, FlavaImageCodebookConfig def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" __a = s.rsplit(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return new.join(_SCREAMING_SNAKE_CASE ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" return sum(param.float().sum() if """encoder.embeddings""" not in key else 0 for key, param in state_dict.items() ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" __a = {} __a = ["""group_1""", """group_2""", """group_3""", """group_4"""] for key, value in state_dict.items(): for group_key in group_keys: if group_key in key: __a = key.replace(f"{group_key}." , f"{group_key}.group." ) if "res_path" in key: __a = key.replace("""res_path.""" , """res_path.path.""" ) if key.endswith(""".w""" ): __a = rreplace(_SCREAMING_SNAKE_CASE , """.w""" , """.weight""" , 1 ) if key.endswith(""".b""" ): __a = rreplace(_SCREAMING_SNAKE_CASE , """.b""" , """.bias""" , 1 ) __a = value.float() return upgrade @torch.no_grad() def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Optional[int]=None , _SCREAMING_SNAKE_CASE : Any=True ): """simple docstring""" from dall_e import Encoder __a = Encoder() if os.path.exists(_SCREAMING_SNAKE_CASE ): __a = torch.load(_SCREAMING_SNAKE_CASE ) else: __a = torch.hub.load_state_dict_from_url(_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __a = ckpt.state_dict() encoder.load_state_dict(_SCREAMING_SNAKE_CASE ) if config_path is not None: __a = FlavaImageCodebookConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) else: __a = FlavaImageCodebookConfig() __a = FlavaImageCodebook(_SCREAMING_SNAKE_CASE ).eval() __a = encoder.state_dict() __a = upgrade_state_dict(_SCREAMING_SNAKE_CASE ) hf_model.load_state_dict(_SCREAMING_SNAKE_CASE ) __a = hf_model.state_dict() __a = count_parameters(_SCREAMING_SNAKE_CASE ) __a = count_parameters(_SCREAMING_SNAKE_CASE ) assert torch.allclose(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , atol=1e-3 ) if save_checkpoint: hf_model.save_pretrained(_SCREAMING_SNAKE_CASE ) else: return hf_state_dict if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to flava checkpoint""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") lowerCamelCase__ = parser.parse_args() convert_dalle_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
302
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) lowerCamelCase__ = { """configuration_blip""": [ """BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP""", """BlipConfig""", """BlipTextConfig""", """BlipVisionConfig""", ], """processing_blip""": ["""BlipProcessor"""], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = ["""BlipImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ """BLIP_PRETRAINED_MODEL_ARCHIVE_LIST""", """BlipModel""", """BlipPreTrainedModel""", """BlipForConditionalGeneration""", """BlipForQuestionAnswering""", """BlipVisionModel""", """BlipTextModel""", """BlipForImageTextRetrieval""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ """TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFBlipModel""", """TFBlipPreTrainedModel""", """TFBlipForConditionalGeneration""", """TFBlipForQuestionAnswering""", """TFBlipVisionModel""", """TFBlipTextModel""", """TFBlipForImageTextRetrieval""", ] if TYPE_CHECKING: from .configuration_blip import BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, BlipConfig, BlipTextConfig, BlipVisionConfig from .processing_blip import BlipProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_blip import BlipImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blip import ( BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, BlipModel, BlipPreTrainedModel, BlipTextModel, BlipVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blip import ( TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFBlipForConditionalGeneration, TFBlipForImageTextRetrieval, TFBlipForQuestionAnswering, TFBlipModel, TFBlipPreTrainedModel, TFBlipTextModel, TFBlipVisionModel, ) else: import sys lowerCamelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
302
1
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import os from ...utils.constants import SAGEMAKER_PARALLEL_EC2_INSTANCES, TORCH_DYNAMO_MODES from ...utils.dataclasses import ComputeEnvironment, SageMakerDistributedType from ...utils.imports import is_botoa_available from .config_args import SageMakerConfig from .config_utils import ( DYNAMO_BACKENDS, _ask_field, _ask_options, _convert_dynamo_backend, _convert_mixed_precision, _convert_sagemaker_distributed_mode, _convert_yes_no_to_bool, ) if is_botoa_available(): import botoa # noqa: F401 def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : str ): """simple docstring""" __a = botoa.client("""iam""" ) __a = { """Version""": """2012-10-17""", """Statement""": [ {"""Effect""": """Allow""", """Principal""": {"""Service""": """sagemaker.amazonaws.com"""}, """Action""": """sts:AssumeRole"""} ], } try: # create the role, associated with the chosen trust policy iam_client.create_role( RoleName=_SCREAMING_SNAKE_CASE , AssumeRolePolicyDocument=json.dumps(_SCREAMING_SNAKE_CASE , indent=2 ) ) __a = { """Version""": """2012-10-17""", """Statement""": [ { """Effect""": """Allow""", """Action""": [ """sagemaker:*""", """ecr:GetDownloadUrlForLayer""", """ecr:BatchGetImage""", """ecr:BatchCheckLayerAvailability""", """ecr:GetAuthorizationToken""", """cloudwatch:PutMetricData""", """cloudwatch:GetMetricData""", """cloudwatch:GetMetricStatistics""", """cloudwatch:ListMetrics""", """logs:CreateLogGroup""", """logs:CreateLogStream""", """logs:DescribeLogStreams""", """logs:PutLogEvents""", """logs:GetLogEvents""", """s3:CreateBucket""", """s3:ListBucket""", """s3:GetBucketLocation""", """s3:GetObject""", """s3:PutObject""", ], """Resource""": """*""", } ], } # attach policy to role iam_client.put_role_policy( RoleName=_SCREAMING_SNAKE_CASE , PolicyName=f"{role_name}_policy_permission" , PolicyDocument=json.dumps(_SCREAMING_SNAKE_CASE , indent=2 ) , ) except iam_client.exceptions.EntityAlreadyExistsException: print(f"role {role_name} already exists. Using existing one" ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : str ): """simple docstring""" __a = botoa.client("""iam""" ) return iam_client.get_role(RoleName=_SCREAMING_SNAKE_CASE )["Role"]["Arn"] def lowerCAmelCase__ ( ): """simple docstring""" __a = _ask_options( """How do you want to authorize?""" , ["""AWS Profile""", """Credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) """] , _SCREAMING_SNAKE_CASE , ) __a = None if credentials_configuration == 0: __a = _ask_field("""Enter your AWS Profile name: [default] """ , default="""default""" ) __a = aws_profile else: print( """Note you will need to provide AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY when you launch you training script with,""" """`accelerate launch --aws_access_key_id XXX --aws_secret_access_key YYY`""" ) __a = _ask_field("""AWS Access Key ID: """ ) __a = aws_access_key_id __a = _ask_field("""AWS Secret Access Key: """ ) __a = aws_secret_access_key __a = _ask_field("""Enter your AWS Region: [us-east-1]""" , default="""us-east-1""" ) __a = aws_region __a = _ask_options( """Do you already have an IAM Role for executing Amazon SageMaker Training Jobs?""" , ["""Provide IAM Role name""", """Create new IAM role using credentials"""] , _SCREAMING_SNAKE_CASE , ) if role_management == 0: __a = _ask_field("""Enter your IAM role name: """ ) else: __a = """accelerate_sagemaker_execution_role""" print(f"Accelerate will create an iam role \"{iam_role_name}\" using the provided credentials" ) _create_iam_role_for_sagemaker(_SCREAMING_SNAKE_CASE ) __a = _ask_field( """Do you want to use custom Docker image? [yes/NO]: """ , _convert_yes_no_to_bool , default=_SCREAMING_SNAKE_CASE , error_message="""Please enter yes or no.""" , ) __a = None if is_custom_docker_image: __a = _ask_field("""Enter your Docker image: """ , lambda _SCREAMING_SNAKE_CASE : str(_SCREAMING_SNAKE_CASE ).lower() ) __a = _ask_field( """Do you want to provide SageMaker input channels with data locations? [yes/NO]: """ , _convert_yes_no_to_bool , default=_SCREAMING_SNAKE_CASE , error_message="""Please enter yes or no.""" , ) __a = None if is_sagemaker_inputs_enabled: __a = _ask_field( """Enter the path to the SageMaker inputs TSV file with columns (channel_name, data_location): """ , lambda _SCREAMING_SNAKE_CASE : str(_SCREAMING_SNAKE_CASE ).lower() , ) __a = _ask_field( """Do you want to enable SageMaker metrics? [yes/NO]: """ , _convert_yes_no_to_bool , default=_SCREAMING_SNAKE_CASE , error_message="""Please enter yes or no.""" , ) __a = None if is_sagemaker_metrics_enabled: __a = _ask_field( """Enter the path to the SageMaker metrics TSV file with columns (metric_name, metric_regex): """ , lambda _SCREAMING_SNAKE_CASE : str(_SCREAMING_SNAKE_CASE ).lower() , ) __a = _ask_options( """What is the distributed mode?""" , ["""No distributed training""", """Data parallelism"""] , _convert_sagemaker_distributed_mode , ) __a = {} __a = _ask_field( """Do you wish to optimize your script with torch dynamo?[yes/NO]:""" , _convert_yes_no_to_bool , default=_SCREAMING_SNAKE_CASE , error_message="""Please enter yes or no.""" , ) if use_dynamo: __a = """dynamo_""" __a = _ask_options( """Which dynamo backend would you like to use?""" , [x.lower() for x in DYNAMO_BACKENDS] , _convert_dynamo_backend , default=2 , ) __a = _ask_field( """Do you want to customize the defaults sent to torch.compile? [yes/NO]: """ , _convert_yes_no_to_bool , default=_SCREAMING_SNAKE_CASE , error_message="""Please enter yes or no.""" , ) if use_custom_options: __a = _ask_options( """Which mode do you want to use?""" , _SCREAMING_SNAKE_CASE , lambda _SCREAMING_SNAKE_CASE : TORCH_DYNAMO_MODES[int(_SCREAMING_SNAKE_CASE )] , default="""default""" , ) __a = _ask_field( """Do you want the fullgraph mode or it is ok to break model into several subgraphs? [yes/NO]: """ , _convert_yes_no_to_bool , default=_SCREAMING_SNAKE_CASE , error_message="""Please enter yes or no.""" , ) __a = _ask_field( """Do you want to enable dynamic shape tracing? [yes/NO]: """ , _convert_yes_no_to_bool , default=_SCREAMING_SNAKE_CASE , error_message="""Please enter yes or no.""" , ) __a = """Which EC2 instance type you want to use for your training?""" if distributed_type != SageMakerDistributedType.NO: __a = _ask_options( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , lambda _SCREAMING_SNAKE_CASE : SAGEMAKER_PARALLEL_EC2_INSTANCES[int(_SCREAMING_SNAKE_CASE )] ) else: eca_instance_query += "? [ml.p3.2xlarge]:" __a = _ask_field(_SCREAMING_SNAKE_CASE , lambda _SCREAMING_SNAKE_CASE : str(_SCREAMING_SNAKE_CASE ).lower() , default="""ml.p3.2xlarge""" ) __a = 1 if distributed_type in (SageMakerDistributedType.DATA_PARALLEL, SageMakerDistributedType.MODEL_PARALLEL): __a = _ask_field( """How many machines do you want use? [1]: """ , _SCREAMING_SNAKE_CASE , default=1 , ) __a = _ask_options( """Do you wish to use FP16 or BF16 (mixed precision)?""" , ["""no""", """fp16""", """bf16""", """fp8"""] , _convert_mixed_precision , ) if use_dynamo and mixed_precision == "no": print( """Torch dynamo used without mixed precision requires TF32 to be efficient. Accelerate will enable it by default when launching your scripts.""" ) return SageMakerConfig( image_uri=_SCREAMING_SNAKE_CASE , compute_environment=ComputeEnvironment.AMAZON_SAGEMAKER , distributed_type=_SCREAMING_SNAKE_CASE , use_cpu=_SCREAMING_SNAKE_CASE , dynamo_config=_SCREAMING_SNAKE_CASE , eca_instance_type=_SCREAMING_SNAKE_CASE , profile=_SCREAMING_SNAKE_CASE , region=_SCREAMING_SNAKE_CASE , iam_role_name=_SCREAMING_SNAKE_CASE , mixed_precision=_SCREAMING_SNAKE_CASE , num_machines=_SCREAMING_SNAKE_CASE , sagemaker_inputs_file=_SCREAMING_SNAKE_CASE , sagemaker_metrics_file=_SCREAMING_SNAKE_CASE , )
302
class SCREAMING_SNAKE_CASE : def __init__( self : List[Any] , __lowercase : Union[str, Any] ): '''simple docstring''' __a = val __a = None __a = None def UpperCamelCase_ ( self : Union[str, Any] , __lowercase : Any ): '''simple docstring''' if self.val: if val < self.val: if self.left is None: __a = Node(__lowercase ) else: self.left.insert(__lowercase ) elif val > self.val: if self.right is None: __a = Node(__lowercase ) else: self.right.insert(__lowercase ) else: __a = val def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : Any ): """simple docstring""" if root: inorder(root.left , _SCREAMING_SNAKE_CASE ) res.append(root.val ) inorder(root.right , _SCREAMING_SNAKE_CASE ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Any ): """simple docstring""" if len(_SCREAMING_SNAKE_CASE ) == 0: return arr __a = Node(arr[0] ) for i in range(1 , len(_SCREAMING_SNAKE_CASE ) ): root.insert(arr[i] ) # Traverse BST in order. __a = [] inorder(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return res if __name__ == "__main__": print(tree_sort([10, 1, 3, 2, 9, 14, 13]))
302
1
def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int = 10 , _SCREAMING_SNAKE_CASE : int = 22 ): """simple docstring""" __a = range(1 , _SCREAMING_SNAKE_CASE ) __a = range(1 , _SCREAMING_SNAKE_CASE ) return sum( 1 for power in powers for base in bases if len(str(base**power ) ) == power ) if __name__ == "__main__": print(F"""{solution(10, 22) = }""")
302
import inspect import unittest from transformers import MobileViTVaConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, MobileViTVaModel from transformers.models.mobilevitva.modeling_mobilevitva import ( MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST, make_divisible, ) if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): def UpperCamelCase_ ( self : str ): '''simple docstring''' __a = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(__lowercase , """width_multiplier""" ) ) class SCREAMING_SNAKE_CASE : def __init__( self : Dict , __lowercase : Union[str, Any] , __lowercase : Dict=13 , __lowercase : int=64 , __lowercase : Tuple=2 , __lowercase : Tuple=3 , __lowercase : Tuple="swish" , __lowercase : List[Any]=3 , __lowercase : List[str]=32 , __lowercase : int=0.1 , __lowercase : Union[str, Any]=0.02 , __lowercase : Optional[int]=True , __lowercase : Dict=True , __lowercase : Tuple=10 , __lowercase : str=None , __lowercase : Optional[Any]=0.25 , __lowercase : str=0.0 , __lowercase : Optional[Any]=0.0 , ): '''simple docstring''' __a = parent __a = batch_size __a = image_size __a = patch_size __a = num_channels __a = make_divisible(512 * width_multiplier , divisor=8 ) __a = hidden_act __a = conv_kernel_size __a = output_stride __a = classifier_dropout_prob __a = use_labels __a = is_training __a = num_labels __a = initializer_range __a = scope __a = width_multiplier __a = ffn_dropout __a = attn_dropout def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' __a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a = None __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.num_labels ) __a = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) __a = self.get_config() return config, pixel_values, labels, pixel_labels def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' return MobileViTVaConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_act=self.hidden_act , conv_kernel_size=self.conv_kernel_size , output_stride=self.output_stride , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , width_multiplier=self.width_multiplier , ffn_dropout=self.ffn_dropout_prob , attn_dropout=self.attn_dropout_prob , ) def UpperCamelCase_ ( self : Tuple , __lowercase : Optional[Any] , __lowercase : int , __lowercase : Optional[Any] , __lowercase : Tuple ): '''simple docstring''' __a = MobileViTVaModel(config=__lowercase ) model.to(__lowercase ) model.eval() __a = model(__lowercase ) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def UpperCamelCase_ ( self : Union[str, Any] , __lowercase : List[Any] , __lowercase : str , __lowercase : Optional[int] , __lowercase : Union[str, Any] ): '''simple docstring''' __a = self.num_labels __a = MobileViTVaForImageClassification(__lowercase ) model.to(__lowercase ) model.eval() __a = model(__lowercase , labels=__lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCamelCase_ ( self : int , __lowercase : str , __lowercase : Any , __lowercase : int , __lowercase : List[str] ): '''simple docstring''' __a = self.num_labels __a = MobileViTVaForSemanticSegmentation(__lowercase ) model.to(__lowercase ) model.eval() __a = model(__lowercase ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) __a = model(__lowercase , labels=__lowercase ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def UpperCamelCase_ ( self : Dict ): '''simple docstring''' __a = self.prepare_config_and_inputs() __a , __a , __a , __a = config_and_inputs __a = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE ( lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase ): __lowerCamelCase : List[Any] =( (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation) if is_torch_available() else () ) __lowerCamelCase : Any =( { 'feature-extraction': MobileViTVaModel, 'image-classification': MobileViTVaForImageClassification, 'image-segmentation': MobileViTVaForSemanticSegmentation, } if is_torch_available() else {} ) __lowerCamelCase : Dict =False __lowerCamelCase : Optional[Any] =False __lowerCamelCase : int =False __lowerCamelCase : Any =False def UpperCamelCase_ ( self : Dict ): '''simple docstring''' __a = MobileViTVaModelTester(self ) __a = MobileViTVaConfigTester(self , config_class=__lowercase , has_text_modality=__lowercase ) def UpperCamelCase_ ( self : Dict ): '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason="""MobileViTV2 does not use inputs_embeds""" ) def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' pass @unittest.skip(reason="""MobileViTV2 does not support input and output embeddings""" ) def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' pass @unittest.skip(reason="""MobileViTV2 does not output attentions""" ) def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' pass @require_torch_multi_gpu @unittest.skip(reason="""Got `CUDA error: misaligned address` for tests after this one being run.""" ) def UpperCamelCase_ ( self : int ): '''simple docstring''' pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' pass def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(__lowercase ) __a = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a = [*signature.parameters.keys()] __a = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , __lowercase ) def UpperCamelCase_ ( self : Dict ): '''simple docstring''' __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowercase ) def UpperCamelCase_ ( self : int ): '''simple docstring''' def check_hidden_states_output(__lowercase : List[str] , __lowercase : Optional[int] , __lowercase : List[str] ): __a = model_class(__lowercase ) model.to(__lowercase ) model.eval() with torch.no_grad(): __a = model(**self._prepare_for_class(__lowercase , __lowercase ) ) __a = outputs.hidden_states __a = 5 self.assertEqual(len(__lowercase ) , __lowercase ) # MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width) # with the width and height being successively divided by 2. __a = 2 for i in range(len(__lowercase ) ): self.assertListEqual( list(hidden_states[i].shape[-2:] ) , [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor] , ) divisor *= 2 self.assertEqual(self.model_tester.output_stride , divisor // 2 ) __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = True check_hidden_states_output(__lowercase , __lowercase , __lowercase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __a = True check_hidden_states_output(__lowercase , __lowercase , __lowercase ) def UpperCamelCase_ ( self : Optional[int] ): '''simple docstring''' __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__lowercase ) def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*__lowercase ) @slow def UpperCamelCase_ ( self : Optional[int] ): '''simple docstring''' for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = MobileViTVaModel.from_pretrained(__lowercase ) self.assertIsNotNone(__lowercase ) def lowerCAmelCase__ ( ): """simple docstring""" __a = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class SCREAMING_SNAKE_CASE ( unittest.TestCase ): @cached_property def UpperCamelCase_ ( self : Dict ): '''simple docstring''' return ( MobileViTImageProcessor.from_pretrained("""apple/mobilevitv2-1.0-imagenet1k-256""" ) if is_vision_available() else None ) @slow def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' __a = MobileViTVaForImageClassification.from_pretrained("""apple/mobilevitv2-1.0-imagenet1k-256""" ).to( __lowercase ) __a = self.default_image_processor __a = prepare_img() __a = image_processor(images=__lowercase , return_tensors="""pt""" ).to(__lowercase ) # forward pass with torch.no_grad(): __a = model(**__lowercase ) # verify the logits __a = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , __lowercase ) __a = torch.tensor([-1.6336E00, -7.3204E-02, -5.1883E-01] ).to(__lowercase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __lowercase , atol=1E-4 ) ) @slow def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' __a = MobileViTVaForSemanticSegmentation.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3""" ) __a = model.to(__lowercase ) __a = MobileViTImageProcessor.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3""" ) __a = prepare_img() __a = image_processor(images=__lowercase , return_tensors="""pt""" ).to(__lowercase ) # forward pass with torch.no_grad(): __a = model(**__lowercase ) __a = outputs.logits # verify the logits __a = torch.Size((1, 21, 32, 32) ) self.assertEqual(logits.shape , __lowercase ) __a = torch.tensor( [ [[7.0863, 7.1525, 6.8201], [6.6931, 6.8770, 6.8933], [6.2978, 7.0366, 6.9636]], [[-3.7134, -3.6712, -3.6675], [-3.5825, -3.3549, -3.4777], [-3.3435, -3.3979, -3.2857]], [[-2.9329, -2.8003, -2.7369], [-3.0564, -2.4780, -2.0207], [-2.6889, -1.9298, -1.7640]], ] , device=__lowercase , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , __lowercase , atol=1E-4 ) ) @slow def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' __a = MobileViTVaForSemanticSegmentation.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3""" ) __a = model.to(__lowercase ) __a = MobileViTImageProcessor.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3""" ) __a = prepare_img() __a = image_processor(images=__lowercase , return_tensors="""pt""" ).to(__lowercase ) # forward pass with torch.no_grad(): __a = model(**__lowercase ) __a = outputs.logits.detach().cpu() __a = image_processor.post_process_semantic_segmentation(outputs=__lowercase , target_sizes=[(50, 60)] ) __a = torch.Size((50, 60) ) self.assertEqual(segmentation[0].shape , __lowercase ) __a = image_processor.post_process_semantic_segmentation(outputs=__lowercase ) __a = torch.Size((32, 32) ) self.assertEqual(segmentation[0].shape , __lowercase )
302
1
import doctest from collections import deque import numpy as np class SCREAMING_SNAKE_CASE : def __init__( self : Union[str, Any] ): '''simple docstring''' __a = [2, 1, 2, -1] __a = [1, 2, 3, 4] def UpperCamelCase_ ( self : int ): '''simple docstring''' __a = len(self.first_signal ) __a = len(self.second_signal ) __a = max(__lowercase , __lowercase ) # create a zero matrix of max_length x max_length __a = [[0] * max_length for i in range(__lowercase )] # fills the smaller signal with zeros to make both signals of same length if length_first_signal < length_second_signal: self.first_signal += [0] * (max_length - length_first_signal) elif length_first_signal > length_second_signal: self.second_signal += [0] * (max_length - length_second_signal) for i in range(__lowercase ): __a = deque(self.second_signal ) rotated_signal.rotate(__lowercase ) for j, item in enumerate(__lowercase ): matrix[i][j] += item # multiply the matrix with the first signal __a = np.matmul(np.transpose(__lowercase ) , np.transpose(self.first_signal ) ) # rounding-off to two decimal places return [round(__lowercase , 2 ) for i in final_signal] if __name__ == "__main__": doctest.testmod()
302
from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import torch from ...utils import BaseOutput, OptionalDependencyNotAvailable, is_torch_available, is_transformers_available @dataclass class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : Union[List[np.ndarray], torch.FloatTensor] 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_text_to_video_synth import TextToVideoSDPipeline from .pipeline_text_to_video_synth_imgaimg import VideoToVideoSDPipeline # noqa: F401 from .pipeline_text_to_video_zero import TextToVideoZeroPipeline
302
1
from __future__ import annotations lowerCamelCase__ = 1.6021e-19 # units = C def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : float , _SCREAMING_SNAKE_CASE : float , _SCREAMING_SNAKE_CASE : float , ): """simple docstring""" if (conductivity, electron_conc, mobility).count(0 ) != 1: raise ValueError("""You cannot supply more or less than 2 values""" ) elif conductivity < 0: raise ValueError("""Conductivity cannot be negative""" ) elif electron_conc < 0: raise ValueError("""Electron concentration cannot be negative""" ) elif mobility < 0: raise ValueError("""mobility cannot be negative""" ) elif conductivity == 0: return ( "conductivity", mobility * electron_conc * ELECTRON_CHARGE, ) elif electron_conc == 0: return ( "electron_conc", conductivity / (mobility * ELECTRON_CHARGE), ) else: return ( "mobility", conductivity / (electron_conc * ELECTRON_CHARGE), ) if __name__ == "__main__": import doctest doctest.testmod()
302
import string import numpy def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int ): """simple docstring""" return b if a == 0 else greatest_common_divisor(b % a , _SCREAMING_SNAKE_CASE ) class SCREAMING_SNAKE_CASE : __lowerCamelCase : List[str] =string.ascii_uppercase + string.digits # This cipher takes alphanumerics into account # i.e. a total of 36 characters # take x and return x % len(key_string) __lowerCamelCase : List[Any] =numpy.vectorize(lambda lowerCamelCase__ : x % 36 ) __lowerCamelCase : Optional[Any] =numpy.vectorize(lowerCamelCase__ ) def __init__( self : Union[str, Any] , __lowercase : numpy.ndarray ): '''simple docstring''' __a = self.modulus(__lowercase ) # mod36 calc's on the encrypt key self.check_determinant() # validate the determinant of the encryption key __a = encrypt_key.shape[0] def UpperCamelCase_ ( self : Dict , __lowercase : str ): '''simple docstring''' return self.key_string.index(__lowercase ) def UpperCamelCase_ ( self : Dict , __lowercase : int ): '''simple docstring''' return self.key_string[round(__lowercase )] def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' __a = round(numpy.linalg.det(self.encrypt_key ) ) if det < 0: __a = det % len(self.key_string ) __a = len(self.key_string ) if greatest_common_divisor(__lowercase , len(self.key_string ) ) != 1: __a = ( F"determinant modular {req_l} of encryption key({det}) " F"is not co prime w.r.t {req_l}.\nTry another key." ) raise ValueError(__lowercase ) def UpperCamelCase_ ( self : Dict , __lowercase : str ): '''simple docstring''' __a = [char for char in text.upper() if char in self.key_string] __a = chars[-1] while len(__lowercase ) % self.break_key != 0: chars.append(__lowercase ) return "".join(__lowercase ) def UpperCamelCase_ ( self : List[str] , __lowercase : str ): '''simple docstring''' __a = self.process_text(text.upper() ) __a = """""" for i in range(0 , len(__lowercase ) - self.break_key + 1 , self.break_key ): __a = text[i : i + self.break_key] __a = [self.replace_letters(__lowercase ) for char in batch] __a = numpy.array([vec] ).T __a = self.modulus(self.encrypt_key.dot(__lowercase ) ).T.tolist()[ 0 ] __a = """""".join( self.replace_digits(__lowercase ) for num in batch_encrypted ) encrypted += encrypted_batch return encrypted def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' __a = round(numpy.linalg.det(self.encrypt_key ) ) if det < 0: __a = det % len(self.key_string ) __a = None for i in range(len(self.key_string ) ): if (det * i) % len(self.key_string ) == 1: __a = i break __a = ( det_inv * numpy.linalg.det(self.encrypt_key ) * numpy.linalg.inv(self.encrypt_key ) ) return self.to_int(self.modulus(__lowercase ) ) def UpperCamelCase_ ( self : Any , __lowercase : str ): '''simple docstring''' __a = self.make_decrypt_key() __a = self.process_text(text.upper() ) __a = """""" for i in range(0 , len(__lowercase ) - self.break_key + 1 , self.break_key ): __a = text[i : i + self.break_key] __a = [self.replace_letters(__lowercase ) for char in batch] __a = numpy.array([vec] ).T __a = self.modulus(decrypt_key.dot(__lowercase ) ).T.tolist()[0] __a = """""".join( self.replace_digits(__lowercase ) for num in batch_decrypted ) decrypted += decrypted_batch return decrypted def lowerCAmelCase__ ( ): """simple docstring""" __a = int(input("""Enter the order of the encryption key: """ ) ) __a = [] print("""Enter each row of the encryption key with space separated integers""" ) for _ in range(_SCREAMING_SNAKE_CASE ): __a = [int(_SCREAMING_SNAKE_CASE ) for x in input().split()] hill_matrix.append(_SCREAMING_SNAKE_CASE ) __a = HillCipher(numpy.array(_SCREAMING_SNAKE_CASE ) ) print("""Would you like to encrypt or decrypt some text? (1 or 2)""" ) __a = input("""\n1. Encrypt\n2. Decrypt\n""" ) if option == "1": __a = input("""What text would you like to encrypt?: """ ) print("""Your encrypted text is:""" ) print(hc.encrypt(_SCREAMING_SNAKE_CASE ) ) elif option == "2": __a = input("""What text would you like to decrypt?: """ ) print("""Your decrypted text is:""" ) print(hc.decrypt(_SCREAMING_SNAKE_CASE ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
302
1
import faiss # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import requests # noqa: F401 # Here to have a nice missing dependency error message early on import sklearn # noqa: F401 # Here to have a nice missing dependency error message early on import tqdm # noqa: F401 # Here to have a nice missing dependency error message early on from mauve import compute_mauve # From: mauve-text import datasets lowerCamelCase__ = """\ @inproceedings{pillutla-etal:mauve:neurips2021, title={MAUVE: Measuring the Gap Between Neural Text and Human Text using Divergence Frontiers}, author={Pillutla, Krishna and Swayamdipta, Swabha and Zellers, Rowan and Thickstun, John and Welleck, Sean and Choi, Yejin and Harchaoui, Zaid}, booktitle = {NeurIPS}, year = {2021} } """ lowerCamelCase__ = """\ MAUVE is a library built on PyTorch and HuggingFace Transformers to measure the gap between neural text and human text with the eponymous MAUVE measure. MAUVE summarizes both Type I and Type II errors measured softly using Kullback–Leibler (KL) divergences. For details, see the MAUVE paper: https://arxiv.org/abs/2102.01454 (Neurips, 2021). This metrics is a wrapper around the official implementation of MAUVE: https://github.com/krishnap25/mauve """ lowerCamelCase__ = """ Calculates MAUVE scores between two lists of generated text and reference text. Args: predictions: list of generated text to score. Each predictions 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. Optional Args: num_buckets: the size of the histogram to quantize P and Q. Options: 'auto' (default) or an integer pca_max_data: the number data points to use for PCA dimensionality reduction prior to clustering. If -1, use all the data. Default -1 kmeans_explained_var: amount of variance of the data to keep in dimensionality reduction by PCA. Default 0.9 kmeans_num_redo: number of times to redo k-means clustering (the best objective is kept). Default 5 kmeans_max_iter: maximum number of k-means iterations. Default 500 featurize_model_name: name of the model from which features are obtained. Default 'gpt2-large' Use one of ['gpt2', 'gpt2-medium', 'gpt2-large', 'gpt2-xl']. device_id: Device for featurization. Supply a GPU id (e.g. 0 or 3) to use GPU. If no GPU with this id is found, use CPU max_text_length: maximum number of tokens to consider. Default 1024 divergence_curve_discretization_size: Number of points to consider on the divergence curve. Default 25 mauve_scaling_factor: \"c\" from the paper. Default 5. verbose: If True (default), print running time updates seed: random seed to initialize k-means cluster assignments. Returns: mauve: MAUVE score, a number between 0 and 1. Larger values indicate that P and Q are closer, frontier_integral: Frontier Integral, a number between 0 and 1. Smaller values indicate that P and Q are closer, divergence_curve: a numpy.ndarray of shape (m, 2); plot it with matplotlib to view the divergence curve, p_hist: a discrete distribution, which is a quantized version of the text distribution p_text, q_hist: same as above, but with q_text. Examples: >>> # faiss segfaults in doctest for some reason, so the .compute call is not tested with doctest >>> import datasets >>> mauve = datasets.load_metric('mauve') >>> predictions = [\"hello there\", \"general kenobi\"] >>> references = [\"hello there\", \"general kenobi\"] >>> out = mauve.compute(predictions=predictions, references=references) # doctest: +SKIP >>> print(out.mauve) # doctest: +SKIP 1.0 """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class SCREAMING_SNAKE_CASE ( datasets.Metric ): def UpperCamelCase_ ( self : int ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage="""https://github.com/krishnap25/mauve""" , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""string""" , id="""sequence""" ), """references""": datasets.Value("""string""" , id="""sequence""" ), } ) , codebase_urls=["""https://github.com/krishnap25/mauve"""] , reference_urls=[ """https://arxiv.org/abs/2102.01454""", """https://github.com/krishnap25/mauve""", ] , ) def UpperCamelCase_ ( self : Optional[Any] , __lowercase : str , __lowercase : Optional[Any] , __lowercase : List[Any]=None , __lowercase : Tuple=None , __lowercase : Union[str, Any]=None , __lowercase : Optional[Any]=None , __lowercase : List[str]="auto" , __lowercase : int=-1 , __lowercase : Tuple=0.9 , __lowercase : Dict=5 , __lowercase : Any=500 , __lowercase : Optional[int]="gpt2-large" , __lowercase : Optional[int]=-1 , __lowercase : Dict=1024 , __lowercase : Any=25 , __lowercase : List[Any]=5 , __lowercase : List[str]=True , __lowercase : List[Any]=25 , ): '''simple docstring''' __a = compute_mauve( p_text=__lowercase , q_text=__lowercase , p_features=__lowercase , q_features=__lowercase , p_tokens=__lowercase , q_tokens=__lowercase , num_buckets=__lowercase , pca_max_data=__lowercase , kmeans_explained_var=__lowercase , kmeans_num_redo=__lowercase , kmeans_max_iter=__lowercase , featurize_model_name=__lowercase , device_id=__lowercase , max_text_length=__lowercase , divergence_curve_discretization_size=__lowercase , mauve_scaling_factor=__lowercase , verbose=__lowercase , seed=__lowercase , ) return out
302
from typing import List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { """huggingface/autoformer-tourism-monthly""": """https://huggingface.co/huggingface/autoformer-tourism-monthly/resolve/main/config.json""", } class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : List[Any] ='autoformer' __lowerCamelCase : str ={ 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', 'num_hidden_layers': 'encoder_layers', } def __init__( self : List[Any] , __lowercase : Optional[int] = None , __lowercase : Optional[int] = None , __lowercase : str = "student_t" , __lowercase : str = "nll" , __lowercase : int = 1 , __lowercase : List[int] = [1, 2, 3, 4, 5, 6, 7] , __lowercase : bool = True , __lowercase : int = 0 , __lowercase : int = 0 , __lowercase : int = 0 , __lowercase : int = 0 , __lowercase : Optional[List[int]] = None , __lowercase : Optional[List[int]] = None , __lowercase : int = 64 , __lowercase : int = 2 , __lowercase : int = 2 , __lowercase : int = 2 , __lowercase : int = 2 , __lowercase : int = 32 , __lowercase : int = 32 , __lowercase : str = "gelu" , __lowercase : float = 0.1 , __lowercase : float = 0.1 , __lowercase : float = 0.1 , __lowercase : float = 0.1 , __lowercase : float = 0.1 , __lowercase : int = 100 , __lowercase : float = 0.02 , __lowercase : bool = True , __lowercase : List[Any]=True , __lowercase : int = 10 , __lowercase : int = 25 , __lowercase : int = 3 , **__lowercase : Optional[int] , ): '''simple docstring''' # time series specific configuration __a = prediction_length __a = context_length if context_length is not None else prediction_length __a = distribution_output __a = loss __a = input_size __a = num_time_features __a = lags_sequence __a = scaling __a = num_dynamic_real_features __a = num_static_real_features __a = num_static_categorical_features if cardinality is not None and num_static_categorical_features > 0: if len(__lowercase ) != num_static_categorical_features: raise ValueError( """The cardinality should be a list of the same length as `num_static_categorical_features`""" ) __a = cardinality else: __a = [0] if embedding_dimension is not None and num_static_categorical_features > 0: if len(__lowercase ) != num_static_categorical_features: raise ValueError( """The embedding dimension should be a list of the same length as `num_static_categorical_features`""" ) __a = embedding_dimension else: __a = [min(50 , (cat + 1) // 2 ) for cat in self.cardinality] __a = num_parallel_samples # Transformer architecture configuration __a = input_size * len(self.lags_sequence ) + self._number_of_features __a = d_model __a = encoder_attention_heads __a = decoder_attention_heads __a = encoder_ffn_dim __a = decoder_ffn_dim __a = encoder_layers __a = decoder_layers __a = dropout __a = attention_dropout __a = activation_dropout __a = encoder_layerdrop __a = decoder_layerdrop __a = activation_function __a = init_std __a = use_cache # Autoformer __a = label_length __a = moving_average __a = autocorrelation_factor super().__init__(is_encoder_decoder=__lowercase , **__lowercase ) @property def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' return ( sum(self.embedding_dimension ) + self.num_dynamic_real_features + self.num_time_features + self.num_static_real_features + self.input_size * 2 # the log1p(abs(loc)) and log(scale) features )
302
1
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse from ...utils.dataclasses import ( ComputeEnvironment, DistributedType, DynamoBackend, PrecisionType, SageMakerDistributedType, ) from ..menu import BulletMenu lowerCamelCase__ = [ """EAGER""", """AOT_EAGER""", """INDUCTOR""", """NVFUSER""", """AOT_NVFUSER""", """AOT_CUDAGRAPHS""", """OFI""", """FX2TRT""", """ONNXRT""", """IPEX""", ] def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Optional[Any]=None , _SCREAMING_SNAKE_CASE : List[str]=None , _SCREAMING_SNAKE_CASE : Any=None ): """simple docstring""" __a = True while ask_again: __a = input(_SCREAMING_SNAKE_CASE ) try: if default is not None and len(_SCREAMING_SNAKE_CASE ) == 0: return default return convert_value(_SCREAMING_SNAKE_CASE ) if convert_value is not None else result except Exception: if error_message is not None: print(_SCREAMING_SNAKE_CASE ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : List[Any]=[] , _SCREAMING_SNAKE_CASE : int=None , _SCREAMING_SNAKE_CASE : Any=0 ): """simple docstring""" __a = BulletMenu(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __a = menu.run(default_choice=_SCREAMING_SNAKE_CASE ) return convert_value(_SCREAMING_SNAKE_CASE ) if convert_value is not None else result def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Optional[int] ): """simple docstring""" __a = int(_SCREAMING_SNAKE_CASE ) return ComputeEnvironment(["""LOCAL_MACHINE""", """AMAZON_SAGEMAKER"""][value] ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Optional[int] ): """simple docstring""" __a = int(_SCREAMING_SNAKE_CASE ) return DistributedType(["""NO""", """MULTI_CPU""", """MULTI_XPU""", """MULTI_GPU""", """MULTI_NPU""", """TPU"""][value] ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : List[Any] ): """simple docstring""" __a = int(_SCREAMING_SNAKE_CASE ) return DynamoBackend(DYNAMO_BACKENDS[value] ).value def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : str ): """simple docstring""" __a = int(_SCREAMING_SNAKE_CASE ) return PrecisionType(["""no""", """fp16""", """bf16""", """fp8"""][value] ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : str ): """simple docstring""" __a = int(_SCREAMING_SNAKE_CASE ) return SageMakerDistributedType(["""NO""", """DATA_PARALLEL""", """MODEL_PARALLEL"""][value] ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : List[Any] ): """simple docstring""" return {"yes": True, "no": False}[value.lower()] class SCREAMING_SNAKE_CASE ( argparse.RawDescriptionHelpFormatter ): def UpperCamelCase_ ( self : List[str] , __lowercase : List[Any] , __lowercase : Dict , __lowercase : Optional[int] , __lowercase : List[str] ): '''simple docstring''' __a = super()._format_usage(__lowercase , __lowercase , __lowercase , __lowercase ) __a = usage.replace("""<command> [<args>] """ , """""" ) return usage
302
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase__ = { """configuration_electra""": ["""ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ElectraConfig""", """ElectraOnnxConfig"""], """tokenization_electra""": ["""ElectraTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = ["""ElectraTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ """ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST""", """ElectraForCausalLM""", """ElectraForMaskedLM""", """ElectraForMultipleChoice""", """ElectraForPreTraining""", """ElectraForQuestionAnswering""", """ElectraForSequenceClassification""", """ElectraForTokenClassification""", """ElectraModel""", """ElectraPreTrainedModel""", """load_tf_weights_in_electra""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ """TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFElectraForMaskedLM""", """TFElectraForMultipleChoice""", """TFElectraForPreTraining""", """TFElectraForQuestionAnswering""", """TFElectraForSequenceClassification""", """TFElectraForTokenClassification""", """TFElectraModel""", """TFElectraPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ """FlaxElectraForCausalLM""", """FlaxElectraForMaskedLM""", """FlaxElectraForMultipleChoice""", """FlaxElectraForPreTraining""", """FlaxElectraForQuestionAnswering""", """FlaxElectraForSequenceClassification""", """FlaxElectraForTokenClassification""", """FlaxElectraModel""", """FlaxElectraPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_electra import ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ElectraConfig, ElectraOnnxConfig from .tokenization_electra import ElectraTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_electra_fast import ElectraTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_electra import ( ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST, ElectraForCausalLM, ElectraForMaskedLM, ElectraForMultipleChoice, ElectraForPreTraining, ElectraForQuestionAnswering, ElectraForSequenceClassification, ElectraForTokenClassification, ElectraModel, ElectraPreTrainedModel, load_tf_weights_in_electra, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_electra import ( TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST, TFElectraForMaskedLM, TFElectraForMultipleChoice, TFElectraForPreTraining, TFElectraForQuestionAnswering, TFElectraForSequenceClassification, TFElectraForTokenClassification, TFElectraModel, TFElectraPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_electra import ( FlaxElectraForCausalLM, FlaxElectraForMaskedLM, FlaxElectraForMultipleChoice, FlaxElectraForPreTraining, FlaxElectraForQuestionAnswering, FlaxElectraForSequenceClassification, FlaxElectraForTokenClassification, FlaxElectraModel, FlaxElectraPreTrainedModel, ) else: import sys lowerCamelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
302
1
from dataclasses import dataclass from typing import Tuple import numpy as np import torch @dataclass class SCREAMING_SNAKE_CASE : __lowerCamelCase : torch.Tensor # [batch_size x 3] __lowerCamelCase : torch.Tensor # [batch_size x 3] __lowerCamelCase : torch.Tensor # [batch_size x 3] __lowerCamelCase : torch.Tensor # [batch_size x 3] __lowerCamelCase : int __lowerCamelCase : int __lowerCamelCase : float __lowerCamelCase : float __lowerCamelCase : Tuple[int] def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' assert self.x.shape[0] == self.y.shape[0] == self.z.shape[0] == self.origin.shape[0] assert self.x.shape[1] == self.y.shape[1] == self.z.shape[1] == self.origin.shape[1] == 3 assert len(self.x.shape ) == len(self.y.shape ) == len(self.z.shape ) == len(self.origin.shape ) == 2 def UpperCamelCase_ ( self : Any ): '''simple docstring''' return torch.from_numpy(np.array([self.width, self.height] , dtype=np.floataa ) ) def UpperCamelCase_ ( self : Dict ): '''simple docstring''' return torch.from_numpy(np.array([self.x_fov, self.y_fov] , dtype=np.floataa ) ) def UpperCamelCase_ ( self : Optional[int] ): '''simple docstring''' __a = torch.arange(self.height * self.width ) __a = torch.stack( [ pixel_indices % self.width, torch.div(__lowercase , self.width , rounding_mode="""trunc""" ), ] , axis=1 , ) return coords @property def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' __a , *__a = self.shape __a = int(np.prod(__lowercase ) ) __a = self.get_image_coords() __a = torch.broadcast_to(coords.unsqueeze(0 ) , [batch_size * inner_batch_size, *coords.shape] ) __a = self.get_camera_rays(__lowercase ) __a = rays.view(__lowercase , inner_batch_size * self.height * self.width , 2 , 3 ) return rays def UpperCamelCase_ ( self : List[Any] , __lowercase : torch.Tensor ): '''simple docstring''' __a , *__a , __a = coords.shape assert n_coords == 2 assert batch_size == self.origin.shape[0] __a = coords.view(__lowercase , -1 , 2 ) __a = self.resolution() __a = self.fov() __a = (flat.float() / (res - 1)) * 2 - 1 __a = fracs * torch.tan(fov / 2 ) __a = fracs.view(__lowercase , -1 , 2 ) __a = ( self.z.view(__lowercase , 1 , 3 ) + self.x.view(__lowercase , 1 , 3 ) * fracs[:, :, :1] + self.y.view(__lowercase , 1 , 3 ) * fracs[:, :, 1:] ) __a = directions / directions.norm(dim=-1 , keepdim=__lowercase ) __a = torch.stack( [ torch.broadcast_to(self.origin.view(__lowercase , 1 , 3 ) , [batch_size, directions.shape[1], 3] ), directions, ] , dim=2 , ) return rays.view(__lowercase , *__lowercase , 2 , 3 ) def UpperCamelCase_ ( self : str , __lowercase : int , __lowercase : int ): '''simple docstring''' assert width * self.height == height * self.width, "The aspect ratio should not change." return DifferentiableProjectiveCamera( origin=self.origin , x=self.x , y=self.y , z=self.z , width=__lowercase , height=__lowercase , x_fov=self.x_fov , y_fov=self.y_fov , ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int ): """simple docstring""" __a = [] __a = [] __a = [] __a = [] for theta in np.linspace(0 , 2 * np.pi , num=20 ): __a = np.array([np.sin(_SCREAMING_SNAKE_CASE ), np.cos(_SCREAMING_SNAKE_CASE ), -0.5] ) z /= np.sqrt(np.sum(z**2 ) ) __a = -z * 4 __a = np.array([np.cos(_SCREAMING_SNAKE_CASE ), -np.sin(_SCREAMING_SNAKE_CASE ), 0.0] ) __a = np.cross(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) origins.append(_SCREAMING_SNAKE_CASE ) xs.append(_SCREAMING_SNAKE_CASE ) ys.append(_SCREAMING_SNAKE_CASE ) zs.append(_SCREAMING_SNAKE_CASE ) return DifferentiableProjectiveCamera( origin=torch.from_numpy(np.stack(_SCREAMING_SNAKE_CASE , axis=0 ) ).float() , x=torch.from_numpy(np.stack(_SCREAMING_SNAKE_CASE , axis=0 ) ).float() , y=torch.from_numpy(np.stack(_SCREAMING_SNAKE_CASE , axis=0 ) ).float() , z=torch.from_numpy(np.stack(_SCREAMING_SNAKE_CASE , axis=0 ) ).float() , width=_SCREAMING_SNAKE_CASE , height=_SCREAMING_SNAKE_CASE , x_fov=0.7 , y_fov=0.7 , shape=(1, len(_SCREAMING_SNAKE_CASE )) , )
302
from __future__ import annotations lowerCamelCase__ = """#""" class SCREAMING_SNAKE_CASE : def __init__( self : Optional[Any] ): '''simple docstring''' __a = {} def UpperCamelCase_ ( self : Optional[Any] , __lowercase : str ): '''simple docstring''' __a = self._trie for char in text: if char not in trie: __a = {} __a = trie[char] __a = True def UpperCamelCase_ ( self : Tuple , __lowercase : str ): '''simple docstring''' __a = self._trie for char in prefix: if char in trie: __a = trie[char] else: return [] return self._elements(__lowercase ) def UpperCamelCase_ ( self : Optional[int] , __lowercase : dict ): '''simple docstring''' __a = [] for c, v in d.items(): __a = [""" """] if c == END else [(c + s) for s in self._elements(__lowercase )] result.extend(__lowercase ) return tuple(__lowercase ) lowerCamelCase__ = Trie() lowerCamelCase__ = ("""depart""", """detergent""", """daring""", """dog""", """deer""", """deal""") for word in words: trie.insert_word(word) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : str ): """simple docstring""" __a = trie.find_word(_SCREAMING_SNAKE_CASE ) return tuple(string + word for word in suffixes ) def lowerCAmelCase__ ( ): """simple docstring""" print(autocomplete_using_trie("""de""" ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
302
1