code
stringlengths
82
53.2k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
"""simple docstring""" import argparse import requests import torch from PIL import Image from transformers import SwinConfig, SwinForMaskedImageModeling, ViTImageProcessor def snake_case ( A__ ): UpperCAmelCase_ : Union[str, Any] = SwinConfig(image_size=1_92 ) if "base" in model_name: UpperCAmelCase_ : Any = 6 UpperCAmelCase_ : Dict = 1_28 UpperCAmelCase_ : List[Any] = (2, 2, 18, 2) UpperCAmelCase_ : Dict = (4, 8, 16, 32) elif "large" in model_name: UpperCAmelCase_ : List[Any] = 12 UpperCAmelCase_ : List[str] = 1_92 UpperCAmelCase_ : Optional[int] = (2, 2, 18, 2) UpperCAmelCase_ : Tuple = (6, 12, 24, 48) else: raise ValueError("Model not supported, only supports base and large variants" ) UpperCAmelCase_ : List[Any] = window_size UpperCAmelCase_ : Union[str, Any] = embed_dim UpperCAmelCase_ : Any = depths UpperCAmelCase_ : str = num_heads return config def snake_case ( A__ ): if "encoder.mask_token" in name: UpperCAmelCase_ : Union[str, Any] = name.replace("encoder.mask_token" ,"embeddings.mask_token" ) if "encoder.patch_embed.proj" in name: UpperCAmelCase_ : Tuple = name.replace("encoder.patch_embed.proj" ,"embeddings.patch_embeddings.projection" ) if "encoder.patch_embed.norm" in name: UpperCAmelCase_ : str = name.replace("encoder.patch_embed.norm" ,"embeddings.norm" ) if "attn.proj" in name: UpperCAmelCase_ : Optional[Any] = name.replace("attn.proj" ,"attention.output.dense" ) if "attn" in name: UpperCAmelCase_ : Tuple = name.replace("attn" ,"attention.self" ) if "norm1" in name: UpperCAmelCase_ : Optional[int] = name.replace("norm1" ,"layernorm_before" ) if "norm2" in name: UpperCAmelCase_ : Tuple = name.replace("norm2" ,"layernorm_after" ) if "mlp.fc1" in name: UpperCAmelCase_ : Union[str, Any] = name.replace("mlp.fc1" ,"intermediate.dense" ) if "mlp.fc2" in name: UpperCAmelCase_ : Any = name.replace("mlp.fc2" ,"output.dense" ) if name == "encoder.norm.weight": UpperCAmelCase_ : Any = "layernorm.weight" if name == "encoder.norm.bias": UpperCAmelCase_ : str = "layernorm.bias" if "decoder" in name: pass else: UpperCAmelCase_ : List[Any] = "swin." + name return name def snake_case ( A__ ,A__ ): for key in orig_state_dict.copy().keys(): UpperCAmelCase_ : Tuple = orig_state_dict.pop(A__ ) if "attn_mask" in key: pass elif "qkv" in key: UpperCAmelCase_ : str = key.split("." ) UpperCAmelCase_ : Optional[int] = int(key_split[2] ) UpperCAmelCase_ : str = int(key_split[4] ) UpperCAmelCase_ : Optional[int] = model.swin.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: UpperCAmelCase_ : List[str] = val[:dim, :] UpperCAmelCase_ : Any = val[ dim : dim * 2, : ] UpperCAmelCase_ : Any = val[-dim:, :] else: UpperCAmelCase_ : Any = val[ :dim ] UpperCAmelCase_ : Optional[Any] = val[ dim : dim * 2 ] UpperCAmelCase_ : Optional[Any] = val[ -dim: ] else: UpperCAmelCase_ : Any = val return orig_state_dict def snake_case ( A__ ,A__ ,A__ ,A__ ): UpperCAmelCase_ : Tuple = torch.load(A__ ,map_location="cpu" )["model"] UpperCAmelCase_ : Dict = get_swin_config(A__ ) UpperCAmelCase_ : int = SwinForMaskedImageModeling(A__ ) model.eval() UpperCAmelCase_ : Dict = convert_state_dict(A__ ,A__ ) model.load_state_dict(A__ ) UpperCAmelCase_ : Dict = "http://images.cocodataset.org/val2017/000000039769.jpg" UpperCAmelCase_ : Optional[Any] = ViTImageProcessor(size={"height": 1_92, "width": 1_92} ) UpperCAmelCase_ : Tuple = Image.open(requests.get(A__ ,stream=A__ ).raw ) UpperCAmelCase_ : Union[str, Any] = image_processor(images=A__ ,return_tensors="pt" ) with torch.no_grad(): UpperCAmelCase_ : Tuple = model(**A__ ).logits print(outputs.keys() ) print("Looks ok!" ) if pytorch_dump_folder_path is not None: print(F"""Saving model {model_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(A__ ) print(F"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(A__ ) if push_to_hub: print(F"""Pushing model and image processor for {model_name} to hub""" ) model.push_to_hub(F"""microsoft/{model_name}""" ) image_processor.push_to_hub(F"""microsoft/{model_name}""" ) if __name__ == "__main__": lowerCamelCase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--model_name''', default='''swin-base-simmim-window6-192''', type=str, choices=['''swin-base-simmim-window6-192''', '''swin-large-simmim-window12-192'''], help='''Name of the Swin SimMIM model you\'d like to convert.''', ) parser.add_argument( '''--checkpoint_path''', default='''/Users/nielsrogge/Documents/SwinSimMIM/simmim_pretrain__swin_base__img192_window6__100ep.pth''', type=str, help='''Path to the original PyTorch checkpoint (.pth file).''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) parser.add_argument( '''--push_to_hub''', action='''store_true''', help='''Whether or not to push the converted model to the 🤗 hub.''' ) lowerCamelCase_ = parser.parse_args() convert_swin_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub)
95
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging __lowercase = logging.get_logger(__name__) if is_vision_available(): import PIL class lowerCamelCase_ ( UpperCAmelCase_ ): '''simple docstring''' a__ : Optional[Any] = ["""pixel_values"""] def __init__( self , __lowercase = True , __lowercase = None , __lowercase = PILImageResampling.BICUBIC , __lowercase = True , __lowercase = None , __lowercase = True , __lowercase = 1 / 255 , __lowercase = True , __lowercase = None , __lowercase = None , __lowercase = True , **__lowercase , ) -> None: super().__init__(**__lowercase) __UpperCamelCase :str = size if size is not None else {'''shortest_edge''': 224} __UpperCamelCase :Tuple = get_size_dict(__lowercase , default_to_square=__lowercase) __UpperCamelCase :List[Any] = crop_size if crop_size is not None else {'''height''': 224, '''width''': 224} __UpperCamelCase :Optional[int] = get_size_dict(__lowercase , default_to_square=__lowercase , param_name='''crop_size''') __UpperCamelCase :List[str] = do_resize __UpperCamelCase :Any = size __UpperCamelCase :Dict = resample __UpperCamelCase :List[Any] = do_center_crop __UpperCamelCase :Any = crop_size __UpperCamelCase :Any = do_rescale __UpperCamelCase :Optional[Any] = rescale_factor __UpperCamelCase :List[str] = do_normalize __UpperCamelCase :List[Any] = image_mean if image_mean is not None else OPENAI_CLIP_MEAN __UpperCamelCase :int = image_std if image_std is not None else OPENAI_CLIP_STD __UpperCamelCase :Tuple = do_convert_rgb def UpperCamelCase__ ( self , __lowercase , __lowercase , __lowercase = PILImageResampling.BICUBIC , __lowercase = None , **__lowercase , ) -> np.ndarray: __UpperCamelCase :Union[str, Any] = get_size_dict(__lowercase , default_to_square=__lowercase) if "shortest_edge" not in size: raise ValueError(f"""The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}""") __UpperCamelCase :Tuple = get_resize_output_image_size(__lowercase , size=size['''shortest_edge'''] , default_to_square=__lowercase) return resize(__lowercase , size=__lowercase , resample=__lowercase , data_format=__lowercase , **__lowercase) def UpperCamelCase__ ( self , __lowercase , __lowercase , __lowercase = None , **__lowercase , ) -> np.ndarray: __UpperCamelCase :Optional[Any] = 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 , __lowercase , __lowercase , __lowercase = None , **__lowercase , ) -> List[Any]: return rescale(__lowercase , scale=__lowercase , data_format=__lowercase , **__lowercase) def UpperCamelCase__ ( self , __lowercase , __lowercase , __lowercase , __lowercase = None , **__lowercase , ) -> np.ndarray: return normalize(__lowercase , mean=__lowercase , std=__lowercase , data_format=__lowercase , **__lowercase) def UpperCamelCase__ ( self , __lowercase , __lowercase = None , __lowercase = None , __lowercase = None , __lowercase = None , __lowercase = None , __lowercase = None , __lowercase = None , __lowercase = None , __lowercase = None , __lowercase = None , __lowercase = None , __lowercase = None , __lowercase = ChannelDimension.FIRST , **__lowercase , ) -> PIL.Image.Image: __UpperCamelCase :List[Any] = do_resize if do_resize is not None else self.do_resize __UpperCamelCase :Optional[int] = size if size is not None else self.size __UpperCamelCase :int = get_size_dict(__lowercase , param_name='''size''' , default_to_square=__lowercase) __UpperCamelCase :str = resample if resample is not None else self.resample __UpperCamelCase :List[str] = do_center_crop if do_center_crop is not None else self.do_center_crop __UpperCamelCase :Dict = crop_size if crop_size is not None else self.crop_size __UpperCamelCase :Dict = get_size_dict(__lowercase , param_name='''crop_size''' , default_to_square=__lowercase) __UpperCamelCase :Dict = do_rescale if do_rescale is not None else self.do_rescale __UpperCamelCase :str = rescale_factor if rescale_factor is not None else self.rescale_factor __UpperCamelCase :Tuple = do_normalize if do_normalize is not None else self.do_normalize __UpperCamelCase :Dict = image_mean if image_mean is not None else self.image_mean __UpperCamelCase :List[Any] = image_std if image_std is not None else self.image_std __UpperCamelCase :List[Any] = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb __UpperCamelCase :Tuple = make_list_of_images(__lowercase) 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.''') if do_normalize and (image_mean is None or image_std is None): raise ValueError('''Image mean and std must be specified if do_normalize is True.''') # PIL RGBA images are converted to RGB if do_convert_rgb: __UpperCamelCase :Optional[int] = [convert_to_rgb(__lowercase) for image in images] # All transformations expect numpy arrays. __UpperCamelCase :Optional[int] = [to_numpy_array(__lowercase) for image in images] if do_resize: __UpperCamelCase :List[Any] = [self.resize(image=__lowercase , size=__lowercase , resample=__lowercase) for image in images] if do_center_crop: __UpperCamelCase :List[Any] = [self.center_crop(image=__lowercase , size=__lowercase) for image in images] if do_rescale: __UpperCamelCase :str = [self.rescale(image=__lowercase , scale=__lowercase) for image in images] if do_normalize: __UpperCamelCase :Union[str, Any] = [self.normalize(image=__lowercase , mean=__lowercase , std=__lowercase) for image in images] __UpperCamelCase :str = [to_channel_dimension_format(__lowercase , __lowercase) for image in images] __UpperCamelCase :Tuple = {'''pixel_values''': images} return BatchFeature(data=__lowercase , tensor_type=__lowercase)
167
0
from __future__ import annotations import math import random from collections.abc import Collection from typing import overload class SCREAMING_SNAKE_CASE_ : """simple docstring""" def __init__( self , _lowerCAmelCase = None ): if components is None: lowerCamelCase__ = [] lowerCamelCase__ = list(_lowerCAmelCase ) def __len__( self ): return len(self.__components ) def __str__( self ): return "(" + ",".join(map(_lowerCAmelCase , self.__components ) ) + ")" def __add__( self , _lowerCAmelCase ): lowerCamelCase__ = len(self ) if size == len(_lowerCAmelCase ): lowerCamelCase__ = [self.__components[i] + other.component(_lowerCAmelCase ) for i in range(_lowerCAmelCase )] return Vector(_lowerCAmelCase ) else: raise Exception("must have the same size" ) def __sub__( self , _lowerCAmelCase ): lowerCamelCase__ = len(self ) if size == len(_lowerCAmelCase ): lowerCamelCase__ = [self.__components[i] - other.component(_lowerCAmelCase ) for i in range(_lowerCAmelCase )] return Vector(_lowerCAmelCase ) else: # error case raise Exception("must have the same size" ) @overload def __mul__( self , _lowerCAmelCase ): ... @overload def __mul__( self , _lowerCAmelCase ): ... def __mul__( self , _lowerCAmelCase ): if isinstance(_lowerCAmelCase , (float, int) ): lowerCamelCase__ = [c * other for c in self.__components] return Vector(_lowerCAmelCase ) elif isinstance(_lowerCAmelCase , _lowerCAmelCase ) and len(self ) == len(_lowerCAmelCase ): lowerCamelCase__ = len(self ) lowerCamelCase__ = [self.__components[i] * other.component(_lowerCAmelCase ) for i in range(_lowerCAmelCase )] return sum(_lowerCAmelCase ) else: # error case raise Exception("invalid operand!" ) def __magic_name__ ( self ): return Vector(self.__components ) def __magic_name__ ( self , _lowerCAmelCase ): if isinstance(_lowerCAmelCase , _lowerCAmelCase ) and -len(self.__components ) <= i < len(self.__components ): return self.__components[i] else: raise Exception("index out of range" ) def __magic_name__ ( self , _lowerCAmelCase , _lowerCAmelCase ): assert -len(self.__components ) <= pos < len(self.__components ) lowerCamelCase__ = value def __magic_name__ ( self ): if len(self.__components ) == 0: raise Exception("Vector is empty" ) lowerCamelCase__ = [c**2 for c in self.__components] return math.sqrt(sum(_lowerCAmelCase ) ) def __magic_name__ ( self , _lowerCAmelCase , _lowerCAmelCase = False ): lowerCamelCase__ = self * other lowerCamelCase__ = self.euclidean_length() * other.euclidean_length() if deg: return math.degrees(math.acos(num / den ) ) else: return math.acos(num / den ) def __UpperCamelCase ( a) ->Vector: assert isinstance(a, a) return Vector([0] * dimension) def __UpperCamelCase ( a, a) ->Vector: assert isinstance(a, a) and (isinstance(a, a)) lowerCamelCase__ = [0] * dimension lowerCamelCase__ = 1 return Vector(a) def __UpperCamelCase ( a, a, a) ->Vector: assert ( isinstance(a, a) and isinstance(a, a) and (isinstance(a, (int, float))) ) return x * scalar + y def __UpperCamelCase ( a, a, a) ->Vector: random.seed(a) lowerCamelCase__ = [random.randint(a, a) for _ in range(a)] return Vector(a) class SCREAMING_SNAKE_CASE_ : """simple docstring""" def __init__( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): lowerCamelCase__ = matrix lowerCamelCase__ = w lowerCamelCase__ = h def __str__( self ): lowerCamelCase__ = "" for i in range(self.__height ): ans += "|" for j in range(self.__width ): if j < self.__width - 1: ans += str(self.__matrix[i][j] ) + "," else: ans += str(self.__matrix[i][j] ) + "|\n" return ans def __add__( self , _lowerCAmelCase ): if self.__width == other.width() and self.__height == other.height(): lowerCamelCase__ = [] for i in range(self.__height ): lowerCamelCase__ = [ self.__matrix[i][j] + other.component(_lowerCAmelCase , _lowerCAmelCase ) for j in range(self.__width ) ] matrix.append(_lowerCAmelCase ) return Matrix(_lowerCAmelCase , self.__width , self.__height ) else: raise Exception("matrix must have the same dimension!" ) def __sub__( self , _lowerCAmelCase ): if self.__width == other.width() and self.__height == other.height(): lowerCamelCase__ = [] for i in range(self.__height ): lowerCamelCase__ = [ self.__matrix[i][j] - other.component(_lowerCAmelCase , _lowerCAmelCase ) for j in range(self.__width ) ] matrix.append(_lowerCAmelCase ) return Matrix(_lowerCAmelCase , self.__width , self.__height ) else: raise Exception("matrices must have the same dimension!" ) @overload def __mul__( self , _lowerCAmelCase ): ... @overload def __mul__( self , _lowerCAmelCase ): ... def __mul__( self , _lowerCAmelCase ): if isinstance(_lowerCAmelCase , _lowerCAmelCase ): # matrix-vector if len(_lowerCAmelCase ) == self.__width: lowerCamelCase__ = zero_vector(self.__height ) for i in range(self.__height ): lowerCamelCase__ = [ self.__matrix[i][j] * other.component(_lowerCAmelCase ) for j in range(self.__width ) ] ans.change_component(_lowerCAmelCase , sum(_lowerCAmelCase ) ) return ans else: raise Exception( "vector must have the same size as the " "number of columns of the matrix!" ) elif isinstance(_lowerCAmelCase , (int, float) ): # matrix-scalar lowerCamelCase__ = [ [self.__matrix[i][j] * other for j in range(self.__width )] for i in range(self.__height ) ] return Matrix(_lowerCAmelCase , self.__width , self.__height ) return None def __magic_name__ ( self ): return self.__height def __magic_name__ ( self ): return self.__width def __magic_name__ ( self , _lowerCAmelCase , _lowerCAmelCase ): if 0 <= x < self.__height and 0 <= y < self.__width: return self.__matrix[x][y] else: raise Exception("change_component: indices out of bounds" ) def __magic_name__ ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): if 0 <= x < self.__height and 0 <= y < self.__width: lowerCamelCase__ = value else: raise Exception("change_component: indices out of bounds" ) def __magic_name__ ( self , _lowerCAmelCase , _lowerCAmelCase ): if self.__height != self.__width: raise Exception("Matrix is not square" ) lowerCamelCase__ = self.__matrix[:x] + self.__matrix[x + 1 :] for i in range(len(_lowerCAmelCase ) ): lowerCamelCase__ = minor[i][:y] + minor[i][y + 1 :] return Matrix(_lowerCAmelCase , self.__width - 1 , self.__height - 1 ).determinant() def __magic_name__ ( self , _lowerCAmelCase , _lowerCAmelCase ): if self.__height != self.__width: raise Exception("Matrix is not square" ) if 0 <= x < self.__height and 0 <= y < self.__width: return (-1) ** (x + y) * self.minor(_lowerCAmelCase , _lowerCAmelCase ) else: raise Exception("Indices out of bounds" ) def __magic_name__ ( self ): if self.__height != self.__width: raise Exception("Matrix is not square" ) if self.__height < 1: raise Exception("Matrix has no element" ) elif self.__height == 1: return self.__matrix[0][0] elif self.__height == 2: return ( self.__matrix[0][0] * self.__matrix[1][1] - self.__matrix[0][1] * self.__matrix[1][0] ) else: lowerCamelCase__ = [ self.__matrix[0][y] * self.cofactor(0 , _lowerCAmelCase ) for y in range(self.__width ) ] return sum(_lowerCAmelCase ) def __UpperCamelCase ( a) ->Matrix: lowerCamelCase__ = [[0] * n for _ in range(a)] return Matrix(a, a, a) def __UpperCamelCase ( a, a, a, a) ->Matrix: random.seed(a) lowerCamelCase__ = [ [random.randint(a, a) for _ in range(a)] for _ in range(a) ] return Matrix(a, a, a)
360
from collections import OrderedDict from typing import TYPE_CHECKING, Any, List, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import TensorType, logging if TYPE_CHECKING: from ...onnx.config import PatchingSpec from ...tokenization_utils_base import PreTrainedTokenizerBase A_ = logging.get_logger(__name__) A_ = { "allenai/longformer-base-4096": "https://huggingface.co/allenai/longformer-base-4096/resolve/main/config.json", "allenai/longformer-large-4096": "https://huggingface.co/allenai/longformer-large-4096/resolve/main/config.json", "allenai/longformer-large-4096-finetuned-triviaqa": ( "https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/config.json" ), "allenai/longformer-base-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/config.json" ), "allenai/longformer-large-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/config.json" ), } class SCREAMING_SNAKE_CASE_ ( lowercase_ ): """simple docstring""" A__ = "longformer" def __init__( self , _lowerCAmelCase = 512 , _lowerCAmelCase = 2 , _lowerCAmelCase = 1 , _lowerCAmelCase = 0 , _lowerCAmelCase = 2 , _lowerCAmelCase = 3_0522 , _lowerCAmelCase = 768 , _lowerCAmelCase = 12 , _lowerCAmelCase = 12 , _lowerCAmelCase = 3072 , _lowerCAmelCase = "gelu" , _lowerCAmelCase = 0.1 , _lowerCAmelCase = 0.1 , _lowerCAmelCase = 512 , _lowerCAmelCase = 2 , _lowerCAmelCase = 0.02 , _lowerCAmelCase = 1E-12 , _lowerCAmelCase = False , **_lowerCAmelCase , ): super().__init__(pad_token_id=_lowerCAmelCase , **_lowerCAmelCase ) lowerCamelCase__ = attention_window lowerCamelCase__ = sep_token_id lowerCamelCase__ = bos_token_id lowerCamelCase__ = eos_token_id lowerCamelCase__ = vocab_size lowerCamelCase__ = hidden_size lowerCamelCase__ = num_hidden_layers lowerCamelCase__ = num_attention_heads lowerCamelCase__ = hidden_act lowerCamelCase__ = intermediate_size lowerCamelCase__ = hidden_dropout_prob lowerCamelCase__ = attention_probs_dropout_prob lowerCamelCase__ = max_position_embeddings lowerCamelCase__ = type_vocab_size lowerCamelCase__ = initializer_range lowerCamelCase__ = layer_norm_eps lowerCamelCase__ = onnx_export class SCREAMING_SNAKE_CASE_ ( lowercase_ ): """simple docstring""" def __init__( self , _lowerCAmelCase , _lowerCAmelCase = "default" , _lowerCAmelCase = None ): super().__init__(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) lowerCamelCase__ = True @property def __magic_name__ ( self ): if self.task == "multiple-choice": lowerCamelCase__ = {0: "batch", 1: "choice", 2: "sequence"} else: lowerCamelCase__ = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ("global_attention_mask", dynamic_axis), ] ) @property def __magic_name__ ( self ): lowerCamelCase__ = super().outputs if self.task == "default": lowerCamelCase__ = {0: "batch"} return outputs @property def __magic_name__ ( self ): return 1E-4 @property def __magic_name__ ( self ): # needs to be >= 14 to support tril operator return max(super().default_onnx_opset , 14 ) def __magic_name__ ( self , _lowerCAmelCase , _lowerCAmelCase = -1 , _lowerCAmelCase = -1 , _lowerCAmelCase = False , _lowerCAmelCase = None , ): lowerCamelCase__ = super().generate_dummy_inputs( preprocessor=_lowerCAmelCase , batch_size=_lowerCAmelCase , seq_length=_lowerCAmelCase , is_pair=_lowerCAmelCase , framework=_lowerCAmelCase ) import torch # for some reason, replacing this code by inputs["global_attention_mask"] = torch.randint(2, inputs["input_ids"].shape, dtype=torch.int64) # makes the export fail randomly lowerCamelCase__ = torch.zeros_like(inputs["input_ids"] ) # make every second token global lowerCamelCase__ = 1 return inputs
360
1
'''simple docstring''' import dataclasses import re import string from typing import Any, Dict, Iterator, List, Mapping, Optional, Sequence, Tuple import numpy as np from . import residue_constants __UpperCamelCase = Mapping[str, np.ndarray] __UpperCamelCase = Mapping[str, Any] # Is a nested dict. __UpperCamelCase = 0.01 @dataclasses.dataclass(frozen=__lowercase ) class _A : lowercase__: np.ndarray # [num_res, num_atom_type, 3] # Amino-acid type for each residue represented as an integer between 0 and # 20, where 20 is 'X'. lowercase__: np.ndarray # [num_res] # Binary float mask to indicate presence of a particular atom. 1.0 if an atom # is present and 0.0 if not. This should be used for loss masking. lowercase__: np.ndarray # [num_res, num_atom_type] # Residue index as used in PDB. It is not necessarily continuous or 0-indexed. lowercase__: np.ndarray # [num_res] # B-factors, or temperature factors, of each residue (in sq. angstroms units), # representing the displacement of the residue from its ground truth mean # value. lowercase__: np.ndarray # [num_res, num_atom_type] # Chain indices for multi-chain predictions lowercase__: Optional[np.ndarray] = None # Optional remark about the protein. Included as a comment in output PDB # files lowercase__: Optional[str] = None # Templates used to generate this protein (prediction-only) lowercase__: Optional[Sequence[str]] = None # Chain corresponding to each parent lowercase__: Optional[Sequence[int]] = None def _a ( _lowerCamelCase ) -> Protein: """simple docstring""" __snake_case : List[str] = R"""(\[[A-Z]+\]\n)""" __snake_case : List[str] = [tag.strip() for tag in re.split(_lowerCamelCase , _lowerCamelCase ) if len(_lowerCamelCase ) > 0] __snake_case : Iterator[Tuple[str, List[str]]] = zip(tags[0::2] , [l.split("""\n""" ) for l in tags[1::2]] ) __snake_case : List[str] = ["N", "CA", "C"] __snake_case : Union[str, Any] = None __snake_case : Optional[Any] = None __snake_case : str = None for g in groups: if "[PRIMARY]" == g[0]: __snake_case : Any = g[1][0].strip() for i in range(len(_lowerCamelCase ) ): if seq[i] not in residue_constants.restypes: __snake_case : Union[str, Any] = """X""" # FIXME: strings are immutable __snake_case : Optional[Any] = np.array( [residue_constants.restype_order.get(_lowerCamelCase , residue_constants.restype_num ) for res_symbol in seq] ) elif "[TERTIARY]" == g[0]: __snake_case : List[List[float]] = [] for axis in range(3 ): tertiary.append(list(map(_lowerCamelCase , g[1][axis].split() ) ) ) __snake_case : Optional[Any] = np.array(_lowerCamelCase ) __snake_case : Any = np.zeros((len(tertiary[0] ) // 3, residue_constants.atom_type_num, 3) ).astype(np.floataa ) for i, atom in enumerate(_lowerCamelCase ): __snake_case : Union[str, Any] = np.transpose(tertiary_np[:, i::3] ) atom_positions *= PICO_TO_ANGSTROM elif "[MASK]" == g[0]: __snake_case : Union[str, Any] = np.array(list(map({"""-""": 0, """+""": 1}.get , g[1][0].strip() ) ) ) __snake_case : List[str] = np.zeros( ( len(_lowerCamelCase ), residue_constants.atom_type_num, ) ).astype(np.floataa ) for i, atom in enumerate(_lowerCamelCase ): __snake_case : Optional[Any] = 1 atom_mask *= mask[..., None] assert aatype is not None return Protein( atom_positions=_lowerCamelCase , atom_mask=_lowerCamelCase , aatype=_lowerCamelCase , residue_index=np.arange(len(_lowerCamelCase ) ) , b_factors=_lowerCamelCase , ) def _a ( _lowerCamelCase , _lowerCamelCase = 0 ) -> List[str]: """simple docstring""" __snake_case : List[str] = [] __snake_case : Tuple = prot.remark if remark is not None: pdb_headers.append(F'''REMARK {remark}''' ) __snake_case : Optional[int] = prot.parents __snake_case : Optional[int] = prot.parents_chain_index if parents is not None and parents_chain_index is not None: __snake_case : Any = [p for i, p in zip(_lowerCamelCase , _lowerCamelCase ) if i == chain_id] if parents is None or len(_lowerCamelCase ) == 0: __snake_case : str = ["""N/A"""] pdb_headers.append(F'''PARENT {" ".join(_lowerCamelCase )}''' ) return pdb_headers def _a ( _lowerCamelCase , _lowerCamelCase ) -> str: """simple docstring""" __snake_case : List[str] = [] __snake_case : int = pdb_str.split("""\n""" ) __snake_case : Union[str, Any] = prot.remark if remark is not None: out_pdb_lines.append(F'''REMARK {remark}''' ) __snake_case : List[List[str]] if prot.parents is not None and len(prot.parents ) > 0: __snake_case : Union[str, Any] = [] if prot.parents_chain_index is not None: __snake_case : Dict[str, List[str]] = {} for p, i in zip(prot.parents , prot.parents_chain_index ): parent_dict.setdefault(str(_lowerCamelCase ) , [] ) parent_dict[str(_lowerCamelCase )].append(_lowerCamelCase ) __snake_case : Optional[int] = max([int(_lowerCamelCase ) for chain_idx in parent_dict] ) for i in range(max_idx + 1 ): __snake_case : Tuple = parent_dict.get(str(_lowerCamelCase ) , ["""N/A"""] ) parents_per_chain.append(_lowerCamelCase ) else: parents_per_chain.append(list(prot.parents ) ) else: __snake_case : Dict = [["""N/A"""]] def make_parent_line(_lowerCamelCase ) -> str: return F'''PARENT {" ".join(_lowerCamelCase )}''' out_pdb_lines.append(make_parent_line(parents_per_chain[0] ) ) __snake_case : Any = 0 for i, l in enumerate(_lowerCamelCase ): if "PARENT" not in l and "REMARK" not in l: out_pdb_lines.append(_lowerCamelCase ) if "TER" in l and "END" not in lines[i + 1]: chain_counter += 1 if not chain_counter >= len(_lowerCamelCase ): __snake_case : int = parents_per_chain[chain_counter] else: __snake_case : int = ["""N/A"""] out_pdb_lines.append(make_parent_line(_lowerCamelCase ) ) return "\n".join(_lowerCamelCase ) def _a ( _lowerCamelCase ) -> str: """simple docstring""" __snake_case : Optional[int] = residue_constants.restypes + ["""X"""] def res_atoa(_lowerCamelCase ) -> str: return residue_constants.restype_atoa.get(restypes[r] , """UNK""" ) __snake_case : Union[str, Any] = residue_constants.atom_types __snake_case : List[str] = [] __snake_case : int = prot.atom_mask __snake_case : Optional[int] = prot.aatype __snake_case : List[str] = prot.atom_positions __snake_case : str = prot.residue_index.astype(np.intaa ) __snake_case : Optional[int] = prot.b_factors __snake_case : str = prot.chain_index if np.any(aatype > residue_constants.restype_num ): raise ValueError("""Invalid aatypes.""" ) __snake_case : Optional[int] = get_pdb_headers(_lowerCamelCase ) if len(_lowerCamelCase ) > 0: pdb_lines.extend(_lowerCamelCase ) __snake_case : Dict = aatype.shape[0] __snake_case : Optional[int] = 1 __snake_case : List[str] = 0 __snake_case : Optional[Any] = string.ascii_uppercase __snake_case : Tuple = None # Add all atom sites. for i in range(_lowerCamelCase ): __snake_case : Optional[Any] = res_atoa(aatype[i] ) for atom_name, pos, mask, b_factor in zip(_lowerCamelCase , atom_positions[i] , atom_mask[i] , b_factors[i] ): if mask < 0.5: continue __snake_case : int = """ATOM""" __snake_case : int = atom_name if len(_lowerCamelCase ) == 4 else F''' {atom_name}''' __snake_case : List[str] = """""" __snake_case : Optional[Any] = """""" __snake_case : Any = 1.00 __snake_case : Optional[Any] = atom_name[0] # Protein supports only C, N, O, S, this works. __snake_case : List[Any] = """""" __snake_case : Tuple = """A""" if chain_index is not None: __snake_case : Optional[int] = chain_tags[chain_index[i]] # PDB is a columnar format, every space matters here! __snake_case : Optional[int] = ( F'''{record_type:<6}{atom_index:>5} {name:<4}{alt_loc:>1}''' F'''{res_name_a:>3} {chain_tag:>1}''' F'''{residue_index[i]:>4}{insertion_code:>1} ''' F'''{pos[0]:>8.3f}{pos[1]:>8.3f}{pos[2]:>8.3f}''' F'''{occupancy:>6.2f}{b_factor:>6.2f} ''' F'''{element:>2}{charge:>2}''' ) pdb_lines.append(_lowerCamelCase ) atom_index += 1 __snake_case : List[str] = i == n - 1 if chain_index is not None: if i != n - 1 and chain_index[i + 1] != prev_chain_index: __snake_case : Optional[Any] = True __snake_case : Union[str, Any] = chain_index[i + 1] if should_terminate: # Close the chain. __snake_case : Optional[Any] = """TER""" __snake_case : List[str] = ( F'''{chain_end:<6}{atom_index:>5} {res_atoa(aatype[i] ):>3} {chain_tag:>1}{residue_index[i]:>4}''' ) pdb_lines.append(_lowerCamelCase ) atom_index += 1 if i != n - 1: # "prev" is a misnomer here. This happens at the beginning of # each new chain. pdb_lines.extend(get_pdb_headers(_lowerCamelCase , _lowerCamelCase ) ) pdb_lines.append("""END""" ) pdb_lines.append("""""" ) return "\n".join(_lowerCamelCase ) def _a ( _lowerCamelCase ) -> np.ndarray: """simple docstring""" return residue_constants.STANDARD_ATOM_MASK[prot.aatype] def _a ( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , ) -> Protein: """simple docstring""" return Protein( aatype=features["""aatype"""] , atom_positions=result["""final_atom_positions"""] , atom_mask=result["""final_atom_mask"""] , residue_index=features["""residue_index"""] + 1 , b_factors=b_factors if b_factors is not None else np.zeros_like(result["""final_atom_mask"""] ) , chain_index=_lowerCamelCase , remark=_lowerCamelCase , parents=_lowerCamelCase , parents_chain_index=_lowerCamelCase , )
26
'''simple docstring''' def _a ( _lowerCamelCase ) -> int: """simple docstring""" if not isinstance(_lowerCamelCase , _lowerCamelCase ): raise TypeError("""only integers accepted as input""" ) else: __snake_case : List[Any] = str(abs(_lowerCamelCase ) ) __snake_case : Union[str, Any] = [list(_lowerCamelCase ) for char in range(len(_lowerCamelCase ) )] for index in range(len(_lowerCamelCase ) ): num_transpositions[index].pop(_lowerCamelCase ) return max( int("""""".join(list(_lowerCamelCase ) ) ) for transposition in num_transpositions ) if __name__ == "__main__": __import__("doctest").testmod()
26
1
import copy import inspect import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import TimesformerConfig from transformers.models.auto import get_values 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 ( MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, TimesformerForVideoClassification, TimesformerModel, ) from transformers.models.timesformer.modeling_timesformer import TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from transformers import VideoMAEImageProcessor class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Any , snake_case__ : Optional[Any] , snake_case__ : Optional[int]=1_3 , snake_case__ : Dict=1_0 , snake_case__ : int=3 , snake_case__ : Any=2 , snake_case__ : Tuple=2 , snake_case__ : Tuple=True , snake_case__ : Any=True , snake_case__ : Union[str, Any]=3_2 , snake_case__ : Tuple=5 , snake_case__ : List[Any]=4 , snake_case__ : str=3_7 , snake_case__ : Union[str, Any]="gelu" , snake_case__ : List[Any]=0.1 , snake_case__ : List[Any]=0.1 , snake_case__ : Any=1_0 , snake_case__ : Optional[Any]=0.02 , snake_case__ : List[str]="divided_space_time" , snake_case__ : List[str]=None , ) -> Dict: _lowerCamelCase = parent _lowerCamelCase = batch_size _lowerCamelCase = image_size _lowerCamelCase = num_channels _lowerCamelCase = patch_size _lowerCamelCase = num_frames _lowerCamelCase = is_training _lowerCamelCase = use_labels _lowerCamelCase = hidden_size _lowerCamelCase = num_hidden_layers _lowerCamelCase = num_attention_heads _lowerCamelCase = intermediate_size _lowerCamelCase = hidden_act _lowerCamelCase = hidden_dropout_prob _lowerCamelCase = attention_probs_dropout_prob _lowerCamelCase = attention_type _lowerCamelCase = initializer_range _lowerCamelCase = scope _lowerCamelCase = num_labels # in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token _lowerCamelCase = (image_size // patch_size) ** 2 _lowerCamelCase = (num_frames) * self.num_patches_per_frame + 1 def _snake_case ( self : Union[str, Any] ) -> Optional[int]: _lowerCamelCase = floats_tensor( [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size] ) _lowerCamelCase = None if self.use_labels: _lowerCamelCase = ids_tensor([self.batch_size] , self.num_labels ) _lowerCamelCase = self.get_config() return config, pixel_values, labels def _snake_case ( self : Tuple ) -> Optional[int]: _lowerCamelCase = TimesformerConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_frames=self.num_frames , 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 , initializer_range=self.initializer_range , attention_type=self.attention_type , ) _lowerCamelCase = self.num_labels return config def _snake_case ( self : Union[str, Any] , snake_case__ : Dict , snake_case__ : Optional[Any] , snake_case__ : Union[str, Any] ) -> Tuple: _lowerCamelCase = TimesformerModel(config=snake_case__ ) model.to(snake_case__ ) model.eval() _lowerCamelCase = model(snake_case__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _snake_case ( self : Dict , snake_case__ : Optional[Any] , snake_case__ : str , snake_case__ : str ) -> List[Any]: _lowerCamelCase = TimesformerForVideoClassification(snake_case__ ) model.to(snake_case__ ) model.eval() _lowerCamelCase = model(snake_case__ ) # verify the logits shape _lowerCamelCase = torch.Size((self.batch_size, self.num_labels) ) self.parent.assertEqual(result.logits.shape , snake_case__ ) def _snake_case ( self : List[Any] ) -> List[str]: _lowerCamelCase = self.prepare_config_and_inputs() _lowerCamelCase , _lowerCamelCase , _lowerCamelCase = config_and_inputs _lowerCamelCase = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,unittest.TestCase ): '''simple docstring''' lowerCAmelCase_ = (TimesformerModel, TimesformerForVideoClassification) if is_torch_available() else () lowerCAmelCase_ = ( {'feature-extraction': TimesformerModel, 'video-classification': TimesformerForVideoClassification} if is_torch_available() else {} ) lowerCAmelCase_ = False lowerCAmelCase_ = False lowerCAmelCase_ = False lowerCAmelCase_ = False def _snake_case ( self : List[Any] ) -> List[Any]: _lowerCamelCase = TimesformerModelTester(self ) _lowerCamelCase = ConfigTester( self , config_class=snake_case__ , has_text_modality=snake_case__ , hidden_size=3_7 ) def _snake_case ( self : Tuple , snake_case__ : List[str] , snake_case__ : Tuple , snake_case__ : Tuple=False ) -> List[str]: _lowerCamelCase = copy.deepcopy(snake_case__ ) if return_labels: if model_class in get_values(snake_case__ ): _lowerCamelCase = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=snake_case__ ) return inputs_dict def _snake_case ( self : List[Any] ) -> str: self.config_tester.run_common_tests() @unittest.skip(reason='TimeSformer does not use inputs_embeds' ) def _snake_case ( self : str ) -> int: pass def _snake_case ( self : Tuple ) -> Union[str, Any]: _lowerCamelCase , _lowerCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCamelCase = model_class(snake_case__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) _lowerCamelCase = model.get_output_embeddings() self.assertTrue(x is None or isinstance(snake_case__ , nn.Linear ) ) def _snake_case ( self : List[str] ) -> Any: _lowerCamelCase , _lowerCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCamelCase = model_class(snake_case__ ) _lowerCamelCase = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _lowerCamelCase = [*signature.parameters.keys()] _lowerCamelCase = ['pixel_values'] self.assertListEqual(arg_names[:1] , snake_case__ ) def _snake_case ( self : Tuple ) -> Dict: _lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case__ ) def _snake_case ( self : Dict ) -> Union[str, Any]: _lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_video_classification(*snake_case__ ) @slow def _snake_case ( self : Tuple ) -> Dict: for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCamelCase = TimesformerModel.from_pretrained(snake_case__ ) self.assertIsNotNone(snake_case__ ) def _snake_case ( self : Any ) -> Any: if not self.has_attentions: pass else: _lowerCamelCase , _lowerCamelCase = self.model_tester.prepare_config_and_inputs_for_common() _lowerCamelCase = True for model_class in self.all_model_classes: _lowerCamelCase = self.model_tester.seq_length _lowerCamelCase = self.model_tester.num_frames _lowerCamelCase = True _lowerCamelCase = False _lowerCamelCase = True _lowerCamelCase = model_class(snake_case__ ) model.to(snake_case__ ) model.eval() with torch.no_grad(): _lowerCamelCase = model(**self._prepare_for_class(snake_case__ , snake_case__ ) ) _lowerCamelCase = outputs.attentions self.assertEqual(len(snake_case__ ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] _lowerCamelCase = True _lowerCamelCase = model_class(snake_case__ ) model.to(snake_case__ ) model.eval() with torch.no_grad(): _lowerCamelCase = model(**self._prepare_for_class(snake_case__ , snake_case__ ) ) _lowerCamelCase = outputs.attentions self.assertEqual(len(snake_case__ ) , self.model_tester.num_hidden_layers ) # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] , ) _lowerCamelCase = len(snake_case__ ) # Check attention is always last and order is fine _lowerCamelCase = True _lowerCamelCase = True _lowerCamelCase = model_class(snake_case__ ) model.to(snake_case__ ) model.eval() with torch.no_grad(): _lowerCamelCase = model(**self._prepare_for_class(snake_case__ , snake_case__ ) ) self.assertEqual(out_len + 1 , len(snake_case__ ) ) _lowerCamelCase = outputs.attentions self.assertEqual(len(snake_case__ ) , self.model_tester.num_hidden_layers ) # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] , ) def _snake_case ( self : Optional[Any] ) -> Optional[int]: def check_hidden_states_output(snake_case__ : List[str] , snake_case__ : Optional[int] , snake_case__ : str ): _lowerCamelCase = model_class(snake_case__ ) model.to(snake_case__ ) model.eval() with torch.no_grad(): _lowerCamelCase = model(**self._prepare_for_class(snake_case__ , snake_case__ ) ) _lowerCamelCase = outputs.hidden_states _lowerCamelCase = self.model_tester.num_hidden_layers + 1 self.assertEqual(len(snake_case__ ) , snake_case__ ) _lowerCamelCase = self.model_tester.seq_length self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) _lowerCamelCase , _lowerCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCamelCase = True check_hidden_states_output(snake_case__ , snake_case__ , snake_case__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _lowerCamelCase = True check_hidden_states_output(snake_case__ , snake_case__ , snake_case__ ) def lowerCamelCase ( ) -> str: _lowerCamelCase = hf_hub_download( repo_id='hf-internal-testing/spaghetti-video' , filename='eating_spaghetti.npy' , repo_type='dataset' ) _lowerCamelCase = np.load(UpperCamelCase ) return list(UpperCamelCase ) @require_torch @require_vision class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @cached_property def _snake_case ( self : Tuple ) -> Tuple: # logits were tested with a different mean and std, so we use the same here return ( VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5] , image_std=[0.5, 0.5, 0.5] ) if is_vision_available() else None ) @slow def _snake_case ( self : Dict ) -> Any: _lowerCamelCase = TimesformerForVideoClassification.from_pretrained('facebook/timesformer-base-finetuned-k400' ).to( snake_case__ ) _lowerCamelCase = self.default_image_processor _lowerCamelCase = prepare_video() _lowerCamelCase = image_processor(video[:8] , return_tensors='pt' ).to(snake_case__ ) # forward pass with torch.no_grad(): _lowerCamelCase = model(**snake_case__ ) # verify the logits _lowerCamelCase = torch.Size((1, 4_0_0) ) self.assertEqual(outputs.logits.shape , snake_case__ ) _lowerCamelCase = torch.tensor([-0.3016, -0.7713, -0.4205] ).to(snake_case__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , snake_case__ , atol=1e-4 ) )
234
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( BertTokenizer, ViltConfig, ViltForImageAndTextRetrieval, ViltForImagesAndTextClassification, ViltForMaskedLM, ViltForQuestionAnswering, ViltImageProcessor, ViltProcessor, ) from transformers.utils import logging logging.set_verbosity_info() A = logging.get_logger(__name__) def lowerCamelCase ( UpperCamelCase : str , UpperCamelCase : Any=False , UpperCamelCase : Union[str, Any]=False , UpperCamelCase : List[Any]=False ) -> List[str]: _lowerCamelCase = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F"""transformer.blocks.{i}.norm1.weight""", F"""vilt.encoder.layer.{i}.layernorm_before.weight""") ) rename_keys.append((F"""transformer.blocks.{i}.norm1.bias""", F"""vilt.encoder.layer.{i}.layernorm_before.bias""") ) rename_keys.append( (F"""transformer.blocks.{i}.attn.proj.weight""", F"""vilt.encoder.layer.{i}.attention.output.dense.weight""") ) rename_keys.append( (F"""transformer.blocks.{i}.attn.proj.bias""", F"""vilt.encoder.layer.{i}.attention.output.dense.bias""") ) rename_keys.append((F"""transformer.blocks.{i}.norm2.weight""", F"""vilt.encoder.layer.{i}.layernorm_after.weight""") ) rename_keys.append((F"""transformer.blocks.{i}.norm2.bias""", F"""vilt.encoder.layer.{i}.layernorm_after.bias""") ) rename_keys.append( (F"""transformer.blocks.{i}.mlp.fc1.weight""", F"""vilt.encoder.layer.{i}.intermediate.dense.weight""") ) rename_keys.append((F"""transformer.blocks.{i}.mlp.fc1.bias""", F"""vilt.encoder.layer.{i}.intermediate.dense.bias""") ) rename_keys.append((F"""transformer.blocks.{i}.mlp.fc2.weight""", F"""vilt.encoder.layer.{i}.output.dense.weight""") ) rename_keys.append((F"""transformer.blocks.{i}.mlp.fc2.bias""", F"""vilt.encoder.layer.{i}.output.dense.bias""") ) # embeddings rename_keys.extend( [ # text embeddings ('text_embeddings.word_embeddings.weight', 'vilt.embeddings.text_embeddings.word_embeddings.weight'), ( 'text_embeddings.position_embeddings.weight', 'vilt.embeddings.text_embeddings.position_embeddings.weight', ), ('text_embeddings.position_ids', 'vilt.embeddings.text_embeddings.position_ids'), ( 'text_embeddings.token_type_embeddings.weight', 'vilt.embeddings.text_embeddings.token_type_embeddings.weight', ), ('text_embeddings.LayerNorm.weight', 'vilt.embeddings.text_embeddings.LayerNorm.weight'), ('text_embeddings.LayerNorm.bias', 'vilt.embeddings.text_embeddings.LayerNorm.bias'), # patch embeddings ('transformer.cls_token', 'vilt.embeddings.cls_token'), ('transformer.patch_embed.proj.weight', 'vilt.embeddings.patch_embeddings.projection.weight'), ('transformer.patch_embed.proj.bias', 'vilt.embeddings.patch_embeddings.projection.bias'), ('transformer.pos_embed', 'vilt.embeddings.position_embeddings'), # token type embeddings ('token_type_embeddings.weight', 'vilt.embeddings.token_type_embeddings.weight'), ] ) # final layernorm + pooler rename_keys.extend( [ ('transformer.norm.weight', 'vilt.layernorm.weight'), ('transformer.norm.bias', 'vilt.layernorm.bias'), ('pooler.dense.weight', 'vilt.pooler.dense.weight'), ('pooler.dense.bias', 'vilt.pooler.dense.bias'), ] ) # classifier head(s) if vqa_model: # classification head rename_keys.extend( [ ('vqa_classifier.0.weight', 'classifier.0.weight'), ('vqa_classifier.0.bias', 'classifier.0.bias'), ('vqa_classifier.1.weight', 'classifier.1.weight'), ('vqa_classifier.1.bias', 'classifier.1.bias'), ('vqa_classifier.3.weight', 'classifier.3.weight'), ('vqa_classifier.3.bias', 'classifier.3.bias'), ] ) elif nlvr_model: # classification head rename_keys.extend( [ ('nlvr2_classifier.0.weight', 'classifier.0.weight'), ('nlvr2_classifier.0.bias', 'classifier.0.bias'), ('nlvr2_classifier.1.weight', 'classifier.1.weight'), ('nlvr2_classifier.1.bias', 'classifier.1.bias'), ('nlvr2_classifier.3.weight', 'classifier.3.weight'), ('nlvr2_classifier.3.bias', 'classifier.3.bias'), ] ) else: pass return rename_keys def lowerCamelCase ( UpperCamelCase : str , UpperCamelCase : str ) -> Tuple: for i in range(config.num_hidden_layers ): _lowerCamelCase = 'vilt.' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) _lowerCamelCase = state_dict.pop(F"""transformer.blocks.{i}.attn.qkv.weight""" ) _lowerCamelCase = state_dict.pop(F"""transformer.blocks.{i}.attn.qkv.bias""" ) # next, add query, keys and values (in that order) to the state dict _lowerCamelCase = in_proj_weight[ : config.hidden_size, : ] _lowerCamelCase = in_proj_bias[: config.hidden_size] _lowerCamelCase = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] _lowerCamelCase = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] _lowerCamelCase = in_proj_weight[ -config.hidden_size :, : ] _lowerCamelCase = in_proj_bias[-config.hidden_size :] def lowerCamelCase ( UpperCamelCase : Tuple ) -> List[Any]: _lowerCamelCase = ['head.weight', 'head.bias'] for k in ignore_keys: state_dict.pop(UpperCamelCase , UpperCamelCase ) def lowerCamelCase ( UpperCamelCase : Tuple , UpperCamelCase : Optional[Any] , UpperCamelCase : str ) -> Any: _lowerCamelCase = dct.pop(UpperCamelCase ) _lowerCamelCase = val @torch.no_grad() def lowerCamelCase ( UpperCamelCase : int , UpperCamelCase : int ) -> Optional[int]: _lowerCamelCase = ViltConfig(image_size=3_84 , patch_size=32 , tie_word_embeddings=UpperCamelCase ) _lowerCamelCase = False _lowerCamelCase = False _lowerCamelCase = False _lowerCamelCase = False if "vqa" in checkpoint_url: _lowerCamelCase = True _lowerCamelCase = 31_29 _lowerCamelCase = 'huggingface/label-files' _lowerCamelCase = 'vqa2-id2label.json' _lowerCamelCase = json.load(open(hf_hub_download(UpperCamelCase , UpperCamelCase , repo_type='dataset' ) , 'r' ) ) _lowerCamelCase = {int(UpperCamelCase ): v for k, v in idalabel.items()} _lowerCamelCase = idalabel _lowerCamelCase = {v: k for k, v in idalabel.items()} _lowerCamelCase = ViltForQuestionAnswering(UpperCamelCase ) elif "nlvr" in checkpoint_url: _lowerCamelCase = True _lowerCamelCase = 2 _lowerCamelCase = {0: 'False', 1: 'True'} _lowerCamelCase = {v: k for k, v in config.idalabel.items()} _lowerCamelCase = 3 _lowerCamelCase = ViltForImagesAndTextClassification(UpperCamelCase ) elif "irtr" in checkpoint_url: _lowerCamelCase = True _lowerCamelCase = ViltForImageAndTextRetrieval(UpperCamelCase ) elif "mlm_itm" in checkpoint_url: _lowerCamelCase = True _lowerCamelCase = ViltForMaskedLM(UpperCamelCase ) else: raise ValueError('Unknown model type' ) # load state_dict of original model, remove and rename some keys _lowerCamelCase = torch.hub.load_state_dict_from_url(UpperCamelCase , map_location='cpu' )['state_dict'] _lowerCamelCase = create_rename_keys(UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) for src, dest in rename_keys: rename_key(UpperCamelCase , UpperCamelCase , UpperCamelCase ) read_in_q_k_v(UpperCamelCase , UpperCamelCase ) if mlm_model or irtr_model: _lowerCamelCase = ['itm_score.fc.weight', 'itm_score.fc.bias'] for k in ignore_keys: state_dict.pop(UpperCamelCase , UpperCamelCase ) # load state dict into HuggingFace model model.eval() if mlm_model: _lowerCamelCase , _lowerCamelCase = model.load_state_dict(UpperCamelCase , strict=UpperCamelCase ) assert missing_keys == ["mlm_score.decoder.bias"] else: model.load_state_dict(UpperCamelCase ) # Define processor _lowerCamelCase = ViltImageProcessor(size=3_84 ) _lowerCamelCase = BertTokenizer.from_pretrained('bert-base-uncased' ) _lowerCamelCase = ViltProcessor(UpperCamelCase , UpperCamelCase ) # Forward pass on example inputs (image + text) if nlvr_model: _lowerCamelCase = Image.open(requests.get('https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg' , stream=UpperCamelCase ).raw ) _lowerCamelCase = Image.open(requests.get('https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg' , stream=UpperCamelCase ).raw ) _lowerCamelCase = ( 'The left image contains twice the number of dogs as the right image, and at least two dogs in total are' ' standing.' ) _lowerCamelCase = processor(UpperCamelCase , UpperCamelCase , return_tensors='pt' ) _lowerCamelCase = processor(UpperCamelCase , UpperCamelCase , return_tensors='pt' ) _lowerCamelCase = model( input_ids=encoding_a.input_ids , pixel_values=encoding_a.pixel_values , pixel_values_a=encoding_a.pixel_values , ) else: _lowerCamelCase = Image.open(requests.get('http://images.cocodataset.org/val2017/000000039769.jpg' , stream=UpperCamelCase ).raw ) if mlm_model: _lowerCamelCase = 'a bunch of [MASK] laying on a [MASK].' else: _lowerCamelCase = 'How many cats are there?' _lowerCamelCase = processor(UpperCamelCase , UpperCamelCase , return_tensors='pt' ) _lowerCamelCase = model(**UpperCamelCase ) # Verify outputs if mlm_model: _lowerCamelCase = torch.Size([1, 11, 3_05_22] ) _lowerCamelCase = torch.tensor([-12.5_061, -12.5_123, -12.5_174] ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3] , UpperCamelCase , atol=1e-4 ) # verify masked token prediction equals "cats" _lowerCamelCase = outputs.logits[0, 4, :].argmax(-1 ).item() assert tokenizer.decode([predicted_id] ) == "cats" elif vqa_model: _lowerCamelCase = torch.Size([1, 31_29] ) _lowerCamelCase = torch.tensor([-15.9_495, -18.1_472, -10.3_041] ) assert torch.allclose(outputs.logits[0, :3] , UpperCamelCase , atol=1e-4 ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3] , UpperCamelCase , atol=1e-4 ) # verify vqa prediction equals "2" _lowerCamelCase = outputs.logits.argmax(-1 ).item() assert model.config.idalabel[predicted_idx] == "2" elif nlvr_model: _lowerCamelCase = torch.Size([1, 2] ) _lowerCamelCase = torch.tensor([-2.8_721, 2.1_291] ) assert torch.allclose(outputs.logits[0, :3] , UpperCamelCase , atol=1e-4 ) assert outputs.logits.shape == expected_shape Path(UpperCamelCase ).mkdir(exist_ok=UpperCamelCase ) print(F"""Saving model and processor to {pytorch_dump_folder_path}""" ) model.save_pretrained(UpperCamelCase ) processor.save_pretrained(UpperCamelCase ) if __name__ == "__main__": A = argparse.ArgumentParser() # Required parameters parser.add_argument( '--checkpoint_url', default='https://github.com/dandelin/ViLT/releases/download/200k/vilt_200k_mlm_itm.ckpt', type=str, help='URL of the checkpoint you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) A = parser.parse_args() convert_vilt_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
234
1
'''simple docstring''' import logging import os import threading import time try: import warnings except ImportError: A : str = None try: import msvcrt except ImportError: A : int = None try: import fcntl except ImportError: A : Any = None # Backward compatibility # ------------------------------------------------ try: TimeoutError except NameError: A : str = OSError # Data # ------------------------------------------------ A : Union[str, Any] = [ 'Timeout', 'BaseFileLock', 'WindowsFileLock', 'UnixFileLock', 'SoftFileLock', 'FileLock', ] A : List[Any] = '3.0.12' A : Dict = None def _a ( ): global _logger snake_case : Dict =_logger or logging.getLogger(__name__ ) return _logger class lowerCAmelCase_ ( __UpperCamelCase ): def __init__( self : Optional[int], _snake_case : Optional[Any] ): '''simple docstring''' snake_case : Optional[int] =lock_file return None def __str__( self : Optional[Any] ): '''simple docstring''' snake_case : str =f'''The file lock \'{self.lock_file}\' could not be acquired.''' return temp class lowerCAmelCase_ : def __init__( self : int, _snake_case : Optional[int] ): '''simple docstring''' snake_case : int =lock return None def __enter__( self : str ): '''simple docstring''' return self.lock def __exit__( self : Tuple, _snake_case : Dict, _snake_case : Union[str, Any], _snake_case : str ): '''simple docstring''' self.lock.release() return None class lowerCAmelCase_ : def __init__( self : Any, _snake_case : List[Any], _snake_case : List[Any]=-1, _snake_case : Union[str, Any]=None ): '''simple docstring''' snake_case : str =max_filename_length if max_filename_length is not None else 255 # Hash the filename if it's too long snake_case : List[str] =self.hash_filename_if_too_long(__snake_case, __snake_case ) # The path to the lock file. snake_case : int =lock_file # The file descriptor for the *_lock_file* as it is returned by the # os.open() function. # This file lock is only NOT None, if the object currently holds the # lock. snake_case : Union[str, Any] =None # The default timeout value. snake_case : List[str] =timeout # We use this lock primarily for the lock counter. snake_case : str =threading.Lock() # The lock counter is used for implementing the nested locking # mechanism. Whenever the lock is acquired, the counter is increased and # the lock is only released, when this value is 0 again. snake_case : int =0 return None @property def __snake_case ( self : Optional[Any] ): '''simple docstring''' return self._lock_file @property def __snake_case ( self : str ): '''simple docstring''' return self._timeout @timeout.setter def __snake_case ( self : Union[str, Any], _snake_case : Optional[Any] ): '''simple docstring''' snake_case : List[Any] =float(__snake_case ) return None def __snake_case ( self : Union[str, Any] ): '''simple docstring''' raise NotImplementedError() def __snake_case ( self : Any ): '''simple docstring''' raise NotImplementedError() @property def __snake_case ( self : List[str] ): '''simple docstring''' return self._lock_file_fd is not None def __snake_case ( self : Dict, _snake_case : str=None, _snake_case : Dict=0.05 ): '''simple docstring''' if timeout is None: snake_case : Optional[Any] =self.timeout # Increment the number right at the beginning. # We can still undo it, if something fails. with self._thread_lock: self._lock_counter += 1 snake_case : Any =id(self ) snake_case : int =self._lock_file snake_case : Tuple =time.time() try: while True: with self._thread_lock: if not self.is_locked: logger().debug(f'''Attempting to acquire lock {lock_id} on {lock_filename}''' ) self._acquire() if self.is_locked: logger().debug(f'''Lock {lock_id} acquired on {lock_filename}''' ) break elif timeout >= 0 and time.time() - start_time > timeout: logger().debug(f'''Timeout on acquiring lock {lock_id} on {lock_filename}''' ) raise Timeout(self._lock_file ) else: logger().debug( f'''Lock {lock_id} not acquired on {lock_filename}, waiting {poll_intervall} seconds ...''' ) time.sleep(__snake_case ) except: # noqa # Something did go wrong, so decrement the counter. with self._thread_lock: snake_case : Tuple =max(0, self._lock_counter - 1 ) raise return _Acquire_ReturnProxy(lock=self ) def __snake_case ( self : Union[str, Any], _snake_case : Tuple=False ): '''simple docstring''' with self._thread_lock: if self.is_locked: self._lock_counter -= 1 if self._lock_counter == 0 or force: snake_case : str =id(self ) snake_case : int =self._lock_file logger().debug(f'''Attempting to release lock {lock_id} on {lock_filename}''' ) self._release() snake_case : Optional[Any] =0 logger().debug(f'''Lock {lock_id} released on {lock_filename}''' ) return None def __enter__( self : Dict ): '''simple docstring''' self.acquire() return self def __exit__( self : Dict, _snake_case : List[Any], _snake_case : Any, _snake_case : List[Any] ): '''simple docstring''' self.release() return None def __del__( self : int ): '''simple docstring''' self.release(force=__snake_case ) return None def __snake_case ( self : Tuple, _snake_case : str, _snake_case : int ): '''simple docstring''' snake_case : Dict =os.path.basename(__snake_case ) if len(__snake_case ) > max_length and max_length > 0: snake_case : Any =os.path.dirname(__snake_case ) snake_case : Dict =str(hash(__snake_case ) ) snake_case : List[Any] =filename[: max_length - len(__snake_case ) - 8] + '''...''' + hashed_filename + '''.lock''' return os.path.join(__snake_case, __snake_case ) else: return path class lowerCAmelCase_ ( __UpperCamelCase ): def __init__( self : int, _snake_case : Union[str, Any], _snake_case : Union[str, Any]=-1, _snake_case : List[Any]=None ): '''simple docstring''' from .file_utils import relative_to_absolute_path super().__init__(__snake_case, timeout=__snake_case, max_filename_length=__snake_case ) snake_case : List[str] ='''\\\\?\\''' + relative_to_absolute_path(self.lock_file ) def __snake_case ( self : str ): '''simple docstring''' snake_case : Optional[Any] =os.O_RDWR | os.O_CREAT | os.O_TRUNC try: snake_case : str =os.open(self._lock_file, __snake_case ) except OSError: pass else: try: msvcrt.locking(__snake_case, msvcrt.LK_NBLCK, 1 ) except OSError: os.close(__snake_case ) else: snake_case : Union[str, Any] =fd return None def __snake_case ( self : str ): '''simple docstring''' snake_case : Union[str, Any] =self._lock_file_fd snake_case : Optional[int] =None msvcrt.locking(__snake_case, msvcrt.LK_UNLCK, 1 ) os.close(__snake_case ) try: os.remove(self._lock_file ) # Probably another instance of the application # that acquired the file lock. except OSError: pass return None class lowerCAmelCase_ ( __UpperCamelCase ): def __init__( self : List[str], _snake_case : Any, _snake_case : List[Any]=-1, _snake_case : List[str]=None ): '''simple docstring''' snake_case : str =os.statvfs(os.path.dirname(__snake_case ) ).f_namemax super().__init__(__snake_case, timeout=__snake_case, max_filename_length=__snake_case ) def __snake_case ( self : Tuple ): '''simple docstring''' snake_case : Optional[int] =os.O_RDWR | os.O_CREAT | os.O_TRUNC snake_case : str =os.open(self._lock_file, __snake_case ) try: fcntl.flock(__snake_case, fcntl.LOCK_EX | fcntl.LOCK_NB ) except OSError: os.close(__snake_case ) else: snake_case : List[Any] =fd return None def __snake_case ( self : Tuple ): '''simple docstring''' snake_case : int =self._lock_file_fd snake_case : List[str] =None fcntl.flock(__snake_case, fcntl.LOCK_UN ) os.close(__snake_case ) return None class lowerCAmelCase_ ( __UpperCamelCase ): def __snake_case ( self : Union[str, Any] ): '''simple docstring''' snake_case : Union[str, Any] =os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC try: snake_case : Any =os.open(self._lock_file, __snake_case ) except OSError: pass else: snake_case : str =fd return None def __snake_case ( self : Any ): '''simple docstring''' os.close(self._lock_file_fd ) snake_case : Union[str, Any] =None try: os.remove(self._lock_file ) # The file is already deleted and that's what we want. except OSError: pass return None A : Any = None if msvcrt: A : Tuple = WindowsFileLock elif fcntl: A : int = UnixFileLock else: A : List[str] = SoftFileLock if warnings is not None: warnings.warn("""only soft file lock is available""")
349
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 AutoFeatureExtractor, WavaVecaFeatureExtractor 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_feature_extraction import CustomFeatureExtractor # noqa E402 _lowerCAmelCase : Dict = get_tests_dir('fixtures') class lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def lowerCamelCase__ ( self : str ) -> str: '''simple docstring''' lowerCamelCase = mock.Mock() lowerCamelCase = 500 lowerCamelCase = {} lowerCamelCase = HTTPError lowerCamelCase = {} # Download this model to make sure it's in the cache. lowerCamelCase = WavaVecaFeatureExtractor.from_pretrained('hf-internal-testing/tiny-random-wav2vec2' ) # Under the mock environment we get a 500 error when trying to reach the model. with mock.patch('requests.Session.request' , return_value=__snake_case ) as mock_head: lowerCamelCase = WavaVecaFeatureExtractor.from_pretrained('hf-internal-testing/tiny-random-wav2vec2' ) # This check we did call the fake head request mock_head.assert_called() def lowerCamelCase__ ( self : Optional[int] ) -> Dict: '''simple docstring''' lowerCamelCase = WavaVecaFeatureExtractor.from_pretrained( 'https://huggingface.co/hf-internal-testing/tiny-random-wav2vec2/resolve/main/preprocessor_config.json' ) @is_staging_test class lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' @classmethod def lowerCamelCase__ ( cls : Any ) -> List[str]: '''simple docstring''' lowerCamelCase = TOKEN HfFolder.save_token(__snake_case ) @classmethod def lowerCamelCase__ ( cls : Union[str, Any] ) -> Tuple: '''simple docstring''' try: delete_repo(token=cls._token , repo_id='test-feature-extractor' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='valid_org/test-feature-extractor-org' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='test-dynamic-feature-extractor' ) except HTTPError: pass def lowerCamelCase__ ( self : Union[str, Any] ) -> Any: '''simple docstring''' lowerCamelCase = WavaVecaFeatureExtractor.from_pretrained(__snake_case ) feature_extractor.push_to_hub('test-feature-extractor' , use_auth_token=self._token ) lowerCamelCase = WavaVecaFeatureExtractor.from_pretrained(F'''{USER}/test-feature-extractor''' ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(__snake_case , getattr(__snake_case , __snake_case ) ) # Reset repo delete_repo(token=self._token , repo_id='test-feature-extractor' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained( __snake_case , repo_id='test-feature-extractor' , push_to_hub=__snake_case , use_auth_token=self._token ) lowerCamelCase = WavaVecaFeatureExtractor.from_pretrained(F'''{USER}/test-feature-extractor''' ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(__snake_case , getattr(__snake_case , __snake_case ) ) def lowerCamelCase__ ( self : str ) -> Any: '''simple docstring''' lowerCamelCase = WavaVecaFeatureExtractor.from_pretrained(__snake_case ) feature_extractor.push_to_hub('valid_org/test-feature-extractor' , use_auth_token=self._token ) lowerCamelCase = WavaVecaFeatureExtractor.from_pretrained('valid_org/test-feature-extractor' ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(__snake_case , getattr(__snake_case , __snake_case ) ) # Reset repo delete_repo(token=self._token , repo_id='valid_org/test-feature-extractor' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained( __snake_case , repo_id='valid_org/test-feature-extractor-org' , push_to_hub=__snake_case , use_auth_token=self._token ) lowerCamelCase = WavaVecaFeatureExtractor.from_pretrained('valid_org/test-feature-extractor-org' ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(__snake_case , getattr(__snake_case , __snake_case ) ) def lowerCamelCase__ ( self : int ) -> List[str]: '''simple docstring''' CustomFeatureExtractor.register_for_auto_class() lowerCamelCase = CustomFeatureExtractor.from_pretrained(__snake_case ) feature_extractor.push_to_hub('test-dynamic-feature-extractor' , use_auth_token=self._token ) # This has added the proper auto_map field to the config self.assertDictEqual( feature_extractor.auto_map , {'AutoFeatureExtractor': 'custom_feature_extraction.CustomFeatureExtractor'} , ) lowerCamelCase = AutoFeatureExtractor.from_pretrained( F'''{USER}/test-dynamic-feature-extractor''' , trust_remote_code=__snake_case ) # Can't make an isinstance check because the new_feature_extractor is from the CustomFeatureExtractor class of a dynamic module self.assertEqual(new_feature_extractor.__class__.__name__ , 'CustomFeatureExtractor' )
246
0
def _UpperCamelCase ( lowercase__ ): if len(_lowerCamelCase ) <= 1: return lst __SCREAMING_SNAKE_CASE : Tuple = 1 while i < len(_lowerCamelCase ): if lst[i - 1] <= lst[i]: i += 1 else: __SCREAMING_SNAKE_CASE : List[Any] = lst[i], lst[i - 1] i -= 1 if i == 0: __SCREAMING_SNAKE_CASE : Union[str, Any] = 1 return lst if __name__ == "__main__": __lowerCAmelCase : Dict =input('Enter numbers separated by a comma:\n').strip() __lowerCAmelCase : int =[int(item) for item in user_input.split(',')] print(gnome_sort(unsorted))
719
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_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging __lowerCAmelCase : Dict =logging.get_logger(__name__) class _lowercase ( A__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = ['''pixel_values'''] def __init__( self :str , lowerCAmelCase__ :bool = True , lowerCAmelCase__ :Optional[Dict[str, int]] = None , lowerCAmelCase__ :PILImageResampling = PILImageResampling.BILINEAR , lowerCAmelCase__ :bool = True , lowerCAmelCase__ :Dict[str, int] = None , lowerCAmelCase__ :bool = True , lowerCAmelCase__ :Union[int, float] = 1 / 255 , lowerCAmelCase__ :bool = True , lowerCAmelCase__ :Optional[Union[float, List[float]]] = None , lowerCAmelCase__ :Optional[Union[float, List[float]]] = None , **lowerCAmelCase__ :Tuple , ) -> None: super().__init__(**lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : int = size if size is not None else {'''shortest_edge''': 256} __SCREAMING_SNAKE_CASE : Optional[int] = get_size_dict(lowerCAmelCase__ , default_to_square=lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : str = crop_size if crop_size is not None else {'''height''': 224, '''width''': 224} __SCREAMING_SNAKE_CASE : Union[str, Any] = get_size_dict(lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : str = do_resize __SCREAMING_SNAKE_CASE : str = size __SCREAMING_SNAKE_CASE : Any = resample __SCREAMING_SNAKE_CASE : Union[str, Any] = do_center_crop __SCREAMING_SNAKE_CASE : Tuple = crop_size __SCREAMING_SNAKE_CASE : List[str] = do_rescale __SCREAMING_SNAKE_CASE : List[Any] = rescale_factor __SCREAMING_SNAKE_CASE : Any = do_normalize __SCREAMING_SNAKE_CASE : Dict = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN __SCREAMING_SNAKE_CASE : Optional[int] = image_std if image_std is not None else IMAGENET_STANDARD_STD def __magic_name__( self :Dict , lowerCAmelCase__ :np.ndarray , lowerCAmelCase__ :Dict[str, int] , lowerCAmelCase__ :PILImageResampling = PILImageResampling.BICUBIC , lowerCAmelCase__ :Optional[Union[str, ChannelDimension]] = None , **lowerCAmelCase__ :int , ) -> np.ndarray: __SCREAMING_SNAKE_CASE : Tuple = get_size_dict(lowerCAmelCase__ , default_to_square=lowerCAmelCase__ ) if "shortest_edge" not in size: raise ValueError(f'''The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}''' ) __SCREAMING_SNAKE_CASE : Optional[int] = get_resize_output_image_size(lowerCAmelCase__ , size=size['''shortest_edge'''] , default_to_square=lowerCAmelCase__ ) return resize(lowerCAmelCase__ , size=lowerCAmelCase__ , resample=lowerCAmelCase__ , data_format=lowerCAmelCase__ , **lowerCAmelCase__ ) def __magic_name__( self :str , lowerCAmelCase__ :np.ndarray , lowerCAmelCase__ :Dict[str, int] , lowerCAmelCase__ :Optional[Union[str, ChannelDimension]] = None , **lowerCAmelCase__ :Any , ) -> np.ndarray: __SCREAMING_SNAKE_CASE : str = get_size_dict(lowerCAmelCase__ ) return center_crop(lowerCAmelCase__ , size=(size['''height'''], size['''width''']) , data_format=lowerCAmelCase__ , **lowerCAmelCase__ ) def __magic_name__( self :List[Any] , lowerCAmelCase__ :np.ndarray , lowerCAmelCase__ :float , lowerCAmelCase__ :Optional[Union[str, ChannelDimension]] = None , **lowerCAmelCase__ :str ) -> np.ndarray: return rescale(lowerCAmelCase__ , scale=lowerCAmelCase__ , data_format=lowerCAmelCase__ , **lowerCAmelCase__ ) def __magic_name__( self :Dict , lowerCAmelCase__ :np.ndarray , lowerCAmelCase__ :Union[float, List[float]] , lowerCAmelCase__ :Union[float, List[float]] , lowerCAmelCase__ :Optional[Union[str, ChannelDimension]] = None , **lowerCAmelCase__ :List[Any] , ) -> np.ndarray: return normalize(lowerCAmelCase__ , mean=lowerCAmelCase__ , std=lowerCAmelCase__ , data_format=lowerCAmelCase__ , **lowerCAmelCase__ ) def __magic_name__( self :Optional[int] , lowerCAmelCase__ :ImageInput , lowerCAmelCase__ :Optional[bool] = None , lowerCAmelCase__ :Dict[str, int] = None , lowerCAmelCase__ :PILImageResampling = None , lowerCAmelCase__ :bool = None , lowerCAmelCase__ :Dict[str, int] = None , lowerCAmelCase__ :Optional[bool] = None , lowerCAmelCase__ :Optional[float] = None , lowerCAmelCase__ :Optional[bool] = None , lowerCAmelCase__ :Optional[Union[float, List[float]]] = None , lowerCAmelCase__ :Optional[Union[float, List[float]]] = None , lowerCAmelCase__ :Optional[Union[str, TensorType]] = None , lowerCAmelCase__ :Union[str, ChannelDimension] = ChannelDimension.FIRST , **lowerCAmelCase__ :Optional[Any] , ) -> Optional[int]: __SCREAMING_SNAKE_CASE : Dict = do_resize if do_resize is not None else self.do_resize __SCREAMING_SNAKE_CASE : Tuple = size if size is not None else self.size __SCREAMING_SNAKE_CASE : Dict = get_size_dict(lowerCAmelCase__ , default_to_square=lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : Dict = resample if resample is not None else self.resample __SCREAMING_SNAKE_CASE : Optional[Any] = do_center_crop if do_center_crop is not None else self.do_center_crop __SCREAMING_SNAKE_CASE : Optional[Any] = crop_size if crop_size is not None else self.crop_size __SCREAMING_SNAKE_CASE : str = get_size_dict(lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : List[str] = do_rescale if do_rescale is not None else self.do_rescale __SCREAMING_SNAKE_CASE : Optional[int] = rescale_factor if rescale_factor is not None else self.rescale_factor __SCREAMING_SNAKE_CASE : Tuple = do_normalize if do_normalize is not None else self.do_normalize __SCREAMING_SNAKE_CASE : int = image_mean if image_mean is not None else self.image_mean __SCREAMING_SNAKE_CASE : int = image_std if image_std is not None else self.image_std __SCREAMING_SNAKE_CASE : int = make_list_of_images(lowerCAmelCase__ ) if not valid_images(lowerCAmelCase__ ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None: raise ValueError('''Size must be specified if do_resize is True.''' ) if do_center_crop and crop_size is None: raise ValueError('''Crop size must be specified if do_center_crop is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('''Image mean and std must be specified if do_normalize is True.''' ) # All transformations expect numpy arrays. __SCREAMING_SNAKE_CASE : Optional[Any] = [to_numpy_array(lowerCAmelCase__ ) for image in images] if do_resize: __SCREAMING_SNAKE_CASE : Union[str, Any] = [self.resize(image=lowerCAmelCase__ , size=lowerCAmelCase__ , resample=lowerCAmelCase__ ) for image in images] if do_center_crop: __SCREAMING_SNAKE_CASE : Union[str, Any] = [self.center_crop(image=lowerCAmelCase__ , size=lowerCAmelCase__ ) for image in images] if do_rescale: __SCREAMING_SNAKE_CASE : Union[str, Any] = [self.rescale(image=lowerCAmelCase__ , scale=lowerCAmelCase__ ) for image in images] if do_normalize: __SCREAMING_SNAKE_CASE : int = [self.normalize(image=lowerCAmelCase__ , mean=lowerCAmelCase__ , std=lowerCAmelCase__ ) for image in images] __SCREAMING_SNAKE_CASE : Tuple = [to_channel_dimension_format(lowerCAmelCase__ , lowerCAmelCase__ ) for image in images] __SCREAMING_SNAKE_CASE : Dict = {'''pixel_values''': images} return BatchFeature(data=lowerCAmelCase__ , tensor_type=lowerCAmelCase__ )
260
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging A_ = logging.get_logger(__name__) A_ = { "google/pegasus-large": "https://huggingface.co/google/pegasus-large/resolve/main/config.json", # See all PEGASUS models at https://huggingface.co/models?filter=pegasus } class __lowerCAmelCase ( UpperCAmelCase ): '''simple docstring''' __lowerCamelCase : Optional[Any] = "pegasus" __lowerCamelCase : List[Any] = ["past_key_values"] __lowerCamelCase : Any = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"} def __init__( self: List[str] , UpperCamelCase_: int=5_0265 , UpperCamelCase_: str=1024 , UpperCamelCase_: Union[str, Any]=12 , UpperCamelCase_: int=4096 , UpperCamelCase_: Any=16 , UpperCamelCase_: Optional[int]=12 , UpperCamelCase_: Dict=4096 , UpperCamelCase_: Dict=16 , UpperCamelCase_: Any=0.0 , UpperCamelCase_: Optional[Any]=0.0 , UpperCamelCase_: Optional[int]=True , UpperCamelCase_: Optional[Any]=True , UpperCamelCase_: List[str]="gelu" , UpperCamelCase_: Dict=1024 , UpperCamelCase_: List[str]=0.1 , UpperCamelCase_: Dict=0.0 , UpperCamelCase_: int=0.0 , UpperCamelCase_: List[Any]=0.02 , UpperCamelCase_: List[Any]=0 , UpperCamelCase_: List[str]=False , UpperCamelCase_: Optional[Any]=0 , UpperCamelCase_: List[str]=1 , UpperCamelCase_: int=1 , **UpperCamelCase_: str , ): UpperCamelCase_ =vocab_size UpperCamelCase_ =max_position_embeddings UpperCamelCase_ =d_model UpperCamelCase_ =encoder_ffn_dim UpperCamelCase_ =encoder_layers UpperCamelCase_ =encoder_attention_heads UpperCamelCase_ =decoder_ffn_dim UpperCamelCase_ =decoder_layers UpperCamelCase_ =decoder_attention_heads UpperCamelCase_ =dropout UpperCamelCase_ =attention_dropout UpperCamelCase_ =activation_dropout UpperCamelCase_ =activation_function UpperCamelCase_ =init_std UpperCamelCase_ =encoder_layerdrop UpperCamelCase_ =decoder_layerdrop UpperCamelCase_ =use_cache UpperCamelCase_ =encoder_layers UpperCamelCase_ =scale_embedding # scale factor will be sqrt(d_model) if True super().__init__( pad_token_id=UpperCamelCase_ , eos_token_id=UpperCamelCase_ , is_encoder_decoder=UpperCamelCase_ , decoder_start_token_id=UpperCamelCase_ , forced_eos_token_id=UpperCamelCase_ , **UpperCamelCase_ , ) @property def UpperCamelCase__ ( self: List[str] ): return self.encoder_attention_heads @property def UpperCamelCase__ ( self: List[str] ): return self.d_model
391
"""simple docstring""" import importlib import inspect import json import os import re import shutil import sys from pathlib import Path from typing import Dict, Optional, Union from urllib import request from huggingface_hub import HfFolder, cached_download, hf_hub_download, model_info from packaging import version from .. import __version__ from . import DIFFUSERS_DYNAMIC_MODULE_NAME, HF_MODULES_CACHE, logging A_ = ( "https://raw.githubusercontent.com/huggingface/diffusers/{revision}/examples/community/{pipeline}.py" ) A_ = logging.get_logger(__name__) # pylint: disable=invalid-name def _UpperCamelCase ( ): UpperCamelCase_ ="https://pypi.org/pypi/diffusers/json" UpperCamelCase_ =json.loads(request.urlopen(A ).read() )["releases"].keys() return sorted(A , key=lambda A : version.Version(A ) ) def _UpperCamelCase ( ): # This function has already been executed if HF_MODULES_CACHE already is in the Python path. if HF_MODULES_CACHE in sys.path: return sys.path.append(A ) os.makedirs(A , exist_ok=A ) UpperCamelCase_ =Path(A ) / "__init__.py" if not init_path.exists(): init_path.touch() def _UpperCamelCase ( A ): init_hf_modules() UpperCamelCase_ =Path(A ) / name # If the parent module does not exist yet, recursively create it. if not dynamic_module_path.parent.exists(): create_dynamic_module(dynamic_module_path.parent ) os.makedirs(A , exist_ok=A ) UpperCamelCase_ =dynamic_module_path / "__init__.py" if not init_path.exists(): init_path.touch() def _UpperCamelCase ( A ): with open(A , "r" , encoding="utf-8" ) as f: UpperCamelCase_ =f.read() # Imports of the form `import .xxx` UpperCamelCase_ =re.findall("^\s*import\s+\.(\S+)\s*$" , A , flags=re.MULTILINE ) # Imports of the form `from .xxx import yyy` relative_imports += re.findall("^\s*from\s+\.(\S+)\s+import" , A , flags=re.MULTILINE ) # Unique-ify return list(set(A ) ) def _UpperCamelCase ( A ): UpperCamelCase_ =False UpperCamelCase_ =[module_file] UpperCamelCase_ =[] # Let's recurse through all relative imports while not no_change: UpperCamelCase_ =[] for f in files_to_check: new_imports.extend(get_relative_imports(A ) ) UpperCamelCase_ =Path(A ).parent UpperCamelCase_ =[str(module_path / m ) for m in new_imports] UpperCamelCase_ =[f for f in new_import_files if f not in all_relative_imports] UpperCamelCase_ =[f"""{f}.py""" for f in new_import_files] UpperCamelCase_ =len(A ) == 0 all_relative_imports.extend(A ) return all_relative_imports def _UpperCamelCase ( A ): with open(A , "r" , encoding="utf-8" ) as f: UpperCamelCase_ =f.read() # Imports of the form `import xxx` UpperCamelCase_ =re.findall("^\s*import\s+(\S+)\s*$" , A , flags=re.MULTILINE ) # Imports of the form `from xxx import yyy` imports += re.findall("^\s*from\s+(\S+)\s+import" , A , flags=re.MULTILINE ) # Only keep the top-level module UpperCamelCase_ =[imp.split("." )[0] for imp in imports if not imp.startswith("." )] # Unique-ify and test we got them all UpperCamelCase_ =list(set(A ) ) UpperCamelCase_ =[] for imp in imports: try: importlib.import_module(A ) except ImportError: missing_packages.append(A ) if len(A ) > 0: raise ImportError( "This modeling file requires the following packages that were not found in your environment: " f"""{", ".join(A )}. Run `pip install {" ".join(A )}`""" ) return get_relative_imports(A ) def _UpperCamelCase ( A , A ): UpperCamelCase_ =module_path.replace(os.path.sep , "." ) UpperCamelCase_ =importlib.import_module(A ) if class_name is None: return find_pipeline_class(A ) return getattr(A , A ) def _UpperCamelCase ( A ): from ..pipelines import DiffusionPipeline UpperCamelCase_ =dict(inspect.getmembers(A , inspect.isclass ) ) UpperCamelCase_ =None for cls_name, cls in cls_members.items(): if ( cls_name != DiffusionPipeline.__name__ and issubclass(cls , A ) and cls.__module__.split("." )[0] != "diffusers" ): if pipeline_class is not None: raise ValueError( f"""Multiple classes that inherit from {DiffusionPipeline.__name__} have been found:""" f""" {pipeline_class.__name__}, and {cls_name}. Please make sure to define only one in""" f""" {loaded_module}.""" ) UpperCamelCase_ =cls return pipeline_class def _UpperCamelCase ( A , A , A = None , A = False , A = False , A = None , A = None , A = None , A = False , ): UpperCamelCase_ =str(A ) UpperCamelCase_ =os.path.join(A , A ) if os.path.isfile(A ): UpperCamelCase_ =module_file_or_url UpperCamelCase_ ="local" elif pretrained_model_name_or_path.count("/" ) == 0: UpperCamelCase_ =get_diffusers_versions() # cut ".dev0" UpperCamelCase_ ="v" + ".".join(__version__.split("." )[:3] ) # retrieve github version that matches if revision is None: UpperCamelCase_ =latest_version if latest_version[1:] in available_versions else "main" logger.info(f"""Defaulting to latest_version: {revision}.""" ) elif revision in available_versions: UpperCamelCase_ =f"""v{revision}""" elif revision == "main": UpperCamelCase_ =revision else: raise ValueError( f"""`custom_revision`: {revision} does not exist. Please make sure to choose one of""" f""" {", ".join(available_versions + ["main"] )}.""" ) # community pipeline on GitHub UpperCamelCase_ =COMMUNITY_PIPELINES_URL.format(revision=A , pipeline=A ) try: UpperCamelCase_ =cached_download( A , cache_dir=A , force_download=A , proxies=A , resume_download=A , local_files_only=A , use_auth_token=A , ) UpperCamelCase_ ="git" UpperCamelCase_ =pretrained_model_name_or_path + ".py" except EnvironmentError: logger.error(f"""Could not locate the {module_file} inside {pretrained_model_name_or_path}.""" ) raise else: try: # Load from URL or cache if already cached UpperCamelCase_ =hf_hub_download( A , A , cache_dir=A , force_download=A , proxies=A , resume_download=A , local_files_only=A , use_auth_token=A , ) UpperCamelCase_ =os.path.join("local" , "--".join(pretrained_model_name_or_path.split("/" ) ) ) except EnvironmentError: logger.error(f"""Could not locate the {module_file} inside {pretrained_model_name_or_path}.""" ) raise # Check we have all the requirements in our environment UpperCamelCase_ =check_imports(A ) # Now we move the module inside our cached dynamic modules. UpperCamelCase_ =DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule create_dynamic_module(A ) UpperCamelCase_ =Path(A ) / full_submodule if submodule == "local" or submodule == "git": # We always copy local files (we could hash the file to see if there was a change, and give them the name of # that hash, to only copy when there is a modification but it seems overkill for now). # The only reason we do the copy is to avoid putting too many folders in sys.path. shutil.copy(A , submodule_path / module_file ) for module_needed in modules_needed: UpperCamelCase_ =f"""{module_needed}.py""" shutil.copy(os.path.join(A , A ) , submodule_path / module_needed ) else: # Get the commit hash # TODO: we will get this info in the etag soon, so retrieve it from there and not here. if isinstance(A , A ): UpperCamelCase_ =use_auth_token elif use_auth_token is True: UpperCamelCase_ =HfFolder.get_token() else: UpperCamelCase_ =None UpperCamelCase_ =model_info(A , revision=A , token=A ).sha # The module file will end up being placed in a subfolder with the git hash of the repo. This way we get the # benefit of versioning. UpperCamelCase_ =submodule_path / commit_hash UpperCamelCase_ =full_submodule + os.path.sep + commit_hash create_dynamic_module(A ) if not (submodule_path / module_file).exists(): shutil.copy(A , submodule_path / module_file ) # Make sure we also have every file with relative for module_needed in modules_needed: if not (submodule_path / module_needed).exists(): get_cached_module_file( A , f"""{module_needed}.py""" , cache_dir=A , force_download=A , resume_download=A , proxies=A , use_auth_token=A , revision=A , local_files_only=A , ) return os.path.join(A , A ) def _UpperCamelCase ( A , A , A = None , A = None , A = False , A = False , A = None , A = None , A = None , A = False , **A , ): UpperCamelCase_ =get_cached_module_file( A , A , cache_dir=A , force_download=A , resume_download=A , proxies=A , use_auth_token=A , revision=A , local_files_only=A , ) return get_class_in_module(A , final_module.replace(".py" , "" ) )
391
1
"""simple docstring""" import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transformers import BartTokenizer, RagTokenizer, TaTokenizer def _a ( _snake_case , _snake_case , _snake_case , _snake_case , _snake_case=True , _snake_case="pt" ): """simple docstring""" UpperCAmelCase = {'add_prefix_space': True} if isinstance(_snake_case , _snake_case ) and not line.startswith(""" """ ) else {} UpperCAmelCase = padding_side return tokenizer( [line] , max_length=_snake_case , padding="""max_length""" if pad_to_max_length else None , truncation=_snake_case , return_tensors=_snake_case , add_special_tokens=_snake_case , **_snake_case , ) def _a ( _snake_case , _snake_case , _snake_case=None , ): """simple docstring""" UpperCAmelCase = input_ids.ne(_snake_case ).any(dim=0 ) if attention_mask is None: return input_ids[:, keep_column_mask] else: return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) class lowerCamelCase__ ( snake_case__ ): def __init__( self ,A ,A ,A ,A ,A="train" ,A=None ,A=None ,A=None ,A="" ,): super().__init__() UpperCAmelCase = Path(_A ).joinpath(type_path + """.source""" ) UpperCAmelCase = Path(_A ).joinpath(type_path + """.target""" ) UpperCAmelCase = self.get_char_lens(self.src_file ) UpperCAmelCase = max_source_length UpperCAmelCase = max_target_length assert min(self.src_lens ) > 0, F'''found empty line in {self.src_file}''' UpperCAmelCase = tokenizer UpperCAmelCase = prefix if n_obs is not None: UpperCAmelCase = self.src_lens[:n_obs] UpperCAmelCase = src_lang UpperCAmelCase = tgt_lang def __len__( self ): return len(self.src_lens ) def __getitem__( self ,A ): UpperCAmelCase = index + 1 # linecache starts at 1 UpperCAmelCase = self.prefix + linecache.getline(str(self.src_file ) ,_A ).rstrip("""\n""" ) UpperCAmelCase = linecache.getline(str(self.tgt_file ) ,_A ).rstrip("""\n""" ) assert source_line, F'''empty source line for index {index}''' assert tgt_line, F'''empty tgt line for index {index}''' # Need to add eos token manually for T5 if isinstance(self.tokenizer ,_A ): source_line += self.tokenizer.eos_token tgt_line += self.tokenizer.eos_token # Pad source and target to the right UpperCAmelCase = ( self.tokenizer.question_encoder if isinstance(self.tokenizer ,_A ) else self.tokenizer ) UpperCAmelCase = self.tokenizer.generator if isinstance(self.tokenizer ,_A ) else self.tokenizer UpperCAmelCase = encode_line(_A ,_A ,self.max_source_length ,"""right""" ) UpperCAmelCase = encode_line(_A ,_A ,self.max_target_length ,"""right""" ) UpperCAmelCase = source_inputs['input_ids'].squeeze() UpperCAmelCase = target_inputs['input_ids'].squeeze() UpperCAmelCase = source_inputs['attention_mask'].squeeze() return { "input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids, } @staticmethod def _UpperCamelCase ( A ): return [len(_A ) for x in Path(_A ).open().readlines()] def _UpperCamelCase ( self ,A ): UpperCAmelCase = torch.stack([x["""input_ids"""] for x in batch] ) UpperCAmelCase = torch.stack([x["""attention_mask"""] for x in batch] ) UpperCAmelCase = torch.stack([x["""decoder_input_ids"""] for x in batch] ) UpperCAmelCase = ( self.tokenizer.generator.pad_token_id if isinstance(self.tokenizer ,_A ) else self.tokenizer.pad_token_id ) UpperCAmelCase = ( self.tokenizer.question_encoder.pad_token_id if isinstance(self.tokenizer ,_A ) else self.tokenizer.pad_token_id ) UpperCAmelCase = trim_batch(_A ,_A ) UpperCAmelCase = trim_batch(_A ,_A ,attention_mask=_A ) UpperCAmelCase = { 'input_ids': source_ids, 'attention_mask': source_mask, 'decoder_input_ids': y, } return batch _UpperCamelCase = getLogger(__name__) def _a ( _snake_case ): """simple docstring""" return list(itertools.chain.from_iterable(_snake_case ) ) def _a ( _snake_case ): """simple docstring""" UpperCAmelCase = get_git_info() save_json(_snake_case , os.path.join(_snake_case , """git_log.json""" ) ) def _a ( _snake_case , _snake_case , _snake_case=4 , **_snake_case ): """simple docstring""" with open(_snake_case , """w""" ) as f: json.dump(_snake_case , _snake_case , indent=_snake_case , **_snake_case ) def _a ( _snake_case ): """simple docstring""" with open(_snake_case ) as f: return json.load(_snake_case ) def _a ( ): """simple docstring""" UpperCAmelCase = git.Repo(search_parent_directories=_snake_case ) UpperCAmelCase = { 'repo_id': str(_snake_case ), 'repo_sha': str(repo.head.object.hexsha ), 'repo_branch': str(repo.active_branch ), 'hostname': str(socket.gethostname() ), } return repo_infos def _a ( _snake_case , _snake_case ): """simple docstring""" return list(map(_snake_case , _snake_case ) ) def _a ( _snake_case , _snake_case ): """simple docstring""" with open(_snake_case , """wb""" ) as f: return pickle.dump(_snake_case , _snake_case ) def _a ( _snake_case ): """simple docstring""" def remove_articles(_snake_case ): return re.sub(R"""\b(a|an|the)\b""" , """ """ , _snake_case ) def white_space_fix(_snake_case ): return " ".join(text.split() ) def remove_punc(_snake_case ): UpperCAmelCase = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(_snake_case ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(_snake_case ) ) ) ) def _a ( _snake_case , _snake_case ): """simple docstring""" UpperCAmelCase = normalize_answer(_snake_case ).split() UpperCAmelCase = normalize_answer(_snake_case ).split() UpperCAmelCase = Counter(_snake_case ) & Counter(_snake_case ) UpperCAmelCase = sum(common.values() ) if num_same == 0: return 0 UpperCAmelCase = 1.0 * num_same / len(_snake_case ) UpperCAmelCase = 1.0 * num_same / len(_snake_case ) UpperCAmelCase = (2 * precision * recall) / (precision + recall) return fa def _a ( _snake_case , _snake_case ): """simple docstring""" return normalize_answer(_snake_case ) == normalize_answer(_snake_case ) def _a ( _snake_case , _snake_case ): """simple docstring""" assert len(_snake_case ) == len(_snake_case ) UpperCAmelCase = 0 for hypo, pred in zip(_snake_case , _snake_case ): em += exact_match_score(_snake_case , _snake_case ) if len(_snake_case ) > 0: em /= len(_snake_case ) return {"em": em} def _a ( _snake_case ): """simple docstring""" return model_prefix.startswith("""rag""" ) def _a ( _snake_case , _snake_case , _snake_case ): """simple docstring""" UpperCAmelCase = {p: p for p in extra_params} # T5 models don't have `dropout` param, they have `dropout_rate` instead UpperCAmelCase = 'dropout_rate' for p in extra_params: if getattr(_snake_case , _snake_case , _snake_case ): if not hasattr(_snake_case , _snake_case ) and not hasattr(_snake_case , equivalent_param[p] ): logger.info("""config doesn\'t have a `{}` attribute""".format(_snake_case ) ) delattr(_snake_case , _snake_case ) continue UpperCAmelCase = p if hasattr(_snake_case , _snake_case ) else equivalent_param[p] setattr(_snake_case , _snake_case , getattr(_snake_case , _snake_case ) ) delattr(_snake_case , _snake_case ) return hparams, config
710
"""simple docstring""" # tests directory-specific settings - this file is run automatically # by pytest before any tests are run import sys import warnings from os.path import abspath, dirname, join # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. _UpperCamelCase = abspath(join(dirname(dirname(__file__)), """src""")) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action="""ignore""", category=FutureWarning) def _a ( _snake_case ): """simple docstring""" from diffusers.utils.testing_utils import pytest_addoption_shared pytest_addoption_shared(_snake_case ) def _a ( _snake_case ): """simple docstring""" from diffusers.utils.testing_utils import pytest_terminal_summary_main UpperCAmelCase = terminalreporter.config.getoption("""--make-reports""" ) if make_reports: pytest_terminal_summary_main(_snake_case , id=_snake_case )
74
0
from unittest import TestCase from datasets import Dataset from minhash_deduplication import deduplicate_dataset, make_duplicate_clusters def A_ ( ) -> int: _snake_case : Optional[int] = { '''repo_name''': ['''test_repo1''', '''test_repo2''', '''test_repo3'''], '''path''': ['''test_1.py''', '''test_2.py''', '''unit_test.py'''], '''content''': ['''a ''' * 20, '''a ''' * 30, '''b ''' * 7], } _snake_case : Tuple = Dataset.from_dict(lowercase_ ) return dataset class A (__UpperCAmelCase ): def __a ( self ) -> Optional[Any]: '''simple docstring''' _snake_case : int = get_dataset() _snake_case : Dict = make_duplicate_clusters(lowercase_ , 0.85 ) self.assertEqual(len(duplicate_clusters[0] ) , 2 ) def __a ( self ) -> Tuple: '''simple docstring''' _snake_case : Tuple = get_dataset() _snake_case , _snake_case : Optional[int] = deduplicate_dataset(lowercase_ ) self.assertEqual(len(lowercase_ ) , 2 ) print(lowercase_ ) self.assertEqual(duplicate_clusters[0][0]['''copies'''] , 2 ) self.assertEqual(duplicate_clusters[0][0]['''is_extreme'''] , lowercase_ )
326
import json import os import unittest from transformers import BatchEncoding, MvpTokenizer, MvpTokenizerFast from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, require_torch from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin, filter_roberta_detectors @require_tokenizers class A (__UpperCAmelCase ,unittest.TestCase ): _SCREAMING_SNAKE_CASE = MvpTokenizer _SCREAMING_SNAKE_CASE = MvpTokenizerFast _SCREAMING_SNAKE_CASE = True _SCREAMING_SNAKE_CASE = filter_roberta_detectors def __a ( self ) -> Union[str, Any]: '''simple docstring''' super().setUp() _snake_case : Union[str, Any] = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''\u0120''', '''\u0120l''', '''\u0120n''', '''\u0120lo''', '''\u0120low''', '''er''', '''\u0120lowest''', '''\u0120newer''', '''\u0120wider''', '''<unk>''', ] _snake_case : Tuple = dict(zip(lowercase_ , range(len(lowercase_ ) ) ) ) _snake_case : List[str] = ['''#version: 0.2''', '''\u0120 l''', '''\u0120l o''', '''\u0120lo w''', '''e r''', ''''''] _snake_case : str = {'''unk_token''': '''<unk>'''} _snake_case : Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) _snake_case : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(lowercase_ ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(lowercase_ ) ) def __a ( self , **lowercase_ ) -> List[Any]: '''simple docstring''' kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **lowercase_ ) def __a ( self , **lowercase_ ) -> Dict: '''simple docstring''' kwargs.update(self.special_tokens_map ) return self.rust_tokenizer_class.from_pretrained(self.tmpdirname , **lowercase_ ) def __a ( self , lowercase_ ) -> Any: '''simple docstring''' return "lower newer", "lower newer" @cached_property def __a ( self ) -> int: '''simple docstring''' return MvpTokenizer.from_pretrained('''RUCAIBox/mvp''' ) @cached_property def __a ( self ) -> str: '''simple docstring''' return MvpTokenizerFast.from_pretrained('''RUCAIBox/mvp''' ) @require_torch def __a ( self ) -> List[str]: '''simple docstring''' _snake_case : int = ['''A long paragraph for summarization.''', '''Another paragraph for summarization.'''] _snake_case : Optional[Any] = [0, 250, 251, 1_7818, 13, 3_9186, 1938, 4, 2] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: _snake_case : Optional[int] = tokenizer(lowercase_ , max_length=len(lowercase_ ) , padding=lowercase_ , return_tensors='''pt''' ) self.assertIsInstance(lowercase_ , lowercase_ ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) _snake_case : int = batch.input_ids.tolist()[0] self.assertListEqual(lowercase_ , lowercase_ ) # Test that special tokens are reset @require_torch def __a ( self ) -> Optional[int]: '''simple docstring''' _snake_case : Dict = ['''A long paragraph for summarization.''', '''Another paragraph for summarization.'''] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: _snake_case : str = tokenizer(lowercase_ , padding=lowercase_ , return_tensors='''pt''' ) # check if input_ids are returned and no labels self.assertIn('''input_ids''' , lowercase_ ) self.assertIn('''attention_mask''' , lowercase_ ) self.assertNotIn('''labels''' , lowercase_ ) self.assertNotIn('''decoder_attention_mask''' , lowercase_ ) @require_torch def __a ( self ) -> Union[str, Any]: '''simple docstring''' _snake_case : Tuple = [ '''Summary of the text.''', '''Another summary.''', ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: _snake_case : List[str] = tokenizer(text_target=lowercase_ , max_length=32 , padding='''max_length''' , return_tensors='''pt''' ) self.assertEqual(32 , targets['''input_ids'''].shape[1] ) @require_torch def __a ( self ) -> Tuple: '''simple docstring''' for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: _snake_case : Union[str, Any] = tokenizer( ['''I am a small frog''' * 1024, '''I am a small frog'''] , padding=lowercase_ , truncation=lowercase_ , return_tensors='''pt''' ) self.assertIsInstance(lowercase_ , lowercase_ ) self.assertEqual(batch.input_ids.shape , (2, 1024) ) @require_torch def __a ( self ) -> int: '''simple docstring''' _snake_case : Dict = ['''A long paragraph for summarization.'''] _snake_case : List[str] = [ '''Summary of the text.''', ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: _snake_case : Dict = tokenizer(lowercase_ , text_target=lowercase_ , return_tensors='''pt''' ) _snake_case : List[Any] = inputs['''input_ids'''] _snake_case : Dict = inputs['''labels'''] self.assertTrue((input_ids[:, 0] == tokenizer.bos_token_id).all().item() ) self.assertTrue((labels[:, 0] == tokenizer.bos_token_id).all().item() ) self.assertTrue((input_ids[:, -1] == tokenizer.eos_token_id).all().item() ) self.assertTrue((labels[:, -1] == tokenizer.eos_token_id).all().item() ) def __a ( self ) -> List[Any]: '''simple docstring''' pass def __a ( self ) -> List[Any]: '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): _snake_case : Dict = self.rust_tokenizer_class.from_pretrained(lowercase_ , **lowercase_ ) _snake_case : str = self.tokenizer_class.from_pretrained(lowercase_ , **lowercase_ ) _snake_case : Optional[Any] = '''A, <mask> AllenNLP sentence.''' _snake_case : Optional[Any] = tokenizer_r.encode_plus(lowercase_ , add_special_tokens=lowercase_ , return_token_type_ids=lowercase_ ) _snake_case : str = tokenizer_p.encode_plus(lowercase_ , add_special_tokens=lowercase_ , return_token_type_ids=lowercase_ ) # token_type_ids should put 0 everywhere self.assertEqual(sum(tokens_r['''token_type_ids'''] ) , sum(tokens_p['''token_type_ids'''] ) ) # attention_mask should put 1 everywhere, so sum over length should be 1 self.assertEqual( sum(tokens_r['''attention_mask'''] ) / len(tokens_r['''attention_mask'''] ) , sum(tokens_p['''attention_mask'''] ) / len(tokens_p['''attention_mask'''] ) , ) _snake_case : List[str] = tokenizer_r.convert_ids_to_tokens(tokens_r['''input_ids'''] ) _snake_case : Dict = tokenizer_p.convert_ids_to_tokens(tokens_p['''input_ids'''] ) # Rust correctly handles the space before the mask while python doesnt self.assertSequenceEqual(tokens_p['''input_ids'''] , [0, 250, 6, 5_0264, 3823, 487, 2_1992, 3645, 4, 2] ) self.assertSequenceEqual(tokens_r['''input_ids'''] , [0, 250, 6, 5_0264, 3823, 487, 2_1992, 3645, 4, 2] ) self.assertSequenceEqual( lowercase_ , ['''<s>''', '''A''', ''',''', '''<mask>''', '''ĠAllen''', '''N''', '''LP''', '''Ġsentence''', '''.''', '''</s>'''] ) self.assertSequenceEqual( lowercase_ , ['''<s>''', '''A''', ''',''', '''<mask>''', '''ĠAllen''', '''N''', '''LP''', '''Ġsentence''', '''.''', '''</s>'''] )
326
1
import copy import inspect import unittest from transformers import AutoBackbone from transformers.configuration_utils import PretrainedConfig from transformers.testing_utils import require_timm, require_torch, torch_device from transformers.utils.import_utils import is_torch_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor if is_torch_available(): import torch from transformers import TimmBackbone, TimmBackboneConfig from ...test_pipeline_mixin import PipelineTesterMixin class SCREAMING_SNAKE_CASE__ : '''simple docstring''' def __init__( self, lowerCamelCase__, lowerCamelCase__=None, lowerCamelCase__=None, lowerCamelCase__=None, lowerCamelCase__="resnet50", lowerCamelCase__=3, lowerCamelCase__=32, lowerCamelCase__=3, lowerCamelCase__=True, lowerCamelCase__=True, ): A : List[Any] = parent A : str = out_indices if out_indices is not None else [4] A : List[Any] = stage_names A : int = out_features A : Dict = backbone A : Any = batch_size A : Dict = image_size A : List[Any] = num_channels A : int = use_pretrained_backbone A : Union[str, Any] = is_training def _lowerCAmelCase ( self ): A : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) A : Dict = self.get_config() return config, pixel_values def _lowerCAmelCase ( self ): return TimmBackboneConfig( image_size=self.image_size, num_channels=self.num_channels, out_features=self.out_features, out_indices=self.out_indices, stage_names=self.stage_names, use_pretrained_backbone=self.use_pretrained_backbone, backbone=self.backbone, ) def _lowerCAmelCase ( self, lowerCamelCase__, lowerCamelCase__ ): A : Dict = TimmBackbone(config=_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() with torch.no_grad(): A : int = model(_lowerCAmelCase ) self.parent.assertEqual( result.feature_map[-1].shape, (self.batch_size, model.channels[-1], 14, 14), ) def _lowerCAmelCase ( self ): A : int = self.prepare_config_and_inputs() A , A : List[Any] = config_and_inputs A : Optional[int] = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch @require_timm class SCREAMING_SNAKE_CASE__ ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' __lowerCamelCase : str = (TimmBackbone,) if is_torch_available() else () __lowerCamelCase : Dict = {'feature-extraction': TimmBackbone} if is_torch_available() else {} __lowerCamelCase : Union[str, Any] = False __lowerCamelCase : List[Any] = False __lowerCamelCase : Tuple = False __lowerCamelCase : Dict = False def _lowerCAmelCase ( self ): A : List[Any] = TimmBackboneModelTester(self ) A : Dict = ConfigTester(self, config_class=_lowerCAmelCase, has_text_modality=_lowerCAmelCase ) def _lowerCAmelCase ( self ): self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _lowerCAmelCase ( self ): A : Optional[int] = """resnet18""" A : Tuple = """microsoft/resnet-18""" A : Optional[Any] = AutoBackbone.from_pretrained(_lowerCAmelCase, use_timm_backbone=_lowerCAmelCase ) A : Tuple = AutoBackbone.from_pretrained(_lowerCAmelCase ) self.assertEqual(len(timm_model.out_features ), len(transformers_model.out_features ) ) self.assertEqual(len(timm_model.stage_names ), len(transformers_model.stage_names ) ) self.assertEqual(timm_model.channels, transformers_model.channels ) # Out indices are set to the last layer by default. For timm models, we don't know # the number of layers in advance, so we set it to (-1,), whereas for transformers # models, we set it to [len(stage_names) - 1] (kept for backward compatibility). self.assertEqual(timm_model.out_indices, (-1,) ) self.assertEqual(transformers_model.out_indices, [len(timm_model.stage_names ) - 1] ) A : Optional[Any] = AutoBackbone.from_pretrained(_lowerCAmelCase, use_timm_backbone=_lowerCAmelCase, out_indices=[1, 2, 3] ) A : Optional[Any] = AutoBackbone.from_pretrained(_lowerCAmelCase, out_indices=[1, 2, 3] ) self.assertEqual(timm_model.out_indices, transformers_model.out_indices ) self.assertEqual(len(timm_model.out_features ), len(transformers_model.out_features ) ) self.assertEqual(timm_model.channels, transformers_model.channels ) @unittest.skip("""TimmBackbone doesn't support feed forward chunking""" ) def _lowerCAmelCase ( self ): pass @unittest.skip("""TimmBackbone doesn't have num_hidden_layers attribute""" ) def _lowerCAmelCase ( self ): pass @unittest.skip("""TimmBackbone initialization is managed on the timm side""" ) def _lowerCAmelCase ( self ): pass @unittest.skip("""TimmBackbone models doesn't have inputs_embeds""" ) def _lowerCAmelCase ( self ): pass @unittest.skip("""TimmBackbone models doesn't have inputs_embeds""" ) def _lowerCAmelCase ( self ): pass @unittest.skip("""TimmBackbone model cannot be created without specifying a backbone checkpoint""" ) def _lowerCAmelCase ( self ): pass @unittest.skip("""Only checkpoints on timm can be loaded into TimmBackbone""" ) def _lowerCAmelCase ( self ): pass @unittest.skip("""model weights aren't tied in TimmBackbone.""" ) def _lowerCAmelCase ( self ): pass @unittest.skip("""model weights aren't tied in TimmBackbone.""" ) def _lowerCAmelCase ( self ): pass @unittest.skip("""Only checkpoints on timm can be loaded into TimmBackbone""" ) def _lowerCAmelCase ( self ): pass @unittest.skip("""Only checkpoints on timm can be loaded into TimmBackbone""" ) def _lowerCAmelCase ( self ): pass @unittest.skip("""TimmBackbone doesn't have hidden size info in its configuration.""" ) def _lowerCAmelCase ( self ): pass @unittest.skip("""TimmBackbone doesn't support output_attentions.""" ) def _lowerCAmelCase ( self ): pass @unittest.skip("""Safetensors is not supported by timm.""" ) def _lowerCAmelCase ( self ): pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def _lowerCAmelCase ( self ): pass def _lowerCAmelCase ( self ): A , A : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A : List[str] = model_class(_lowerCAmelCase ) A : Optional[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic A : List[str] = [*signature.parameters.keys()] A : Any = ["""pixel_values"""] self.assertListEqual(arg_names[:1], _lowerCAmelCase ) def _lowerCAmelCase ( self ): A , A : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() A : str = True A : List[Any] = self.has_attentions # no need to test all models as different heads yield the same functionality A : List[Any] = self.all_model_classes[0] A : List[Any] = model_class(_lowerCAmelCase ) model.to(_lowerCAmelCase ) A : Union[str, Any] = self._prepare_for_class(_lowerCAmelCase, _lowerCAmelCase ) A : Tuple = model(**_lowerCAmelCase ) A : Any = outputs[0][-1] # Encoder-/Decoder-only models A : Any = outputs.hidden_states[0] hidden_states.retain_grad() if self.has_attentions: A : List[str] = outputs.attentions[0] attentions.retain_grad() output.flatten()[0].backward(retain_graph=_lowerCAmelCase ) self.assertIsNotNone(hidden_states.grad ) if self.has_attentions: self.assertIsNotNone(attentions.grad ) def _lowerCAmelCase ( self ): A , A : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A : Tuple = model_class(_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() A : List[Any] = model(**_lowerCAmelCase ) self.assertEqual(len(result.feature_maps ), len(config.out_indices ) ) self.assertEqual(len(model.channels ), len(config.out_indices ) ) # Check output of last stage is taken if out_features=None, out_indices=None A : List[str] = copy.deepcopy(_lowerCAmelCase ) A : str = None A : List[str] = model_class(_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() A : Tuple = model(**_lowerCAmelCase ) self.assertEqual(len(result.feature_maps ), 1 ) self.assertEqual(len(model.channels ), 1 ) # Check backbone can be initialized with fresh weights A : Optional[int] = copy.deepcopy(_lowerCAmelCase ) A : List[Any] = False A : List[str] = model_class(_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() A : Dict = model(**_lowerCAmelCase )
709
import itertools import random import unittest import numpy as np from transformers import is_speech_available from transformers.testing_utils import require_torch, require_torchaudio from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import SpeechaTextFeatureExtractor SCREAMING_SNAKE_CASE_:Union[str, Any] = random.Random() def __UpperCamelCase ( _lowerCAmelCase , _lowerCAmelCase=1.0 , _lowerCAmelCase=None , _lowerCAmelCase=None ) -> Optional[Any]: """simple docstring""" if rng is None: A : str = global_rng A : Optional[int] = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch @require_torchaudio class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): '''simple docstring''' def __init__( self, lowerCamelCase__, lowerCamelCase__=7, lowerCamelCase__=400, lowerCamelCase__=2000, lowerCamelCase__=24, lowerCamelCase__=24, lowerCamelCase__=0.0, lowerCamelCase__=1_6000, lowerCamelCase__=True, lowerCamelCase__=True, ): A : Optional[int] = parent A : List[Any] = batch_size A : str = min_seq_length A : str = max_seq_length A : List[str] = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) A : Dict = feature_size A : Any = num_mel_bins A : int = padding_value A : Optional[int] = sampling_rate A : str = return_attention_mask A : int = do_normalize def _lowerCAmelCase ( self ): return { "feature_size": self.feature_size, "num_mel_bins": self.num_mel_bins, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def _lowerCAmelCase ( self, lowerCamelCase__=False, lowerCamelCase__=False ): def _flatten(lowerCamelCase__ ): return list(itertools.chain(*lowerCamelCase__ ) ) if equal_length: A : Optional[Any] = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size A : Optional[Any] = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length, self.max_seq_length, self.seq_length_diff ) ] if numpify: A : Tuple = [np.asarray(lowerCamelCase__ ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE__ , unittest.TestCase ): '''simple docstring''' __lowerCamelCase : List[str] = SpeechaTextFeatureExtractor if is_speech_available() else None def _lowerCAmelCase ( self ): A : Tuple = SpeechaTextFeatureExtractionTester(self ) def _lowerCAmelCase ( self, lowerCamelCase__ ): self.assertTrue(np.all(np.mean(lowerCamelCase__, axis=0 ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(lowerCamelCase__, axis=0 ) - 1 ) < 1e-3 ) ) def _lowerCAmelCase ( self ): # Tests that all call wrap to encode_plus and batch_encode_plus A : Optional[int] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 A : List[str] = [floats_list((1, x) )[0] for x in range(800, 1400, 200 )] A : List[Any] = [np.asarray(lowerCamelCase__ ) for speech_input in speech_inputs] # Test feature size A : Any = feature_extractor(lowerCamelCase__, padding=lowerCamelCase__, return_tensors="""np""" ).input_features self.assertTrue(input_features.ndim == 3 ) self.assertTrue(input_features.shape[-1] == feature_extractor.feature_size ) # Test not batched input A : List[str] = feature_extractor(speech_inputs[0], return_tensors="""np""" ).input_features A : Tuple = feature_extractor(np_speech_inputs[0], return_tensors="""np""" ).input_features self.assertTrue(np.allclose(lowerCamelCase__, lowerCamelCase__, atol=1e-3 ) ) # Test batched A : List[Any] = feature_extractor(lowerCamelCase__, return_tensors="""np""" ).input_features A : int = feature_extractor(lowerCamelCase__, return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(lowerCamelCase__, lowerCamelCase__ ): self.assertTrue(np.allclose(lowerCamelCase__, lowerCamelCase__, atol=1e-3 ) ) # Test 2-D numpy arrays are batched. A : Tuple = [floats_list((1, x) )[0] for x in (800, 800, 800)] A : Optional[Any] = np.asarray(lowerCamelCase__ ) A : List[Any] = feature_extractor(lowerCamelCase__, return_tensors="""np""" ).input_features A : str = feature_extractor(lowerCamelCase__, return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(lowerCamelCase__, lowerCamelCase__ ): self.assertTrue(np.allclose(lowerCamelCase__, lowerCamelCase__, atol=1e-3 ) ) def _lowerCAmelCase ( self ): A : Optional[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) A : Dict = [floats_list((1, x) )[0] for x in range(800, 1400, 200 )] A : Any = ["""longest""", """max_length""", """do_not_pad"""] A : int = [None, 16, None] for max_length, padding in zip(lowerCamelCase__, lowerCamelCase__ ): A : Tuple = feature_extractor( lowerCamelCase__, padding=lowerCamelCase__, max_length=lowerCamelCase__, return_attention_mask=lowerCamelCase__ ) A : Tuple = inputs.input_features A : Union[str, Any] = inputs.attention_mask A : Optional[Any] = [np.sum(lowerCamelCase__ ) for x in attention_mask] self._check_zero_mean_unit_variance(input_features[0][: fbank_feat_lengths[0]] ) self._check_zero_mean_unit_variance(input_features[1][: fbank_feat_lengths[1]] ) self._check_zero_mean_unit_variance(input_features[2][: fbank_feat_lengths[2]] ) def _lowerCAmelCase ( self ): A : Optional[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) A : str = [floats_list((1, x) )[0] for x in range(800, 1400, 200 )] A : List[str] = ["""longest""", """max_length""", """do_not_pad"""] A : Tuple = [None, 16, None] for max_length, padding in zip(lowerCamelCase__, lowerCamelCase__ ): A : Union[str, Any] = feature_extractor( lowerCamelCase__, max_length=lowerCamelCase__, padding=lowerCamelCase__, return_tensors="""np""", return_attention_mask=lowerCamelCase__ ) A : Optional[int] = inputs.input_features A : List[Any] = inputs.attention_mask A : str = [np.sum(lowerCamelCase__ ) for x in attention_mask] self._check_zero_mean_unit_variance(input_features[0][: fbank_feat_lengths[0]] ) self.assertTrue(input_features[0][fbank_feat_lengths[0] :].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_features[1][: fbank_feat_lengths[1]] ) self.assertTrue(input_features[0][fbank_feat_lengths[1] :].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_features[2][: fbank_feat_lengths[2]] ) def _lowerCAmelCase ( self ): A : int = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) A : str = [floats_list((1, x) )[0] for x in range(800, 1400, 200 )] A : Optional[Any] = feature_extractor( lowerCamelCase__, padding="""max_length""", max_length=4, truncation=lowerCamelCase__, return_tensors="""np""", return_attention_mask=lowerCamelCase__, ) A : Union[str, Any] = inputs.input_features A : Optional[Any] = inputs.attention_mask A : Dict = np.sum(attention_mask == 1, axis=1 ) self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]] ) self._check_zero_mean_unit_variance(input_features[1] ) self._check_zero_mean_unit_variance(input_features[2] ) def _lowerCAmelCase ( self ): A : str = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) A : Dict = [floats_list((1, x) )[0] for x in range(800, 1400, 200 )] A : List[Any] = feature_extractor( lowerCamelCase__, padding="""longest""", max_length=4, truncation=lowerCamelCase__, return_tensors="""np""", return_attention_mask=lowerCamelCase__, ) A : List[Any] = inputs.input_features A : Optional[Any] = inputs.attention_mask A : List[str] = np.sum(attention_mask == 1, axis=1 ) self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]] ) self._check_zero_mean_unit_variance(input_features[1, : fbank_feat_lengths[1]] ) self._check_zero_mean_unit_variance(input_features[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertEqual(input_features.shape, (3, 4, 24) ) A : int = [floats_list((1, x) )[0] for x in range(800, 1400, 200 )] A : List[str] = feature_extractor( lowerCamelCase__, padding="""longest""", max_length=16, truncation=lowerCamelCase__, return_tensors="""np""", return_attention_mask=lowerCamelCase__, ) A : List[Any] = inputs.input_features A : List[str] = inputs.attention_mask A : List[str] = np.sum(attention_mask == 1, axis=1 ) self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]] ) self._check_zero_mean_unit_variance(input_features[1, : fbank_feat_lengths[1]] ) self._check_zero_mean_unit_variance(input_features[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertEqual(input_features.shape, (3, 6, 24) ) def _lowerCAmelCase ( self ): import torch A : Optional[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) A : Dict = np.random.rand(100, 32 ).astype(np.floataa ) A : str = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: A : Optional[Any] = feature_extractor.pad([{"""input_features""": inputs}], return_tensors="""np""" ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) A : str = feature_extractor.pad([{"""input_features""": inputs}], return_tensors="""pt""" ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def _lowerCAmelCase ( self, lowerCamelCase__ ): from datasets import load_dataset A : List[str] = load_dataset("""hf-internal-testing/librispeech_asr_dummy""", """clean""", split="""validation""" ) # automatic decoding with librispeech A : int = ds.sort("""id""" ).select(range(lowerCamelCase__ ) )[:num_samples]["""audio"""] return [x["array"] for x in speech_samples] def _lowerCAmelCase ( self ): # fmt: off A : Optional[Any] = np.array([ -1.5745, -1.7713, -1.7020, -1.6069, -1.2250, -1.1105, -0.9072, -0.8241, -1.2310, -0.8098, -0.3320, -0.4101, -0.7985, -0.4996, -0.8213, -0.9128, -1.0420, -1.1286, -1.0440, -0.7999, -0.8405, -1.2275, -1.5443, -1.4625, ] ) # fmt: on A : Optional[Any] = self._load_datasamples(1 ) A : Any = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) A : Optional[Any] = feature_extractor(lowerCamelCase__, return_tensors="""pt""" ).input_features self.assertEquals(input_features.shape, (1, 584, 24) ) self.assertTrue(np.allclose(input_features[0, 0, :30], lowerCamelCase__, atol=1e-4 ) )
520
0
import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device if is_torch_available(): from transformers import AutoModelForSeqaSeqLM, AutoTokenizer @require_torch @require_sentencepiece @require_tokenizers class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @slow def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : Any = AutoModelForSeqaSeqLM.from_pretrained("google/mt5-small" , return_dict=UpperCAmelCase_ ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = AutoTokenizer.from_pretrained("google/mt5-small" ) SCREAMING_SNAKE_CASE : str = tokenizer("Hello there" , return_tensors="pt" ).input_ids SCREAMING_SNAKE_CASE : Any = tokenizer("Hi I am" , return_tensors="pt" ).input_ids SCREAMING_SNAKE_CASE : str = model(input_ids.to(UpperCAmelCase_ ) , labels=labels.to(UpperCAmelCase_ ) ).loss SCREAMING_SNAKE_CASE : List[str] = -(labels.shape[-1] * loss.item()) SCREAMING_SNAKE_CASE : Any = -84.9_127 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1E-4 )
62
# 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 ): '''simple docstring''' UpperCamelCase_ : int = StableDiffusionControlNetImgaImgPipeline UpperCamelCase_ : List[Any] = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width'''} UpperCamelCase_ : Optional[Any] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS UpperCamelCase_ : Tuple = IMAGE_TO_IMAGE_IMAGE_PARAMS.union({'''control_image'''} ) UpperCamelCase_ : Any = IMAGE_TO_IMAGE_IMAGE_PARAMS def _A ( self : List[str] ): torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[int] = 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 ) SCREAMING_SNAKE_CASE : int = 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 ) SCREAMING_SNAKE_CASE : Optional[Any] = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=UpperCAmelCase_ , set_alpha_to_one=UpperCAmelCase_ , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Any = 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 ) SCREAMING_SNAKE_CASE : int = 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 , ) SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPTextModel(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) SCREAMING_SNAKE_CASE : str = { "unet": unet, "controlnet": controlnet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "safety_checker": None, "feature_extractor": None, } return components def _A ( self : str , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : int=0 ): if str(UpperCAmelCase_ ).startswith("mps" ): SCREAMING_SNAKE_CASE : Any = torch.manual_seed(UpperCAmelCase_ ) else: SCREAMING_SNAKE_CASE : Optional[Any] = torch.Generator(device=UpperCAmelCase_ ).manual_seed(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = 2 SCREAMING_SNAKE_CASE : Union[str, Any] = randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=UpperCAmelCase_ , device=torch.device(UpperCAmelCase_ ) , ) SCREAMING_SNAKE_CASE : Tuple = floats_tensor(control_image.shape , rng=random.Random(UpperCAmelCase_ ) ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE : str = Image.fromarray(np.uinta(UpperCAmelCase_ ) ).convert("RGB" ).resize((64, 64) ) SCREAMING_SNAKE_CASE : List[str] = { "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 _A ( self : int ): 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 _A ( self : str ): self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2E-3 ) def _A ( self : Union[str, Any] ): self._test_inference_batch_single_identical(expected_max_diff=2E-3 ) class SCREAMING_SNAKE_CASE ( lowerCAmelCase , lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : List[str] = StableDiffusionControlNetImgaImgPipeline UpperCamelCase_ : str = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width'''} UpperCamelCase_ : Optional[int] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS UpperCamelCase_ : Dict = frozenset([] ) # TO_DO: add image_params once refactored VaeImageProcessor.preprocess def _A ( self : Optional[Any] ): torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[Any] = 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(UpperCAmelCase_ : List[Any] ): if isinstance(UpperCAmelCase_ , torch.nn.Convad ): torch.nn.init.normal(m.weight ) m.bias.data.fill_(1.0 ) SCREAMING_SNAKE_CASE : List[str] = 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(UpperCAmelCase_ ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Any = 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(UpperCAmelCase_ ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Any = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=UpperCAmelCase_ , set_alpha_to_one=UpperCAmelCase_ , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Dict = 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 ) SCREAMING_SNAKE_CASE : Tuple = 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 , ) SCREAMING_SNAKE_CASE : Any = CLIPTextModel(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) SCREAMING_SNAKE_CASE : Tuple = MultiControlNetModel([controlneta, controlneta] ) SCREAMING_SNAKE_CASE : Optional[int] = { "unet": unet, "controlnet": controlnet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "safety_checker": None, "feature_extractor": None, } return components def _A ( self : List[str] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Any=0 ): if str(UpperCAmelCase_ ).startswith("mps" ): SCREAMING_SNAKE_CASE : Dict = torch.manual_seed(UpperCAmelCase_ ) else: SCREAMING_SNAKE_CASE : str = torch.Generator(device=UpperCAmelCase_ ).manual_seed(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = 2 SCREAMING_SNAKE_CASE : Tuple = [ randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=UpperCAmelCase_ , device=torch.device(UpperCAmelCase_ ) , ), randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=UpperCAmelCase_ , device=torch.device(UpperCAmelCase_ ) , ), ] SCREAMING_SNAKE_CASE : Optional[int] = floats_tensor(control_image[0].shape , rng=random.Random(UpperCAmelCase_ ) ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE : Union[str, Any] = Image.fromarray(np.uinta(UpperCAmelCase_ ) ).convert("RGB" ).resize((64, 64) ) SCREAMING_SNAKE_CASE : Optional[Any] = { "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 _A ( self : Tuple ): SCREAMING_SNAKE_CASE : Any = self.get_dummy_components() SCREAMING_SNAKE_CASE : str = self.pipeline_class(**UpperCAmelCase_ ) pipe.to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = 10.0 SCREAMING_SNAKE_CASE : Any = 4 SCREAMING_SNAKE_CASE : Optional[int] = self.get_dummy_inputs(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = steps SCREAMING_SNAKE_CASE : int = scale SCREAMING_SNAKE_CASE : Optional[int] = pipe(**UpperCAmelCase_ )[0] SCREAMING_SNAKE_CASE : Optional[Any] = self.get_dummy_inputs(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = steps SCREAMING_SNAKE_CASE : Any = scale SCREAMING_SNAKE_CASE : List[str] = pipe(**UpperCAmelCase_ , control_guidance_start=0.1 , control_guidance_end=0.2 )[0] SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_dummy_inputs(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = steps SCREAMING_SNAKE_CASE : int = scale SCREAMING_SNAKE_CASE : List[Any] = pipe(**UpperCAmelCase_ , control_guidance_start=[0.1, 0.3] , control_guidance_end=[0.2, 0.7] )[0] SCREAMING_SNAKE_CASE : Optional[Any] = self.get_dummy_inputs(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = steps SCREAMING_SNAKE_CASE : Dict = scale SCREAMING_SNAKE_CASE : Dict = pipe(**UpperCAmelCase_ , 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 _A ( self : Union[str, Any] ): 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 _A ( self : str ): self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2E-3 ) def _A ( self : List[Any] ): self._test_inference_batch_single_identical(expected_max_diff=2E-3 ) def _A ( self : Any ): SCREAMING_SNAKE_CASE : Dict = self.get_dummy_components() SCREAMING_SNAKE_CASE : Dict = self.pipeline_class(**UpperCAmelCase_ ) pipe.to(UpperCAmelCase_ ) pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) with tempfile.TemporaryDirectory() as tmpdir: try: # save_pretrained is not implemented for Multi-ControlNet pipe.save_pretrained(UpperCAmelCase_ ) except NotImplementedError: pass @slow @require_torch_gpu class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _A ( self : Optional[Any] ): super().tearDown() gc.collect() torch.cuda.empty_cache() def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : str = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny" ) SCREAMING_SNAKE_CASE : Union[str, Any] = StableDiffusionControlNetImgaImgPipeline.from_pretrained( "runwayml/stable-diffusion-v1-5" , safety_checker=UpperCAmelCase_ , controlnet=UpperCAmelCase_ ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = torch.Generator(device="cpu" ).manual_seed(0 ) SCREAMING_SNAKE_CASE : str = "evil space-punk bird" SCREAMING_SNAKE_CASE : Optional[Any] = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png" ).resize((512, 512) ) SCREAMING_SNAKE_CASE : Optional[int] = load_image( "https://huggingface.co/lllyasviel/sd-controlnet-canny/resolve/main/images/bird.png" ).resize((512, 512) ) SCREAMING_SNAKE_CASE : str = pipe( UpperCAmelCase_ , UpperCAmelCase_ , control_image=UpperCAmelCase_ , generator=UpperCAmelCase_ , output_type="np" , num_inference_steps=50 , strength=0.6 , ) SCREAMING_SNAKE_CASE : int = output.images[0] assert image.shape == (512, 512, 3) SCREAMING_SNAKE_CASE : Dict = 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
62
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) A_ = { "configuration_layoutlmv3": [ "LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP", "LayoutLMv3Config", "LayoutLMv3OnnxConfig", ], "processing_layoutlmv3": ["LayoutLMv3Processor"], "tokenization_layoutlmv3": ["LayoutLMv3Tokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = ["LayoutLMv3TokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ "LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST", "LayoutLMv3ForQuestionAnswering", "LayoutLMv3ForSequenceClassification", "LayoutLMv3ForTokenClassification", "LayoutLMv3Model", "LayoutLMv3PreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ "TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST", "TFLayoutLMv3ForQuestionAnswering", "TFLayoutLMv3ForSequenceClassification", "TFLayoutLMv3ForTokenClassification", "TFLayoutLMv3Model", "TFLayoutLMv3PreTrainedModel", ] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = ["LayoutLMv3FeatureExtractor"] A_ = ["LayoutLMv3ImageProcessor"] if TYPE_CHECKING: from .configuration_layoutlmva import ( LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP, LayoutLMvaConfig, LayoutLMvaOnnxConfig, ) from .processing_layoutlmva import LayoutLMvaProcessor from .tokenization_layoutlmva import LayoutLMvaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutlmva_fast import LayoutLMvaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_layoutlmva import ( LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaModel, LayoutLMvaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_layoutlmva import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, TFLayoutLMvaPreTrainedModel, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_layoutlmva import LayoutLMvaFeatureExtractor from .image_processing_layoutlmva import LayoutLMvaImageProcessor else: import sys A_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
360
def __UpperCamelCase ( a, a, a=False) ->Dict: if isinstance(a, a) and isinstance(a, a): lowerCamelCase__ = len(set_a.intersection(a)) if alternative_union: lowerCamelCase__ = len(a) + len(a) else: lowerCamelCase__ = len(set_a.union(a)) return intersection / union if isinstance(a, (list, tuple)) and isinstance(a, (list, tuple)): lowerCamelCase__ = [element for element in set_a if element in set_b] if alternative_union: lowerCamelCase__ = len(a) + len(a) return len(a) / union else: lowerCamelCase__ = set_a + [element for element in set_b if element not in set_a] return len(a) / len(a) return len(a) / len(a) return None if __name__ == "__main__": A_ = {"a", "b", "c", "d", "e"} A_ = {"c", "d", "e", "f", "h", "i"} print(jaccard_similarity(set_a, set_b))
360
1
from __future__ import annotations def a_ ( SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : float ): '''simple docstring''' if (voltage, current, resistance).count(0 ) != 1: raise ValueError('One and only one argument must be 0' ) if resistance < 0: raise ValueError('Resistance cannot be negative' ) if voltage == 0: return {"voltage": float(current * resistance )} elif current == 0: return {"current": voltage / resistance} elif resistance == 0: return {"resistance": voltage / current} else: raise ValueError('Exactly one argument must be 0' ) if __name__ == "__main__": import doctest doctest.testmod()
464
from math import isqrt def a_ ( SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' _lowerCamelCase : Optional[int] =[True] * max_number for i in range(2 , isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): _lowerCamelCase : str =False return [i for i in range(2 , SCREAMING_SNAKE_CASE__ ) if is_prime[i]] def a_ ( SCREAMING_SNAKE_CASE__ : int = 10**8 ): '''simple docstring''' _lowerCamelCase : Union[str, Any] =calculate_prime_numbers(max_number // 2 ) _lowerCamelCase : Dict =0 _lowerCamelCase : int =0 _lowerCamelCase : Optional[Any] =len(SCREAMING_SNAKE_CASE__ ) - 1 while left <= right: while prime_numbers[left] * prime_numbers[right] >= max_number: right -= 1 semiprimes_count += right - left + 1 left += 1 return semiprimes_count if __name__ == "__main__": print(F"""{solution() = }""")
464
1
'''simple docstring''' from manim import * class __UpperCAmelCase ( __a ): def UpperCAmelCase_ ( self ): lowerCAmelCase_ = Rectangle(height=0.5 , width=0.5 ) lowerCAmelCase_ = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 ) lowerCAmelCase_ = [mem.copy() for i in range(6 )] lowerCAmelCase_ = [mem.copy() for i in range(6 )] lowerCAmelCase_ = VGroup(*_lowerCamelCase ).arrange(_lowerCamelCase , buff=0 ) lowerCAmelCase_ = VGroup(*_lowerCamelCase ).arrange(_lowerCamelCase , buff=0 ) lowerCAmelCase_ = VGroup(_lowerCamelCase , _lowerCamelCase ).arrange(_lowerCamelCase , buff=0 ) lowerCAmelCase_ = Text('''CPU''' , font_size=24 ) lowerCAmelCase_ = Group(_lowerCamelCase , _lowerCamelCase ).arrange(_lowerCamelCase , buff=0.5 , aligned_edge=_lowerCamelCase ) cpu.move_to([-2.5, -0.5, 0] ) self.add(_lowerCamelCase ) lowerCAmelCase_ = [mem.copy() for i in range(4 )] lowerCAmelCase_ = VGroup(*_lowerCamelCase ).arrange(_lowerCamelCase , buff=0 ) lowerCAmelCase_ = Text('''GPU''' , font_size=24 ) lowerCAmelCase_ = Group(_lowerCamelCase , _lowerCamelCase ).arrange(_lowerCamelCase , buff=0.5 , aligned_edge=_lowerCamelCase ) gpu.move_to([-1, -1, 0] ) self.add(_lowerCamelCase ) lowerCAmelCase_ = [mem.copy() for i in range(6 )] lowerCAmelCase_ = VGroup(*_lowerCamelCase ).arrange(_lowerCamelCase , buff=0 ) lowerCAmelCase_ = Text('''Model''' , font_size=24 ) lowerCAmelCase_ = Group(_lowerCamelCase , _lowerCamelCase ).arrange(_lowerCamelCase , buff=0.5 , aligned_edge=_lowerCamelCase ) model.move_to([3, -1.0, 0] ) self.add(_lowerCamelCase ) lowerCAmelCase_ = [] for i, rect in enumerate(_lowerCamelCase ): rect.set_stroke(_lowerCamelCase ) # target = fill.copy().set_fill(YELLOW, opacity=0.7) # target.move_to(rect) # self.add(target) lowerCAmelCase_ = Rectangle(height=0.46 / 4 , width=0.46 / 3 ).set_stroke(width=0.0 ).set_fill(_lowerCamelCase , opacity=0.7 ) if i == 0: cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.02 , direction=_lowerCamelCase ) cpu_target.set_x(cpu_target.get_x() + 0.1 ) elif i == 3: cpu_target.next_to(cpu_targs[0] , direction=_lowerCamelCase , buff=0.0 ) else: cpu_target.next_to(cpu_targs[i - 1] , direction=_lowerCamelCase , buff=0.0 ) self.add(_lowerCamelCase ) cpu_targs.append(_lowerCamelCase ) lowerCAmelCase_ = [mem.copy() for i in range(6 )] lowerCAmelCase_ = VGroup(*_lowerCamelCase ).arrange(_lowerCamelCase , buff=0 ) lowerCAmelCase_ = Text('''Loaded Checkpoint''' , font_size=24 ) lowerCAmelCase_ = Group(_lowerCamelCase , _lowerCamelCase ).arrange(_lowerCamelCase , aligned_edge=_lowerCamelCase , buff=0.4 ) checkpoint.move_to([3, 0.5, 0] ) lowerCAmelCase_ = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) lowerCAmelCase_ = MarkupText( F'''<b>Key:</b>\n\n<span fgcolor=\'{YELLOW}\'>●</span> Empty Model''' , font_size=18 , ) key_text.move_to([-5, 2.4, 0] ) self.add(_lowerCamelCase , _lowerCamelCase ) lowerCAmelCase_ = MarkupText( F'''<span fgcolor=\'{BLUE}\'>●</span> Checkpoint''' , font_size=18 , ) blue_text.next_to(_lowerCamelCase , DOWN * 2.4 , aligned_edge=key_text.get_left() ) lowerCAmelCase_ = MarkupText( F'''Next, a <i><span fgcolor="{BLUE}">second</span></i> model is loaded into memory,\nwith the weights of a <span fgcolor="{BLUE}">single shard</span>.''' , font_size=24 , ) step_a.move_to([2, 2, 0] ) self.play(Write(_lowerCamelCase ) , Write(_lowerCamelCase ) ) self.play(Write(_lowerCamelCase , run_time=1 ) , Create(_lowerCamelCase , run_time=1 ) ) lowerCAmelCase_ = [] lowerCAmelCase_ = [] for i, rect in enumerate(_lowerCamelCase ): lowerCAmelCase_ = fill.copy().set_fill(_lowerCamelCase , opacity=0.7 ) target.move_to(_lowerCamelCase ) first_animations.append(GrowFromCenter(_lowerCamelCase , run_time=1 ) ) lowerCAmelCase_ = target.copy() cpu_target.generate_target() if i < 5: cpu_target.target.move_to(cpu_left_col_base[i + 1] ) else: cpu_target.target.move_to(cpu_right_col_base[i - 5] ) second_animations.append(MoveToTarget(_lowerCamelCase , run_time=1.5 ) ) self.play(*_lowerCamelCase ) self.play(*_lowerCamelCase ) self.wait()
606
'''simple docstring''' from io import BytesIO from typing import List, Union import requests from ..utils import add_end_docstrings, is_decord_available, is_torch_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_decord_available(): import numpy as np from decord import VideoReader if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING A_ : Optional[int] =logging.get_logger(__name__) @add_end_docstrings(__a ) class __UpperCAmelCase ( __a ): def __init__( self , *_lowerCamelCase , **_lowerCamelCase ): super().__init__(*_lowerCamelCase , **_lowerCamelCase ) requires_backends(self , '''decord''' ) self.check_model_type(_lowerCamelCase ) def UpperCAmelCase_ ( self , _lowerCamelCase=None , _lowerCamelCase=None , _lowerCamelCase=None ): lowerCAmelCase_ = {} if frame_sampling_rate is not None: lowerCAmelCase_ = frame_sampling_rate if num_frames is not None: lowerCAmelCase_ = num_frames lowerCAmelCase_ = {} if top_k is not None: lowerCAmelCase_ = top_k return preprocess_params, {}, postprocess_params def __call__( self , _lowerCamelCase , **_lowerCamelCase ): return super().__call__(_lowerCamelCase , **_lowerCamelCase ) def UpperCAmelCase_ ( self , _lowerCamelCase , _lowerCamelCase=None , _lowerCamelCase=1 ): if num_frames is None: lowerCAmelCase_ = self.model.config.num_frames if video.startswith('''http://''' ) or video.startswith('''https://''' ): lowerCAmelCase_ = BytesIO(requests.get(_lowerCamelCase ).content ) lowerCAmelCase_ = VideoReader(_lowerCamelCase ) videoreader.seek(0 ) lowerCAmelCase_ = 0 lowerCAmelCase_ = num_frames * frame_sampling_rate - 1 lowerCAmelCase_ = np.linspace(_lowerCamelCase , _lowerCamelCase , num=_lowerCamelCase , dtype=np.intaa ) lowerCAmelCase_ = videoreader.get_batch(_lowerCamelCase ).asnumpy() lowerCAmelCase_ = list(_lowerCamelCase ) lowerCAmelCase_ = self.image_processor(_lowerCamelCase , return_tensors=self.framework ) return model_inputs def UpperCAmelCase_ ( self , _lowerCamelCase ): lowerCAmelCase_ = self.model(**_lowerCamelCase ) return model_outputs def UpperCAmelCase_ ( self , _lowerCamelCase , _lowerCamelCase=5 ): if top_k > self.model.config.num_labels: lowerCAmelCase_ = self.model.config.num_labels if self.framework == "pt": lowerCAmelCase_ = model_outputs.logits.softmax(-1 )[0] lowerCAmelCase_ ,lowerCAmelCase_ = probs.topk(_lowerCamelCase ) else: raise ValueError(F'''Unsupported framework: {self.framework}''' ) lowerCAmelCase_ = scores.tolist() lowerCAmelCase_ = ids.tolist() return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(_lowerCamelCase , _lowerCamelCase )]
606
1
'''simple docstring''' class lowercase__ : '''simple docstring''' def __init__( self ): '''simple docstring''' UpperCamelCase = {} def UpperCAmelCase ( self ): '''simple docstring''' print(self.vertex ) for i in self.vertex: print(lowerCamelCase__ , ''' -> ''' , ''' -> '''.join([str(lowerCamelCase__ ) for j in self.vertex[i]] ) ) def UpperCAmelCase ( self , lowerCamelCase__ , lowerCamelCase__ ): '''simple docstring''' if from_vertex in self.vertex: self.vertex[from_vertex].append(lowerCamelCase__ ) else: # else make a new vertex UpperCamelCase = [to_vertex] def UpperCAmelCase ( self ): '''simple docstring''' UpperCamelCase = [False] * len(self.vertex ) # call the recursive helper function for i in range(len(self.vertex ) ): if not visited[i]: self.dfs_recursive(lowerCamelCase__ , lowerCamelCase__ ) def UpperCAmelCase ( self , lowerCamelCase__ , lowerCamelCase__ ): '''simple docstring''' UpperCamelCase = True print(lowerCamelCase__ , end=''' ''' ) # Recur for all the vertices that are adjacent to this node for i in self.vertex: if not visited[i]: self.dfs_recursive(lowerCamelCase__ , lowerCamelCase__ ) if __name__ == "__main__": snake_case_ : Optional[int] = Graph() g.add_edge(0, 1) g.add_edge(0, 2) g.add_edge(1, 2) g.add_edge(2, 0) g.add_edge(2, 3) g.add_edge(3, 3) g.print_graph() print('DFS:') g.dfs() # OUTPUT: # 0 -> 1 -> 2 # 1 -> 2 # 2 -> 0 -> 3 # 3 -> 3 # DFS: # 0 1 2 3
212
'''simple docstring''' import unittest import numpy as np from transformers import RobertaConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): from transformers.models.roberta.modeling_flax_roberta import ( FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaModel, ) class lowercase__ ( unittest.TestCase ): '''simple docstring''' def __init__( self , lowerCamelCase__ , lowerCamelCase__=1_3 , lowerCamelCase__=7 , lowerCamelCase__=True , lowerCamelCase__=True , lowerCamelCase__=True , lowerCamelCase__=True , lowerCamelCase__=9_9 , lowerCamelCase__=3_2 , lowerCamelCase__=5 , lowerCamelCase__=4 , lowerCamelCase__=3_7 , lowerCamelCase__="gelu" , lowerCamelCase__=0.1 , lowerCamelCase__=0.1 , lowerCamelCase__=5_1_2 , lowerCamelCase__=1_6 , lowerCamelCase__=2 , lowerCamelCase__=0.02 , lowerCamelCase__=4 , ): '''simple docstring''' UpperCamelCase = parent UpperCamelCase = batch_size UpperCamelCase = seq_length UpperCamelCase = is_training UpperCamelCase = use_attention_mask UpperCamelCase = use_token_type_ids UpperCamelCase = use_labels UpperCamelCase = vocab_size UpperCamelCase = hidden_size UpperCamelCase = num_hidden_layers UpperCamelCase = num_attention_heads UpperCamelCase = intermediate_size UpperCamelCase = hidden_act UpperCamelCase = hidden_dropout_prob UpperCamelCase = attention_probs_dropout_prob UpperCamelCase = max_position_embeddings UpperCamelCase = type_vocab_size UpperCamelCase = type_sequence_label_size UpperCamelCase = initializer_range UpperCamelCase = num_choices def UpperCAmelCase ( self ): '''simple docstring''' UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase = None if self.use_attention_mask: UpperCamelCase = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase = None if self.use_token_type_ids: UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCamelCase = RobertaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=lowerCamelCase__ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def UpperCAmelCase ( self ): '''simple docstring''' UpperCamelCase = self.prepare_config_and_inputs() UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = config_and_inputs UpperCamelCase = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': attention_mask} return config, inputs_dict def UpperCAmelCase ( self ): '''simple docstring''' UpperCamelCase = self.prepare_config_and_inputs() UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = config_and_inputs UpperCamelCase = True UpperCamelCase = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, encoder_hidden_states, encoder_attention_mask, ) @require_flax class lowercase__ ( snake_case_, unittest.TestCase ): '''simple docstring''' _snake_case = True _snake_case = ( ( FlaxRobertaModel, FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, ) if is_flax_available() else () ) def UpperCAmelCase ( self ): '''simple docstring''' UpperCamelCase = FlaxRobertaModelTester(self ) @slow def UpperCAmelCase ( self ): '''simple docstring''' for model_class_name in self.all_model_classes: UpperCamelCase = model_class_name.from_pretrained('''roberta-base''' , from_pt=lowerCamelCase__ ) UpperCamelCase = model(np.ones((1, 1) ) ) self.assertIsNotNone(lowerCamelCase__ )
212
1
'''simple docstring''' from collections import defaultdict def UpperCamelCase__ ( _lowercase : str , _lowercase : str ) -> bool: __UpperCAmelCase: Dict = first_str.lower().strip() __UpperCAmelCase: List[Any] = second_str.lower().strip() # Remove whitespace __UpperCAmelCase: Optional[int] = first_str.replace(""" """ , """""" ) __UpperCAmelCase: Optional[int] = second_str.replace(""" """ , """""" ) # Strings of different lengths are not anagrams if len(_A ) != len(_A ): return False # Default values for count should be 0 __UpperCAmelCase: Tuple = defaultdict(_A ) # For each character in input strings, # increment count in the corresponding for i in range(len(_A ) ): count[first_str[i]] += 1 count[second_str[i]] -= 1 return all(_count == 0 for _count in count.values() ) if __name__ == "__main__": from doctest import testmod testmod() SCREAMING_SNAKE_CASE_ = input('Enter the first string ').strip() SCREAMING_SNAKE_CASE_ = input('Enter the second string ').strip() SCREAMING_SNAKE_CASE_ = check_anagrams(input_a, input_b) print(f"""{input_a} and {input_b} are {"" if status else "not "}anagrams.""")
709
'''simple docstring''' def UpperCamelCase__ ( _lowercase : list ) -> list: if len(_lowercase ) <= 1: return lst __UpperCAmelCase: List[str] = 1 while i < len(_lowercase ): if lst[i - 1] <= lst[i]: i += 1 else: __UpperCAmelCase, __UpperCAmelCase: Tuple = lst[i], lst[i - 1] i -= 1 if i == 0: __UpperCAmelCase: List[str] = 1 return lst if __name__ == "__main__": SCREAMING_SNAKE_CASE_ = input('Enter numbers separated by a comma:\n').strip() SCREAMING_SNAKE_CASE_ = [int(item) for item in user_input.split(',')] print(gnome_sort(unsorted))
466
0
"""simple docstring""" import math def SCREAMING_SNAKE_CASE ( __UpperCAmelCase ) -> bool: SCREAMING_SNAKE_CASE__ = math.loga(math.sqrt(4 * positive_integer + 1 ) / 2 + 1 / 2 ) return exponent == int(__UpperCAmelCase ) def SCREAMING_SNAKE_CASE ( __UpperCAmelCase = 1 / 12_345 ) -> int: SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 3 while True: SCREAMING_SNAKE_CASE__ = (integer**2 - 1) / 4 # if candidate is an integer, then there is a partition for k if partition_candidate == int(__UpperCAmelCase ): SCREAMING_SNAKE_CASE__ = int(__UpperCAmelCase ) total_partitions += 1 if check_partition_perfect(__UpperCAmelCase ): perfect_partitions += 1 if perfect_partitions > 0: if perfect_partitions / total_partitions < max_proportion: return int(__UpperCAmelCase ) integer += 1 if __name__ == "__main__": print(F'{solution() = }')
159
"""simple docstring""" import re from pathlib import Path from unittest import TestCase import pytest @pytest.mark.integration class lowerCamelCase (_SCREAMING_SNAKE_CASE ): '''simple docstring''' def lowerCAmelCase_ ( self : Optional[Any] , _snake_case : str ) -> List[str]: with open(_snake_case , encoding="utf-8" ) as input_file: SCREAMING_SNAKE_CASE__ = re.compile(r"(?!.*\b(?:encoding|rb|w|wb|w+|wb+|ab|ab+)\b)(?<=\s)(open)\((.*)\)" ) SCREAMING_SNAKE_CASE__ = input_file.read() SCREAMING_SNAKE_CASE__ = regexp.search(_snake_case ) return match def lowerCAmelCase_ ( self : str , _snake_case : str ) -> List[str]: with open(_snake_case , encoding="utf-8" ) as input_file: SCREAMING_SNAKE_CASE__ = re.compile(r"#[^\r\n]*print\(|\"[^\r\n]*print\(|\"\"\".*?print\(.*?\"\"\"|(print\()" , re.DOTALL ) SCREAMING_SNAKE_CASE__ = input_file.read() # use `re.finditer` to handle the case where the ignored groups would be matched first by `re.search` SCREAMING_SNAKE_CASE__ = regexp.finditer(_snake_case ) SCREAMING_SNAKE_CASE__ = [match for match in matches if match is not None and match.group(1 ) is not None] return matches[0] if matches else None def lowerCAmelCase_ ( self : Tuple ) -> str: SCREAMING_SNAKE_CASE__ = Path("./datasets" ) SCREAMING_SNAKE_CASE__ = list(dataset_paths.absolute().glob("**/*.py" ) ) for dataset in dataset_files: if self._no_encoding_on_file_open(str(_snake_case ) ): raise AssertionError(F"""open(...) must use utf-8 encoding in {dataset}""" ) def lowerCAmelCase_ ( self : int ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ = Path("./datasets" ) SCREAMING_SNAKE_CASE__ = list(dataset_paths.absolute().glob("**/*.py" ) ) for dataset in dataset_files: if self._no_print_statements(str(_snake_case ) ): raise AssertionError(F"""print statement found in {dataset}. Use datasets.logger/logging instead.""" )
159
1
'''simple docstring''' import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ConvNextConfig, SegformerImageProcessor, UperNetConfig, UperNetForSemanticSegmentation def __UpperCamelCase( _A : Optional[int] ): '''simple docstring''' UpperCAmelCase__ : Union[str, Any] = 3_84 if "tiny" in model_name: UpperCAmelCase__ : List[Any] = [3, 3, 9, 3] UpperCAmelCase__ : List[Any] = [96, 1_92, 3_84, 7_68] if "small" in model_name: UpperCAmelCase__ : Union[str, Any] = [3, 3, 27, 3] UpperCAmelCase__ : Any = [96, 1_92, 3_84, 7_68] if "base" in model_name: UpperCAmelCase__ : List[Any] = [3, 3, 27, 3] UpperCAmelCase__ : Dict = [1_28, 2_56, 5_12, 10_24] UpperCAmelCase__ : Optional[int] = 5_12 if "large" in model_name: UpperCAmelCase__ : str = [3, 3, 27, 3] UpperCAmelCase__ : Tuple = [1_92, 3_84, 7_68, 15_36] UpperCAmelCase__ : int = 7_68 if "xlarge" in model_name: UpperCAmelCase__ : int = [3, 3, 27, 3] UpperCAmelCase__ : Union[str, Any] = [2_56, 5_12, 10_24, 20_48] UpperCAmelCase__ : Any = 10_24 # set label information UpperCAmelCase__ : List[Any] = 1_50 UpperCAmelCase__ : Union[str, Any] = '''huggingface/label-files''' UpperCAmelCase__ : Optional[Any] = '''ade20k-id2label.json''' UpperCAmelCase__ : Union[str, Any] = json.load(open(hf_hub_download(_A , _A , repo_type='''dataset''' ) , '''r''' ) ) UpperCAmelCase__ : List[Any] = {int(_A ): v for k, v in idalabel.items()} UpperCAmelCase__ : Tuple = {v: k for k, v in idalabel.items()} UpperCAmelCase__ : int = ConvNextConfig( depths=_A , hidden_sizes=_A , out_features=['''stage1''', '''stage2''', '''stage3''', '''stage4'''] ) UpperCAmelCase__ : Optional[int] = UperNetConfig( backbone_config=_A , auxiliary_in_channels=_A , num_labels=_A , idalabel=_A , labelaid=_A , ) return config def __UpperCamelCase( _A : Dict ): '''simple docstring''' UpperCAmelCase__ : Any = [] # fmt: off # stem rename_keys.append(('''backbone.downsample_layers.0.0.weight''', '''backbone.embeddings.patch_embeddings.weight''') ) rename_keys.append(('''backbone.downsample_layers.0.0.bias''', '''backbone.embeddings.patch_embeddings.bias''') ) rename_keys.append(('''backbone.downsample_layers.0.1.weight''', '''backbone.embeddings.layernorm.weight''') ) rename_keys.append(('''backbone.downsample_layers.0.1.bias''', '''backbone.embeddings.layernorm.bias''') ) # stages for i in range(len(config.backbone_config.depths ) ): for j in range(config.backbone_config.depths[i] ): rename_keys.append((F'''backbone.stages.{i}.{j}.gamma''', F'''backbone.encoder.stages.{i}.layers.{j}.layer_scale_parameter''') ) rename_keys.append((F'''backbone.stages.{i}.{j}.depthwise_conv.weight''', F'''backbone.encoder.stages.{i}.layers.{j}.dwconv.weight''') ) rename_keys.append((F'''backbone.stages.{i}.{j}.depthwise_conv.bias''', F'''backbone.encoder.stages.{i}.layers.{j}.dwconv.bias''') ) rename_keys.append((F'''backbone.stages.{i}.{j}.norm.weight''', F'''backbone.encoder.stages.{i}.layers.{j}.layernorm.weight''') ) rename_keys.append((F'''backbone.stages.{i}.{j}.norm.bias''', F'''backbone.encoder.stages.{i}.layers.{j}.layernorm.bias''') ) rename_keys.append((F'''backbone.stages.{i}.{j}.pointwise_conv1.weight''', F'''backbone.encoder.stages.{i}.layers.{j}.pwconv1.weight''') ) rename_keys.append((F'''backbone.stages.{i}.{j}.pointwise_conv1.bias''', F'''backbone.encoder.stages.{i}.layers.{j}.pwconv1.bias''') ) rename_keys.append((F'''backbone.stages.{i}.{j}.pointwise_conv2.weight''', F'''backbone.encoder.stages.{i}.layers.{j}.pwconv2.weight''') ) rename_keys.append((F'''backbone.stages.{i}.{j}.pointwise_conv2.bias''', F'''backbone.encoder.stages.{i}.layers.{j}.pwconv2.bias''') ) if i > 0: rename_keys.append((F'''backbone.downsample_layers.{i}.0.weight''', F'''backbone.encoder.stages.{i}.downsampling_layer.0.weight''') ) rename_keys.append((F'''backbone.downsample_layers.{i}.0.bias''', F'''backbone.encoder.stages.{i}.downsampling_layer.0.bias''') ) rename_keys.append((F'''backbone.downsample_layers.{i}.1.weight''', F'''backbone.encoder.stages.{i}.downsampling_layer.1.weight''') ) rename_keys.append((F'''backbone.downsample_layers.{i}.1.bias''', F'''backbone.encoder.stages.{i}.downsampling_layer.1.bias''') ) rename_keys.append((F'''backbone.norm{i}.weight''', F'''backbone.hidden_states_norms.stage{i+1}.weight''') ) rename_keys.append((F'''backbone.norm{i}.bias''', F'''backbone.hidden_states_norms.stage{i+1}.bias''') ) # decode head rename_keys.extend( [ ('''decode_head.conv_seg.weight''', '''decode_head.classifier.weight'''), ('''decode_head.conv_seg.bias''', '''decode_head.classifier.bias'''), ('''auxiliary_head.conv_seg.weight''', '''auxiliary_head.classifier.weight'''), ('''auxiliary_head.conv_seg.bias''', '''auxiliary_head.classifier.bias'''), ] ) # fmt: on return rename_keys def __UpperCamelCase( _A : str , _A : Any , _A : Optional[int] ): '''simple docstring''' UpperCAmelCase__ : Tuple = dct.pop(_A ) UpperCAmelCase__ : Dict = val def __UpperCamelCase( _A : List[str] , _A : Dict , _A : int ): '''simple docstring''' UpperCAmelCase__ : Any = { '''upernet-convnext-tiny''': '''https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_tiny_fp16_512x512_160k_ade20k/upernet_convnext_tiny_fp16_512x512_160k_ade20k_20220227_124553-cad485de.pth''', '''upernet-convnext-small''': '''https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_small_fp16_512x512_160k_ade20k/upernet_convnext_small_fp16_512x512_160k_ade20k_20220227_131208-1b1e394f.pth''', '''upernet-convnext-base''': '''https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_base_fp16_512x512_160k_ade20k/upernet_convnext_base_fp16_512x512_160k_ade20k_20220227_181227-02a24fc6.pth''', '''upernet-convnext-large''': '''https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_large_fp16_640x640_160k_ade20k/upernet_convnext_large_fp16_640x640_160k_ade20k_20220226_040532-e57aa54d.pth''', '''upernet-convnext-xlarge''': '''https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_xlarge_fp16_640x640_160k_ade20k/upernet_convnext_xlarge_fp16_640x640_160k_ade20k_20220226_080344-95fc38c2.pth''', } UpperCAmelCase__ : Optional[int] = model_name_to_url[model_name] UpperCAmelCase__ : Any = torch.hub.load_state_dict_from_url(_A , map_location='''cpu''' )['''state_dict'''] UpperCAmelCase__ : Union[str, Any] = get_upernet_config(_A ) UpperCAmelCase__ : str = UperNetForSemanticSegmentation(_A ) model.eval() # replace "bn" => "batch_norm" for key in state_dict.copy().keys(): UpperCAmelCase__ : Optional[Any] = state_dict.pop(_A ) if "bn" in key: UpperCAmelCase__ : int = key.replace('''bn''' , '''batch_norm''' ) UpperCAmelCase__ : Union[str, Any] = val # rename keys UpperCAmelCase__ : int = create_rename_keys(_A ) for src, dest in rename_keys: rename_key(_A , _A , _A ) model.load_state_dict(_A ) # verify on image UpperCAmelCase__ : str = '''https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg''' UpperCAmelCase__ : Union[str, Any] = Image.open(requests.get(_A , stream=_A ).raw ).convert('''RGB''' ) UpperCAmelCase__ : Union[str, Any] = SegformerImageProcessor() UpperCAmelCase__ : Tuple = processor(_A , return_tensors='''pt''' ).pixel_values with torch.no_grad(): UpperCAmelCase__ : Dict = model(_A ) if model_name == "upernet-convnext-tiny": UpperCAmelCase__ : Dict = torch.tensor( [[-8.8_1_1_0, -8.8_1_1_0, -8.6_5_2_1], [-8.8_1_1_0, -8.8_1_1_0, -8.6_5_2_1], [-8.7_7_4_6, -8.7_7_4_6, -8.6_1_3_0]] ) elif model_name == "upernet-convnext-small": UpperCAmelCase__ : Any = torch.tensor( [[-8.8_2_3_6, -8.8_2_3_6, -8.6_7_7_1], [-8.8_2_3_6, -8.8_2_3_6, -8.6_7_7_1], [-8.7_6_3_8, -8.7_6_3_8, -8.6_2_4_0]] ) elif model_name == "upernet-convnext-base": UpperCAmelCase__ : Dict = torch.tensor( [[-8.8_5_5_8, -8.8_5_5_8, -8.6_9_0_5], [-8.8_5_5_8, -8.8_5_5_8, -8.6_9_0_5], [-8.7_6_6_9, -8.7_6_6_9, -8.6_0_2_1]] ) elif model_name == "upernet-convnext-large": UpperCAmelCase__ : Optional[Any] = torch.tensor( [[-8.6_6_6_0, -8.6_6_6_0, -8.6_2_1_0], [-8.6_6_6_0, -8.6_6_6_0, -8.6_2_1_0], [-8.6_3_1_0, -8.6_3_1_0, -8.5_9_6_4]] ) elif model_name == "upernet-convnext-xlarge": UpperCAmelCase__ : Tuple = torch.tensor( [[-8.4_9_8_0, -8.4_9_8_0, -8.3_9_7_7], [-8.4_9_8_0, -8.4_9_8_0, -8.3_9_7_7], [-8.4_3_7_9, -8.4_3_7_9, -8.3_4_1_2]] ) print('''Logits:''' , outputs.logits[0, 0, :3, :3] ) assert torch.allclose(outputs.logits[0, 0, :3, :3] , _A , atol=1e-4 ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: print(F'''Saving model {model_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(_A ) print(F'''Saving processor to {pytorch_dump_folder_path}''' ) processor.save_pretrained(_A ) if push_to_hub: print(F'''Pushing model and processor for {model_name} to hub''' ) model.push_to_hub(F'''openmmlab/{model_name}''' ) processor.push_to_hub(F'''openmmlab/{model_name}''' ) if __name__ == "__main__": UpperCamelCase__ : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='upernet-convnext-tiny', type=str, choices=[f"""upernet-convnext-{size}""" for size in ['tiny', 'small', 'base', 'large', 'xlarge']], help='Name of the ConvNext UperNet 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.' ) UpperCamelCase__ : List[Any] = parser.parse_args() convert_upernet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
496
'''simple docstring''' import collections import inspect import unittest from typing import Dict, List, Tuple from transformers import MaskFormerSwinConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, torch_device from transformers.utils import is_torch_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import MaskFormerSwinBackbone from transformers.models.maskformer import MaskFormerSwinModel class _lowercase : '''simple docstring''' def __init__( self ,lowerCamelCase_ ,lowerCamelCase_=13 ,lowerCamelCase_=32 ,lowerCamelCase_=2 ,lowerCamelCase_=3 ,lowerCamelCase_=16 ,lowerCamelCase_=[1, 2, 1] ,lowerCamelCase_=[2, 2, 4] ,lowerCamelCase_=2 ,lowerCamelCase_=2.0 ,lowerCamelCase_=True ,lowerCamelCase_=0.0 ,lowerCamelCase_=0.0 ,lowerCamelCase_=0.1 ,lowerCamelCase_="gelu" ,lowerCamelCase_=False ,lowerCamelCase_=True ,lowerCamelCase_=0.02 ,lowerCamelCase_=1e-5 ,lowerCamelCase_=True ,lowerCamelCase_=None ,lowerCamelCase_=True ,lowerCamelCase_=10 ,lowerCamelCase_=8 ,lowerCamelCase_=["stage1", "stage2", "stage3"] ,lowerCamelCase_=[1, 2, 3] ,) -> str: '''simple docstring''' UpperCAmelCase__ : Optional[Any] = parent UpperCAmelCase__ : Optional[Any] = batch_size UpperCAmelCase__ : Tuple = image_size UpperCAmelCase__ : Tuple = patch_size UpperCAmelCase__ : int = num_channels UpperCAmelCase__ : str = embed_dim UpperCAmelCase__ : List[str] = depths UpperCAmelCase__ : List[Any] = num_heads UpperCAmelCase__ : Optional[Any] = window_size UpperCAmelCase__ : Tuple = mlp_ratio UpperCAmelCase__ : List[str] = qkv_bias UpperCAmelCase__ : List[str] = hidden_dropout_prob UpperCAmelCase__ : str = attention_probs_dropout_prob UpperCAmelCase__ : Any = drop_path_rate UpperCAmelCase__ : List[Any] = hidden_act UpperCAmelCase__ : Optional[int] = use_absolute_embeddings UpperCAmelCase__ : int = patch_norm UpperCAmelCase__ : Dict = layer_norm_eps UpperCAmelCase__ : Tuple = initializer_range UpperCAmelCase__ : Optional[int] = is_training UpperCAmelCase__ : List[Any] = scope UpperCAmelCase__ : Any = use_labels UpperCAmelCase__ : Any = type_sequence_label_size UpperCAmelCase__ : Any = encoder_stride UpperCAmelCase__ : Optional[int] = out_features UpperCAmelCase__ : Optional[Any] = out_indices def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' UpperCAmelCase__ : List[str] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCAmelCase__ : Any = None if self.use_labels: UpperCAmelCase__ : List[str] = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) UpperCAmelCase__ : Tuple = self.get_config() return config, pixel_values, labels def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' return MaskFormerSwinConfig( image_size=self.image_size ,patch_size=self.patch_size ,num_channels=self.num_channels ,embed_dim=self.embed_dim ,depths=self.depths ,num_heads=self.num_heads ,window_size=self.window_size ,mlp_ratio=self.mlp_ratio ,qkv_bias=self.qkv_bias ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,drop_path_rate=self.drop_path_rate ,hidden_act=self.hidden_act ,use_absolute_embeddings=self.use_absolute_embeddings ,path_norm=self.patch_norm ,layer_norm_eps=self.layer_norm_eps ,initializer_range=self.initializer_range ,encoder_stride=self.encoder_stride ,out_features=self.out_features ,out_indices=self.out_indices ,) def lowerCAmelCase__ ( self ,lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ) -> List[str]: '''simple docstring''' UpperCAmelCase__ : Union[str, Any] = MaskFormerSwinModel(config=lowerCamelCase_ ) model.to(lowerCamelCase_ ) model.eval() UpperCAmelCase__ : Union[str, Any] = model(lowerCamelCase_ ) UpperCAmelCase__ : Any = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) UpperCAmelCase__ : Optional[int] = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, expected_seq_len, expected_dim) ) def lowerCAmelCase__ ( self ,lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ) -> Union[str, Any]: '''simple docstring''' UpperCAmelCase__ : Union[str, Any] = MaskFormerSwinBackbone(config=lowerCamelCase_ ) model.to(lowerCamelCase_ ) model.eval() UpperCAmelCase__ : Optional[Any] = model(lowerCamelCase_ ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) ,len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) ,[13, 16, 16, 16] ) # verify channels self.parent.assertEqual(len(model.channels ) ,len(config.out_features ) ) self.parent.assertListEqual(model.channels ,[16, 32, 64] ) # verify ValueError with self.parent.assertRaises(lowerCamelCase_ ): UpperCAmelCase__ : List[Any] = ['''stem'''] UpperCAmelCase__ : int = MaskFormerSwinBackbone(config=lowerCamelCase_ ) def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' UpperCAmelCase__ : List[Any] = self.prepare_config_and_inputs() UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ : List[Any] = config_and_inputs UpperCAmelCase__ : str = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class _lowercase ( lowerCAmelCase ,lowerCAmelCase ,unittest.TestCase ): '''simple docstring''' UpperCAmelCase_ : str = ( ( MaskFormerSwinModel, MaskFormerSwinBackbone, ) if is_torch_available() else () ) UpperCAmelCase_ : Union[str, Any] = {'''feature-extraction''': MaskFormerSwinModel} if is_torch_available() else {} UpperCAmelCase_ : Optional[Any] = False UpperCAmelCase_ : Any = False UpperCAmelCase_ : str = False UpperCAmelCase_ : Union[str, Any] = False UpperCAmelCase_ : List[str] = False def lowerCAmelCase__ ( self ) -> Any: '''simple docstring''' UpperCAmelCase__ : Tuple = MaskFormerSwinModelTester(self ) UpperCAmelCase__ : List[str] = ConfigTester(self ,config_class=lowerCamelCase_ ,embed_dim=37 ) @require_torch_multi_gpu @unittest.skip( reason=( '''`MaskFormerSwinModel` outputs `hidden_states_spatial_dimensions` which doesn\'t work well with''' ''' `nn.DataParallel`''' ) ) def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' pass def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' return def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' UpperCAmelCase__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCamelCase_ ) def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*lowerCamelCase_ ) @unittest.skip('''Swin does not use inputs_embeds''' ) def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' pass @unittest.skip('''Swin does not support feedforward chunking''' ) def lowerCAmelCase__ ( self ) -> Any: '''simple docstring''' pass def lowerCAmelCase__ ( self ) -> Any: '''simple docstring''' UpperCAmelCase__ , UpperCAmelCase__ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase__ : Optional[int] = model_class(lowerCamelCase_ ) self.assertIsInstance(model.get_input_embeddings() ,(nn.Module) ) UpperCAmelCase__ : int = model.get_output_embeddings() self.assertTrue(x is None or isinstance(lowerCamelCase_ ,nn.Linear ) ) def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' UpperCAmelCase__ , UpperCAmelCase__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase__ : List[Any] = model_class(lowerCamelCase_ ) UpperCAmelCase__ : Optional[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCAmelCase__ : Dict = [*signature.parameters.keys()] UpperCAmelCase__ : Optional[int] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] ,lowerCamelCase_ ) @unittest.skip(reason='''MaskFormerSwin is only used as backbone and doesn\'t support output_attentions''' ) def lowerCAmelCase__ ( self ) -> Any: '''simple docstring''' pass @unittest.skip(reason='''MaskFormerSwin is only used as an internal backbone''' ) def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' pass def lowerCAmelCase__ ( self ,lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ) -> Optional[int]: '''simple docstring''' UpperCAmelCase__ : str = model_class(lowerCamelCase_ ) model.to(lowerCamelCase_ ) model.eval() with torch.no_grad(): UpperCAmelCase__ : List[Any] = model(**self._prepare_for_class(lowerCamelCase_ ,lowerCamelCase_ ) ) UpperCAmelCase__ : Optional[int] = outputs.hidden_states UpperCAmelCase__ : Union[str, Any] = getattr( self.model_tester ,'''expected_num_hidden_layers''' ,len(self.model_tester.depths ) + 1 ) self.assertEqual(len(lowerCamelCase_ ) ,lowerCamelCase_ ) # Swin has a different seq_length UpperCAmelCase__ : Tuple = ( config.patch_size if isinstance(config.patch_size ,collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) UpperCAmelCase__ : Union[str, Any] = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) ,[num_patches, self.model_tester.embed_dim] ,) def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' UpperCAmelCase__ , UpperCAmelCase__ : int = self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase__ : Optional[int] = ( self.model_tester.image_size if isinstance(self.model_tester.image_size ,collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes: UpperCAmelCase__ : Tuple = True self.check_hidden_states_output(lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCAmelCase__ : Optional[Any] = True self.check_hidden_states_output(lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ) def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' UpperCAmelCase__ , UpperCAmelCase__ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase__ : List[Any] = 3 UpperCAmelCase__ : List[Any] = ( self.model_tester.image_size if isinstance(self.model_tester.image_size ,collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) UpperCAmelCase__ : Optional[Any] = ( config.patch_size if isinstance(config.patch_size ,collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) UpperCAmelCase__ : List[Any] = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) UpperCAmelCase__ : Optional[int] = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: UpperCAmelCase__ : Optional[int] = True self.check_hidden_states_output(lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,(padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCAmelCase__ : int = True self.check_hidden_states_output(lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,(padded_height, padded_width) ) @unittest.skip(reason='''MaskFormerSwin doesn\'t have pretrained checkpoints''' ) def lowerCAmelCase__ ( self ) -> Any: '''simple docstring''' pass @unittest.skip(reason='''This will be fixed once MaskFormerSwin is replaced by native Swin''' ) def lowerCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' pass @unittest.skip(reason='''This will be fixed once MaskFormerSwin is replaced by native Swin''' ) def lowerCAmelCase__ ( self ) -> Any: '''simple docstring''' pass def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' UpperCAmelCase__ , UpperCAmelCase__ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() def set_nan_tensor_to_zero(lowerCamelCase_ ): UpperCAmelCase__ : int = 0 return t def check_equivalence(lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_={} ): with torch.no_grad(): UpperCAmelCase__ : Any = model(**lowerCamelCase_ ,return_dict=lowerCamelCase_ ,**lowerCamelCase_ ) UpperCAmelCase__ : Optional[int] = model(**lowerCamelCase_ ,return_dict=lowerCamelCase_ ,**lowerCamelCase_ ).to_tuple() def recursive_check(lowerCamelCase_ ,lowerCamelCase_ ): if isinstance(lowerCamelCase_ ,(List, Tuple) ): for tuple_iterable_value, dict_iterable_value in zip(lowerCamelCase_ ,lowerCamelCase_ ): recursive_check(lowerCamelCase_ ,lowerCamelCase_ ) elif isinstance(lowerCamelCase_ ,lowerCamelCase_ ): for tuple_iterable_value, dict_iterable_value in zip( tuple_object.values() ,dict_object.values() ): recursive_check(lowerCamelCase_ ,lowerCamelCase_ ) elif tuple_object is None: return else: self.assertTrue( torch.allclose( set_nan_tensor_to_zero(lowerCamelCase_ ) ,set_nan_tensor_to_zero(lowerCamelCase_ ) ,atol=1e-5 ) ,msg=( '''Tuple and dict output are not equal. Difference:''' f''' {torch.max(torch.abs(tuple_object - dict_object ) )}. Tuple has `nan`:''' f''' {torch.isnan(lowerCamelCase_ ).any()} and `inf`: {torch.isinf(lowerCamelCase_ )}. Dict has''' f''' `nan`: {torch.isnan(lowerCamelCase_ ).any()} and `inf`: {torch.isinf(lowerCamelCase_ )}.''' ) ,) recursive_check(lowerCamelCase_ ,lowerCamelCase_ ) for model_class in self.all_model_classes: UpperCAmelCase__ : List[str] = model_class(lowerCamelCase_ ) model.to(lowerCamelCase_ ) model.eval() UpperCAmelCase__ : Optional[int] = self._prepare_for_class(lowerCamelCase_ ,lowerCamelCase_ ) UpperCAmelCase__ : Any = self._prepare_for_class(lowerCamelCase_ ,lowerCamelCase_ ) check_equivalence(lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ) UpperCAmelCase__ : List[str] = self._prepare_for_class(lowerCamelCase_ ,lowerCamelCase_ ,return_labels=lowerCamelCase_ ) UpperCAmelCase__ : Tuple = self._prepare_for_class(lowerCamelCase_ ,lowerCamelCase_ ,return_labels=lowerCamelCase_ ) check_equivalence(lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ) UpperCAmelCase__ : int = self._prepare_for_class(lowerCamelCase_ ,lowerCamelCase_ ) UpperCAmelCase__ : Optional[Any] = self._prepare_for_class(lowerCamelCase_ ,lowerCamelCase_ ) check_equivalence(lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,{'''output_hidden_states''': True} ) UpperCAmelCase__ : List[Any] = self._prepare_for_class(lowerCamelCase_ ,lowerCamelCase_ ,return_labels=lowerCamelCase_ ) UpperCAmelCase__ : List[str] = self._prepare_for_class(lowerCamelCase_ ,lowerCamelCase_ ,return_labels=lowerCamelCase_ ) check_equivalence(lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,{'''output_hidden_states''': True} ) @require_torch class _lowercase ( unittest.TestCase ,lowerCAmelCase ): '''simple docstring''' UpperCAmelCase_ : Dict = (MaskFormerSwinBackbone,) if is_torch_available() else () UpperCAmelCase_ : Optional[int] = MaskFormerSwinConfig def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' UpperCAmelCase__ : Tuple = MaskFormerSwinModelTester(self ) def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' UpperCAmelCase__ , UpperCAmelCase__ : str = self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase__ : List[str] = inputs_dict['''pixel_values'''].shape[0] for backbone_class in self.all_model_classes: UpperCAmelCase__ : List[str] = backbone_class(lowerCamelCase_ ) backbone.to(lowerCamelCase_ ) backbone.eval() UpperCAmelCase__ : List[Any] = backbone(**lowerCamelCase_ ) # Test default outputs and verify feature maps self.assertIsInstance(outputs.feature_maps ,lowerCamelCase_ ) self.assertTrue(len(outputs.feature_maps ) == len(backbone.channels ) ) for feature_map, n_channels in zip(outputs.feature_maps ,backbone.channels ): self.assertTrue(feature_map.shape[:2] ,(batch_size, n_channels) ) self.assertIsNone(outputs.hidden_states ) self.assertIsNone(outputs.attentions ) # Test output_hidden_states=True UpperCAmelCase__ : str = backbone(**lowerCamelCase_ ,output_hidden_states=lowerCamelCase_ ) self.assertIsNotNone(outputs.hidden_states ) self.assertTrue(len(outputs.hidden_states ) ,len(backbone.stage_names ) ) # We skip the stem layer for hidden_states, n_channels in zip(outputs.hidden_states[1:] ,backbone.channels ): for hidden_state in hidden_states: # Hidden states are in the format (batch_size, (height * width), n_channels) UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ : int = hidden_state.shape self.assertTrue((h_batch_size, h_n_channels) ,(batch_size, n_channels) ) # Test output_attentions=True if self.has_attentions: UpperCAmelCase__ : List[str] = backbone(**lowerCamelCase_ ,output_attentions=lowerCamelCase_ ) self.assertIsNotNone(outputs.attentions )
496
1
def __lowerCAmelCase ( SCREAMING_SNAKE_CASE_ = 100_0000 ): lowercase__ = set(range(3 , SCREAMING_SNAKE_CASE_ , 2 ) ) primes.add(2 ) for p in range(3 , SCREAMING_SNAKE_CASE_ , 2 ): if p not in primes: continue primes.difference_update(set(range(p * p , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) ) lowercase__ = [float(SCREAMING_SNAKE_CASE_ ) for n in range(limit + 1 )] for p in primes: for n in range(SCREAMING_SNAKE_CASE_ , limit + 1 , SCREAMING_SNAKE_CASE_ ): phi[n] *= 1 - 1 / p return int(sum(phi[2:] ) ) if __name__ == "__main__": print(F'{solution() = }')
413
import math def __lowerCAmelCase ( ): lowercase__ = input("Enter message: " ) lowercase__ = int(input(f'''Enter key [2-{len(SCREAMING_SNAKE_CASE_ ) - 1}]: ''' ) ) lowercase__ = input("Encryption/Decryption [e/d]: " ) if mode.lower().startswith("e" ): lowercase__ = encrypt_message(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) elif mode.lower().startswith("d" ): lowercase__ = decrypt_message(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Append pipe symbol (vertical bar) to identify spaces at the end. print(f'''Output:\n{text + "|"}''' ) def __lowerCAmelCase ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): lowercase__ = [""] * key for col in range(SCREAMING_SNAKE_CASE_ ): lowercase__ = col while pointer < len(SCREAMING_SNAKE_CASE_ ): cipher_text[col] += message[pointer] pointer += key return "".join(SCREAMING_SNAKE_CASE_ ) def __lowerCAmelCase ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): lowercase__ = math.ceil(len(SCREAMING_SNAKE_CASE_ ) / key ) lowercase__ = key lowercase__ = (num_cols * num_rows) - len(SCREAMING_SNAKE_CASE_ ) lowercase__ = [""] * num_cols lowercase__ = 0 lowercase__ = 0 for symbol in message: plain_text[col] += symbol col += 1 if ( (col == num_cols) or (col == num_cols - 1) and (row >= num_rows - num_shaded_boxes) ): lowercase__ = 0 row += 1 return "".join(SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": import doctest doctest.testmod() main()
413
1
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, DDIMScheduler, LDMTextToImagePipeline, UNetaDConditionModel from diffusers.utils.testing_utils import ( enable_full_determinism, load_numpy, nightly, require_torch_gpu, slow, torch_device, ) from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class UpperCamelCase ( __snake_case , unittest.TestCase ): __UpperCamelCase =LDMTextToImagePipeline __UpperCamelCase =TEXT_TO_IMAGE_PARAMS - { "negative_prompt", "negative_prompt_embeds", "cross_attention_kwargs", "prompt_embeds", } __UpperCamelCase =PipelineTesterMixin.required_optional_params - { "num_images_per_prompt", "callback", "callback_steps", } __UpperCamelCase =TEXT_TO_IMAGE_BATCH_PARAMS __UpperCamelCase =False def UpperCamelCase ( self : Dict ): """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = UNetaDConditionModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=3_2 , ) SCREAMING_SNAKE_CASE = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule='scaled_linear' , clip_sample=_lowercase , set_alpha_to_one=_lowercase , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = AutoencoderKL( block_out_channels=(3_2, 6_4) , in_channels=3 , out_channels=3 , down_block_types=('DownEncoderBlock2D', 'DownEncoderBlock2D') , up_block_types=('UpDecoderBlock2D', 'UpDecoderBlock2D') , latent_channels=4 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , intermediate_size=3_7 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , ) SCREAMING_SNAKE_CASE = CLIPTextModel(_lowercase ) SCREAMING_SNAKE_CASE = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) SCREAMING_SNAKE_CASE = { """unet""": unet, """scheduler""": scheduler, """vqvae""": vae, """bert""": text_encoder, """tokenizer""": tokenizer, } return components def UpperCamelCase ( self : Any , snake_case__ : List[str] , snake_case__ : List[str]=0 ): """simple docstring""" if str(_lowercase ).startswith('mps' ): SCREAMING_SNAKE_CASE = torch.manual_seed(_lowercase ) else: SCREAMING_SNAKE_CASE = torch.Generator(device=_lowercase ).manual_seed(_lowercase ) SCREAMING_SNAKE_CASE = { """prompt""": """A painting of a squirrel eating a burger""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def UpperCamelCase ( self : int ): """simple docstring""" SCREAMING_SNAKE_CASE = """cpu""" # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = LDMTextToImagePipeline(**_lowercase ) pipe.to(_lowercase ) pipe.set_progress_bar_config(disable=_lowercase ) SCREAMING_SNAKE_CASE = self.get_dummy_inputs(_lowercase ) SCREAMING_SNAKE_CASE = pipe(**_lowercase ).images SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] assert image.shape == (1, 1_6, 1_6, 3) SCREAMING_SNAKE_CASE = np.array([0.6_101, 0.6_156, 0.5_622, 0.4_895, 0.6_661, 0.3_804, 0.5_748, 0.6_136, 0.5_014] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 @slow @require_torch_gpu class UpperCamelCase ( unittest.TestCase ): def UpperCamelCase ( self : Any ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase ( self : Union[str, Any] , snake_case__ : List[str] , snake_case__ : Optional[int]=torch.floataa , snake_case__ : int=0 ): """simple docstring""" SCREAMING_SNAKE_CASE = torch.manual_seed(_lowercase ) SCREAMING_SNAKE_CASE = np.random.RandomState(_lowercase ).standard_normal((1, 4, 3_2, 3_2) ) SCREAMING_SNAKE_CASE = torch.from_numpy(_lowercase ).to(device=_lowercase , dtype=_lowercase ) SCREAMING_SNAKE_CASE = { """prompt""": """A painting of a squirrel eating a burger""", """latents""": latents, """generator""": generator, """num_inference_steps""": 3, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def UpperCamelCase ( self : int ): """simple docstring""" SCREAMING_SNAKE_CASE = LDMTextToImagePipeline.from_pretrained('CompVis/ldm-text2im-large-256' ).to(_lowercase ) pipe.set_progress_bar_config(disable=_lowercase ) SCREAMING_SNAKE_CASE = self.get_inputs(_lowercase ) SCREAMING_SNAKE_CASE = pipe(**_lowercase ).images SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 2_5_6, 2_5_6, 3) SCREAMING_SNAKE_CASE = np.array([0.51_825, 0.52_850, 0.52_543, 0.54_258, 0.52_304, 0.52_569, 0.54_363, 0.55_276, 0.56_878] ) SCREAMING_SNAKE_CASE = np.abs(expected_slice - image_slice ).max() assert max_diff < 1E-3 @nightly @require_torch_gpu class UpperCamelCase ( unittest.TestCase ): def UpperCamelCase ( self : List[Any] ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase ( self : Optional[int] , snake_case__ : Any , snake_case__ : Dict=torch.floataa , snake_case__ : Union[str, Any]=0 ): """simple docstring""" SCREAMING_SNAKE_CASE = torch.manual_seed(_lowercase ) SCREAMING_SNAKE_CASE = np.random.RandomState(_lowercase ).standard_normal((1, 4, 3_2, 3_2) ) SCREAMING_SNAKE_CASE = torch.from_numpy(_lowercase ).to(device=_lowercase , dtype=_lowercase ) SCREAMING_SNAKE_CASE = { """prompt""": """A painting of a squirrel eating a burger""", """latents""": latents, """generator""": generator, """num_inference_steps""": 5_0, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def UpperCamelCase ( self : Optional[Any] ): """simple docstring""" SCREAMING_SNAKE_CASE = LDMTextToImagePipeline.from_pretrained('CompVis/ldm-text2im-large-256' ).to(_lowercase ) pipe.set_progress_bar_config(disable=_lowercase ) SCREAMING_SNAKE_CASE = self.get_inputs(_lowercase ) SCREAMING_SNAKE_CASE = pipe(**_lowercase ).images[0] SCREAMING_SNAKE_CASE = load_numpy( 'https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/ldm_text2img/ldm_large_256_ddim.npy' ) SCREAMING_SNAKE_CASE = np.abs(expected_image - image ).max() assert max_diff < 1E-3
719
import heapq import sys import numpy as np a_ : Optional[int] = tuple[int, int] class UpperCamelCase : def __init__( self : Dict ): """simple docstring""" SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = set() def UpperCamelCase ( self : List[Any] ): """simple docstring""" if not self.empty(): return self.elements[0][0] else: return float('inf' ) def UpperCamelCase ( self : List[str] ): """simple docstring""" return len(self.elements ) == 0 def UpperCamelCase ( self : Union[str, Any] , snake_case__ : Optional[Any] , snake_case__ : List[Any] ): """simple docstring""" if item not in self.set: heapq.heappush(self.elements , (priority, item) ) self.set.add(snake_case__ ) else: # update # print("update", item) SCREAMING_SNAKE_CASE = [] ((SCREAMING_SNAKE_CASE) , (SCREAMING_SNAKE_CASE)) = heapq.heappop(self.elements ) while x != item: temp.append((pri, x) ) ((SCREAMING_SNAKE_CASE) , (SCREAMING_SNAKE_CASE)) = heapq.heappop(self.elements ) temp.append((priority, item) ) for pro, xxx in temp: heapq.heappush(self.elements , (pro, xxx) ) def UpperCamelCase ( self : Dict , snake_case__ : Dict ): """simple docstring""" if item in self.set: self.set.remove(snake_case__ ) SCREAMING_SNAKE_CASE = [] ((SCREAMING_SNAKE_CASE) , (SCREAMING_SNAKE_CASE)) = heapq.heappop(self.elements ) while x != item: temp.append((pro, x) ) ((SCREAMING_SNAKE_CASE) , (SCREAMING_SNAKE_CASE)) = heapq.heappop(self.elements ) for prito, yyy in temp: heapq.heappush(self.elements , (prito, yyy) ) def UpperCamelCase ( self : str ): """simple docstring""" return self.elements[0][1] def UpperCamelCase ( self : Tuple ): """simple docstring""" ((SCREAMING_SNAKE_CASE) , (SCREAMING_SNAKE_CASE)) = heapq.heappop(self.elements ) self.set.remove(snake_case__ ) return (priority, item) def __lowerCAmelCase ( _UpperCamelCase : TPos , _UpperCamelCase : TPos ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = np.array(_UpperCamelCase ) SCREAMING_SNAKE_CASE = np.array(_UpperCamelCase ) return np.linalg.norm(a - b ) def __lowerCAmelCase ( _UpperCamelCase : TPos , _UpperCamelCase : TPos ) -> Dict: '''simple docstring''' return consistent_heuristic(_UpperCamelCase , _UpperCamelCase ) // t def __lowerCAmelCase ( _UpperCamelCase : TPos , _UpperCamelCase : TPos ) -> Optional[int]: '''simple docstring''' return abs(p[0] - goal[0] ) + abs(p[1] - goal[1] ) def __lowerCAmelCase ( _UpperCamelCase : TPos , _UpperCamelCase : int , _UpperCamelCase : TPos , _UpperCamelCase : dict[TPos, float] ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE = g_function[start] + Wa * heuristics[i](_UpperCamelCase , _UpperCamelCase ) return ans def __lowerCAmelCase ( _UpperCamelCase : List[str] , _UpperCamelCase : int , _UpperCamelCase : Tuple ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE = np.chararray((n, n) ) for i in range(_UpperCamelCase ): for j in range(_UpperCamelCase ): SCREAMING_SNAKE_CASE = '*' for i in range(_UpperCamelCase ): for j in range(_UpperCamelCase ): if (j, (n - 1) - i) in blocks: SCREAMING_SNAKE_CASE = '#' SCREAMING_SNAKE_CASE = '-' SCREAMING_SNAKE_CASE = back_pointer[goal] while x != start: ((SCREAMING_SNAKE_CASE) , (SCREAMING_SNAKE_CASE)) = x # print(x) SCREAMING_SNAKE_CASE = '-' SCREAMING_SNAKE_CASE = back_pointer[x] SCREAMING_SNAKE_CASE = '-' for i in range(_UpperCamelCase ): for j in range(_UpperCamelCase ): if (i, j) == (0, n - 1): print(grid[i][j] , end=' ' ) print('<-- End position' , end=' ' ) else: print(grid[i][j] , end=' ' ) print() print('^' ) print('Start position' ) print() print('# is an obstacle' ) print('- is the path taken by algorithm' ) print('PATH TAKEN BY THE ALGORITHM IS:-' ) SCREAMING_SNAKE_CASE = back_pointer[goal] while x != start: print(_UpperCamelCase , end=' ' ) SCREAMING_SNAKE_CASE = back_pointer[x] print(_UpperCamelCase ) sys.exit() def __lowerCAmelCase ( _UpperCamelCase : TPos ) -> Any: '''simple docstring''' if p[0] < 0 or p[0] > n - 1: return False if p[1] < 0 or p[1] > n - 1: return False return True def __lowerCAmelCase ( _UpperCamelCase : List[Any] , _UpperCamelCase : Tuple , _UpperCamelCase : Any , _UpperCamelCase : Union[str, Any] , _UpperCamelCase : Union[str, Any] , _UpperCamelCase : Tuple , _UpperCamelCase : List[Any] , _UpperCamelCase : Optional[Any] , ) -> List[Any]: '''simple docstring''' for itera in range(_UpperCamelCase ): open_list[itera].remove_element(_UpperCamelCase ) # print("s", s) # print("j", j) ((SCREAMING_SNAKE_CASE) , (SCREAMING_SNAKE_CASE)) = s SCREAMING_SNAKE_CASE = (x - 1, y) SCREAMING_SNAKE_CASE = (x + 1, y) SCREAMING_SNAKE_CASE = (x, y + 1) SCREAMING_SNAKE_CASE = (x, y - 1) for neighbours in [left, right, up, down]: if neighbours not in blocks: if valid(_UpperCamelCase ) and neighbours not in visited: # print("neighbour", neighbours) visited.add(_UpperCamelCase ) SCREAMING_SNAKE_CASE = -1 SCREAMING_SNAKE_CASE = float('inf' ) if valid(_UpperCamelCase ) and g_function[neighbours] > g_function[s] + 1: SCREAMING_SNAKE_CASE = g_function[s] + 1 SCREAMING_SNAKE_CASE = s if neighbours not in close_list_anchor: open_list[0].put(_UpperCamelCase , key(_UpperCamelCase , 0 , _UpperCamelCase , _UpperCamelCase ) ) if neighbours not in close_list_inad: for var in range(1 , _UpperCamelCase ): if key(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) <= Wa * key( _UpperCamelCase , 0 , _UpperCamelCase , _UpperCamelCase ): open_list[j].put( _UpperCamelCase , key(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) ) def __lowerCAmelCase ( ) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE = [] for x in range(1 , 5 ): for y in range(1 , 6 ): some_list.append((x, y) ) for x in range(15 , 20 ): some_list.append((x, 17) ) for x in range(10 , 19 ): for y in range(1 , 15 ): some_list.append((x, y) ) # L block for x in range(1 , 4 ): for y in range(12 , 19 ): some_list.append((x, y) ) for x in range(3 , 13 ): for y in range(16 , 19 ): some_list.append((x, y) ) return some_list a_ : str = {0: consistent_heuristic, 1: heuristic_a, 2: heuristic_a} a_ : List[str] = [ (0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1), (8, 1), (9, 1), (10, 1), (11, 1), (12, 1), (13, 1), (14, 1), (15, 1), (16, 1), (17, 1), (18, 1), (19, 1), ] a_ : Union[str, Any] = make_common_ground() a_ : Tuple = blocks_blk # hyper parameters a_ : Any = 1 a_ : List[str] = 1 a_ : Union[str, Any] = 20 a_ : Optional[Any] = 3 # one consistent and two other inconsistent # start and end destination a_ : int = (0, 0) a_ : Optional[int] = (n - 1, n - 1) a_ : Union[str, Any] = 1 def __lowerCAmelCase ( _UpperCamelCase : TPos , _UpperCamelCase : TPos , _UpperCamelCase : int ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = {start: 0, goal: float('inf' )} SCREAMING_SNAKE_CASE = {start: -1, goal: -1} SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = set() for i in range(_UpperCamelCase ): open_list.append(PriorityQueue() ) open_list[i].put(_UpperCamelCase , key(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) ) SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = [] while open_list[0].minkey() < float('inf' ): for i in range(1 , _UpperCamelCase ): # print(open_list[0].minkey(), open_list[i].minkey()) if open_list[i].minkey() <= Wa * open_list[0].minkey(): global t t += 1 if g_function[goal] <= open_list[i].minkey(): if g_function[goal] < float('inf' ): do_something(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) else: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = open_list[i].top_show() visited.add(_UpperCamelCase ) expand_state( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , ) close_list_inad.append(_UpperCamelCase ) else: if g_function[goal] <= open_list[0].minkey(): if g_function[goal] < float('inf' ): do_something(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) else: SCREAMING_SNAKE_CASE = open_list[0].top_show() visited.add(_UpperCamelCase ) expand_state( _UpperCamelCase , 0 , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , ) close_list_anchor.append(_UpperCamelCase ) print('No path found to goal' ) print() for i in range(n - 1 , -1 , -1 ): for j in range(_UpperCamelCase ): if (j, i) in blocks: print('#' , end=' ' ) elif (j, i) in back_pointer: if (j, i) == (n - 1, n - 1): print('*' , end=' ' ) else: print('-' , end=' ' ) else: print('*' , end=' ' ) if (j, i) == (n - 1, n - 1): print('<-- End position' , end=' ' ) print() print('^' ) print('Start position' ) print() print('# is an obstacle' ) print('- is the path taken by algorithm' ) if __name__ == "__main__": multi_a_star(start, goal, n_heuristic)
673
0
'''simple docstring''' from __future__ import annotations def _lowerCAmelCase ( lowerCamelCase_ : list , lowerCamelCase_ : int ): # Checks if the entire collection has been sorted if len(lowerCamelCase_ ) <= 1 or n <= 1: return insert_next(lowerCamelCase_ , n - 1 ) rec_insertion_sort(lowerCamelCase_ , n - 1 ) def _lowerCAmelCase ( lowerCamelCase_ : list , lowerCamelCase_ : int ): # Checks order between adjacent elements if index >= len(lowerCamelCase_ ) or collection[index - 1] <= collection[index]: return # Swaps adjacent elements since they are not in ascending order __lowercase , __lowercase = ( collection[index], collection[index - 1], ) insert_next(lowerCamelCase_ , index + 1 ) if __name__ == "__main__": _SCREAMING_SNAKE_CASE = input('''Enter integers separated by spaces: ''') _SCREAMING_SNAKE_CASE = [int(num) for num in numbers.split()] rec_insertion_sort(number_list, len(number_list)) print(number_list)
502
'''simple docstring''' import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class __lowercase ( lowerCAmelCase__ ): '''simple docstring''' a : List[Any] = ["image_processor", "tokenizer"] a : Optional[int] = "ChineseCLIPImageProcessor" a : Dict = ("BertTokenizer", "BertTokenizerFast") def __init__(self ,_lowerCamelCase=None ,_lowerCamelCase=None ,**_lowerCamelCase ) -> str: '''simple docstring''' __lowercase = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' ,_lowerCamelCase ,) __lowercase = kwargs.pop('''feature_extractor''' ) __lowercase = 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__(_lowerCamelCase ,_lowerCamelCase ) __lowercase = self.image_processor def __call__(self ,_lowerCamelCase=None ,_lowerCamelCase=None ,_lowerCamelCase=None ,**_lowerCamelCase ) -> List[Any]: '''simple docstring''' if text is None and images is None: raise ValueError('''You have to specify either text or images. Both cannot be none.''' ) if text is not None: __lowercase = self.tokenizer(_lowerCamelCase ,return_tensors=_lowerCamelCase ,**_lowerCamelCase ) if images is not None: __lowercase = self.image_processor(_lowerCamelCase ,return_tensors=_lowerCamelCase ,**_lowerCamelCase ) if text is not None and images is not None: __lowercase = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**_lowerCamelCase ) ,tensor_type=_lowerCamelCase ) def _UpperCAmelCase (self ,*_lowerCamelCase ,**_lowerCamelCase ) -> str: '''simple docstring''' return self.tokenizer.batch_decode(*_lowerCamelCase ,**_lowerCamelCase ) def _UpperCAmelCase (self ,*_lowerCamelCase ,**_lowerCamelCase ) -> Dict: '''simple docstring''' return self.tokenizer.decode(*_lowerCamelCase ,**_lowerCamelCase ) @property def _UpperCAmelCase (self ) -> Dict: '''simple docstring''' __lowercase = self.tokenizer.model_input_names __lowercase = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def _UpperCAmelCase (self ) -> int: '''simple docstring''' warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' ,_lowerCamelCase ,) return self.image_processor_class
502
1
"""simple docstring""" from __future__ import annotations from collections.abc import Callable from typing import Any, Generic, TypeVar UpperCAmelCase__ : str = TypeVar("""T""") class a ( Generic[T] ): def __init__( self : str , __lowerCAmelCase : list[T] , __lowerCAmelCase : Callable[[T, T], T] ): _UpperCAmelCase = None _UpperCAmelCase = len(__lowerCAmelCase ) _UpperCAmelCase = [any_type for _ in range(self.N )] + arr _UpperCAmelCase = fnc self.build() def lowerCAmelCase_ ( self : Union[str, Any] ): for p in range(self.N - 1 , 0 , -1 ): _UpperCAmelCase = self.fn(self.st[p * 2] , self.st[p * 2 + 1] ) def lowerCAmelCase_ ( self : Any , __lowerCAmelCase : int , __lowerCAmelCase : T ): p += self.N _UpperCAmelCase = v while p > 1: _UpperCAmelCase = p // 2 _UpperCAmelCase = self.fn(self.st[p * 2] , self.st[p * 2 + 1] ) def lowerCAmelCase_ ( self : int , __lowerCAmelCase : int , __lowerCAmelCase : int ): # noqa: E741 _UpperCAmelCase , _UpperCAmelCase = l + self.N, r + self.N _UpperCAmelCase = None while l <= r: if l % 2 == 1: _UpperCAmelCase = self.st[l] if res is None else self.fn(__lowerCAmelCase , self.st[l] ) if r % 2 == 0: _UpperCAmelCase = self.st[r] if res is None else self.fn(__lowerCAmelCase , self.st[r] ) _UpperCAmelCase , _UpperCAmelCase = (l + 1) // 2, (r - 1) // 2 return res if __name__ == "__main__": from functools import reduce UpperCAmelCase__ : List[str] = [1, 1_0, -2, 9, -3, 8, 4, -7, 5, 6, 1_1, -1_2] UpperCAmelCase__ : Optional[Any] = { 0: 7, 1: 2, 2: 6, 3: -1_4, 4: 5, 5: 4, 6: 7, 7: -1_0, 8: 9, 9: 1_0, 1_0: 1_2, 1_1: 1, } UpperCAmelCase__ : Tuple = SegmentTree(test_array, min) UpperCAmelCase__ : int = SegmentTree(test_array, max) UpperCAmelCase__ : int = SegmentTree(test_array, lambda a, b: a + b) def __UpperCAmelCase ( ): """simple docstring""" for i in range(len(lowercase ) ): for j in range(lowercase ,len(lowercase ) ): _UpperCAmelCase = reduce(lowercase ,test_array[i : j + 1] ) _UpperCAmelCase = reduce(lowercase ,test_array[i : j + 1] ) _UpperCAmelCase = reduce(lambda lowercase ,lowercase : a + b ,test_array[i : j + 1] ) assert min_range == min_segment_tree.query(lowercase ,lowercase ) assert max_range == max_segment_tree.query(lowercase ,lowercase ) assert sum_range == sum_segment_tree.query(lowercase ,lowercase ) test_all_segments() for index, value in test_updates.items(): UpperCAmelCase__ : str = value min_segment_tree.update(index, value) max_segment_tree.update(index, value) sum_segment_tree.update(index, value) test_all_segments()
718
"""simple docstring""" # Lint as: python3 import itertools import os import re UpperCAmelCase__ = re.compile(r"""([A-Z]+)([A-Z][a-z])""") UpperCAmelCase__ = re.compile(r"""([a-z\d])([A-Z])""") UpperCAmelCase__ = re.compile(r"""(?<!_)_(?!_)""") UpperCAmelCase__ = re.compile(r"""(_{2,})""") UpperCAmelCase__ = r"""^\w+(\.\w+)*$""" UpperCAmelCase__ = r"""<>:/\|?*""" def __UpperCAmelCase ( lowercase ): """simple docstring""" _UpperCAmelCase = _uppercase_uppercase_re.sub(R"""\1_\2""" ,lowercase ) _UpperCAmelCase = _lowercase_uppercase_re.sub(R"""\1_\2""" ,lowercase ) return name.lower() def __UpperCAmelCase ( lowercase ): """simple docstring""" _UpperCAmelCase = _single_underscore_re.split(lowercase ) _UpperCAmelCase = [_multiple_underscores_re.split(lowercase ) for n in name] return "".join(n.capitalize() for n in itertools.chain.from_iterable(lowercase ) if n != """""" ) def __UpperCAmelCase ( lowercase ): """simple docstring""" if os.path.basename(lowercase ) != name: raise ValueError(f'''Should be a dataset name, not a path: {name}''' ) return camelcase_to_snakecase(lowercase ) def __UpperCAmelCase ( lowercase ,lowercase ): """simple docstring""" if os.path.basename(lowercase ) != name: raise ValueError(f'''Should be a dataset name, not a path: {name}''' ) if not re.match(_split_re ,lowercase ): raise ValueError(f'''Split name should match \'{_split_re}\'\' but got \'{split}\'.''' ) return f'''{filename_prefix_for_name(lowercase )}-{split}''' def __UpperCAmelCase ( lowercase ,lowercase ,lowercase ,lowercase=None ): """simple docstring""" _UpperCAmelCase = filename_prefix_for_split(lowercase ,lowercase ) if filetype_suffix: prefix += f'''.{filetype_suffix}''' _UpperCAmelCase = os.path.join(lowercase ,lowercase ) return f'''{filepath}*''' def __UpperCAmelCase ( lowercase ,lowercase ,lowercase ,lowercase=None ,lowercase=None ): """simple docstring""" _UpperCAmelCase = filename_prefix_for_split(lowercase ,lowercase ) _UpperCAmelCase = os.path.join(lowercase ,lowercase ) if shard_lengths: _UpperCAmelCase = len(lowercase ) _UpperCAmelCase = [f'''{prefix}-{shard_id:05d}-of-{num_shards:05d}''' for shard_id in range(lowercase )] if filetype_suffix: _UpperCAmelCase = [filename + f'''.{filetype_suffix}''' for filename in filenames] return filenames else: _UpperCAmelCase = prefix if filetype_suffix: filename += f'''.{filetype_suffix}''' return [filename]
275
0
"""simple docstring""" import numpy # List of input, output pairs __lowercase : List[Any] = ( ((5, 2, 3), 1_5), ((6, 5, 9), 2_5), ((1_1, 1_2, 1_3), 4_1), ((1, 1, 1), 8), ((1_1, 1_2, 1_3), 4_1), ) __lowercase : int = (((5_1_5, 2_2, 1_3), 5_5_5), ((6_1, 3_5, 4_9), 1_5_0)) __lowercase : Dict = [2, 4, 1, 5] __lowercase : Tuple = len(train_data) __lowercase : List[str] = 0.0_0_9 def lowerCamelCase_ ( _lowerCamelCase : int , _lowerCamelCase : str="train" ): return calculate_hypothesis_value(_lowerCamelCase , _lowerCamelCase ) - output( _lowerCamelCase , _lowerCamelCase ) def lowerCamelCase_ ( _lowerCamelCase : Any ): lowerCamelCase_ = 0 for i in range(len(_lowerCamelCase ) - 1 ): hyp_val += data_input_tuple[i] * parameter_vector[i + 1] hyp_val += parameter_vector[0] return hyp_val def lowerCamelCase_ ( _lowerCamelCase : str , _lowerCamelCase : Optional[int] ): if data_set == "train": return train_data[example_no][1] elif data_set == "test": return test_data[example_no][1] return None def lowerCamelCase_ ( _lowerCamelCase : Union[str, Any] , _lowerCamelCase : Tuple ): if data_set == "train": return _hypothesis_value(train_data[example_no][0] ) elif data_set == "test": return _hypothesis_value(test_data[example_no][0] ) return None def lowerCamelCase_ ( _lowerCamelCase : Optional[int] , _lowerCamelCase : Tuple=m ): lowerCamelCase_ = 0 for i in range(_lowerCamelCase ): if index == -1: summation_value += _error(_lowerCamelCase ) else: summation_value += _error(_lowerCamelCase ) * train_data[i][0][index] return summation_value def lowerCamelCase_ ( _lowerCamelCase : Optional[Any] ): lowerCamelCase_ = summation_of_cost_derivative(_lowerCamelCase , _lowerCamelCase ) / m return cost_derivative_value def lowerCamelCase_ ( ): global parameter_vector # Tune these values to set a tolerance value for predicted output lowerCamelCase_ = 0.00_00_02 lowerCamelCase_ = 0 lowerCamelCase_ = 0 while True: j += 1 lowerCamelCase_ = [0, 0, 0, 0] for i in range(0 , len(_lowerCamelCase ) ): lowerCamelCase_ = get_cost_derivative(i - 1 ) lowerCamelCase_ = ( parameter_vector[i] - LEARNING_RATE * cost_derivative ) if numpy.allclose( _lowerCamelCase , _lowerCamelCase , atol=_lowerCamelCase , rtol=_lowerCamelCase , ): break lowerCamelCase_ = temp_parameter_vector print(('''Number of iterations:''', j) ) def lowerCamelCase_ ( ): for i in range(len(_lowerCamelCase ) ): print(('''Actual output value:''', output(_lowerCamelCase , '''test''' )) ) print(('''Hypothesis output:''', calculate_hypothesis_value(_lowerCamelCase , '''test''' )) ) if __name__ == "__main__": run_gradient_descent() print("""\nTesting gradient descent for a linear hypothesis function.\n""") test_gradient_descent()
142
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) __lowercase : Optional[Any] = { """configuration_funnel""": ["""FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP""", """FunnelConfig"""], """convert_funnel_original_tf_checkpoint_to_pytorch""": [], """tokenization_funnel""": ["""FunnelTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : int = ["""FunnelTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : Optional[Any] = [ """FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST""", """FunnelBaseModel""", """FunnelForMaskedLM""", """FunnelForMultipleChoice""", """FunnelForPreTraining""", """FunnelForQuestionAnswering""", """FunnelForSequenceClassification""", """FunnelForTokenClassification""", """FunnelModel""", """FunnelPreTrainedModel""", """load_tf_weights_in_funnel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : Union[str, Any] = [ """TF_FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFFunnelBaseModel""", """TFFunnelForMaskedLM""", """TFFunnelForMultipleChoice""", """TFFunnelForPreTraining""", """TFFunnelForQuestionAnswering""", """TFFunnelForSequenceClassification""", """TFFunnelForTokenClassification""", """TFFunnelModel""", """TFFunnelPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_funnel import FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP, FunnelConfig from .tokenization_funnel import FunnelTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_funnel_fast import FunnelTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_funnel import ( FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST, FunnelBaseModel, FunnelForMaskedLM, FunnelForMultipleChoice, FunnelForPreTraining, FunnelForQuestionAnswering, FunnelForSequenceClassification, FunnelForTokenClassification, FunnelModel, FunnelPreTrainedModel, load_tf_weights_in_funnel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_funnel import ( TF_FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST, TFFunnelBaseModel, TFFunnelForMaskedLM, TFFunnelForMultipleChoice, TFFunnelForPreTraining, TFFunnelForQuestionAnswering, TFFunnelForSequenceClassification, TFFunnelForTokenClassification, TFFunnelModel, TFFunnelPreTrainedModel, ) else: import sys __lowercase : str = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
142
1
'''simple docstring''' import math from datetime import datetime, timedelta def snake_case_ ( __snake_case : int) -> datetime: lowerCAmelCase_ = year % 19 lowerCAmelCase_ = year % 4 lowerCAmelCase_ = year % 7 lowerCAmelCase_ = math.floor(year / 100) lowerCAmelCase_ = math.floor((13 + 8 * leap_day_inhibits) / 25) lowerCAmelCase_ = leap_day_inhibits / 4 lowerCAmelCase_ = ( 15 - lunar_orbit_correction + leap_day_inhibits - leap_day_reinstall_number ) % 30 lowerCAmelCase_ = (4 + leap_day_inhibits - leap_day_reinstall_number) % 7 # days to be added to March 21 lowerCAmelCase_ = (19 * metonic_cycle + secular_moon_shift) % 30 # PHM -> Paschal Full Moon lowerCAmelCase_ = ( 2 * julian_leap_year + 4 * non_leap_year + 6 * days_to_add + century_starting_point ) % 7 if days_to_add == 29 and days_from_phm_to_sunday == 6: return datetime(__snake_case , 4 , 19) elif days_to_add == 28 and days_from_phm_to_sunday == 6: return datetime(__snake_case , 4 , 18) else: return datetime(__snake_case , 3 , 22) + timedelta( days=int(days_to_add + days_from_phm_to_sunday)) if __name__ == "__main__": for year in (19_94, 20_00, 20_10, 20_21, 20_23): A_ : Tuple ='''will be''' if year > datetime.now().year else '''was''' print(f'''Easter in {year} {tense} {gauss_easter(year)}''')
606
'''simple docstring''' import argparse import os from pathlib import Path from typing import Dict import tensorflow as tf import torch from tqdm import tqdm from transformers import PegasusConfig, PegasusForConditionalGeneration, PegasusTokenizer from transformers.models.pegasus.configuration_pegasus import DEFAULTS, task_specific_params A_ : Tuple =[ # replace left string with right string to get the relevant state_dict key (identical state dict to bart) ['''memory_attention''', '''encoder_attn'''], ['''attention''', '''attn'''], ['''/''', '''.'''], ['''.LayerNorm.gamma''', '''_layer_norm.weight'''], ['''.LayerNorm.beta''', '''_layer_norm.bias'''], ['''r.layer_''', '''r.layers.'''], ['''output_proj''', '''out_proj'''], ['''ffn.dense_1.''', '''fc2.'''], ['''ffn.dense.''', '''fc1.'''], ['''ffn_layer_norm''', '''final_layer_norm'''], ['''kernel''', '''weight'''], ['''encoder_layer_norm.''', '''encoder.layer_norm.'''], ['''decoder_layer_norm.''', '''decoder.layer_norm.'''], ['''embeddings.weights''', '''shared.weight'''], ] def snake_case_ ( __snake_case : Union[str, Any]) -> Optional[Any]: for pegasus_name, hf_name in PATTERNS: lowerCAmelCase_ = k.replace(__snake_case , __snake_case) return k def snake_case_ ( __snake_case : dict , __snake_case : dict) -> PegasusForConditionalGeneration: lowerCAmelCase_ = DEFAULTS.copy() cfg_kwargs.update(__snake_case) lowerCAmelCase_ = PegasusConfig(**__snake_case) lowerCAmelCase_ = PegasusForConditionalGeneration(__snake_case) lowerCAmelCase_ = torch_model.model.state_dict() lowerCAmelCase_ = {} for k, v in tf_weights.items(): lowerCAmelCase_ = rename_state_dict_key(__snake_case) if new_k not in sd: raise ValueError(F'''could not find new key {new_k} in state dict. (converted from {k})''') if "dense" in k or "proj" in new_k: lowerCAmelCase_ = v.T lowerCAmelCase_ = torch.tensor(__snake_case , dtype=sd[new_k].dtype) assert v.shape == sd[new_k].shape, F'''{new_k}, {k}, {v.shape}, {sd[new_k].shape}''' # make sure embedding.padding_idx is respected lowerCAmelCase_ = torch.zeros_like(mapping['''shared.weight'''][cfg.pad_token_id + 1]) lowerCAmelCase_ = mapping['''shared.weight'''] lowerCAmelCase_ = mapping['''shared.weight'''] lowerCAmelCase_ = {k: torch.zeros_like(__snake_case) for k, v in sd.items() if k.endswith('''bias''') and k not in mapping} mapping.update(**__snake_case) lowerCAmelCase_ ,lowerCAmelCase_ = torch_model.model.load_state_dict(__snake_case , strict=__snake_case) lowerCAmelCase_ = [ k for k in missing if k not in ['''encoder.embed_positions.weight''', '''decoder.embed_positions.weight'''] ] assert unexpected_missing == [], F'''no matches found for the following torch keys {unexpected_missing}''' assert extra == [], F'''no matches found for the following tf keys {extra}''' return torch_model def snake_case_ ( __snake_case : Optional[int]="./ckpt/aeslc/model.ckpt-32000") -> Dict: lowerCAmelCase_ = tf.train.list_variables(__snake_case) lowerCAmelCase_ = {} lowerCAmelCase_ = ['''Adafactor''', '''global_step'''] for name, shape in tqdm(__snake_case , desc='''converting tf checkpoint to dict'''): lowerCAmelCase_ = any(pat in name for pat in ignore_name) if skip_key: continue lowerCAmelCase_ = tf.train.load_variable(__snake_case , __snake_case) lowerCAmelCase_ = array return tf_weights def snake_case_ ( __snake_case : str , __snake_case : str) -> Optional[int]: # save tokenizer first lowerCAmelCase_ = Path(__snake_case).parent.name lowerCAmelCase_ = task_specific_params[F'''summarization_{dataset}''']['''max_position_embeddings'''] lowerCAmelCase_ = PegasusTokenizer.from_pretrained('''sshleifer/pegasus''' , model_max_length=__snake_case) assert tok.model_max_length == desired_max_model_length tok.save_pretrained(__snake_case) # convert model lowerCAmelCase_ = get_tf_weights_as_numpy(__snake_case) lowerCAmelCase_ = task_specific_params[F'''summarization_{dataset}'''] if dataset == "large": lowerCAmelCase_ = task_specific_params lowerCAmelCase_ = convert_pegasus(__snake_case , __snake_case) torch_model.save_pretrained(__snake_case) lowerCAmelCase_ = torch_model.state_dict() sd.pop('''model.decoder.embed_positions.weight''') sd.pop('''model.encoder.embed_positions.weight''') torch.save(__snake_case , Path(__snake_case) / '''pytorch_model.bin''') if __name__ == "__main__": A_ : str =argparse.ArgumentParser() # Required parameters parser.add_argument('''tf_ckpt_path''', type=str, help='''passed to tf.train.list_variables''') parser.add_argument('''save_dir''', default=None, type=str, help='''Path to the output PyTorch model.''') A_ : Union[str, Any] =parser.parse_args() if args.save_dir is None: A_ : List[Any] =Path(args.tf_ckpt_path).parent.name A_ : Optional[int] =os.path.join('''pegasus''', dataset) convert_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir)
606
1
from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers import TFCamembertModel @require_tf @require_sentencepiece @require_tokenizers class __lowerCamelCase (unittest.TestCase ): @slow def snake_case_ ( self: Any ): '''simple docstring''' __UpperCamelCase = TFCamembertModel.from_pretrained('jplu/tf-camembert-base' ) __UpperCamelCase = tf.convert_to_tensor( [[5, 121, 11, 660, 16, 730, 2_5543, 110, 83, 6]],dtype=tf.intaa,) # J'aime le camembert !" __UpperCamelCase = model(A_ )['last_hidden_state'] __UpperCamelCase = tf.TensorShape((1, 10, 768) ) self.assertEqual(output.shape,A_ ) # compare the actual values for a slice. __UpperCamelCase = tf.convert_to_tensor( [[[-0.0_2_5_4, 0.0_2_3_5, 0.1_0_2_7], [0.0_6_0_6, -0.1_8_1_1, -0.0_4_1_8], [-0.1_5_6_1, -0.1_1_2_7, 0.2_6_8_7]]],dtype=tf.floataa,) # camembert = torch.hub.load('pytorch/fairseq', 'camembert.v0') # camembert.eval() # expected_slice = roberta.model.forward(input_ids)[0][:, :3, :3].detach() self.assertTrue(np.allclose(output[:, :3, :3].numpy(),expected_slice.numpy(),atol=1E-4 ) )
1
import json import os import re import unicodedata from json.encoder import INFINITY from typing import Any, Dict, List, Optional, Tuple, Union import numpy as np import regex from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, is_flax_available, is_tf_available, is_torch_available, logging from ...utils.generic import _is_jax, _is_numpy snake_case__ : Optional[Any] = logging.get_logger(__name__) snake_case__ : List[Any] = { 'artists_file': 'artists.json', 'lyrics_file': 'lyrics.json', 'genres_file': 'genres.json', } snake_case__ : int = { 'artists_file': { 'jukebox': 'https://huggingface.co/ArthurZ/jukebox/blob/main/artists.json', }, 'genres_file': { 'jukebox': 'https://huggingface.co/ArthurZ/jukebox/blob/main/genres.json', }, 'lyrics_file': { 'jukebox': 'https://huggingface.co/ArthurZ/jukebox/blob/main/lyrics.json', }, } snake_case__ : Optional[int] = { 'jukebox': 5_1_2, } class _a ( A__ ): """simple docstring""" snake_case =VOCAB_FILES_NAMES snake_case =PRETRAINED_VOCAB_FILES_MAP snake_case =PRETRAINED_LYRIC_TOKENS_SIZES snake_case =["""input_ids""", """attention_mask"""] def __init__( self , _snake_case , _snake_case , _snake_case , _snake_case=["v3", "v2", "v2"] , _snake_case=512 , _snake_case=5 , _snake_case="<|endoftext|>" , **_snake_case , ): _UpperCAmelCase =AddedToken(_snake_case , lstrip=_snake_case , rstrip=_snake_case ) if isinstance(_snake_case , _snake_case ) else unk_token super().__init__( unk_token=_snake_case , n_genres=_snake_case , version=_snake_case , max_n_lyric_tokens=_snake_case , **_snake_case , ) _UpperCAmelCase =version _UpperCAmelCase =max_n_lyric_tokens _UpperCAmelCase =n_genres with open(_snake_case , encoding="utf-8" ) as vocab_handle: _UpperCAmelCase =json.load(_snake_case ) with open(_snake_case , encoding="utf-8" ) as vocab_handle: _UpperCAmelCase =json.load(_snake_case ) with open(_snake_case , encoding="utf-8" ) as vocab_handle: _UpperCAmelCase =json.load(_snake_case ) _UpperCAmelCase =R"[^A-Za-z0-9.,:;!?\-'\"()\[\] \t\n]+" # In v2, we had a n_vocab=80 and in v3 we missed + and so n_vocab=79 of characters. if len(self.lyrics_encoder ) == 79: _UpperCAmelCase =oov.replace(R"\-'" , R"\-+'" ) _UpperCAmelCase =regex.compile(_snake_case ) _UpperCAmelCase ={v: k for k, v in self.artists_encoder.items()} _UpperCAmelCase ={v: k for k, v in self.genres_encoder.items()} _UpperCAmelCase ={v: k for k, v in self.lyrics_encoder.items()} @property def SCREAMING_SNAKE_CASE ( self ): return len(self.artists_encoder ) + len(self.genres_encoder ) + len(self.lyrics_encoder ) def SCREAMING_SNAKE_CASE ( self ): return dict(self.artists_encoder , self.genres_encoder , self.lyrics_encoder ) def SCREAMING_SNAKE_CASE ( self , _snake_case , _snake_case , _snake_case ): _UpperCAmelCase =[self.artists_encoder.get(_snake_case , 0 ) for artist in list_artists] for genres in range(len(_snake_case ) ): _UpperCAmelCase =[self.genres_encoder.get(_snake_case , 0 ) for genre in list_genres[genres]] _UpperCAmelCase =list_genres[genres] + [-1] * (self.n_genres - len(list_genres[genres] )) _UpperCAmelCase =[[self.lyrics_encoder.get(_snake_case , 0 ) for character in list_lyrics[0]], [], []] return artists_id, list_genres, lyric_ids def SCREAMING_SNAKE_CASE ( self , _snake_case ): return list(_snake_case ) def SCREAMING_SNAKE_CASE ( self , _snake_case , _snake_case , _snake_case , **_snake_case ): _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase =self.prepare_for_tokenization(_snake_case , _snake_case , _snake_case ) _UpperCAmelCase =self._tokenize(_snake_case ) return artist, genre, lyrics def SCREAMING_SNAKE_CASE ( self , _snake_case , _snake_case , _snake_case , _snake_case = False ): for idx in range(len(self.version ) ): if self.version[idx] == "v3": _UpperCAmelCase =artists[idx].lower() _UpperCAmelCase =[genres[idx].lower()] else: _UpperCAmelCase =self._normalize(artists[idx] ) + ".v2" _UpperCAmelCase =[ self._normalize(_snake_case ) + ".v2" for genre in genres[idx].split("_" ) ] # split is for the full dictionary with combined genres if self.version[0] == "v2": _UpperCAmelCase =regex.compile(R"[^A-Za-z0-9.,:;!?\-'\"()\[\] \t\n]+" ) _UpperCAmelCase ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,:;!?-+'\"()[] \t\n" _UpperCAmelCase ={vocab[index]: index + 1 for index in range(len(_snake_case ) )} _UpperCAmelCase =0 _UpperCAmelCase =len(_snake_case ) + 1 _UpperCAmelCase =self.vocab _UpperCAmelCase ={v: k for k, v in self.vocab.items()} _UpperCAmelCase ="" else: _UpperCAmelCase =regex.compile(R"[^A-Za-z0-9.,:;!?\-+'\"()\[\] \t\n]+" ) _UpperCAmelCase =self._run_strip_accents(_snake_case ) _UpperCAmelCase =lyrics.replace("\\" , "\n" ) _UpperCAmelCase =self.out_of_vocab.sub("" , _snake_case ), [], [] return artists, genres, lyrics def SCREAMING_SNAKE_CASE ( self , _snake_case ): _UpperCAmelCase =unicodedata.normalize("NFD" , _snake_case ) _UpperCAmelCase =[] for char in text: _UpperCAmelCase =unicodedata.category(_snake_case ) if cat == "Mn": continue output.append(_snake_case ) return "".join(_snake_case ) def SCREAMING_SNAKE_CASE ( self , _snake_case ): _UpperCAmelCase =( [chr(_snake_case ) for i in range(ord("a" ) , ord("z" ) + 1 )] + [chr(_snake_case ) for i in range(ord("A" ) , ord("Z" ) + 1 )] + [chr(_snake_case ) for i in range(ord("0" ) , ord("9" ) + 1 )] + ["."] ) _UpperCAmelCase =frozenset(_snake_case ) _UpperCAmelCase =re.compile(R"_+" ) _UpperCAmelCase ="".join([c if c in accepted else "_" for c in text.lower()] ) _UpperCAmelCase =pattern.sub("_" , _snake_case ).strip("_" ) return text def SCREAMING_SNAKE_CASE ( self , _snake_case ): return " ".join(_snake_case ) def SCREAMING_SNAKE_CASE ( self , _snake_case , _snake_case = None , _snake_case = False ): # Convert to TensorType if not isinstance(_snake_case , _snake_case ): _UpperCAmelCase =TensorType(_snake_case ) # Get a function reference for the correct framework if tensor_type == TensorType.TENSORFLOW: if not is_tf_available(): raise ImportError( "Unable to convert output to TensorFlow tensors format, TensorFlow is not installed." ) import tensorflow as tf _UpperCAmelCase =tf.constant _UpperCAmelCase =tf.is_tensor elif tensor_type == TensorType.PYTORCH: if not is_torch_available(): raise ImportError("Unable to convert output to PyTorch tensors format, PyTorch is not installed." ) import torch _UpperCAmelCase =torch.tensor _UpperCAmelCase =torch.is_tensor elif tensor_type == TensorType.JAX: if not is_flax_available(): raise ImportError("Unable to convert output to JAX tensors format, JAX is not installed." ) import jax.numpy as jnp # noqa: F811 _UpperCAmelCase =jnp.array _UpperCAmelCase =_is_jax else: _UpperCAmelCase =np.asarray _UpperCAmelCase =_is_numpy # Do the tensor conversion in batch try: if prepend_batch_axis: _UpperCAmelCase =[inputs] if not is_tensor(_snake_case ): _UpperCAmelCase =as_tensor(_snake_case ) except: # noqa E722 raise ValueError( "Unable to create tensor, you should probably activate truncation and/or padding " "with 'padding=True' 'truncation=True' to have batched tensors with the same length." ) return inputs def __call__( self , _snake_case , _snake_case , _snake_case="" , _snake_case="pt" ): _UpperCAmelCase =[0, 0, 0] _UpperCAmelCase =[artist] * len(self.version ) _UpperCAmelCase =[genres] * len(self.version ) _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase =self.tokenize(_snake_case , _snake_case , _snake_case ) _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase =self._convert_token_to_id(_snake_case , _snake_case , _snake_case ) _UpperCAmelCase =[-INFINITY] * len(full_tokens[-1] ) _UpperCAmelCase =[ self.convert_to_tensors( [input_ids + [artists_id[i]] + genres_ids[i] + full_tokens[i]] , tensor_type=_snake_case ) for i in range(len(self.version ) ) ] return BatchEncoding({"input_ids": input_ids, "attention_masks": attention_masks} ) def SCREAMING_SNAKE_CASE ( self , _snake_case , _snake_case = None ): if not os.path.isdir(_snake_case ): logger.error(F"Vocabulary path ({save_directory}) should be a directory" ) return _UpperCAmelCase =os.path.join( _snake_case , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["artists_file"] ) with open(_snake_case , "w" , encoding="utf-8" ) as f: f.write(json.dumps(self.artists_encoder , ensure_ascii=_snake_case ) ) _UpperCAmelCase =os.path.join( _snake_case , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["genres_file"] ) with open(_snake_case , "w" , encoding="utf-8" ) as f: f.write(json.dumps(self.genres_encoder , ensure_ascii=_snake_case ) ) _UpperCAmelCase =os.path.join( _snake_case , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["lyrics_file"] ) with open(_snake_case , "w" , encoding="utf-8" ) as f: f.write(json.dumps(self.lyrics_encoder , ensure_ascii=_snake_case ) ) return (artists_file, genres_file, lyrics_file) def SCREAMING_SNAKE_CASE ( self , _snake_case , _snake_case , _snake_case ): _UpperCAmelCase =self.artists_decoder.get(_snake_case ) _UpperCAmelCase =[self.genres_decoder.get(_snake_case ) for genre in genres_index] _UpperCAmelCase =[self.lyrics_decoder.get(_snake_case ) for character in lyric_index] return artist, genres, lyrics
408
0
'''simple docstring''' from __future__ import annotations import unittest import numpy as np from transformers import BlipTextConfig from transformers.testing_utils import require_tf, slow from transformers.utils import is_tf_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask if is_tf_available(): import tensorflow as tf from transformers import TFBlipTextModel from transformers.models.blip.modeling_tf_blip import TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCAmelCase__ : def __init__( self : Optional[int] , lowerCamelCase__ : Optional[int] , lowerCamelCase__ : Optional[int]=12 , lowerCamelCase__ : Union[str, Any]=7 , lowerCamelCase__ : List[Any]=True , lowerCamelCase__ : Optional[int]=True , lowerCamelCase__ : Dict=True , lowerCamelCase__ : Dict=99 , lowerCamelCase__ : str=32 , lowerCamelCase__ : List[str]=32 , lowerCamelCase__ : Dict=2 , lowerCamelCase__ : int=4 , lowerCamelCase__ : Any=37 , lowerCamelCase__ : Optional[Any]=0.1 , lowerCamelCase__ : Any=0.1 , lowerCamelCase__ : Tuple=5_12 , lowerCamelCase__ : List[Any]=0.0_2 , lowerCamelCase__ : List[Any]=0 , lowerCamelCase__ : Optional[int]=None , ) ->List[Any]: '''simple docstring''' _UpperCAmelCase : List[str] = parent _UpperCAmelCase : List[Any] = batch_size _UpperCAmelCase : str = seq_length _UpperCAmelCase : Dict = is_training _UpperCAmelCase : str = use_input_mask _UpperCAmelCase : Optional[Any] = use_labels _UpperCAmelCase : Union[str, Any] = vocab_size _UpperCAmelCase : int = hidden_size _UpperCAmelCase : Optional[int] = projection_dim _UpperCAmelCase : Dict = num_hidden_layers _UpperCAmelCase : Optional[int] = num_attention_heads _UpperCAmelCase : Any = intermediate_size _UpperCAmelCase : Optional[Any] = dropout _UpperCAmelCase : Optional[Any] = attention_dropout _UpperCAmelCase : Tuple = max_position_embeddings _UpperCAmelCase : int = initializer_range _UpperCAmelCase : List[Any] = scope _UpperCAmelCase : int = bos_token_id def lowerCAmelCase__ ( self : Optional[Any] ) ->Dict: '''simple docstring''' _UpperCAmelCase : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _UpperCAmelCase : str = None if self.use_input_mask: _UpperCAmelCase : Union[str, Any] = random_attention_mask([self.batch_size, self.seq_length] ) if input_mask is not None: _UpperCAmelCase : int = input_mask.numpy() _UpperCAmelCase : List[Any] = input_mask.shape _UpperCAmelCase : Dict = np.random.randint(1 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(lowerCamelCase__ ): _UpperCAmelCase : List[str] = 1 _UpperCAmelCase : List[Any] = 0 _UpperCAmelCase : List[Any] = self.get_config() return config, input_ids, tf.convert_to_tensor(lowerCamelCase__ ) def lowerCAmelCase__ ( self : str ) ->List[str]: '''simple docstring''' return BlipTextConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , projection_dim=self.projection_dim , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , dropout=self.dropout , attention_dropout=self.attention_dropout , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , bos_token_id=self.bos_token_id , ) def lowerCAmelCase__ ( self : Any , lowerCamelCase__ : int , lowerCamelCase__ : str , lowerCamelCase__ : Tuple ) ->Dict: '''simple docstring''' _UpperCAmelCase : int = TFBlipTextModel(config=lowerCamelCase__ ) _UpperCAmelCase : Optional[int] = model(lowerCamelCase__ , attention_mask=lowerCamelCase__ , training=lowerCamelCase__ ) _UpperCAmelCase : Dict = model(lowerCamelCase__ , training=lowerCamelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def lowerCAmelCase__ ( self : Any ) ->Tuple: '''simple docstring''' _UpperCAmelCase : Union[str, Any] = self.prepare_config_and_inputs() _UpperCAmelCase : Tuple = config_and_inputs _UpperCAmelCase : Optional[Any] = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_tf class lowerCAmelCase__ ( UpperCAmelCase__ , unittest.TestCase ): lowerCAmelCase : Tuple = (TFBlipTextModel,) if is_tf_available() else () lowerCAmelCase : List[str] = False lowerCAmelCase : List[Any] = False lowerCAmelCase : Optional[Any] = False def lowerCAmelCase__ ( self : str ) ->List[str]: '''simple docstring''' _UpperCAmelCase : Optional[Any] = BlipTextModelTester(self ) _UpperCAmelCase : Any = ConfigTester(self , config_class=lowerCamelCase__ , hidden_size=37 ) def lowerCAmelCase__ ( self : Optional[Any] ) ->Union[str, Any]: '''simple docstring''' self.config_tester.run_common_tests() def lowerCAmelCase__ ( self : Optional[int] ) ->Tuple: '''simple docstring''' _UpperCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCamelCase__ ) def lowerCAmelCase__ ( self : Optional[Any] ) ->Optional[int]: '''simple docstring''' pass def lowerCAmelCase__ ( self : Tuple ) ->Dict: '''simple docstring''' pass @unittest.skip(reason="Blip does not use inputs_embeds" ) def lowerCAmelCase__ ( self : Optional[int] ) ->List[str]: '''simple docstring''' pass @unittest.skip(reason="BlipTextModel has no base class and is not available in MODEL_MAPPING" ) def lowerCAmelCase__ ( self : str ) ->Any: '''simple docstring''' pass @unittest.skip(reason="BlipTextModel has no base class and is not available in MODEL_MAPPING" ) def lowerCAmelCase__ ( self : Union[str, Any] ) ->Optional[int]: '''simple docstring''' pass @slow def lowerCAmelCase__ ( self : int ) ->Optional[Any]: '''simple docstring''' for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _UpperCAmelCase : Tuple = TFBlipTextModel.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) def lowerCAmelCase__ ( self : str , lowerCamelCase__ : Tuple=True ) ->Dict: '''simple docstring''' super().test_pt_tf_model_equivalence(allow_missing_keys=lowerCamelCase__ )
708
'''simple docstring''' import argparse import torch from transformers import BertForMaskedLM if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser( description=( 'Extraction some layers of the full BertForMaskedLM or RObertaForMaskedLM for Transfer Learned' ' Distillation' ) ) parser.add_argument('--model_type', default='bert', choices=['bert']) parser.add_argument('--model_name', default='bert-base-uncased', type=str) parser.add_argument('--dump_checkpoint', default='serialization_dir/tf_bert-base-uncased_0247911.pth', type=str) parser.add_argument('--vocab_transform', action='store_true') lowerCamelCase__ = parser.parse_args() if args.model_type == "bert": lowerCamelCase__ = BertForMaskedLM.from_pretrained(args.model_name) lowerCamelCase__ = 'bert' else: raise ValueError('args.model_type should be "bert".') lowerCamelCase__ = model.state_dict() lowerCamelCase__ = {} for w in ["word_embeddings", "position_embeddings"]: lowerCamelCase__ = state_dict[F'''{prefix}.embeddings.{w}.weight'''] for w in ["weight", "bias"]: lowerCamelCase__ = state_dict[F'''{prefix}.embeddings.LayerNorm.{w}'''] lowerCamelCase__ = 0 for teacher_idx in [0, 2, 4, 7, 9, 11]: for w in ["weight", "bias"]: lowerCamelCase__ = state_dict[ F'''{prefix}.encoder.layer.{teacher_idx}.attention.self.query.{w}''' ] lowerCamelCase__ = state_dict[ F'''{prefix}.encoder.layer.{teacher_idx}.attention.self.key.{w}''' ] lowerCamelCase__ = state_dict[ F'''{prefix}.encoder.layer.{teacher_idx}.attention.self.value.{w}''' ] lowerCamelCase__ = state_dict[ F'''{prefix}.encoder.layer.{teacher_idx}.attention.output.dense.{w}''' ] lowerCamelCase__ = state_dict[ F'''{prefix}.encoder.layer.{teacher_idx}.attention.output.LayerNorm.{w}''' ] lowerCamelCase__ = state_dict[ F'''{prefix}.encoder.layer.{teacher_idx}.intermediate.dense.{w}''' ] lowerCamelCase__ = state_dict[ F'''{prefix}.encoder.layer.{teacher_idx}.output.dense.{w}''' ] lowerCamelCase__ = state_dict[ F'''{prefix}.encoder.layer.{teacher_idx}.output.LayerNorm.{w}''' ] std_idx += 1 lowerCamelCase__ = state_dict['cls.predictions.decoder.weight'] lowerCamelCase__ = state_dict['cls.predictions.bias'] if args.vocab_transform: for w in ["weight", "bias"]: lowerCamelCase__ = state_dict[F'''cls.predictions.transform.dense.{w}'''] lowerCamelCase__ = state_dict[F'''cls.predictions.transform.LayerNorm.{w}'''] print(F'''N layers selected for distillation: {std_idx}''') print(F'''Number of params transferred for distillation: {len(compressed_sd.keys())}''') print(F'''Save transferred checkpoint to {args.dump_checkpoint}.''') torch.save(compressed_sd, args.dump_checkpoint)
40
0
import math def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Tuple = 100 ): """simple docstring""" __a = sum(i * i for i in range(1 , n + 1 ) ) __a = int(math.pow(sum(range(1 , n + 1 ) ) , 2 ) ) return square_of_sum - sum_of_squares if __name__ == "__main__": print(F"""{solution() = }""")
225
from __future__ import annotations import unittest from transformers import BlenderbotSmallConfig, BlenderbotSmallTokenizer, is_tf_available from transformers.testing_utils import require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel @require_tf class _A : '''simple docstring''' _snake_case : int = BlenderbotSmallConfig _snake_case : Optional[int] = {} _snake_case : int = """gelu""" def __init__( self : int , lowerCamelCase : Any , lowerCamelCase : Union[str, Any]=13 , lowerCamelCase : Union[str, Any]=7 , lowerCamelCase : Dict=True , lowerCamelCase : Tuple=False , lowerCamelCase : Union[str, Any]=99 , lowerCamelCase : List[Any]=32 , lowerCamelCase : int=2 , lowerCamelCase : List[Any]=4 , lowerCamelCase : List[Any]=37 , lowerCamelCase : List[str]=0.1 , lowerCamelCase : Dict=0.1 , lowerCamelCase : Union[str, Any]=20 , lowerCamelCase : Dict=2 , lowerCamelCase : int=1 , lowerCamelCase : Tuple=0 , ): '''simple docstring''' __lowercase = parent __lowercase = batch_size __lowercase = seq_length __lowercase = is_training __lowercase = use_labels __lowercase = vocab_size __lowercase = hidden_size __lowercase = num_hidden_layers __lowercase = num_attention_heads __lowercase = intermediate_size __lowercase = hidden_dropout_prob __lowercase = attention_probs_dropout_prob __lowercase = max_position_embeddings __lowercase = eos_token_id __lowercase = pad_token_id __lowercase = bos_token_id def _snake_case ( self : Dict ): '''simple docstring''' __lowercase = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) __lowercase = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) __lowercase = tf.concat([input_ids, eos_tensor] , axis=1 ) __lowercase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __lowercase = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) __lowercase = prepare_blenderbot_small_inputs_dict(lowerCamelCase , lowerCamelCase , lowerCamelCase ) return config, inputs_dict def _snake_case ( self : Union[str, Any] , lowerCamelCase : List[Any] , lowerCamelCase : List[Any] ): '''simple docstring''' __lowercase = TFBlenderbotSmallModel(config=lowerCamelCase ).get_decoder() __lowercase = inputs_dict["input_ids"] __lowercase = input_ids[:1, :] __lowercase = inputs_dict["attention_mask"][:1, :] __lowercase = inputs_dict["head_mask"] __lowercase = 1 # first forward pass __lowercase = model(lowerCamelCase , attention_mask=lowerCamelCase , head_mask=lowerCamelCase , use_cache=lowerCamelCase ) __lowercase , __lowercase = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids __lowercase = ids_tensor((self.batch_size, 3) , config.vocab_size ) __lowercase = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and __lowercase = tf.concat([input_ids, next_tokens] , axis=-1 ) __lowercase = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) __lowercase = model(lowerCamelCase , attention_mask=lowerCamelCase )[0] __lowercase = model(lowerCamelCase , attention_mask=lowerCamelCase , past_key_values=lowerCamelCase )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice __lowercase = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) __lowercase = output_from_no_past[:, -3:, random_slice_idx] __lowercase = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(lowerCamelCase , lowerCamelCase , rtol=1e-3 ) def snake_case_ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , ): if attention_mask is None: __lowercase = tf.cast(tf.math.not_equal(_SCREAMING_SNAKE_CASE , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: __lowercase = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: __lowercase = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: __lowercase = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: __lowercase = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class _A ( _lowercase , _lowercase , unittest.TestCase ): '''simple docstring''' _snake_case : str = ( (TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel) if is_tf_available() else () ) _snake_case : List[str] = (TFBlenderbotSmallForConditionalGeneration,) if is_tf_available() else () _snake_case : int = ( { """conversational""": TFBlenderbotSmallForConditionalGeneration, """feature-extraction""": TFBlenderbotSmallModel, """summarization""": TFBlenderbotSmallForConditionalGeneration, """text2text-generation""": TFBlenderbotSmallForConditionalGeneration, """translation""": TFBlenderbotSmallForConditionalGeneration, } if is_tf_available() else {} ) _snake_case : Optional[int] = True _snake_case : List[str] = False _snake_case : Optional[Any] = False def _snake_case ( self : int ): '''simple docstring''' __lowercase = TFBlenderbotSmallModelTester(self ) __lowercase = ConfigTester(self , config_class=lowerCamelCase ) def _snake_case ( self : Tuple ): '''simple docstring''' self.config_tester.run_common_tests() def _snake_case ( self : Optional[Any] ): '''simple docstring''' __lowercase = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*lowerCamelCase ) @require_tokenizers @require_tf class _A ( unittest.TestCase ): '''simple docstring''' _snake_case : Optional[int] = [ """Social anxiety\nWow, I am never shy. Do you have anxiety?\nYes. I end up sweating and blushing and feel like """ """ i'm going to throw up.\nand why is that?""" ] _snake_case : str = """facebook/blenderbot_small-90M""" @cached_property def _snake_case ( self : Dict ): '''simple docstring''' return BlenderbotSmallTokenizer.from_pretrained("facebook/blenderbot-90M" ) @cached_property def _snake_case ( self : Dict ): '''simple docstring''' __lowercase = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model @slow def _snake_case ( self : Tuple ): '''simple docstring''' __lowercase = self.tokenizer(self.src_text , return_tensors="tf" ) __lowercase = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=lowerCamelCase , ) __lowercase = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=lowerCamelCase )[0] assert generated_words in ( "i don't know. i just feel like i'm going to throw up. it's not fun.", "i'm not sure. i just feel like i've been feeling like i have to be in a certain place", "i'm not sure. i just feel like i've been in a bad situation.", )
402
0
__UpperCamelCase : dict[str, float] = { "joule": 1.0, "kilojoule": 1000, "megajoule": 1000000, "gigajoule": 1000000000, "wattsecond": 1.0, "watthour": 3600, "kilowatthour": 3600000, "newtonmeter": 1.0, "calorie_nutr": 4_186.8, "kilocalorie_nutr": 4186800.00, "electronvolt": 1.6_0217_6634E-19, "britishthermalunit_it": 1_055.05_585, "footpound": 1.355_818, } def snake_case_ ( __lowercase , __lowercase , __lowercase ): if to_type not in ENERGY_CONVERSION or from_type not in ENERGY_CONVERSION: UpperCAmelCase_ : List[Any] = ( F'''Incorrect \'from_type\' or \'to_type\' value: {from_type!r}, {to_type!r}\n''' F'''Valid values are: {', '.join(_lowerCAmelCase )}''' ) raise ValueError(_lowerCAmelCase ) return value * ENERGY_CONVERSION[from_type] / ENERGY_CONVERSION[to_type] if __name__ == "__main__": import doctest doctest.testmod()
716
import argparse import hashlib # hashlib is only used inside the Test class import struct class lowerCAmelCase__: '''simple docstring''' def __init__( self : List[str] , __snake_case : Union[str, Any] ): '''simple docstring''' UpperCAmelCase_ : str = data UpperCAmelCase_ : List[Any] = [0X67_45_23_01, 0Xef_cd_ab_89, 0X98_ba_dc_fe, 0X10_32_54_76, 0Xc3_d2_e1_f0] @staticmethod def _lowerCamelCase ( __snake_case : Dict , __snake_case : Dict ): '''simple docstring''' return ((n << b) | (n >> (32 - b))) & 0Xff_ff_ff_ff def _lowerCamelCase ( self : Dict ): '''simple docstring''' UpperCAmelCase_ : Optional[int] = B'''\x80''' + B'''\x00''' * (63 - (len(self.data ) + 8) % 64) UpperCAmelCase_ : Union[str, Any] = self.data + padding + struct.pack('''>Q''' , 8 * len(self.data ) ) return padded_data def _lowerCamelCase ( self : Tuple ): '''simple docstring''' return [ self.padded_data[i : i + 64] for i in range(0 , len(self.padded_data ) , 64 ) ] def _lowerCamelCase ( self : Dict , __snake_case : Optional[int] ): '''simple docstring''' UpperCAmelCase_ : Any = list(struct.unpack('''>16L''' , __snake_case ) ) + [0] * 64 for i in range(16 , 80 ): UpperCAmelCase_ : str = self.rotate((w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]) , 1 ) return w def _lowerCamelCase ( self : Union[str, Any] ): '''simple docstring''' UpperCAmelCase_ : Optional[int] = self.padding() UpperCAmelCase_ : str = self.split_blocks() for block in self.blocks: UpperCAmelCase_ : Any = self.expand_block(__snake_case ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : List[str] = self.h for i in range(0 , 80 ): if 0 <= i < 20: UpperCAmelCase_ : Optional[Any] = (b & c) | ((~b) & d) UpperCAmelCase_ : Optional[Any] = 0X5a_82_79_99 elif 20 <= i < 40: UpperCAmelCase_ : List[Any] = b ^ c ^ d UpperCAmelCase_ : str = 0X6e_d9_eb_a1 elif 40 <= i < 60: UpperCAmelCase_ : str = (b & c) | (b & d) | (c & d) UpperCAmelCase_ : Optional[int] = 0X8f_1b_bc_dc elif 60 <= i < 80: UpperCAmelCase_ : Union[str, Any] = b ^ c ^ d UpperCAmelCase_ : Dict = 0Xca_62_c1_d6 UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : int = ( self.rotate(__snake_case , 5 ) + f + e + k + expanded_block[i] & 0Xff_ff_ff_ff, a, self.rotate(__snake_case , 30 ), c, d, ) UpperCAmelCase_ : Optional[Any] = ( self.h[0] + a & 0Xff_ff_ff_ff, self.h[1] + b & 0Xff_ff_ff_ff, self.h[2] + c & 0Xff_ff_ff_ff, self.h[3] + d & 0Xff_ff_ff_ff, self.h[4] + e & 0Xff_ff_ff_ff, ) return ("{:08x}" * 5).format(*self.h ) def snake_case_ ( ): UpperCAmelCase_ : Tuple = B'''Test String''' assert SHAaHash(__lowercase ).final_hash() == hashlib.shaa(__lowercase ).hexdigest() # noqa: S324 def snake_case_ ( ): UpperCAmelCase_ : int = argparse.ArgumentParser(description='''Process some strings or files''' ) parser.add_argument( '''--string''' , dest='''input_string''' , default='''Hello World!! Welcome to Cryptography''' , help='''Hash the string''' , ) parser.add_argument('''--file''' , dest='''input_file''' , help='''Hash contents of a file''' ) UpperCAmelCase_ : List[Any] = parser.parse_args() UpperCAmelCase_ : Optional[Any] = args.input_string # In any case hash input should be a bytestring if args.input_file: with open(args.input_file , '''rb''' ) as f: UpperCAmelCase_ : List[str] = f.read() else: UpperCAmelCase_ : Tuple = bytes(__lowercase , '''utf-8''' ) print(SHAaHash(__lowercase ).final_hash() ) if __name__ == "__main__": main() import doctest doctest.testmod()
641
0
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 rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL lowerCamelCase__ : Dict = logging.get_logger(__name__) def UpperCAmelCase_ ( __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : List[Any] ) -> Union[str, Any]: SCREAMING_SNAKE_CASE_ = b.T SCREAMING_SNAKE_CASE_ = np.sum(np.square(__UpperCAmelCase ) , axis=1 ) SCREAMING_SNAKE_CASE_ = np.sum(np.square(__UpperCAmelCase ) , axis=0 ) SCREAMING_SNAKE_CASE_ = np.matmul(__UpperCAmelCase , __UpperCAmelCase ) SCREAMING_SNAKE_CASE_ = aa[:, None] - 2 * ab + ba[None, :] return d def UpperCAmelCase_ ( __UpperCAmelCase : Dict , __UpperCAmelCase : Optional[Any] ) -> Optional[int]: SCREAMING_SNAKE_CASE_ = x.reshape(-1 , 3 ) SCREAMING_SNAKE_CASE_ = squared_euclidean_distance(__UpperCAmelCase , __UpperCAmelCase ) return np.argmin(__UpperCAmelCase , axis=1 ) class lowerCamelCase_ ( _SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = ["pixel_values"] def __init__( self : List[Any] , _lowerCAmelCase : Optional[Union[List[List[int]], np.ndarray]] = None , _lowerCAmelCase : bool = True , _lowerCAmelCase : Dict[str, int] = None , _lowerCAmelCase : PILImageResampling = PILImageResampling.BILINEAR , _lowerCAmelCase : bool = True , _lowerCAmelCase : bool = True , **_lowerCAmelCase : List[Any] , ): super().__init__(**_lowerCAmelCase ) SCREAMING_SNAKE_CASE_ = size if size is not None else {'height': 256, 'width': 256} SCREAMING_SNAKE_CASE_ = get_size_dict(_lowerCAmelCase ) SCREAMING_SNAKE_CASE_ = np.array(_lowerCAmelCase ) if clusters is not None else None SCREAMING_SNAKE_CASE_ = do_resize SCREAMING_SNAKE_CASE_ = size SCREAMING_SNAKE_CASE_ = resample SCREAMING_SNAKE_CASE_ = do_normalize SCREAMING_SNAKE_CASE_ = do_color_quantize def lowerCAmelCase_ ( self : str , _lowerCAmelCase : np.ndarray , _lowerCAmelCase : Dict[str, int] , _lowerCAmelCase : PILImageResampling = PILImageResampling.BILINEAR , _lowerCAmelCase : Optional[Union[str, ChannelDimension]] = None , **_lowerCAmelCase : Tuple , ): SCREAMING_SNAKE_CASE_ = get_size_dict(_lowerCAmelCase ) if "height" not in size or "width" not in size: raise ValueError(F"Size dictionary must contain both height and width keys. Got {size.keys()}" ) return resize( _lowerCAmelCase , size=(size['height'], size['width']) , resample=_lowerCAmelCase , data_format=_lowerCAmelCase , **_lowerCAmelCase ) def lowerCAmelCase_ ( self : Union[str, Any] , _lowerCAmelCase : np.ndarray , _lowerCAmelCase : Optional[Union[str, ChannelDimension]] = None , ): SCREAMING_SNAKE_CASE_ = rescale(image=_lowerCAmelCase , scale=1 / 127.5 , data_format=_lowerCAmelCase ) SCREAMING_SNAKE_CASE_ = image - 1 return image def lowerCAmelCase_ ( self : List[Any] , _lowerCAmelCase : ImageInput , _lowerCAmelCase : bool = None , _lowerCAmelCase : Dict[str, int] = None , _lowerCAmelCase : PILImageResampling = None , _lowerCAmelCase : bool = None , _lowerCAmelCase : Optional[bool] = None , _lowerCAmelCase : Optional[Union[List[List[int]], np.ndarray]] = None , _lowerCAmelCase : Optional[Union[str, TensorType]] = None , _lowerCAmelCase : Optional[Union[str, ChannelDimension]] = ChannelDimension.FIRST , **_lowerCAmelCase : Optional[Any] , ): SCREAMING_SNAKE_CASE_ = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE_ = size if size is not None else self.size SCREAMING_SNAKE_CASE_ = get_size_dict(_lowerCAmelCase ) SCREAMING_SNAKE_CASE_ = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE_ = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE_ = do_color_quantize if do_color_quantize is not None else self.do_color_quantize SCREAMING_SNAKE_CASE_ = clusters if clusters is not None else self.clusters SCREAMING_SNAKE_CASE_ = np.array(_lowerCAmelCase ) SCREAMING_SNAKE_CASE_ = make_list_of_images(_lowerCAmelCase ) if not valid_images(_lowerCAmelCase ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None or resample is None: raise ValueError('Size and resample must be specified if do_resize is True.' ) if do_color_quantize and clusters is None: raise ValueError('Clusters must be specified if do_color_quantize is True.' ) # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE_ = [to_numpy_array(_lowerCAmelCase ) for image in images] if do_resize: SCREAMING_SNAKE_CASE_ = [self.resize(image=_lowerCAmelCase , size=_lowerCAmelCase , resample=_lowerCAmelCase ) for image in images] if do_normalize: SCREAMING_SNAKE_CASE_ = [self.normalize(image=_lowerCAmelCase ) for image in images] if do_color_quantize: SCREAMING_SNAKE_CASE_ = [to_channel_dimension_format(_lowerCAmelCase , ChannelDimension.LAST ) for image in images] # color quantize from (batch_size, height, width, 3) to (batch_size, height, width) SCREAMING_SNAKE_CASE_ = np.array(_lowerCAmelCase ) SCREAMING_SNAKE_CASE_ = color_quantize(_lowerCAmelCase , _lowerCAmelCase ).reshape(images.shape[:-1] ) # flatten to (batch_size, height*width) SCREAMING_SNAKE_CASE_ = images.shape[0] SCREAMING_SNAKE_CASE_ = images.reshape(_lowerCAmelCase , -1 ) # We need to convert back to a list of images to keep consistent behaviour across processors. SCREAMING_SNAKE_CASE_ = list(_lowerCAmelCase ) else: SCREAMING_SNAKE_CASE_ = [to_channel_dimension_format(_lowerCAmelCase , _lowerCAmelCase ) for image in images] SCREAMING_SNAKE_CASE_ = {'input_ids': images} return BatchFeature(data=_lowerCAmelCase , tensor_type=_lowerCAmelCase )
31
"""simple docstring""" import inspect import tempfile from collections import OrderedDict, UserDict from collections.abc import MutableMapping from contextlib import ExitStack, contextmanager from dataclasses import fields from enum import Enum from typing import Any, ContextManager, List, Tuple import numpy as np from .import_utils import is_flax_available, is_tf_available, is_torch_available, is_torch_fx_proxy if is_flax_available(): import jax.numpy as jnp class SCREAMING_SNAKE_CASE ( a_ ): """simple docstring""" def __get__( self : List[Any] ,lowercase_ : Any ,lowercase_ : List[str]=None ): # See docs.python.org/3/howto/descriptor.html#properties if obj is None: return self if self.fget is None: raise AttributeError('''unreadable attribute''' ) lowerCAmelCase__ : Optional[Any] = '''__cached_''' + self.fget.__name__ lowerCAmelCase__ : Any = getattr(lowercase_ ,lowercase_ ,lowercase_ ) if cached is None: lowerCAmelCase__ : str = self.fget(lowercase_ ) setattr(lowercase_ ,lowercase_ ,lowercase_ ) return cached def __SCREAMING_SNAKE_CASE ( A_ ): lowerCAmelCase__ : int = val.lower() if val in {"y", "yes", "t", "true", "on", "1"}: return 1 if val in {"n", "no", "f", "false", "off", "0"}: return 0 raise ValueError(f'invalid truth value {val!r}' ) def __SCREAMING_SNAKE_CASE ( A_ ): if is_torch_fx_proxy(A_ ): return True if is_torch_available(): import torch if isinstance(A_ , torch.Tensor ): return True if is_tf_available(): import tensorflow as tf if isinstance(A_ , tf.Tensor ): return True if is_flax_available(): import jax.numpy as jnp from jax.core import Tracer if isinstance(A_ , (jnp.ndarray, Tracer) ): return True return isinstance(A_ , np.ndarray ) def __SCREAMING_SNAKE_CASE ( A_ ): return isinstance(A_ , np.ndarray ) def __SCREAMING_SNAKE_CASE ( A_ ): return _is_numpy(A_ ) def __SCREAMING_SNAKE_CASE ( A_ ): import torch return isinstance(A_ , torch.Tensor ) def __SCREAMING_SNAKE_CASE ( A_ ): return False if not is_torch_available() else _is_torch(A_ ) def __SCREAMING_SNAKE_CASE ( A_ ): import torch return isinstance(A_ , torch.device ) def __SCREAMING_SNAKE_CASE ( A_ ): return False if not is_torch_available() else _is_torch_device(A_ ) def __SCREAMING_SNAKE_CASE ( A_ ): import torch if isinstance(A_ , A_ ): if hasattr(A_ , A_ ): lowerCAmelCase__ : int = getattr(A_ , A_ ) else: return False return isinstance(A_ , torch.dtype ) def __SCREAMING_SNAKE_CASE ( A_ ): return False if not is_torch_available() else _is_torch_dtype(A_ ) def __SCREAMING_SNAKE_CASE ( A_ ): import tensorflow as tf return isinstance(A_ , tf.Tensor ) def __SCREAMING_SNAKE_CASE ( A_ ): return False if not is_tf_available() else _is_tensorflow(A_ ) def __SCREAMING_SNAKE_CASE ( A_ ): import tensorflow as tf # the `is_symbolic_tensor` predicate is only available starting with TF 2.14 if hasattr(A_ , '''is_symbolic_tensor''' ): return tf.is_symbolic_tensor(A_ ) return type(A_ ) == tf.Tensor def __SCREAMING_SNAKE_CASE ( A_ ): return False if not is_tf_available() else _is_tf_symbolic_tensor(A_ ) def __SCREAMING_SNAKE_CASE ( A_ ): import jax.numpy as jnp # noqa: F811 return isinstance(A_ , jnp.ndarray ) def __SCREAMING_SNAKE_CASE ( A_ ): return False if not is_flax_available() else _is_jax(A_ ) def __SCREAMING_SNAKE_CASE ( A_ ): if isinstance(A_ , (dict, UserDict) ): return {k: to_py_obj(A_ ) for k, v in obj.items()} elif isinstance(A_ , (list, tuple) ): return [to_py_obj(A_ ) for o in obj] elif is_tf_tensor(A_ ): return obj.numpy().tolist() elif is_torch_tensor(A_ ): return obj.detach().cpu().tolist() elif is_jax_tensor(A_ ): return np.asarray(A_ ).tolist() elif isinstance(A_ , (np.ndarray, np.number) ): # tolist also works on 0d np arrays return obj.tolist() else: return obj def __SCREAMING_SNAKE_CASE ( A_ ): if isinstance(A_ , (dict, UserDict) ): return {k: to_numpy(A_ ) for k, v in obj.items()} elif isinstance(A_ , (list, tuple) ): return np.array(A_ ) elif is_tf_tensor(A_ ): return obj.numpy() elif is_torch_tensor(A_ ): return obj.detach().cpu().numpy() elif is_jax_tensor(A_ ): return np.asarray(A_ ) else: return obj class SCREAMING_SNAKE_CASE ( a_ ): """simple docstring""" def __lowerCAmelCase ( self : Any ): lowerCAmelCase__ : Optional[int] = fields(self ) # Safety and consistency checks if not len(lowercase_ ): raise ValueError(F'{self.__class__.__name__} has no fields.' ) if not all(field.default is None for field in class_fields[1:] ): raise ValueError(F'{self.__class__.__name__} should not have more than one required field.' ) lowerCAmelCase__ : str = getattr(self ,class_fields[0].name ) lowerCAmelCase__ : List[str] = all(getattr(self ,field.name ) is None for field in class_fields[1:] ) if other_fields_are_none and not is_tensor(lowercase_ ): if isinstance(lowercase_ ,lowercase_ ): lowerCAmelCase__ : str = first_field.items() lowerCAmelCase__ : List[str] = True else: try: lowerCAmelCase__ : Union[str, Any] = iter(lowercase_ ) lowerCAmelCase__ : int = True except TypeError: lowerCAmelCase__ : Dict = False # if we provided an iterator as first field and the iterator is a (key, value) iterator # set the associated fields if first_field_iterator: for idx, element in enumerate(lowercase_ ): if ( not isinstance(lowercase_ ,(list, tuple) ) or not len(lowercase_ ) == 2 or not isinstance(element[0] ,lowercase_ ) ): if idx == 0: # If we do not have an iterator of key/values, set it as attribute lowerCAmelCase__ : Tuple = first_field else: # If we have a mixed iterator, raise an error raise ValueError( F'Cannot set key/value for {element}. It needs to be a tuple (key, value).' ) break setattr(self ,element[0] ,element[1] ) if element[1] is not None: lowerCAmelCase__ : Dict = element[1] elif first_field is not None: lowerCAmelCase__ : Any = first_field else: for field in class_fields: lowerCAmelCase__ : Any = getattr(self ,field.name ) if v is not None: lowerCAmelCase__ : List[str] = v def __delitem__( self : List[str] ,*lowercase_ : List[str] ,**lowercase_ : Any ): raise Exception(F'You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.' ) def __lowerCAmelCase ( self : Optional[int] ,*lowercase_ : Union[str, Any] ,**lowercase_ : List[Any] ): raise Exception(F'You cannot use ``setdefault`` on a {self.__class__.__name__} instance.' ) def __lowerCAmelCase ( self : str ,*lowercase_ : Union[str, Any] ,**lowercase_ : Any ): raise Exception(F'You cannot use ``pop`` on a {self.__class__.__name__} instance.' ) def __lowerCAmelCase ( self : int ,*lowercase_ : List[str] ,**lowercase_ : int ): raise Exception(F'You cannot use ``update`` on a {self.__class__.__name__} instance.' ) def __getitem__( self : Any ,lowercase_ : Any ): if isinstance(lowercase_ ,lowercase_ ): lowerCAmelCase__ : Optional[Any] = dict(self.items() ) return inner_dict[k] else: return self.to_tuple()[k] def __setattr__( self : Dict ,lowercase_ : Dict ,lowercase_ : int ): if name in self.keys() and value is not None: # Don't call self.__setitem__ to avoid recursion errors super().__setitem__(lowercase_ ,lowercase_ ) super().__setattr__(lowercase_ ,lowercase_ ) def __setitem__( self : str ,lowercase_ : Optional[int] ,lowercase_ : Optional[Any] ): # Will raise a KeyException if needed super().__setitem__(lowercase_ ,lowercase_ ) # Don't call self.__setattr__ to avoid recursion errors super().__setattr__(lowercase_ ,lowercase_ ) def __lowerCAmelCase ( self : Optional[int] ): return tuple(self[k] for k in self.keys() ) class SCREAMING_SNAKE_CASE ( a_ , a_ ): """simple docstring""" @classmethod def __lowerCAmelCase ( cls : Dict ,lowercase_ : Optional[Any] ): raise ValueError( F'{value} is not a valid {cls.__name__}, please select one of {list(cls._valueamember_map_.keys() )}' ) class SCREAMING_SNAKE_CASE ( a_ ): """simple docstring""" lowercase__ = "longest" lowercase__ = "max_length" lowercase__ = "do_not_pad" class SCREAMING_SNAKE_CASE ( a_ ): """simple docstring""" lowercase__ = "pt" lowercase__ = "tf" lowercase__ = "np" lowercase__ = "jax" class SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : List[Any] ,lowercase_ : List[ContextManager] ): lowerCAmelCase__ : Optional[int] = context_managers lowerCAmelCase__ : Tuple = ExitStack() def __enter__( self : str ): for context_manager in self.context_managers: self.stack.enter_context(lowercase_ ) def __exit__( self : Tuple ,*lowercase_ : Tuple ,**lowercase_ : List[Any] ): self.stack.__exit__(*lowercase_ ,**lowercase_ ) def __SCREAMING_SNAKE_CASE ( A_ ): lowerCAmelCase__ : Union[str, Any] = infer_framework(A_ ) if framework == "tf": lowerCAmelCase__ : List[str] = inspect.signature(model_class.call ) # TensorFlow models elif framework == "pt": lowerCAmelCase__ : Any = inspect.signature(model_class.forward ) # PyTorch models else: lowerCAmelCase__ : Dict = inspect.signature(model_class.__call__ ) # Flax models for p in signature.parameters: if p == "return_loss" and signature.parameters[p].default is True: return True return False def __SCREAMING_SNAKE_CASE ( A_ ): lowerCAmelCase__ : List[str] = model_class.__name__ lowerCAmelCase__ : List[Any] = infer_framework(A_ ) if framework == "tf": lowerCAmelCase__ : Tuple = inspect.signature(model_class.call ) # TensorFlow models elif framework == "pt": lowerCAmelCase__ : List[str] = inspect.signature(model_class.forward ) # PyTorch models else: lowerCAmelCase__ : Optional[int] = inspect.signature(model_class.__call__ ) # Flax models if "QuestionAnswering" in model_name: return [p for p in signature.parameters if "label" in p or p in ("start_positions", "end_positions")] else: return [p for p in signature.parameters if "label" in p] def __SCREAMING_SNAKE_CASE ( A_ , A_ = "" , A_ = "." ): def _flatten_dict(A_ , A_="" , A_="." ): for k, v in d.items(): lowerCAmelCase__ : Any = str(A_ ) + delimiter + str(A_ ) if parent_key else k if v and isinstance(A_ , A_ ): yield from flatten_dict(A_ , A_ , delimiter=A_ ).items() else: yield key, v return dict(_flatten_dict(A_ , A_ , A_ ) ) @contextmanager def __SCREAMING_SNAKE_CASE ( A_ , A_ = False ): if use_temp_dir: with tempfile.TemporaryDirectory() as tmp_dir: yield tmp_dir else: yield working_dir def __SCREAMING_SNAKE_CASE ( A_ , A_=None ): if is_numpy_array(A_ ): return np.transpose(A_ , axes=A_ ) elif is_torch_tensor(A_ ): return array.T if axes is None else array.permute(*A_ ) elif is_tf_tensor(A_ ): import tensorflow as tf return tf.transpose(A_ , perm=A_ ) elif is_jax_tensor(A_ ): return jnp.transpose(A_ , axes=A_ ) else: raise ValueError(f'Type not supported for transpose: {type(A_ )}.' ) def __SCREAMING_SNAKE_CASE ( A_ , A_ ): if is_numpy_array(A_ ): return np.reshape(A_ , A_ ) elif is_torch_tensor(A_ ): return array.reshape(*A_ ) elif is_tf_tensor(A_ ): import tensorflow as tf return tf.reshape(A_ , A_ ) elif is_jax_tensor(A_ ): return jnp.reshape(A_ , A_ ) else: raise ValueError(f'Type not supported for reshape: {type(A_ )}.' ) def __SCREAMING_SNAKE_CASE ( A_ , A_=None ): if is_numpy_array(A_ ): return np.squeeze(A_ , axis=A_ ) elif is_torch_tensor(A_ ): return array.squeeze() if axis is None else array.squeeze(dim=A_ ) elif is_tf_tensor(A_ ): import tensorflow as tf return tf.squeeze(A_ , axis=A_ ) elif is_jax_tensor(A_ ): return jnp.squeeze(A_ , axis=A_ ) else: raise ValueError(f'Type not supported for squeeze: {type(A_ )}.' ) def __SCREAMING_SNAKE_CASE ( A_ , A_ ): if is_numpy_array(A_ ): return np.expand_dims(A_ , A_ ) elif is_torch_tensor(A_ ): return array.unsqueeze(dim=A_ ) elif is_tf_tensor(A_ ): import tensorflow as tf return tf.expand_dims(A_ , axis=A_ ) elif is_jax_tensor(A_ ): return jnp.expand_dims(A_ , axis=A_ ) else: raise ValueError(f'Type not supported for expand_dims: {type(A_ )}.' ) def __SCREAMING_SNAKE_CASE ( A_ ): if is_numpy_array(A_ ): return np.size(A_ ) elif is_torch_tensor(A_ ): return array.numel() elif is_tf_tensor(A_ ): import tensorflow as tf return tf.size(A_ ) elif is_jax_tensor(A_ ): return array.size else: raise ValueError(f'Type not supported for expand_dims: {type(A_ )}.' ) def __SCREAMING_SNAKE_CASE ( A_ , A_ ): for key, value in auto_map.items(): if isinstance(A_ , (tuple, list) ): lowerCAmelCase__ : Tuple = [f'{repo_id}--{v}' if (v is not None and '''--''' not in v) else v for v in value] elif value is not None and "--" not in value: lowerCAmelCase__ : Tuple = f'{repo_id}--{value}' return auto_map def __SCREAMING_SNAKE_CASE ( A_ ): for base_class in inspect.getmro(A_ ): lowerCAmelCase__ : List[str] = base_class.__module__ lowerCAmelCase__ : List[Any] = base_class.__name__ if module.startswith('''tensorflow''' ) or module.startswith('''keras''' ) or name == "TFPreTrainedModel": return "tf" elif module.startswith('''torch''' ) or name == "PreTrainedModel": return "pt" elif module.startswith('''flax''' ) or module.startswith('''jax''' ) or name == "FlaxPreTrainedModel": return "flax" else: raise TypeError(f'Could not infer framework from class {model_class}.' )
450
0
from ...configuration_utils import PretrainedConfig from ...utils import logging _a : int = logging.get_logger(__name__) _a : int = { 'facebook/timesformer': 'https://huggingface.co/facebook/timesformer/resolve/main/config.json', } class UpperCamelCase_ ( __UpperCamelCase ): """simple docstring""" A = '''timesformer''' def __init__( self , UpperCAmelCase=2_2_4 , UpperCAmelCase=1_6 , UpperCAmelCase=3 , UpperCAmelCase=8 , UpperCAmelCase=7_6_8 , UpperCAmelCase=1_2 , UpperCAmelCase=1_2 , UpperCAmelCase=3_0_7_2 , UpperCAmelCase="gelu" , UpperCAmelCase=0.0 , UpperCAmelCase=0.0 , UpperCAmelCase=0.02 , UpperCAmelCase=1E-6 , UpperCAmelCase=True , UpperCAmelCase="divided_space_time" , UpperCAmelCase=0 , **UpperCAmelCase , ): super().__init__(**UpperCAmelCase ) __lowerCamelCase = image_size __lowerCamelCase = patch_size __lowerCamelCase = num_channels __lowerCamelCase = num_frames __lowerCamelCase = hidden_size __lowerCamelCase = num_hidden_layers __lowerCamelCase = num_attention_heads __lowerCamelCase = intermediate_size __lowerCamelCase = hidden_act __lowerCamelCase = hidden_dropout_prob __lowerCamelCase = attention_probs_dropout_prob __lowerCamelCase = initializer_range __lowerCamelCase = layer_norm_eps __lowerCamelCase = qkv_bias __lowerCamelCase = attention_type __lowerCamelCase = drop_path_rate
571
from ...processing_utils import ProcessorMixin class UpperCamelCase_ ( __UpperCamelCase ): """simple docstring""" A = ['''image_processor''', '''feature_extractor'''] A = '''TvltImageProcessor''' A = '''TvltFeatureExtractor''' def __init__( self , UpperCAmelCase , UpperCAmelCase ): super().__init__(image_processor=UpperCAmelCase , feature_extractor=UpperCAmelCase ) __lowerCamelCase = image_processor __lowerCamelCase = feature_extractor def __call__( self , UpperCAmelCase=None , UpperCAmelCase=None , UpperCAmelCase=None , UpperCAmelCase=None , UpperCAmelCase=False , UpperCAmelCase=False , *UpperCAmelCase , **UpperCAmelCase , ): if images is None and audio is None: raise ValueError("""You need to specify either an `images` or `audio` input to process.""" ) __lowerCamelCase = None if images is not None: __lowerCamelCase = self.image_processor(UpperCAmelCase , mask_pixel=UpperCAmelCase , *UpperCAmelCase , **UpperCAmelCase ) if images_mixed is not None: __lowerCamelCase = self.image_processor(UpperCAmelCase , is_mixed=UpperCAmelCase , *UpperCAmelCase , **UpperCAmelCase ) if audio is not None: __lowerCamelCase = self.feature_extractor( UpperCAmelCase , *UpperCAmelCase , sampling_rate=UpperCAmelCase , mask_audio=UpperCAmelCase , **UpperCAmelCase ) __lowerCamelCase = {} if audio is not None: output_dict.update(UpperCAmelCase ) if images is not None: output_dict.update(UpperCAmelCase ) if images_mixed_dict is not None: output_dict.update(UpperCAmelCase ) return output_dict @property def lowerCamelCase_ ( self ): __lowerCamelCase = self.image_processor.model_input_names __lowerCamelCase = self.feature_extractor.model_input_names return list(dict.fromkeys(image_processor_input_names + feature_extractor_input_names ) )
571
1
import os SCREAMING_SNAKE_CASE__ = {'''I''': 1, '''V''': 5, '''X''': 10, '''L''': 50, '''C''': 100, '''D''': 500, '''M''': 1000} def UpperCAmelCase__ ( lowerCamelCase_ : str ): __a : Optional[Any] = 0 __a : Dict = 0 while index < len(lowerCamelCase_ ) - 1: __a : Optional[Any] = SYMBOLS[numerals[index]] __a : Union[str, Any] = SYMBOLS[numerals[index + 1]] if current_value < next_value: total_value -= current_value else: total_value += current_value index += 1 total_value += SYMBOLS[numerals[index]] return total_value def UpperCAmelCase__ ( lowerCamelCase_ : int ): __a : Optional[Any] = '' __a : int = num // 1_0_0_0 numerals += m_count * "M" num %= 1_0_0_0 __a : Tuple = num // 1_0_0 if c_count == 9: numerals += "CM" c_count -= 9 elif c_count == 4: numerals += "CD" c_count -= 4 if c_count >= 5: numerals += "D" c_count -= 5 numerals += c_count * "C" num %= 1_0_0 __a : Optional[int] = num // 1_0 if x_count == 9: numerals += "XC" x_count -= 9 elif x_count == 4: numerals += "XL" x_count -= 4 if x_count >= 5: numerals += "L" x_count -= 5 numerals += x_count * "X" num %= 1_0 if num == 9: numerals += "IX" num -= 9 elif num == 4: numerals += "IV" num -= 4 if num >= 5: numerals += "V" num -= 5 numerals += num * "I" return numerals def UpperCAmelCase__ ( lowerCamelCase_ : str = "/p089_roman.txt" ): __a : List[Any] = 0 with open(os.path.dirname(lowerCamelCase_ ) + roman_numerals_filename ) as filea: __a : Tuple = filea.readlines() for line in lines: __a : str = line.strip() __a : Dict = parse_roman_numerals(lowerCamelCase_ ) __a : str = generate_roman_numerals(lowerCamelCase_ ) savings += len(lowerCamelCase_ ) - len(lowerCamelCase_ ) return savings if __name__ == "__main__": print(F"{solution() = }")
47
def UpperCAmelCase_ ( __lowerCAmelCase , __lowerCAmelCase ) -> float: return price * (1 + tax_rate) if __name__ == "__main__": print(F'{price_plus_tax(100, 0.25) = }') print(F'{price_plus_tax(125.50, 0.05) = }')
509
0
'''simple docstring''' import io import json import unittest from parameterized import parameterized from transformers import FSMTForConditionalGeneration, FSMTTokenizer from transformers.testing_utils import get_tests_dir, require_torch, slow, torch_device from utils import calculate_bleu _snake_case : Union[str, Any] = get_tests_dir() + """/test_data/fsmt/fsmt_val_data.json""" with io.open(filename, """r""", encoding="""utf-8""") as f: _snake_case : List[Any] = json.load(f) @require_torch class lowerCAmelCase ( unittest.TestCase ): def lowercase ( self , UpperCamelCase ): return FSMTTokenizer.from_pretrained(UpperCamelCase ) def lowercase ( self , UpperCamelCase ): _SCREAMING_SNAKE_CASE = FSMTForConditionalGeneration.from_pretrained(UpperCamelCase ).to(UpperCamelCase ) if torch_device == "cuda": model.half() return model @parameterized.expand( [ ["en-ru", 26.0], ["ru-en", 22.0], ["en-de", 22.0], ["de-en", 29.0], ] ) @slow def lowercase ( self , UpperCamelCase , UpperCamelCase ): # note: this test is not testing the best performance since it only evals a small batch # but it should be enough to detect a regression in the output quality _SCREAMING_SNAKE_CASE = F'facebook/wmt19-{pair}' _SCREAMING_SNAKE_CASE = self.get_tokenizer(UpperCamelCase ) _SCREAMING_SNAKE_CASE = self.get_model(UpperCamelCase ) _SCREAMING_SNAKE_CASE = bleu_data[pair]["src"] _SCREAMING_SNAKE_CASE = bleu_data[pair]["tgt"] _SCREAMING_SNAKE_CASE = tokenizer(UpperCamelCase , return_tensors="pt" , truncation=UpperCamelCase , padding="longest" ).to(UpperCamelCase ) _SCREAMING_SNAKE_CASE = model.generate( input_ids=batch.input_ids , num_beams=8 , ) _SCREAMING_SNAKE_CASE = tokenizer.batch_decode( UpperCamelCase , skip_special_tokens=UpperCamelCase , clean_up_tokenization_spaces=UpperCamelCase ) _SCREAMING_SNAKE_CASE = calculate_bleu(UpperCamelCase , UpperCamelCase ) print(UpperCamelCase ) self.assertGreaterEqual(scores["bleu"] , UpperCamelCase )
493
'''simple docstring''' import os import unittest from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowerCAmelCase ( __UpperCAmelCase , unittest.TestCase ): a : int = LayoutLMTokenizer a : Optional[int] = LayoutLMTokenizerFast a : Optional[int] = True a : Any = True def lowercase ( self ): super().setUp() _SCREAMING_SNAKE_CASE = [ "[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest", ] _SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) def lowercase ( self , **UpperCamelCase ): return LayoutLMTokenizer.from_pretrained(self.tmpdirname , **UpperCamelCase ) def lowercase ( self , UpperCamelCase ): _SCREAMING_SNAKE_CASE = "UNwant\u00E9d,running" _SCREAMING_SNAKE_CASE = "unwanted, running" return input_text, output_text def lowercase ( self ): _SCREAMING_SNAKE_CASE = self.tokenizer_class(self.vocab_file ) _SCREAMING_SNAKE_CASE = tokenizer.tokenize("UNwant\u00E9d,running" ) self.assertListEqual(UpperCamelCase , ["un", "##want", "##ed", ",", "runn", "##ing"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCamelCase ) , [7, 4, 5, 10, 8, 9] ) def lowercase ( self ): pass
493
1
import unittest import numpy as np from transformers import RobertaPreLayerNormConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roberta_prelayernorm.modeling_flax_roberta_prelayernorm import ( FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormModel, ) class UpperCamelCase_ ( unittest.TestCase ): def __init__( self : Dict , lowerCamelCase : Union[str, Any] , lowerCamelCase : Dict=13 , lowerCamelCase : Optional[Any]=7 , lowerCamelCase : int=True , lowerCamelCase : str=True , lowerCamelCase : int=True , lowerCamelCase : Optional[int]=True , lowerCamelCase : Optional[int]=99 , lowerCamelCase : List[Any]=32 , lowerCamelCase : Any=5 , lowerCamelCase : Dict=4 , lowerCamelCase : int=37 , lowerCamelCase : int="gelu" , lowerCamelCase : Tuple=0.1 , lowerCamelCase : List[str]=0.1 , lowerCamelCase : Optional[int]=5_12 , lowerCamelCase : str=16 , lowerCamelCase : List[str]=2 , lowerCamelCase : Dict=0.02 , lowerCamelCase : int=4 , ): lowerCamelCase_ : Tuple = parent lowerCamelCase_ : int = batch_size lowerCamelCase_ : Any = seq_length lowerCamelCase_ : Optional[Any] = is_training lowerCamelCase_ : List[str] = use_attention_mask lowerCamelCase_ : Any = use_token_type_ids lowerCamelCase_ : Any = use_labels lowerCamelCase_ : Tuple = vocab_size lowerCamelCase_ : Union[str, Any] = hidden_size lowerCamelCase_ : str = num_hidden_layers lowerCamelCase_ : Dict = num_attention_heads lowerCamelCase_ : int = intermediate_size lowerCamelCase_ : str = hidden_act lowerCamelCase_ : Dict = hidden_dropout_prob lowerCamelCase_ : Optional[int] = attention_probs_dropout_prob lowerCamelCase_ : str = max_position_embeddings lowerCamelCase_ : Optional[Any] = type_vocab_size lowerCamelCase_ : Optional[Any] = type_sequence_label_size lowerCamelCase_ : str = initializer_range lowerCamelCase_ : List[Any] = num_choices def __a ( self : Union[str, Any] ): lowerCamelCase_ : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCamelCase_ : Any = None if self.use_attention_mask: lowerCamelCase_ : Tuple = random_attention_mask([self.batch_size, self.seq_length] ) lowerCamelCase_ : Tuple = None if self.use_token_type_ids: lowerCamelCase_ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowerCamelCase_ : str = RobertaPreLayerNormConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=a__ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def __a ( self : int ): lowerCamelCase_ : str = self.prepare_config_and_inputs() lowerCamelCase_ : Optional[int] = config_and_inputs lowerCamelCase_ : List[Any] = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": attention_mask} return config, inputs_dict def __a ( self : List[str] ): lowerCamelCase_ : Union[str, Any] = self.prepare_config_and_inputs() lowerCamelCase_ : int = config_and_inputs lowerCamelCase_ : Optional[Any] = True lowerCamelCase_ : List[Any] = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) lowerCamelCase_ : List[str] = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, encoder_hidden_states, encoder_attention_mask, ) @require_flax # Copied from tests.models.roberta.test_modelling_flax_roberta.FlaxRobertaPreLayerNormModelTest with ROBERTA->ROBERTA_PRELAYERNORM,Roberta->RobertaPreLayerNorm,roberta-base->andreasmadsen/efficient_mlm_m0.40 class UpperCamelCase_ ( lowercase_ , unittest.TestCase ): _a : Tuple = True _a : Optional[int] = ( ( FlaxRobertaPreLayerNormModel, FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, ) if is_flax_available() else () ) def __a ( self : Optional[int] ): lowerCamelCase_ : Dict = FlaxRobertaPreLayerNormModelTester(self ) @slow def __a ( self : List[Any] ): for model_class_name in self.all_model_classes: lowerCamelCase_ : List[str] = model_class_name.from_pretrained('andreasmadsen/efficient_mlm_m0.40' , from_pt=a__ ) lowerCamelCase_ : Union[str, Any] = model(np.ones((1, 1) ) ) self.assertIsNotNone(a__ ) @require_flax class UpperCamelCase_ ( unittest.TestCase ): @slow def __a ( self : int ): lowerCamelCase_ : Dict = FlaxRobertaPreLayerNormForMaskedLM.from_pretrained('andreasmadsen/efficient_mlm_m0.40' , from_pt=a__ ) lowerCamelCase_ : List[Any] = np.array([[0, 3_14_14, 2_32, 3_28, 7_40, 11_40, 1_26_95, 69, 4_60_78, 15_88, 2]] , dtype=jnp.intaa ) lowerCamelCase_ : int = model(a__ )[0] lowerCamelCase_ : str = [1, 11, 5_02_65] self.assertEqual(list(output.shape ) , a__ ) # compare the actual values for a slice. lowerCamelCase_ : Optional[Any] = np.array( [[[40.4_880, 18.0_199, -5.2_367], [-1.8_877, -4.0_885, 10.7_085], [-2.2_613, -5.6_110, 7.2_665]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , a__ , atol=1E-4 ) ) @slow def __a ( self : Union[str, Any] ): lowerCamelCase_ : List[Any] = FlaxRobertaPreLayerNormModel.from_pretrained('andreasmadsen/efficient_mlm_m0.40' , from_pt=a__ ) lowerCamelCase_ : Tuple = np.array([[0, 3_14_14, 2_32, 3_28, 7_40, 11_40, 1_26_95, 69, 4_60_78, 15_88, 2]] , dtype=jnp.intaa ) lowerCamelCase_ : Any = model(a__ )[0] # compare the actual values for a slice. lowerCamelCase_ : str = np.array( [[[0.0_208, -0.0_356, 0.0_237], [-0.1_569, -0.0_411, -0.2_626], [0.1_879, 0.0_125, -0.0_089]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , a__ , atol=1E-4 ) )
364
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 snake_case__ ( nn.Module): '''simple docstring''' def __init__( self , a__ , a__ , a__ = 3 , a__ = 1 , a__ = "relu" ) -> Optional[Any]: '''simple docstring''' super().__init__() __snake_case :Dict = nn.Convad( a__ , a__ , kernel_size=a__ , stride=a__ , padding=kernel_size // 2 , bias=a__ ) __snake_case :str = nn.BatchNormad(a__ ) __snake_case :List[Any] = ACTaFN[activation] if activation is not None else nn.Identity() def __lowercase ( self , a__ ) -> Tensor: '''simple docstring''' __snake_case :int = self.convolution(a__ ) __snake_case :Any = self.normalization(a__ ) __snake_case :Optional[int] = self.activation(a__ ) return hidden_state class snake_case__ ( nn.Module): '''simple docstring''' def __init__( self , a__ ) -> str: '''simple docstring''' super().__init__() __snake_case :Dict = ResNetConvLayer( config.num_channels , config.embedding_size , kernel_size=7 , stride=2 , activation=config.hidden_act ) __snake_case :List[Any] = nn.MaxPoolad(kernel_size=3 , stride=2 , padding=1 ) __snake_case :Tuple = config.num_channels def __lowercase ( self , a__ ) -> Tensor: '''simple docstring''' __snake_case :Optional[Any] = 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.""" ) __snake_case :Optional[int] = self.embedder(a__ ) __snake_case :int = self.pooler(a__ ) return embedding class snake_case__ ( nn.Module): '''simple docstring''' def __init__( self , a__ , a__ , a__ = 2 ) -> Optional[Any]: '''simple docstring''' super().__init__() __snake_case :Optional[Any] = nn.Convad(a__ , a__ , kernel_size=1 , stride=a__ , bias=a__ ) __snake_case :Tuple = nn.BatchNormad(a__ ) def __lowercase ( self , a__ ) -> Tensor: '''simple docstring''' __snake_case :Any = self.convolution(a__ ) __snake_case :str = self.normalization(a__ ) return hidden_state class snake_case__ ( nn.Module): '''simple docstring''' def __init__( self , a__ , a__ , a__ = 1 , a__ = "relu" ) -> List[str]: '''simple docstring''' super().__init__() __snake_case :int = in_channels != out_channels or stride != 1 __snake_case :Tuple = ( ResNetShortCut(a__ , a__ , stride=a__ ) if should_apply_shortcut else nn.Identity() ) __snake_case :Optional[int] = nn.Sequential( ResNetConvLayer(a__ , a__ , stride=a__ ) , ResNetConvLayer(a__ , a__ , activation=a__ ) , ) __snake_case :Union[str, Any] = ACTaFN[activation] def __lowercase ( self , a__ ) -> Union[str, Any]: '''simple docstring''' __snake_case :int = hidden_state __snake_case :Dict = self.layer(a__ ) __snake_case :Any = self.shortcut(a__ ) hidden_state += residual __snake_case :List[Any] = self.activation(a__ ) return hidden_state class snake_case__ ( nn.Module): '''simple docstring''' def __init__( self , a__ , a__ , a__ = 1 , a__ = "relu" , a__ = 4 ) -> List[Any]: '''simple docstring''' super().__init__() __snake_case :Optional[int] = in_channels != out_channels or stride != 1 __snake_case :List[Any] = out_channels // reduction __snake_case :List[str] = ( ResNetShortCut(a__ , a__ , stride=a__ ) if should_apply_shortcut else nn.Identity() ) __snake_case :int = nn.Sequential( ResNetConvLayer(a__ , a__ , kernel_size=1 ) , ResNetConvLayer(a__ , a__ , stride=a__ ) , ResNetConvLayer(a__ , a__ , kernel_size=1 , activation=a__ ) , ) __snake_case :Dict = ACTaFN[activation] def __lowercase ( self , a__ ) -> Any: '''simple docstring''' __snake_case :List[str] = hidden_state __snake_case :List[Any] = self.layer(a__ ) __snake_case :List[Any] = self.shortcut(a__ ) hidden_state += residual __snake_case :Optional[Any] = self.activation(a__ ) return hidden_state class snake_case__ ( nn.Module): '''simple docstring''' def __init__( self , a__ , a__ , a__ , a__ = 2 , a__ = 2 , ) -> Any: '''simple docstring''' super().__init__() __snake_case :Optional[int] = ResNetBottleNeckLayer if config.layer_type == """bottleneck""" else ResNetBasicLayer __snake_case :Tuple = nn.Sequential( # downsampling is done in the first layer with stride of 2 layer(a__ , a__ , stride=a__ , activation=config.hidden_act ) , *[layer(a__ , a__ , activation=config.hidden_act ) for _ in range(depth - 1 )] , ) def __lowercase ( self , a__ ) -> Tensor: '''simple docstring''' __snake_case :Union[str, Any] = input for layer in self.layers: __snake_case :str = layer(a__ ) return hidden_state class snake_case__ ( nn.Module): '''simple docstring''' def __init__( self , a__ ) -> Union[str, Any]: '''simple docstring''' super().__init__() __snake_case :Optional[int] = 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( a__ , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , ) ) __snake_case :Tuple = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for (in_channels, out_channels), depth in zip(a__ , config.depths[1:] ): self.stages.append(ResNetStage(a__ , a__ , a__ , depth=a__ ) ) def __lowercase ( self , a__ , a__ = False , a__ = True ) -> BaseModelOutputWithNoAttention: '''simple docstring''' __snake_case :Dict = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: __snake_case :Optional[int] = hidden_states + (hidden_state,) __snake_case :Tuple = stage_module(a__ ) if output_hidden_states: __snake_case :Optional[Any] = 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=a__ , hidden_states=a__ , ) class snake_case__ ( lowercase_): '''simple docstring''' lowerCamelCase : List[Any] = ResNetConfig lowerCamelCase : Optional[Any] = "resnet" lowerCamelCase : str = "pixel_values" lowerCamelCase : Optional[int] = True def __lowercase ( self , a__ ) -> Dict: '''simple docstring''' if isinstance(a__ , nn.Convad ): nn.init.kaiming_normal_(module.weight , mode="""fan_out""" , nonlinearity="""relu""" ) elif isinstance(a__ , (nn.BatchNormad, nn.GroupNorm) ): nn.init.constant_(module.weight , 1 ) nn.init.constant_(module.bias , 0 ) def __lowercase ( self , a__ , a__=False ) -> Optional[int]: '''simple docstring''' if isinstance(a__ , a__ ): __snake_case :Union[str, Any] = 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." , lowercase_ , ) class snake_case__ ( lowercase_): '''simple docstring''' def __init__( self , a__ ) -> Tuple: '''simple docstring''' super().__init__(a__ ) __snake_case :int = config __snake_case :Any = ResNetEmbeddings(a__ ) __snake_case :Dict = ResNetEncoder(a__ ) __snake_case :Dict = nn.AdaptiveAvgPoolad((1, 1) ) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(a__ ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=a__ , config_class=_CONFIG_FOR_DOC , modality="""vision""" , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def __lowercase ( self , a__ , a__ = None , a__ = None ) -> BaseModelOutputWithPoolingAndNoAttention: '''simple docstring''' __snake_case :List[str] = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __snake_case :List[str] = return_dict if return_dict is not None else self.config.use_return_dict __snake_case :int = self.embedder(a__ ) __snake_case :Any = self.encoder( a__ , output_hidden_states=a__ , return_dict=a__ ) __snake_case :Any = encoder_outputs[0] __snake_case :int = self.pooler(a__ ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return BaseModelOutputWithPoolingAndNoAttention( last_hidden_state=a__ , pooler_output=a__ , 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 " , lowercase_ , ) class snake_case__ ( lowercase_): '''simple docstring''' def __init__( self , a__ ) -> List[Any]: '''simple docstring''' super().__init__(a__ ) __snake_case :Union[str, Any] = config.num_labels __snake_case :Optional[int] = ResNetModel(a__ ) # classification head __snake_case :List[str] = 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(a__ ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=a__ , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def __lowercase ( self , a__ = None , a__ = None , a__ = None , a__ = None , ) -> ImageClassifierOutputWithNoAttention: '''simple docstring''' __snake_case :Union[str, Any] = return_dict if return_dict is not None else self.config.use_return_dict __snake_case :Tuple = self.resnet(a__ , output_hidden_states=a__ , return_dict=a__ ) __snake_case :Optional[Any] = outputs.pooler_output if return_dict else outputs[1] __snake_case :Optional[Any] = self.classifier(a__ ) __snake_case :Any = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: __snake_case :List[Any] = """regression""" elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): __snake_case :List[Any] = """single_label_classification""" else: __snake_case :Union[str, Any] = """multi_label_classification""" if self.config.problem_type == "regression": __snake_case :Any = MSELoss() if self.num_labels == 1: __snake_case :Optional[Any] = loss_fct(logits.squeeze() , labels.squeeze() ) else: __snake_case :Any = loss_fct(a__ , a__ ) elif self.config.problem_type == "single_label_classification": __snake_case :int = CrossEntropyLoss() __snake_case :List[Any] = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": __snake_case :List[str] = BCEWithLogitsLoss() __snake_case :int = loss_fct(a__ , a__ ) if not return_dict: __snake_case :int = (logits,) + outputs[2:] return (loss,) + output if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=a__ , logits=a__ , hidden_states=outputs.hidden_states ) @add_start_docstrings( "\n ResNet backbone, to be used with frameworks like DETR and MaskFormer.\n " , lowercase_ , ) class snake_case__ ( lowercase_ , lowercase_): '''simple docstring''' def __init__( self , a__ ) -> int: '''simple docstring''' super().__init__(a__ ) super()._init_backbone(a__ ) __snake_case :Optional[int] = [config.embedding_size] + config.hidden_sizes __snake_case :str = ResNetEmbeddings(a__ ) __snake_case :Any = ResNetEncoder(a__ ) # initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(a__ ) @replace_return_docstrings(output_type=a__ , config_class=_CONFIG_FOR_DOC ) def __lowercase ( self , a__ , a__ = None , a__ = None ) -> BackboneOutput: '''simple docstring''' __snake_case :int = return_dict if return_dict is not None else self.config.use_return_dict __snake_case :Union[str, Any] = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __snake_case :List[str] = self.embedder(a__ ) __snake_case :List[Any] = self.encoder(a__ , output_hidden_states=a__ , return_dict=a__ ) __snake_case :Optional[int] = outputs.hidden_states __snake_case :Tuple = () for idx, stage in enumerate(self.stage_names ): if stage in self.out_features: feature_maps += (hidden_states[idx],) if not return_dict: __snake_case :Union[str, Any] = (feature_maps,) if output_hidden_states: output += (outputs.hidden_states,) return output return BackboneOutput( feature_maps=a__ , hidden_states=outputs.hidden_states if output_hidden_states else None , attentions=a__ , )
455
0
import logging import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.bert.modeling_bert import ( BERT_INPUTS_DOCSTRING, BERT_START_DOCSTRING, BertEncoder, BertModel, BertPreTrainedModel, ) lowercase_ = logging.getLogger(__name__) class SCREAMING_SNAKE_CASE__ ( __UpperCamelCase ): def snake_case__ ( self : Union[str, Any] , _lowerCAmelCase : Optional[Any] , _lowerCAmelCase : Dict , _lowerCAmelCase : Optional[int]=None , _lowerCAmelCase : List[Any]=None ): __snake_case : Optional[Any] = self.layer[current_layer](_lowerCAmelCase , _lowerCAmelCase , head_mask[current_layer] ) __snake_case : Dict = layer_outputs[0] return hidden_states @add_start_docstrings( "The bare Bert Model transformer with PABEE outputting raw hidden-states without any specific head on top." , __UpperCamelCase , ) class SCREAMING_SNAKE_CASE__ ( __UpperCamelCase ): def __init__( self : str , _lowerCAmelCase : Optional[int] ): super().__init__(_lowerCAmelCase ) __snake_case : List[Any] = BertEncoderWithPabee(_lowerCAmelCase ) self.init_weights() __snake_case : List[str] = 0 __snake_case : Dict = 0 __snake_case : List[Any] = 0 __snake_case : List[Any] = 0 def snake_case__ ( self : Union[str, Any] , _lowerCAmelCase : Dict ): __snake_case : List[Any] = threshold def snake_case__ ( self : Dict , _lowerCAmelCase : str ): __snake_case : List[Any] = patience def snake_case__ ( self : str ): __snake_case : List[str] = 0 __snake_case : str = 0 def snake_case__ ( self : Optional[int] ): __snake_case : Tuple = self.inference_layers_num / self.inference_instances_num __snake_case : List[str] = ( f'''*** Patience = {self.patience} Avg. Inference Layers = {avg_inf_layers:.2f} Speed Up =''' f''' {1 - avg_inf_layers / self.config.num_hidden_layers:.2f} ***''' ) print(_lowerCAmelCase ) @add_start_docstrings_to_model_forward(_lowerCAmelCase ) def snake_case__ ( self : List[str] , _lowerCAmelCase : List[str]=None , _lowerCAmelCase : Any=None , _lowerCAmelCase : Any=None , _lowerCAmelCase : Tuple=None , _lowerCAmelCase : List[Any]=None , _lowerCAmelCase : str=None , _lowerCAmelCase : List[Any]=None , _lowerCAmelCase : str=None , _lowerCAmelCase : Optional[Any]=None , _lowerCAmelCase : str=None , _lowerCAmelCase : int=False , ): if input_ids is not None and inputs_embeds is not None: raise ValueError("""You cannot specify both input_ids and inputs_embeds at the same time""" ) elif input_ids is not None: __snake_case : Dict = input_ids.size() elif inputs_embeds is not None: __snake_case : Optional[int] = inputs_embeds.size()[:-1] else: raise ValueError("""You have to specify either input_ids or inputs_embeds""" ) __snake_case : int = input_ids.device if input_ids is not None else inputs_embeds.device if attention_mask is None: __snake_case : Union[str, Any] = torch.ones(_lowerCAmelCase , device=_lowerCAmelCase ) if token_type_ids is None: __snake_case : Any = torch.zeros(_lowerCAmelCase , dtype=torch.long , device=_lowerCAmelCase ) # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] # ourselves in which case we just need to make it broadcastable to all heads. __snake_case : torch.Tensor = self.get_extended_attention_mask(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) # If a 2D ou 3D attention mask is provided for the cross-attention # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length] if self.config.is_decoder and encoder_hidden_states is not None: __snake_case , __snake_case , __snake_case : Tuple = encoder_hidden_states.size() __snake_case : int = (encoder_batch_size, encoder_sequence_length) if encoder_attention_mask is None: __snake_case : List[Any] = torch.ones(_lowerCAmelCase , device=_lowerCAmelCase ) __snake_case : Optional[Any] = self.invert_attention_mask(_lowerCAmelCase ) else: __snake_case : Any = None # Prepare head mask if needed # 1.0 in head_mask indicate we keep the head # attention_probs has shape bsz x n_heads x N x N # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length] __snake_case : Optional[Any] = self.get_head_mask(_lowerCAmelCase , self.config.num_hidden_layers ) __snake_case : str = self.embeddings( input_ids=_lowerCAmelCase , position_ids=_lowerCAmelCase , token_type_ids=_lowerCAmelCase , inputs_embeds=_lowerCAmelCase ) __snake_case : List[str] = embedding_output if self.training: __snake_case : Optional[int] = [] for i in range(self.config.num_hidden_layers ): __snake_case : int = self.encoder.adaptive_forward( _lowerCAmelCase , current_layer=_lowerCAmelCase , attention_mask=_lowerCAmelCase , head_mask=_lowerCAmelCase ) __snake_case : Optional[int] = self.pooler(_lowerCAmelCase ) __snake_case : int = output_layers[i](output_dropout(_lowerCAmelCase ) ) res.append(_lowerCAmelCase ) elif self.patience == 0: # Use all layers for inference __snake_case : Union[str, Any] = self.encoder( _lowerCAmelCase , attention_mask=_lowerCAmelCase , head_mask=_lowerCAmelCase , encoder_hidden_states=_lowerCAmelCase , encoder_attention_mask=_lowerCAmelCase , ) __snake_case : Any = self.pooler(encoder_outputs[0] ) __snake_case : Tuple = [output_layers[self.config.num_hidden_layers - 1](_lowerCAmelCase )] else: __snake_case : Optional[int] = 0 __snake_case : Union[str, Any] = None __snake_case : Optional[Any] = 0 for i in range(self.config.num_hidden_layers ): calculated_layer_num += 1 __snake_case : str = self.encoder.adaptive_forward( _lowerCAmelCase , current_layer=_lowerCAmelCase , attention_mask=_lowerCAmelCase , head_mask=_lowerCAmelCase ) __snake_case : str = self.pooler(_lowerCAmelCase ) __snake_case : Any = output_layers[i](_lowerCAmelCase ) if regression: __snake_case : List[str] = logits.detach() if patient_result is not None: __snake_case : Union[str, Any] = patient_result.detach() if (patient_result is not None) and torch.abs(patient_result - labels ) < self.regression_threshold: patient_counter += 1 else: __snake_case : Union[str, Any] = 0 else: __snake_case : Union[str, Any] = logits.detach().argmax(dim=1 ) if patient_result is not None: __snake_case : List[str] = patient_result.detach().argmax(dim=1 ) if (patient_result is not None) and torch.all(labels.eq(_lowerCAmelCase ) ): patient_counter += 1 else: __snake_case : Optional[Any] = 0 __snake_case : str = logits if patient_counter == self.patience: break __snake_case : Tuple = [patient_result] self.inference_layers_num += calculated_layer_num self.inference_instances_num += 1 return res @add_start_docstrings( "Bert Model transformer with PABEE and a sequence classification/regression head on top (a linear layer on top of\n the pooled output) e.g. for GLUE tasks. " , __UpperCamelCase , ) class SCREAMING_SNAKE_CASE__ ( __UpperCamelCase ): def __init__( self : Optional[int] , _lowerCAmelCase : str ): super().__init__(_lowerCAmelCase ) __snake_case : Union[str, Any] = config.num_labels __snake_case : List[Any] = BertModelWithPabee(_lowerCAmelCase ) __snake_case : Tuple = nn.Dropout(config.hidden_dropout_prob ) __snake_case : Any = nn.ModuleList( [nn.Linear(config.hidden_size , self.config.num_labels ) for _ in range(config.num_hidden_layers )] ) self.init_weights() @add_start_docstrings_to_model_forward(_lowerCAmelCase ) def snake_case__ ( self : List[Any] , _lowerCAmelCase : Tuple=None , _lowerCAmelCase : str=None , _lowerCAmelCase : str=None , _lowerCAmelCase : Optional[int]=None , _lowerCAmelCase : Dict=None , _lowerCAmelCase : Tuple=None , _lowerCAmelCase : int=None , ): __snake_case : Optional[Any] = self.bert( input_ids=_lowerCAmelCase , attention_mask=_lowerCAmelCase , token_type_ids=_lowerCAmelCase , position_ids=_lowerCAmelCase , head_mask=_lowerCAmelCase , inputs_embeds=_lowerCAmelCase , output_dropout=self.dropout , output_layers=self.classifiers , regression=self.num_labels == 1 , ) __snake_case : Union[str, Any] = (logits[-1],) if labels is not None: __snake_case : Optional[Any] = None __snake_case : Optional[int] = 0 for ix, logits_item in enumerate(_lowerCAmelCase ): if self.num_labels == 1: # We are doing regression __snake_case : Dict = MSELoss() __snake_case : Optional[Any] = loss_fct(logits_item.view(-1 ) , labels.view(-1 ) ) else: __snake_case : Any = CrossEntropyLoss() __snake_case : str = loss_fct(logits_item.view(-1 , self.num_labels ) , labels.view(-1 ) ) if total_loss is None: __snake_case : Tuple = loss else: total_loss += loss * (ix + 1) total_weights += ix + 1 __snake_case : List[str] = (total_loss / total_weights,) + outputs return outputs
390
import argparse from transformers import ( TapasConfig, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasTokenizer, load_tf_weights_in_tapas, ) from transformers.utils import logging logging.set_verbosity_info() def __lowerCAmelCase ( __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Optional[Any] ): '''simple docstring''' # Initialise PyTorch model. # If you want to convert a checkpoint that uses absolute position embeddings, make sure to set reset_position_index_per_cell of # TapasConfig to False. # initialize configuration from json file __snake_case : Union[str, Any] = TapasConfig.from_json_file(__SCREAMING_SNAKE_CASE ) # set absolute/relative position embeddings parameter __snake_case : Tuple = reset_position_index_per_cell # set remaining parameters of TapasConfig as well as the model based on the task if task == "SQA": __snake_case : Dict = TapasForQuestionAnswering(config=__SCREAMING_SNAKE_CASE ) elif task == "WTQ": # run_task_main.py hparams __snake_case : int = 4 __snake_case : Dict = True # hparam_utils.py hparams __snake_case : Any = 0.66_46_94 __snake_case : Optional[int] = 0.20_79_51 __snake_case : str = 0.12_11_94 __snake_case : Optional[int] = True __snake_case : int = True __snake_case : int = False __snake_case : List[Any] = 0.0_35_25_13 __snake_case : Any = TapasForQuestionAnswering(config=__SCREAMING_SNAKE_CASE ) elif task == "WIKISQL_SUPERVISED": # run_task_main.py hparams __snake_case : Any = 4 __snake_case : Union[str, Any] = False # hparam_utils.py hparams __snake_case : Any = 36.45_19 __snake_case : Union[str, Any] = 0.90_34_21 __snake_case : Any = 2_22.0_88 __snake_case : Tuple = True __snake_case : List[str] = True __snake_case : Any = True __snake_case : str = 0.76_31_41 __snake_case : Optional[Any] = TapasForQuestionAnswering(config=__SCREAMING_SNAKE_CASE ) elif task == "TABFACT": __snake_case : int = TapasForSequenceClassification(config=__SCREAMING_SNAKE_CASE ) elif task == "MLM": __snake_case : int = TapasForMaskedLM(config=__SCREAMING_SNAKE_CASE ) elif task == "INTERMEDIATE_PRETRAINING": __snake_case : Optional[int] = TapasModel(config=__SCREAMING_SNAKE_CASE ) else: raise ValueError(F'''Task {task} not supported.''' ) print(F'''Building PyTorch model from configuration: {config}''' ) # Load weights from tf checkpoint load_tf_weights_in_tapas(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Save pytorch-model (weights and configuration) print(F'''Save PyTorch model to {pytorch_dump_path}''' ) model.save_pretrained(__SCREAMING_SNAKE_CASE ) # Save tokenizer files print(F'''Save tokenizer files to {pytorch_dump_path}''' ) __snake_case : Tuple = TapasTokenizer(vocab_file=tf_checkpoint_path[:-1_0] + """vocab.txt""" , model_max_length=5_1_2 ) tokenizer.save_pretrained(__SCREAMING_SNAKE_CASE ) print("""Used relative position embeddings:""" , model.config.reset_position_index_per_cell ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( "--task", default="SQA", type=str, help="Model task for which to convert a checkpoint. Defaults to SQA." ) parser.add_argument( "--reset_position_index_per_cell", default=False, action="store_true", help="Whether to use relative position embeddings or not. Defaults to True.", ) parser.add_argument( "--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path." ) parser.add_argument( "--tapas_config_file", default=None, type=str, required=True, help=( "The config json file corresponding to the pre-trained TAPAS 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." ) lowercase_ = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.task, args.reset_position_index_per_cell, args.tf_checkpoint_path, args.tapas_config_file, args.pytorch_dump_path, )
390
1
"""simple docstring""" import argparse import os import transformers from .convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS from .utils import logging logging.set_verbosity_info() _UpperCamelCase = logging.get_logger(__name__) _UpperCamelCase = {name: getattr(transformers, name + 'Fast') for name in SLOW_TO_FAST_CONVERTERS} def lowerCAmelCase_ ( SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : Union[str, Any] , SCREAMING_SNAKE_CASE : Dict ): '''simple docstring''' if tokenizer_name is not None and tokenizer_name not in TOKENIZER_CLASSES: raise ValueError(F'Unrecognized tokenizer name, should be one of {list(TOKENIZER_CLASSES.keys() )}.' ) if tokenizer_name is None: __lowerCamelCase : int =TOKENIZER_CLASSES else: __lowerCamelCase : Union[str, Any] ={tokenizer_name: getattr(SCREAMING_SNAKE_CASE , tokenizer_name + '''Fast''' )} logger.info(F'Loading tokenizer classes: {tokenizer_names}' ) for tokenizer_name in tokenizer_names: __lowerCamelCase : List[Any] =TOKENIZER_CLASSES[tokenizer_name] __lowerCamelCase : Union[str, Any] =True if checkpoint_name is None: __lowerCamelCase : Any =list(tokenizer_class.max_model_input_sizes.keys() ) else: __lowerCamelCase : Any =[checkpoint_name] logger.info(F'For tokenizer {tokenizer_class.__class__.__name__} loading checkpoints: {checkpoint_names}' ) for checkpoint in checkpoint_names: logger.info(F'Loading {tokenizer_class.__class__.__name__} {checkpoint}' ) # Load tokenizer __lowerCamelCase : Optional[Any] =tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE , force_download=SCREAMING_SNAKE_CASE ) # Save fast tokenizer logger.info(F'Save fast tokenizer to {dump_path} with prefix {checkpoint} add_prefix {add_prefix}' ) # For organization names we create sub-directories if "/" in checkpoint: __lowerCamelCase , __lowerCamelCase : Optional[Any] =checkpoint.split('''/''' ) __lowerCamelCase : Dict =os.path.join(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) elif add_prefix: __lowerCamelCase : Union[str, Any] =checkpoint __lowerCamelCase : str =dump_path else: __lowerCamelCase : List[Any] =None __lowerCamelCase : Union[str, Any] =dump_path logger.info(F'=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}' ) if checkpoint in list(tokenizer.pretrained_vocab_files_map.values() )[0]: __lowerCamelCase : int =list(tokenizer.pretrained_vocab_files_map.values() )[0][checkpoint] __lowerCamelCase : List[str] =file_path.split(SCREAMING_SNAKE_CASE )[-1][0] if next_char == "/": __lowerCamelCase : Union[str, Any] =os.path.join(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) __lowerCamelCase : List[Any] =None logger.info(F'=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}' ) __lowerCamelCase : Optional[Any] =tokenizer.save_pretrained( SCREAMING_SNAKE_CASE , legacy_format=SCREAMING_SNAKE_CASE , filename_prefix=SCREAMING_SNAKE_CASE ) logger.info(F'=> File names {file_names}' ) for file_name in file_names: if not file_name.endswith('''tokenizer.json''' ): os.remove(SCREAMING_SNAKE_CASE ) logger.info(F'=> removing {file_name}' ) if __name__ == "__main__": _UpperCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '--dump_path', default=None, type=str, required=True, help='Path to output generated fast tokenizer files.' ) parser.add_argument( '--tokenizer_name', default=None, type=str, help=( f'''Optional tokenizer type selected in the list of {list(TOKENIZER_CLASSES.keys())}. If not given, will ''' 'download and convert all the checkpoints from AWS.' ), ) parser.add_argument( '--checkpoint_name', default=None, type=str, help='Optional checkpoint name. If not given, will download and convert the canonical checkpoints from AWS.', ) parser.add_argument( '--force_download', action='store_true', help='Re-download checkpoints.', ) _UpperCamelCase = parser.parse_args() convert_slow_checkpoint_to_fast(args.tokenizer_name, args.checkpoint_name, args.dump_path, args.force_download)
179
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool class SCREAMING_SNAKE_CASE_ ( snake_case__ ): """simple docstring""" __snake_case : int = """philschmid/bart-large-cnn-samsum""" __snake_case : Optional[int] = ( """This is a tool that summarizes an English text. It takes an input `text` containing the text to summarize, """ """and returns a summary of the text.""" ) __snake_case : Dict = """summarizer""" __snake_case : str = AutoTokenizer __snake_case : List[str] = AutoModelForSeqaSeqLM __snake_case : List[Any] = ["""text"""] __snake_case : Dict = ["""text"""] def __lowercase ( self :int , __lowercase :List[Any] ): return self.pre_processor(__lowercase , return_tensors='''pt''' , truncation=__lowercase ) def __lowercase ( self :Optional[int] , __lowercase :Optional[int] ): return self.model.generate(**__lowercase )[0] def __lowercase ( self :List[Any] , __lowercase :str ): return self.pre_processor.decode(__lowercase , skip_special_tokens=__lowercase , clean_up_tokenization_spaces=__lowercase )
179
1
import unittest from transformers import BertGenerationConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import BertGenerationDecoder, BertGenerationEncoder class _lowercase : def __init__( self : Union[str, Any] , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : int=13 , __lowerCAmelCase : int=7 , __lowerCAmelCase : List[Any]=True , __lowerCAmelCase : Optional[int]=True , __lowerCAmelCase : Dict=99 , __lowerCAmelCase : Tuple=32 , __lowerCAmelCase : Optional[int]=5 , __lowerCAmelCase : Dict=4 , __lowerCAmelCase : str=37 , __lowerCAmelCase : List[Any]="gelu" , __lowerCAmelCase : List[str]=0.1 , __lowerCAmelCase : int=0.1 , __lowerCAmelCase : Tuple=50 , __lowerCAmelCase : List[Any]=0.0_2 , __lowerCAmelCase : List[Any]=True , __lowerCAmelCase : List[Any]=None , ) -> Any: """simple docstring""" a = parent a = batch_size a = seq_length a = is_training a = use_input_mask a = vocab_size 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 = max_position_embeddings a = initializer_range a = use_labels a = scope def A ( self : int ) -> str: """simple docstring""" a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a = None if self.use_input_mask: a = random_attention_mask([self.batch_size, self.seq_length] ) if self.use_labels: a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a = self.get_config() return config, input_ids, input_mask, token_labels def A ( self : Union[str, Any] ) -> Dict: """simple docstring""" return BertGenerationConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , is_decoder=__lowerCAmelCase , initializer_range=self.initializer_range , ) def A ( self : Dict ) -> Tuple: """simple docstring""" ( ( a ) , ( a ) , ( a ) , ( a ) , ) = self.prepare_config_and_inputs() a = True a = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) a = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, input_mask, token_labels, encoder_hidden_states, encoder_attention_mask, ) def A ( self : int , __lowerCAmelCase : Any , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : Tuple , __lowerCAmelCase : int , **__lowerCAmelCase : Union[str, Any] , ) -> List[Any]: """simple docstring""" a = BertGenerationEncoder(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() a = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase ) a = model(__lowerCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def A ( self : str , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Any , __lowerCAmelCase : int , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : Optional[int] , **__lowerCAmelCase : Tuple , ) -> Dict: """simple docstring""" a = True a = BertGenerationEncoder(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() a = model( __lowerCAmelCase , attention_mask=__lowerCAmelCase , encoder_hidden_states=__lowerCAmelCase , encoder_attention_mask=__lowerCAmelCase , ) a = model( __lowerCAmelCase , attention_mask=__lowerCAmelCase , encoder_hidden_states=__lowerCAmelCase , ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def A ( self : Tuple , __lowerCAmelCase : List[str] , __lowerCAmelCase : List[str] , __lowerCAmelCase : Dict , __lowerCAmelCase : Any , __lowerCAmelCase : List[str] , __lowerCAmelCase : List[Any] , **__lowerCAmelCase : str , ) -> Any: """simple docstring""" a = True a = True a = BertGenerationDecoder(config=__lowerCAmelCase ).to(__lowerCAmelCase ).eval() # first forward pass a = model( __lowerCAmelCase , attention_mask=__lowerCAmelCase , encoder_hidden_states=__lowerCAmelCase , encoder_attention_mask=__lowerCAmelCase , use_cache=__lowerCAmelCase , ) a = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids a = ids_tensor((self.batch_size, 3) , config.vocab_size ) a = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and a = torch.cat([input_ids, next_tokens] , dim=-1 ) a = torch.cat([input_mask, next_mask] , dim=-1 ) a = model( __lowerCAmelCase , attention_mask=__lowerCAmelCase , encoder_hidden_states=__lowerCAmelCase , encoder_attention_mask=__lowerCAmelCase , output_hidden_states=__lowerCAmelCase , )["hidden_states"][0] a = model( __lowerCAmelCase , attention_mask=__lowerCAmelCase , encoder_hidden_states=__lowerCAmelCase , encoder_attention_mask=__lowerCAmelCase , past_key_values=__lowerCAmelCase , output_hidden_states=__lowerCAmelCase , )["hidden_states"][0] # select random slice a = ids_tensor((1,) , output_from_past.shape[-1] ).item() a = output_from_no_past[:, -3:, random_slice_idx].detach() a = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(__lowerCAmelCase , __lowerCAmelCase , atol=1E-3 ) ) def A ( self : Optional[int] , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Optional[int] , *__lowerCAmelCase : Union[str, Any] , ) -> Optional[Any]: """simple docstring""" a = BertGenerationDecoder(__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() a = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase , labels=__lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def A ( self : Union[str, Any] ) -> List[Any]: """simple docstring""" a , a , a , a = self.prepare_config_and_inputs() a = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class _lowercase ( UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__, unittest.TestCase ): _UpperCAmelCase = (BertGenerationEncoder, BertGenerationDecoder) if is_torch_available() else () _UpperCAmelCase = (BertGenerationDecoder,) if is_torch_available() else () _UpperCAmelCase = ( {'''feature-extraction''': BertGenerationEncoder, '''text-generation''': BertGenerationDecoder} if is_torch_available() else {} ) def A ( self : Any ) -> Dict: """simple docstring""" a = BertGenerationEncoderTester(self ) a = ConfigTester(self , config_class=__lowerCAmelCase , hidden_size=37 ) def A ( self : Optional[Any] ) -> Dict: """simple docstring""" self.config_tester.run_common_tests() def A ( self : Optional[Any] ) -> Tuple: """simple docstring""" a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCAmelCase ) def A ( self : Optional[Any] ) -> Optional[Any]: """simple docstring""" a , a , a , a = self.model_tester.prepare_config_and_inputs() a = "bert" self.model_tester.create_and_check_model(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) def A ( self : Optional[Any] ) -> List[str]: """simple docstring""" a = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*__lowerCAmelCase ) def A ( self : Any ) -> Tuple: """simple docstring""" a = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_decoder_model_past_large_inputs(*__lowerCAmelCase ) def A ( self : str ) -> int: """simple docstring""" ( ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ) = self.model_tester.prepare_config_and_inputs_for_decoder() a = None self.model_tester.create_and_check_model_as_decoder( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) def A ( self : Optional[int] ) -> Optional[int]: """simple docstring""" a = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_for_causal_lm(*__lowerCAmelCase ) @slow def A ( self : Optional[int] ) -> str: """simple docstring""" a = BertGenerationEncoder.from_pretrained("google/bert_for_seq_generation_L-24_bbc_encoder" ) self.assertIsNotNone(__lowerCAmelCase ) @require_torch class _lowercase ( unittest.TestCase ): @slow def A ( self : Optional[int] ) -> Optional[int]: """simple docstring""" a = BertGenerationEncoder.from_pretrained("google/bert_for_seq_generation_L-24_bbc_encoder" ) a = torch.tensor([[101, 7592, 1010, 2026, 3899, 2003, 1_0140, 102]] ) with torch.no_grad(): a = model(__lowerCAmelCase )[0] a = torch.Size([1, 8, 1024] ) self.assertEqual(output.shape , __lowerCAmelCase ) a = torch.tensor( [[[0.1_7_7_5, 0.0_0_8_3, -0.0_3_2_1], [1.6_0_0_2, 0.1_2_8_7, 0.3_9_1_2], [2.1_4_7_3, 0.5_7_9_1, 0.6_0_6_6]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , __lowerCAmelCase , atol=1E-4 ) ) @require_torch class _lowercase ( unittest.TestCase ): @slow def A ( self : List[Any] ) -> List[str]: """simple docstring""" a = BertGenerationDecoder.from_pretrained("google/bert_for_seq_generation_L-24_bbc_encoder" ) a = torch.tensor([[101, 7592, 1010, 2026, 3899, 2003, 1_0140, 102]] ) with torch.no_grad(): a = model(__lowerCAmelCase )[0] a = torch.Size([1, 8, 5_0358] ) self.assertEqual(output.shape , __lowerCAmelCase ) a = torch.tensor( [[[-0.5_7_8_8, -2.5_9_9_4, -3.7_0_5_4], [0.0_4_3_8, 4.7_9_9_7, 1.8_7_9_5], [1.5_8_6_2, 6.6_4_0_9, 4.4_6_3_8]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , __lowerCAmelCase , atol=1E-4 ) )
32
import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskFormerForInstanceSegmentation, MaskFormerModel if is_vision_available(): from transformers import MaskFormerImageProcessor if is_vision_available(): from PIL import Image class _lowercase : def __init__( self : Any , __lowerCAmelCase : Any , __lowerCAmelCase : Tuple=2 , __lowerCAmelCase : Optional[int]=True , __lowerCAmelCase : Optional[int]=False , __lowerCAmelCase : int=10 , __lowerCAmelCase : Any=3 , __lowerCAmelCase : Optional[int]=32 * 4 , __lowerCAmelCase : Dict=32 * 6 , __lowerCAmelCase : str=4 , __lowerCAmelCase : Dict=32 , ) -> Any: """simple docstring""" a = parent a = batch_size a = is_training a = use_auxiliary_loss a = num_queries a = num_channels a = min_size a = max_size a = num_labels a = mask_feature_size def A ( self : Union[str, Any] ) -> Dict: """simple docstring""" a = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( __lowerCAmelCase ) a = torch.ones([self.batch_size, self.min_size, self.max_size] , device=__lowerCAmelCase ) a = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=__lowerCAmelCase ) > 0.5 ).float() a = (torch.rand((self.batch_size, self.num_labels) , device=__lowerCAmelCase ) > 0.5).long() a = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def A ( self : str ) -> Any: """simple docstring""" return MaskFormerConfig.from_backbone_and_decoder_configs( backbone_config=SwinConfig( depths=[1, 1, 1, 1] , ) , decoder_config=DetrConfig( decoder_ffn_dim=128 , num_queries=self.num_queries , decoder_attention_heads=2 , d_model=self.mask_feature_size , ) , mask_feature_size=self.mask_feature_size , fpn_feature_size=self.mask_feature_size , num_channels=self.num_channels , num_labels=self.num_labels , ) def A ( self : Union[str, Any] ) -> Any: """simple docstring""" a , a , a , a , a = self.prepare_config_and_inputs() a = {"pixel_values": pixel_values, "pixel_mask": pixel_mask} return config, inputs_dict def A ( self : Tuple , __lowerCAmelCase : Any , __lowerCAmelCase : Dict ) -> str: """simple docstring""" a = output.encoder_hidden_states a = output.pixel_decoder_hidden_states a = output.transformer_decoder_hidden_states self.parent.assertTrue(len(__lowerCAmelCase ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(__lowerCAmelCase ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(__lowerCAmelCase ) , config.decoder_config.decoder_layers ) def A ( self : List[str] , __lowerCAmelCase : List[str] , __lowerCAmelCase : Dict , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : List[str]=False ) -> Tuple: """simple docstring""" with torch.no_grad(): a = MaskFormerModel(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() a = model(pixel_values=__lowerCAmelCase , pixel_mask=__lowerCAmelCase ) a = model(__lowerCAmelCase , output_hidden_states=__lowerCAmelCase ) # the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the # encoder and pixel decoder self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.mask_feature_size) , ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(__lowerCAmelCase , __lowerCAmelCase ) def A ( self : List[str] , __lowerCAmelCase : str , __lowerCAmelCase : List[Any] , __lowerCAmelCase : int , __lowerCAmelCase : Any , __lowerCAmelCase : List[str] ) -> Optional[int]: """simple docstring""" a = MaskFormerForInstanceSegmentation(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() def comm_check_on_output(__lowerCAmelCase : Tuple ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , ) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): a = model(pixel_values=__lowerCAmelCase , pixel_mask=__lowerCAmelCase ) a = model(__lowerCAmelCase ) comm_check_on_output(__lowerCAmelCase ) a = model( pixel_values=__lowerCAmelCase , pixel_mask=__lowerCAmelCase , mask_labels=__lowerCAmelCase , class_labels=__lowerCAmelCase ) comm_check_on_output(__lowerCAmelCase ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape , torch.Size([1] ) ) @require_torch class _lowercase ( UpperCAmelCase__, UpperCAmelCase__, unittest.TestCase ): _UpperCAmelCase = (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else () _UpperCAmelCase = ( {'''feature-extraction''': MaskFormerModel, '''image-segmentation''': MaskFormerForInstanceSegmentation} if is_torch_available() else {} ) _UpperCAmelCase = False _UpperCAmelCase = False _UpperCAmelCase = False _UpperCAmelCase = False def A ( self : List[str] ) -> List[Any]: """simple docstring""" a = MaskFormerModelTester(self ) a = ConfigTester(self , config_class=__lowerCAmelCase , has_text_modality=__lowerCAmelCase ) def A ( self : Any ) -> List[str]: """simple docstring""" self.config_tester.run_common_tests() def A ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" a , a = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(__lowerCAmelCase , **__lowerCAmelCase , output_hidden_states=__lowerCAmelCase ) def A ( self : int ) -> int: """simple docstring""" a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*__lowerCAmelCase ) @unittest.skip(reason="MaskFormer does not use inputs_embeds" ) def A ( self : List[Any] ) -> Optional[Any]: """simple docstring""" pass @unittest.skip(reason="MaskFormer does not have a get_input_embeddings method" ) def A ( self : str ) -> Union[str, Any]: """simple docstring""" pass @unittest.skip(reason="MaskFormer is not a generative model" ) def A ( self : Tuple ) -> Optional[Any]: """simple docstring""" pass @unittest.skip(reason="MaskFormer does not use token embeddings" ) def A ( self : Tuple ) -> Optional[Any]: """simple docstring""" pass @require_torch_multi_gpu @unittest.skip( reason="MaskFormer has some layers using `add_module` which doesn't work well with `nn.DataParallel`" ) def A ( self : Optional[int] ) -> List[str]: """simple docstring""" pass @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." ) def A ( self : List[str] ) -> Any: """simple docstring""" pass def A ( self : Optional[Any] ) -> 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(__lowerCAmelCase ) 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] , __lowerCAmelCase ) @slow def A ( self : Tuple ) -> List[Any]: """simple docstring""" for model_name in ["facebook/maskformer-swin-small-coco"]: a = MaskFormerModel.from_pretrained(__lowerCAmelCase ) self.assertIsNotNone(__lowerCAmelCase ) def A ( self : str ) -> Dict: """simple docstring""" a = (self.model_tester.min_size,) * 2 a = { "pixel_values": torch.randn((2, 3, *size) , device=__lowerCAmelCase ), "mask_labels": torch.randn((2, 10, *size) , device=__lowerCAmelCase ), "class_labels": torch.zeros(2 , 10 , device=__lowerCAmelCase ).long(), } a = MaskFormerForInstanceSegmentation(MaskFormerConfig() ).to(__lowerCAmelCase ) a = model(**__lowerCAmelCase ) self.assertTrue(outputs.loss is not None ) def A ( self : Union[str, Any] ) -> List[Any]: """simple docstring""" a , a = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(__lowerCAmelCase , **__lowerCAmelCase , output_hidden_states=__lowerCAmelCase ) def A ( self : List[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(__lowerCAmelCase ).to(__lowerCAmelCase ) a = model(**__lowerCAmelCase , output_attentions=__lowerCAmelCase ) self.assertTrue(outputs.attentions is not None ) def A ( self : Optional[Any] ) -> Union[str, Any]: """simple docstring""" if not self.model_tester.is_training: return # only MaskFormerForInstanceSegmentation has the loss a = self.all_model_classes[1] a , a , a , a , a = self.model_tester.prepare_config_and_inputs() a = model_class(__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.train() a = model(__lowerCAmelCase , mask_labels=__lowerCAmelCase , class_labels=__lowerCAmelCase ).loss loss.backward() def A ( self : List[str] ) -> Union[str, Any]: """simple docstring""" a = self.all_model_classes[1] a , a , a , a , a = self.model_tester.prepare_config_and_inputs() a = True a = True a = model_class(__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.train() a = model(__lowerCAmelCase , mask_labels=__lowerCAmelCase , class_labels=__lowerCAmelCase ) a = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() a = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() # we requires_grad=True in inputs_embeds (line 2152), the original implementation don't a = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() a = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=__lowerCAmelCase ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) A_ : int = 1E-4 def UpperCAmelCase__ ( ): '''simple docstring''' a = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_vision @slow class _lowercase ( unittest.TestCase ): @cached_property def A ( self : int ) -> Optional[int]: """simple docstring""" return ( MaskFormerImageProcessor.from_pretrained("facebook/maskformer-swin-small-coco" ) if is_vision_available() else None ) def A ( self : List[Any] ) -> Optional[Any]: """simple docstring""" a = MaskFormerModel.from_pretrained("facebook/maskformer-swin-small-coco" ).to(__lowerCAmelCase ) a = self.default_image_processor a = prepare_img() a = image_processor(__lowerCAmelCase , return_tensors="pt" ).to(__lowerCAmelCase ) a = inputs["pixel_values"].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(__lowerCAmelCase , (1, 3, 800, 1088) ) with torch.no_grad(): a = model(**__lowerCAmelCase ) a = torch.tensor( [[-0.0_4_8_2, 0.9_2_2_8, 0.4_9_5_1], [-0.2_5_4_7, 0.8_0_1_7, 0.8_5_2_7], [-0.0_0_6_9, 0.3_3_8_5, -0.0_0_8_9]] ).to(__lowerCAmelCase ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , __lowerCAmelCase , atol=__lowerCAmelCase ) ) a = torch.tensor( [[-0.8_4_2_2, -0.8_4_3_4, -0.9_7_1_8], [-1.0_1_4_4, -0.5_5_6_5, -0.4_1_9_5], [-1.0_0_3_8, -0.4_4_8_4, -0.1_9_6_1]] ).to(__lowerCAmelCase ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , __lowerCAmelCase , atol=__lowerCAmelCase ) ) a = torch.tensor( [[0.2_8_5_2, -0.0_1_5_9, 0.9_7_3_5], [0.6_2_5_4, 0.1_8_5_8, 0.8_5_2_9], [-0.0_6_8_0, -0.4_1_1_6, 1.8_4_1_3]] ).to(__lowerCAmelCase ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , __lowerCAmelCase , atol=__lowerCAmelCase ) ) def A ( self : str ) -> Union[str, Any]: """simple docstring""" a = ( MaskFormerForInstanceSegmentation.from_pretrained("facebook/maskformer-swin-small-coco" ) .to(__lowerCAmelCase ) .eval() ) a = self.default_image_processor a = prepare_img() a = image_processor(__lowerCAmelCase , return_tensors="pt" ).to(__lowerCAmelCase ) a = inputs["pixel_values"].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(__lowerCAmelCase , (1, 3, 800, 1088) ) with torch.no_grad(): a = model(**__lowerCAmelCase ) # masks_queries_logits a = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) a = [ [-1.3_7_3_7_1_2_4, -1.7_7_2_4_9_3_7, -1.9_3_6_4_2_3_3], [-1.5_9_7_7_2_8_1, -1.9_8_6_7_9_3_9, -2.1_5_2_3_6_9_5], [-1.5_7_9_5_3_9_8, -1.9_2_6_9_8_3_2, -2.0_9_3_9_4_2], ] a = torch.tensor(__lowerCAmelCase ).to(__lowerCAmelCase ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , __lowerCAmelCase , atol=__lowerCAmelCase ) ) # class_queries_logits a = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) a = torch.tensor( [ [1.65_12E00, -5.25_72E00, -3.35_19E00], [3.61_69E-02, -5.90_25E00, -2.93_13E00], [1.07_66E-04, -7.76_30E00, -5.12_63E00], ] ).to(__lowerCAmelCase ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , __lowerCAmelCase , atol=__lowerCAmelCase ) ) def A ( self : List[Any] ) -> Any: """simple docstring""" a = ( MaskFormerForInstanceSegmentation.from_pretrained("facebook/maskformer-resnet101-coco-stuff" ) .to(__lowerCAmelCase ) .eval() ) a = self.default_image_processor a = prepare_img() a = image_processor(__lowerCAmelCase , return_tensors="pt" ).to(__lowerCAmelCase ) a = inputs["pixel_values"].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(__lowerCAmelCase , (1, 3, 800, 1088) ) with torch.no_grad(): a = model(**__lowerCAmelCase ) # masks_queries_logits a = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) a = [[-0.9_0_4_6, -2.6_3_6_6, -4.6_0_6_2], [-3.4_1_7_9, -5.7_8_9_0, -8.8_0_5_7], [-4.9_1_7_9, -7.6_5_6_0, -1_0.7_7_1_1]] a = torch.tensor(__lowerCAmelCase ).to(__lowerCAmelCase ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , __lowerCAmelCase , atol=__lowerCAmelCase ) ) # class_queries_logits a = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) a = torch.tensor( [[4.7_1_8_8, -3.2_5_8_5, -2.8_8_5_7], [6.6_8_7_1, -2.9_1_8_1, -1.2_4_8_7], [7.2_4_4_9, -2.2_7_6_4, -2.1_8_7_4]] ).to(__lowerCAmelCase ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , __lowerCAmelCase , atol=__lowerCAmelCase ) ) def A ( self : int ) -> Any: """simple docstring""" a = ( MaskFormerForInstanceSegmentation.from_pretrained("facebook/maskformer-swin-small-coco" ) .to(__lowerCAmelCase ) .eval() ) a = self.default_image_processor a = image_processor( [np.zeros((3, 800, 1333) ), np.zeros((3, 800, 1333) )] , segmentation_maps=[np.zeros((384, 384) ).astype(np.floataa ), np.zeros((384, 384) ).astype(np.floataa )] , return_tensors="pt" , ) a = inputs["pixel_values"].to(__lowerCAmelCase ) a = [el.to(__lowerCAmelCase ) for el in inputs["mask_labels"]] a = [el.to(__lowerCAmelCase ) for el in inputs["class_labels"]] with torch.no_grad(): a = model(**__lowerCAmelCase ) self.assertTrue(outputs.loss is not None )
32
1
from __future__ import annotations from dataclasses import dataclass @dataclass class lowerCAmelCase_ : UpperCAmelCase = 42 UpperCAmelCase = None UpperCAmelCase = None def _snake_case ( __snake_case ): # Validation def is_valid_tree(__snake_case ) -> bool: if node is None: return True if not isinstance(__snake_case , __snake_case ): return False try: float(node.data ) except (TypeError, ValueError): return False return is_valid_tree(node.left ) and is_valid_tree(node.right ) if not is_valid_tree(__snake_case ): raise ValueError( '''Each node should be type of TreeNode and data should be float.''' ) def is_binary_search_tree_recursive_check( __snake_case , __snake_case , __snake_case ) -> bool: if node is None: return True return ( left_bound < node.data < right_bound and is_binary_search_tree_recursive_check(node.left , __snake_case , node.data ) and is_binary_search_tree_recursive_check( node.right , node.data , __snake_case ) ) return is_binary_search_tree_recursive_check(__snake_case , -float('''inf''' ) , float('''inf''' ) ) if __name__ == "__main__": import doctest doctest.testmod()
10
import os import tempfile import unittest from transformers import FlaubertConfig, is_torch_available from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( FlaubertForMultipleChoice, FlaubertForQuestionAnswering, FlaubertForQuestionAnsweringSimple, FlaubertForSequenceClassification, FlaubertForTokenClassification, FlaubertModel, FlaubertWithLMHeadModel, ) from transformers.models.flaubert.modeling_flaubert import FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCAmelCase_ ( __lowercase ): def __init__( self : Union[str, Any] , _A : Optional[Any] , _A : Any=13 , _A : Union[str, Any]=7 , _A : List[str]=True , _A : List[str]=True , _A : List[str]=True , _A : List[str]=True , _A : List[Any]=True , _A : Optional[int]=False , _A : Any=False , _A : int=False , _A : Optional[Any]=2 , _A : Any=99 , _A : str=0 , _A : Union[str, Any]=32 , _A : List[Any]=5 , _A : Tuple=4 , _A : List[str]=0.1 , _A : Union[str, Any]=0.1 , _A : int=512 , _A : Union[str, Any]=12 , _A : List[str]=2 , _A : int=0.02 , _A : Optional[Any]=3 , _A : Any=4 , _A : Optional[int]="last" , _A : Any=None , _A : Dict=None , ): _UpperCamelCase = parent _UpperCamelCase = batch_size _UpperCamelCase = seq_length _UpperCamelCase = is_training _UpperCamelCase = use_input_lengths _UpperCamelCase = use_token_type_ids _UpperCamelCase = use_labels _UpperCamelCase = gelu_activation _UpperCamelCase = sinusoidal_embeddings _UpperCamelCase = causal _UpperCamelCase = asm _UpperCamelCase = n_langs _UpperCamelCase = vocab_size _UpperCamelCase = n_special _UpperCamelCase = hidden_size _UpperCamelCase = num_hidden_layers _UpperCamelCase = num_attention_heads _UpperCamelCase = hidden_dropout_prob _UpperCamelCase = attention_probs_dropout_prob _UpperCamelCase = max_position_embeddings _UpperCamelCase = type_vocab_size _UpperCamelCase = type_sequence_label_size _UpperCamelCase = initializer_range _UpperCamelCase = num_labels _UpperCamelCase = num_choices _UpperCamelCase = summary_type _UpperCamelCase = use_proj _UpperCamelCase = scope def UpperCamelCase_ ( self : List[str] ): _UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _UpperCamelCase = random_attention_mask([self.batch_size, self.seq_length] ) _UpperCamelCase = None if self.use_input_lengths: _UpperCamelCase = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length _UpperCamelCase = None if self.use_token_type_ids: _UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) _UpperCamelCase = None _UpperCamelCase = None _UpperCamelCase = None if self.use_labels: _UpperCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _UpperCamelCase = ids_tensor([self.batch_size] , 2 ).float() _UpperCamelCase = ids_tensor([self.batch_size] , self.num_choices ) _UpperCamelCase = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def UpperCamelCase_ ( self : str ): return FlaubertConfig( vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , ) def UpperCamelCase_ ( self : str , _A : Union[str, Any] , _A : Optional[Any] , _A : str , _A : Tuple , _A : List[str] , _A : List[Any] , _A : Any , _A : str , _A : Optional[int] , ): _UpperCamelCase = FlaubertModel(config=_A ) model.to(_A ) model.eval() _UpperCamelCase = model(_A , lengths=_A , langs=_A ) _UpperCamelCase = model(_A , langs=_A ) _UpperCamelCase = model(_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase_ ( self : Tuple , _A : List[Any] , _A : str , _A : Optional[int] , _A : Optional[Any] , _A : List[str] , _A : int , _A : str , _A : List[Any] , _A : Any , ): _UpperCamelCase = FlaubertWithLMHeadModel(_A ) model.to(_A ) model.eval() _UpperCamelCase = model(_A , token_type_ids=_A , labels=_A ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCamelCase_ ( self : Tuple , _A : List[str] , _A : List[str] , _A : Optional[Any] , _A : Union[str, Any] , _A : str , _A : List[str] , _A : Tuple , _A : Optional[int] , _A : Dict , ): _UpperCamelCase = FlaubertForQuestionAnsweringSimple(_A ) model.to(_A ) model.eval() _UpperCamelCase = model(_A ) _UpperCamelCase = model(_A , start_positions=_A , end_positions=_A ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def UpperCamelCase_ ( self : Tuple , _A : str , _A : Tuple , _A : Tuple , _A : Union[str, Any] , _A : List[str] , _A : int , _A : str , _A : Dict , _A : List[Any] , ): _UpperCamelCase = FlaubertForQuestionAnswering(_A ) model.to(_A ) model.eval() _UpperCamelCase = model(_A ) _UpperCamelCase = model( _A , start_positions=_A , end_positions=_A , cls_index=_A , is_impossible=_A , p_mask=_A , ) _UpperCamelCase = model( _A , start_positions=_A , end_positions=_A , cls_index=_A , is_impossible=_A , ) ((_UpperCamelCase) , ) = result_with_labels.to_tuple() _UpperCamelCase = model(_A , start_positions=_A , end_positions=_A ) ((_UpperCamelCase) , ) = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape , () ) self.parent.assertEqual(result.start_top_log_probs.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape , (self.batch_size,) ) def UpperCamelCase_ ( self : List[Any] , _A : Union[str, Any] , _A : Tuple , _A : str , _A : int , _A : int , _A : Optional[int] , _A : Optional[int] , _A : int , _A : List[str] , ): _UpperCamelCase = FlaubertForSequenceClassification(_A ) model.to(_A ) model.eval() _UpperCamelCase = model(_A ) _UpperCamelCase = model(_A , labels=_A ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def UpperCamelCase_ ( self : Optional[int] , _A : List[str] , _A : Optional[Any] , _A : str , _A : Union[str, Any] , _A : List[Any] , _A : int , _A : List[Any] , _A : str , _A : List[str] , ): _UpperCamelCase = self.num_labels _UpperCamelCase = FlaubertForTokenClassification(_A ) model.to(_A ) model.eval() _UpperCamelCase = model(_A , attention_mask=_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCamelCase_ ( self : Tuple , _A : Dict , _A : str , _A : Optional[Any] , _A : List[str] , _A : Any , _A : Optional[int] , _A : Optional[Any] , _A : List[Any] , _A : List[str] , ): _UpperCamelCase = self.num_choices _UpperCamelCase = FlaubertForMultipleChoice(config=_A ) model.to(_A ) model.eval() _UpperCamelCase = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _UpperCamelCase = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _UpperCamelCase = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _UpperCamelCase = model( _A , attention_mask=_A , token_type_ids=_A , labels=_A , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCamelCase_ ( self : Tuple ): _UpperCamelCase = self.prepare_config_and_inputs() ( ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ) = config_and_inputs _UpperCamelCase = { '''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''lengths''': input_lengths, '''attention_mask''': input_mask, } return config, inputs_dict @require_torch class lowerCAmelCase_ ( __lowercase, __lowercase, unittest.TestCase ): UpperCAmelCase = ( ( FlaubertModel, FlaubertWithLMHeadModel, FlaubertForQuestionAnswering, FlaubertForQuestionAnsweringSimple, FlaubertForSequenceClassification, FlaubertForTokenClassification, FlaubertForMultipleChoice, ) if is_torch_available() else () ) UpperCAmelCase = ( { "feature-extraction": FlaubertModel, "fill-mask": FlaubertWithLMHeadModel, "question-answering": FlaubertForQuestionAnsweringSimple, "text-classification": FlaubertForSequenceClassification, "token-classification": FlaubertForTokenClassification, "zero-shot": FlaubertForSequenceClassification, } if is_torch_available() else {} ) def UpperCamelCase_ ( self : Union[str, Any] , _A : Dict , _A : Dict , _A : Tuple , _A : int , _A : Any ): if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith('''Fast''' ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def UpperCamelCase_ ( self : str , _A : Any , _A : List[str] , _A : Optional[int]=False ): _UpperCamelCase = super()._prepare_for_class(_A , _A , return_labels=_A ) if return_labels: if model_class.__name__ == "FlaubertForQuestionAnswering": _UpperCamelCase = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=_A ) _UpperCamelCase = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=_A ) return inputs_dict def UpperCamelCase_ ( self : str ): _UpperCamelCase = FlaubertModelTester(self ) _UpperCamelCase = ConfigTester(self , config_class=_A , emb_dim=37 ) def UpperCamelCase_ ( self : Optional[Any] ): self.config_tester.run_common_tests() def UpperCamelCase_ ( self : str ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_model(*_A ) def UpperCamelCase_ ( self : Optional[Any] ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_lm_head(*_A ) def UpperCamelCase_ ( self : Optional[Any] ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_simple_qa(*_A ) def UpperCamelCase_ ( self : Union[str, Any] ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_qa(*_A ) def UpperCamelCase_ ( self : Optional[int] ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_sequence_classif(*_A ) def UpperCamelCase_ ( self : Any ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_token_classif(*_A ) def UpperCamelCase_ ( self : Optional[int] ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_multiple_choice(*_A ) @slow def UpperCamelCase_ ( self : str ): for model_name in FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _UpperCamelCase = FlaubertModel.from_pretrained(_A ) self.assertIsNotNone(_A ) @slow @require_torch_gpu def UpperCamelCase_ ( self : List[Any] ): _UpperCamelCase , _UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # FlauBertForMultipleChoice behaves incorrectly in JIT environments. if model_class == FlaubertForMultipleChoice: return _UpperCamelCase = True _UpperCamelCase = model_class(config=_A ) _UpperCamelCase = self._prepare_for_class(_A , _A ) _UpperCamelCase = torch.jit.trace( _A , (inputs_dict['''input_ids'''].to('''cpu''' ), inputs_dict['''attention_mask'''].to('''cpu''' )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(_A , os.path.join(_A , '''traced_model.pt''' ) ) _UpperCamelCase = torch.jit.load(os.path.join(_A , '''traced_model.pt''' ) , map_location=_A ) loaded(inputs_dict['''input_ids'''].to(_A ) , inputs_dict['''attention_mask'''].to(_A ) ) @require_torch class lowerCAmelCase_ ( unittest.TestCase ): @slow def UpperCamelCase_ ( self : int ): _UpperCamelCase = FlaubertModel.from_pretrained('''flaubert/flaubert_base_cased''' ) _UpperCamelCase = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] ) with torch.no_grad(): _UpperCamelCase = model(_A )[0] _UpperCamelCase = torch.Size((1, 11, 768) ) self.assertEqual(output.shape , _A ) _UpperCamelCase = torch.tensor( [[[-2.6251, -1.4298, -0.0227], [-2.8510, -1.6387, 0.2258], [-2.8114, -1.1832, -0.3066]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , _A , atol=1e-4 ) )
10
1
'''simple docstring''' from abc import ABC, abstractmethod from typing import List, Optional class a ( SCREAMING_SNAKE_CASE ): """simple docstring""" def __init__( self : int ): '''simple docstring''' self.test() def __magic_name__ ( self : str ): '''simple docstring''' snake_case__ : int = 0 snake_case__ : Union[str, Any] = False while not completed: if counter == 1: self.reset() snake_case__ : List[str] = self.advance() if not self.does_advance(snake_case_ ): raise Exception( '''Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true.''' ) snake_case__ , snake_case__ , snake_case__ : int = self.update(snake_case_ ) counter += 1 if counter > 1_0_0_0_0: raise Exception('''update() does not fulfill the constraint.''' ) if self.remaining() != 0: raise Exception('''Custom Constraint is not defined correctly.''' ) @abstractmethod def __magic_name__ ( self : Any ): '''simple docstring''' raise NotImplementedError( F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""" ) @abstractmethod def __magic_name__ ( self : int , snake_case_ : int ): '''simple docstring''' raise NotImplementedError( F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""" ) @abstractmethod def __magic_name__ ( self : List[Any] , snake_case_ : int ): '''simple docstring''' raise NotImplementedError( F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""" ) @abstractmethod def __magic_name__ ( self : Optional[Any] ): '''simple docstring''' raise NotImplementedError( F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""" ) @abstractmethod def __magic_name__ ( self : Any ): '''simple docstring''' raise NotImplementedError( F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""" ) @abstractmethod def __magic_name__ ( self : Any , snake_case_ : Any=False ): '''simple docstring''' raise NotImplementedError( F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""" ) class a ( SCREAMING_SNAKE_CASE ): """simple docstring""" def __init__( self : List[Any] , snake_case_ : List[int] ): '''simple docstring''' super(snake_case_ , self ).__init__() if not isinstance(snake_case_ , snake_case_ ) or len(snake_case_ ) == 0: raise ValueError(F"""`token_ids` has to be a non-empty list, but is {token_ids}.""" ) if any((not isinstance(snake_case_ , snake_case_ ) or token_id < 0) for token_id in token_ids ): raise ValueError(F"""Each list in `token_ids` has to be a list of positive integers, but is {token_ids}.""" ) snake_case__ : Optional[Any] = token_ids snake_case__ : Any = len(self.token_ids ) snake_case__ : Optional[int] = -1 # the index of the currently fulfilled step snake_case__ : Dict = False def __magic_name__ ( self : Optional[Any] ): '''simple docstring''' if self.completed: return None return self.token_ids[self.fulfilled_idx + 1] def __magic_name__ ( self : Dict , snake_case_ : int ): '''simple docstring''' if not isinstance(snake_case_ , snake_case_ ): raise ValueError(F"""`token_id` has to be an `int`, but is {token_id} of type {type(snake_case_ )}""" ) if self.completed: return False return token_id == self.token_ids[self.fulfilled_idx + 1] def __magic_name__ ( self : List[Any] , snake_case_ : int ): '''simple docstring''' if not isinstance(snake_case_ , snake_case_ ): raise ValueError(F"""`token_id` has to be an `int`, but is {token_id} of type {type(snake_case_ )}""" ) snake_case__ : Optional[Any] = False snake_case__ : Tuple = False snake_case__ : Optional[Any] = False if self.does_advance(snake_case_ ): self.fulfilled_idx += 1 snake_case__ : str = True if self.fulfilled_idx == (self.seqlen - 1): snake_case__ : Optional[int] = True snake_case__ : List[str] = completed else: # failed to make progress. snake_case__ : Dict = True self.reset() return stepped, completed, reset def __magic_name__ ( self : Union[str, Any] ): '''simple docstring''' snake_case__ : Tuple = False snake_case__ : List[str] = 0 def __magic_name__ ( self : Any ): '''simple docstring''' return self.seqlen - (self.fulfilled_idx + 1) def __magic_name__ ( self : str , snake_case_ : Tuple=False ): '''simple docstring''' snake_case__ : Any = PhrasalConstraint(self.token_ids ) if stateful: snake_case__ : Optional[int] = self.seqlen snake_case__ : List[str] = self.fulfilled_idx snake_case__ : Union[str, Any] = self.completed return new_constraint class a : """simple docstring""" def __init__( self : Any , snake_case_ : List[List[int]] , snake_case_ : int=True ): '''simple docstring''' snake_case__ : List[str] = max([len(snake_case_ ) for one in nested_token_ids] ) snake_case__ : Tuple = {} for token_ids in nested_token_ids: snake_case__ : List[str] = root for tidx, token_id in enumerate(snake_case_ ): if token_id not in level: snake_case__ : int = {} snake_case__ : Union[str, Any] = level[token_id] if no_subsets and self.has_subsets(snake_case_ , snake_case_ ): raise ValueError( '''Each list in `nested_token_ids` can\'t be a complete subset of another list, but is''' F""" {nested_token_ids}.""" ) snake_case__ : Optional[Any] = root def __magic_name__ ( self : Tuple , snake_case_ : str ): '''simple docstring''' snake_case__ : Any = self.trie for current_token in current_seq: snake_case__ : str = start[current_token] snake_case__ : List[str] = list(start.keys() ) return next_tokens def __magic_name__ ( self : Optional[Any] , snake_case_ : Dict ): '''simple docstring''' snake_case__ : Optional[int] = self.next_tokens(snake_case_ ) return len(snake_case_ ) == 0 def __magic_name__ ( self : List[Any] , snake_case_ : Union[str, Any] ): '''simple docstring''' snake_case__ : str = list(root.values() ) if len(snake_case_ ) == 0: return 1 else: return sum([self.count_leaves(snake_case_ ) for nn in next_nodes] ) def __magic_name__ ( self : int , snake_case_ : int , snake_case_ : Optional[Any] ): '''simple docstring''' snake_case__ : Dict = self.count_leaves(snake_case_ ) return len(snake_case_ ) != leaf_count class a ( SCREAMING_SNAKE_CASE ): """simple docstring""" def __init__( self : Optional[Any] , snake_case_ : List[List[int]] ): '''simple docstring''' super(snake_case_ , self ).__init__() if not isinstance(snake_case_ , snake_case_ ) or len(snake_case_ ) == 0: raise ValueError(F"""`nested_token_ids` has to be a non-empty list, but is {nested_token_ids}.""" ) if any(not isinstance(snake_case_ , snake_case_ ) for token_ids in nested_token_ids ): raise ValueError(F"""`nested_token_ids` has to be a list of lists, but is {nested_token_ids}.""" ) if any( any((not isinstance(snake_case_ , snake_case_ ) or token_id < 0) for token_id in token_ids ) for token_ids in nested_token_ids ): raise ValueError( F"""Each list in `nested_token_ids` has to be a list of positive integers, but is {nested_token_ids}.""" ) snake_case__ : List[str] = DisjunctiveTrie(snake_case_ ) snake_case__ : List[str] = nested_token_ids snake_case__ : int = self.trie.max_height snake_case__ : Dict = [] snake_case__ : Optional[int] = False def __magic_name__ ( self : Optional[Any] ): '''simple docstring''' snake_case__ : int = self.trie.next_tokens(self.current_seq ) if len(snake_case_ ) == 0: return None else: return token_list def __magic_name__ ( self : Any , snake_case_ : int ): '''simple docstring''' if not isinstance(snake_case_ , snake_case_ ): raise ValueError(F"""`token_id` is supposed to be type `int`, but is {token_id} of type {type(snake_case_ )}""" ) snake_case__ : Tuple = self.trie.next_tokens(self.current_seq ) return token_id in next_tokens def __magic_name__ ( self : Union[str, Any] , snake_case_ : int ): '''simple docstring''' if not isinstance(snake_case_ , snake_case_ ): raise ValueError(F"""`token_id` is supposed to be type `int`, but is {token_id} of type {type(snake_case_ )}""" ) snake_case__ : str = False snake_case__ : List[str] = False snake_case__ : Optional[int] = False if self.does_advance(snake_case_ ): self.current_seq.append(snake_case_ ) snake_case__ : int = True else: snake_case__ : Optional[int] = True self.reset() snake_case__ : Tuple = self.trie.reached_leaf(self.current_seq ) snake_case__ : Optional[Any] = completed return stepped, completed, reset def __magic_name__ ( self : Optional[int] ): '''simple docstring''' snake_case__ : Dict = False snake_case__ : Dict = [] def __magic_name__ ( self : Any ): '''simple docstring''' if self.completed: # since this can be completed without reaching max height return 0 else: return self.seqlen - len(self.current_seq ) def __magic_name__ ( self : Dict , snake_case_ : Any=False ): '''simple docstring''' snake_case__ : int = DisjunctiveConstraint(self.token_ids ) if stateful: snake_case__ : Dict = self.seqlen snake_case__ : Optional[int] = self.current_seq snake_case__ : List[Any] = self.completed return new_constraint class a : """simple docstring""" def __init__( self : List[Any] , snake_case_ : List[Constraint] ): '''simple docstring''' snake_case__ : List[Any] = constraints # max # of steps required to fulfill a given constraint snake_case__ : Union[str, Any] = max([c.seqlen for c in constraints] ) snake_case__ : Tuple = len(snake_case_ ) snake_case__ : List[str] = False self.init_state() def __magic_name__ ( self : Any ): '''simple docstring''' snake_case__ : int = [] snake_case__ : List[Any] = None snake_case__ : str = [constraint.copy(stateful=snake_case_ ) for constraint in self.constraints] def __magic_name__ ( self : Optional[int] ): '''simple docstring''' snake_case__ : Tuple = 0 if self.inprogress_constraint: # extra points for having a constraint mid-fulfilled add += self.max_seqlen - self.inprogress_constraint.remaining() return (len(self.complete_constraints ) * self.max_seqlen) + add def __magic_name__ ( self : Dict ): '''simple docstring''' snake_case__ : Optional[int] = [] if self.inprogress_constraint is None: for constraint in self.pending_constraints: # "pending" == "unfulfilled yet" snake_case__ : Optional[Any] = constraint.advance() if isinstance(snake_case_ , snake_case_ ): token_list.append(snake_case_ ) elif isinstance(snake_case_ , snake_case_ ): token_list.extend(snake_case_ ) else: snake_case__ : Tuple = self.inprogress_constraint.advance() if isinstance(snake_case_ , snake_case_ ): token_list.append(snake_case_ ) elif isinstance(snake_case_ , snake_case_ ): token_list.extend(snake_case_ ) if len(snake_case_ ) == 0: return None else: return token_list def __magic_name__ ( self : Optional[Any] , snake_case_ : Optional[List[int]] ): '''simple docstring''' self.init_state() if token_ids is not None: for token in token_ids: # completes or steps **one** constraint snake_case__ , snake_case__ : Optional[int] = self.add(snake_case_ ) # the entire list of constraints are fulfilled if self.completed: break def __magic_name__ ( self : Optional[int] , snake_case_ : int ): '''simple docstring''' if not isinstance(snake_case_ , snake_case_ ): raise ValueError(F"""`token_id` should be an `int`, but is `{token_id}`.""" ) snake_case__ , snake_case__ : Any = False, False if self.completed: snake_case__ : Union[str, Any] = True snake_case__ : Union[str, Any] = False return complete, stepped if self.inprogress_constraint is not None: # In the middle of fulfilling a constraint. If the `token_id` *does* makes an incremental progress to current # job, simply update the state snake_case__ , snake_case__ , snake_case__ : Union[str, Any] = self.inprogress_constraint.update(snake_case_ ) if reset: # 1. If the next token breaks the progress, then we must restart. # e.g. constraint = "I love pies" and sequence so far is "I love" but `token_id` == "books". # But that doesn't mean we self.init_state(), since we only reset the state for this particular # constraint, not the full list of constraints. self.pending_constraints.append(self.inprogress_constraint.copy(stateful=snake_case_ ) ) snake_case__ : Dict = None if complete: # 2. If the next token completes the constraint, move it to completed list, set # inprogress to None. If there are no pending constraints either, then this full list of constraints # is complete. self.complete_constraints.append(self.inprogress_constraint ) snake_case__ : str = None if len(self.pending_constraints ) == 0: # we're done! snake_case__ : Dict = True else: # Not in the middle of fulfilling a constraint. So does this `token_id` helps us step towards any of our list # of constraints? for cidx, pending_constraint in enumerate(self.pending_constraints ): if pending_constraint.does_advance(snake_case_ ): snake_case__ , snake_case__ , snake_case__ : List[Any] = pending_constraint.update(snake_case_ ) if not stepped: raise Exception( '''`constraint.update(token_id)` is not yielding incremental progress, ''' '''even though `constraint.does_advance(token_id)` is true.''' ) if complete: self.complete_constraints.append(snake_case_ ) snake_case__ : List[Any] = None if not complete and stepped: snake_case__ : Any = pending_constraint if complete or stepped: # If we made any progress at all, then it's at least not a "pending constraint". snake_case__ : Optional[Any] = ( self.pending_constraints[:cidx] + self.pending_constraints[cidx + 1 :] ) if len(self.pending_constraints ) == 0 and self.inprogress_constraint is None: # If there's no longer any pending after this and no inprogress either, then we must be # complete. snake_case__ : int = True break # prevent accidentally stepping through multiple constraints with just one token. return complete, stepped def __magic_name__ ( self : List[str] , snake_case_ : str=True ): '''simple docstring''' snake_case__ : Optional[int] = ConstraintListState(self.constraints ) # we actually never though self.constraints objects # throughout this process. So it's at initialization state. if stateful: snake_case__ : Any = [ constraint.copy(stateful=snake_case_ ) for constraint in self.complete_constraints ] if self.inprogress_constraint is not None: snake_case__ : Union[str, Any] = self.inprogress_constraint.copy(stateful=snake_case_ ) snake_case__ : Optional[int] = [constraint.copy() for constraint in self.pending_constraints] return new_state
502
'''simple docstring''' from bisect import bisect from itertools import accumulate def _a ( __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Tuple , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Optional[Any] ): """simple docstring""" snake_case__ : Any = sorted(zip(__lowerCAmelCase , __lowerCAmelCase ) , key=lambda __lowerCAmelCase : x[0] / x[1] , reverse=__lowerCAmelCase ) snake_case__ , snake_case__ : Union[str, Any] = [i[0] for i in r], [i[1] for i in r] snake_case__ : Dict = list(accumulate(__lowerCAmelCase ) ) snake_case__ : Optional[int] = bisect(__lowerCAmelCase , __lowerCAmelCase ) return ( 0 if k == 0 else sum(vl[:k] ) + (w - acc[k - 1]) * (vl[k]) / (wt[k]) if k != n else sum(vl[:k] ) ) if __name__ == "__main__": import doctest doctest.testmod()
502
1
"""simple docstring""" import copy import tempfile import unittest from huggingface_hub import HfFolder, delete_repo from parameterized import parameterized from requests.exceptions import HTTPError from transformers import AutoConfig, GenerationConfig from transformers.testing_utils import TOKEN, USER, is_staging_test class SCREAMING_SNAKE_CASE ( unittest.TestCase ): """simple docstring""" @parameterized.expand([(None,), ('foo.json',)] ) def _lowerCAmelCase ( self : Tuple , _snake_case : Any ) -> Optional[Any]: '''simple docstring''' a__ = GenerationConfig( do_sample=_snake_case , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(_snake_case , config_name=_snake_case ) a__ = GenerationConfig.from_pretrained(_snake_case , config_name=_snake_case ) # Checks parameters that were specified self.assertEqual(loaded_config.do_sample , _snake_case ) self.assertEqual(loaded_config.temperature , 0.7 ) self.assertEqual(loaded_config.length_penalty , 1.0 ) self.assertEqual(loaded_config.bad_words_ids , [[1, 2, 3], [4, 5]] ) # Checks parameters that were not specified (defaults) self.assertEqual(loaded_config.top_k , 50 ) self.assertEqual(loaded_config.max_length , 20 ) self.assertEqual(loaded_config.max_time , _snake_case ) def _lowerCAmelCase ( self : Dict ) -> Dict: '''simple docstring''' a__ = AutoConfig.from_pretrained('gpt2' ) a__ = GenerationConfig.from_model_config(_snake_case ) a__ = GenerationConfig() # The generation config has loaded a few non-default parameters from the model config self.assertNotEqual(_snake_case , _snake_case ) # One of those parameters is eos_token_id -- check if it matches self.assertNotEqual(generation_config_from_model.eos_token_id , default_generation_config.eos_token_id ) self.assertEqual(generation_config_from_model.eos_token_id , model_config.eos_token_id ) def _lowerCAmelCase ( self : Optional[int] ) -> int: '''simple docstring''' a__ = GenerationConfig() a__ = { 'max_new_tokens': 1024, 'foo': 'bar', } a__ = copy.deepcopy(_snake_case ) a__ = generation_config.update(**_snake_case ) # update_kwargs was not modified (no side effects) self.assertEqual(_snake_case , _snake_case ) # update_kwargs was used to update the config on valid attributes self.assertEqual(generation_config.max_new_tokens , 1024 ) # `.update()` returns a dictionary of unused kwargs self.assertEqual(_snake_case , {'foo': 'bar'} ) def _lowerCAmelCase ( self : Dict ) -> Optional[Any]: '''simple docstring''' a__ = GenerationConfig() a__ = 'bar' with tempfile.TemporaryDirectory('test-generation-config' ) as tmp_dir: generation_config.save_pretrained(_snake_case ) a__ = GenerationConfig.from_pretrained(_snake_case ) # update_kwargs was used to update the config on valid attributes self.assertEqual(new_config.foo , 'bar' ) a__ = GenerationConfig.from_model_config(_snake_case ) assert not hasattr(_snake_case , 'foo' ) # no new kwargs should be initialized if from config def _lowerCAmelCase ( self : Optional[Any] ) -> str: '''simple docstring''' a__ = GenerationConfig() self.assertEqual(default_config.temperature , 1.0 ) self.assertEqual(default_config.do_sample , _snake_case ) self.assertEqual(default_config.num_beams , 1 ) a__ = GenerationConfig( do_sample=_snake_case , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) self.assertEqual(config.temperature , 0.7 ) self.assertEqual(config.do_sample , _snake_case ) self.assertEqual(config.num_beams , 1 ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(_snake_case ) a__ = GenerationConfig.from_pretrained(_snake_case , temperature=1.0 ) self.assertEqual(loaded_config.temperature , 1.0 ) self.assertEqual(loaded_config.do_sample , _snake_case ) self.assertEqual(loaded_config.num_beams , 1 ) # default value @is_staging_test class SCREAMING_SNAKE_CASE ( unittest.TestCase ): """simple docstring""" @classmethod def _lowerCAmelCase ( cls : Dict ) -> str: '''simple docstring''' a__ = TOKEN HfFolder.save_token(_snake_case ) @classmethod def _lowerCAmelCase ( cls : Optional[int] ) -> str: '''simple docstring''' try: delete_repo(token=cls._token , repo_id='test-generation-config' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='valid_org/test-generation-config-org' ) except HTTPError: pass def _lowerCAmelCase ( self : Tuple ) -> Dict: '''simple docstring''' a__ = GenerationConfig( do_sample=_snake_case , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub('test-generation-config' , use_auth_token=self._token ) a__ = GenerationConfig.from_pretrained(F'''{USER}/test-generation-config''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(_snake_case , getattr(_snake_case , _snake_case ) ) # Reset repo delete_repo(token=self._token , repo_id='test-generation-config' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( _snake_case , repo_id='test-generation-config' , push_to_hub=_snake_case , use_auth_token=self._token ) a__ = GenerationConfig.from_pretrained(F'''{USER}/test-generation-config''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(_snake_case , getattr(_snake_case , _snake_case ) ) def _lowerCAmelCase ( self : int ) -> Dict: '''simple docstring''' a__ = GenerationConfig( do_sample=_snake_case , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub('valid_org/test-generation-config-org' , use_auth_token=self._token ) a__ = GenerationConfig.from_pretrained('valid_org/test-generation-config-org' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(_snake_case , getattr(_snake_case , _snake_case ) ) # Reset repo delete_repo(token=self._token , repo_id='valid_org/test-generation-config-org' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( _snake_case , repo_id='valid_org/test-generation-config-org' , push_to_hub=_snake_case , use_auth_token=self._token ) a__ = GenerationConfig.from_pretrained('valid_org/test-generation-config-org' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(_snake_case , getattr(_snake_case , _snake_case ) )
232
"""simple docstring""" def _lowerCamelCase ( UpperCAmelCase__ = 60_08_51_47_51_43 ) -> int: '''simple docstring''' try: a__ = int(UpperCAmelCase__ ) except (TypeError, ValueError): raise TypeError('Parameter n must be int or castable to int.' ) if n <= 0: raise ValueError('Parameter n must be greater than or equal to one.' ) a__ = 2 a__ = 0 if n == 2: return 2 while n > 2: while n % i != 0: i += 1 a__ = i while n % i == 0: a__ = n // i i += 1 return int(UpperCAmelCase__ ) if __name__ == "__main__": print(F'''{solution() = }''')
232
1
import logging import os from .state import PartialState class __A ( logging.LoggerAdapter ): @staticmethod def _snake_case ( UpperCAmelCase_ ): lowerCamelCase =PartialState() return not main_process_only or (main_process_only and state.is_main_process) def _snake_case ( self , UpperCAmelCase_ , UpperCAmelCase_ , *UpperCAmelCase_ , **UpperCAmelCase_ ): if PartialState._shared_state == {}: raise RuntimeError( """You must initialize the accelerate state by calling either `PartialState()` or `Accelerator()` before using the logging utility.""" ) lowerCamelCase =kwargs.pop("""main_process_only""" , UpperCAmelCase_ ) lowerCamelCase =kwargs.pop("""in_order""" , UpperCAmelCase_ ) if self.isEnabledFor(UpperCAmelCase_ ): if self._should_log(UpperCAmelCase_ ): lowerCamelCase , lowerCamelCase =self.process(UpperCAmelCase_ , UpperCAmelCase_ ) self.logger.log(UpperCAmelCase_ , UpperCAmelCase_ , *UpperCAmelCase_ , **UpperCAmelCase_ ) elif in_order: lowerCamelCase =PartialState() for i in range(state.num_processes ): if i == state.process_index: lowerCamelCase , lowerCamelCase =self.process(UpperCAmelCase_ , UpperCAmelCase_ ) self.logger.log(UpperCAmelCase_ , UpperCAmelCase_ , *UpperCAmelCase_ , **UpperCAmelCase_ ) state.wait_for_everyone() def _lowercase ( _UpperCAmelCase , _UpperCAmelCase = None ) -> Union[str, Any]: if log_level is None: lowerCamelCase =os.environ.get("""ACCELERATE_LOG_LEVEL""" , _UpperCAmelCase ) lowerCamelCase =logging.getLogger(_UpperCAmelCase ) if log_level is not None: logger.setLevel(log_level.upper() ) logger.root.setLevel(log_level.upper() ) return MultiProcessAdapter(_UpperCAmelCase , {} )
721
def _lowercase ( _UpperCAmelCase , _UpperCAmelCase ) -> List[str]: lowerCamelCase =[0 for i in range(r + 1 )] # nc0 = 1 lowerCamelCase =1 for i in range(1 , n + 1 ): # to compute current row from previous row. lowerCamelCase =min(_UpperCAmelCase , _UpperCAmelCase ) while j > 0: c[j] += c[j - 1] j -= 1 return c[r] print(binomial_coefficient(n=10, r=5))
269
0
import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def _lowerCAmelCase ( __magic_name__ :List[str] ): monkeypatch.setattr('''datasets.utils.deprecation_utils._emitted_deprecation_warnings''' , set() ) @pytest.fixture def _lowerCAmelCase ( __magic_name__ :Optional[int] ): class snake_case__ : '''simple docstring''' def __init__( self : List[Any] , lowerCAmelCase_ : Optional[int] ) -> int: UpperCAmelCase_ = metric_id class snake_case__ : '''simple docstring''' __A = [MetricMock(__snake_case ) for metric_id in ['''accuracy''', '''mse''', '''precision''', '''codeparrot/apps_metric''']] def UpperCamelCase ( self : Any ) -> str: return self._metrics monkeypatch.setattr('''datasets.inspect.huggingface_hub''' , HfhMock() ) @pytest.mark.parametrize( '''func, args''' , [(load_metric, ('''metrics/mse''',)), (list_metrics, ()), (inspect_metric, ('''metrics/mse''', '''tmp_path'''))] ) def _lowerCAmelCase ( __magic_name__ :List[str] , __magic_name__ :int , __magic_name__ :Union[str, Any] , __magic_name__ :List[Any] , __magic_name__ :str ): if "tmp_path" in args: UpperCAmelCase_ = tuple(arg if arg != '''tmp_path''' else tmp_path for arg in args ) with pytest.warns(__magic_name__ , match='''https://huggingface.co/docs/evaluate''' ): func(*__magic_name__ )
121
_lowerCamelCase : dict[tuple[int, int, int], int] = {} def _lowerCAmelCase ( __magic_name__ :int , __magic_name__ :int , __magic_name__ :int ): # if we are absent twice, or late 3 consecutive days, # no further prize strings are possible if late == 3 or absent == 2: return 0 # if we have no days left, and have not failed any other rules, # we have a prize string if days == 0: return 1 # No easy solution, so now we need to do the recursive calculation # First, check if the combination is already in the cache, and # if yes, return the stored value from there since we already # know the number of possible prize strings from this point on UpperCAmelCase_ = (days, absent, late) if key in cache: return cache[key] # now we calculate the three possible ways that can unfold from # this point on, depending on our attendance today # 1) if we are late (but not absent), the "absent" counter stays as # it is, but the "late" counter increases by one UpperCAmelCase_ = _calculate(days - 1 , __magic_name__ , late + 1 ) # 2) if we are absent, the "absent" counter increases by 1, and the # "late" counter resets to 0 UpperCAmelCase_ = _calculate(days - 1 , absent + 1 , 0 ) # 3) if we are on time, this resets the "late" counter and keeps the # absent counter UpperCAmelCase_ = _calculate(days - 1 , __magic_name__ , 0 ) UpperCAmelCase_ = state_late + state_absent + state_ontime UpperCAmelCase_ = prizestrings return prizestrings def _lowerCAmelCase ( __magic_name__ :int = 3_0 ): return _calculate(__magic_name__ , absent=0 , late=0 ) if __name__ == "__main__": print(solution())
121
1
import numpy as np import skfuzzy as fuzz if __name__ == "__main__": # Create universe of discourse in Python using linspace () __lowerCAmelCase = np.linspace(start=0, stop=75, num=75, endpoint=True, retstep=False) # Create two fuzzy sets by defining any membership function # (trapmf(), gbellmf(), gaussmf(), etc). __lowerCAmelCase = [0, 25, 50] __lowerCAmelCase = [25, 50, 75] __lowerCAmelCase = fuzz.membership.trimf(X, abca) __lowerCAmelCase = fuzz.membership.trimf(X, abca) # Compute the different operations using inbuilt functions. __lowerCAmelCase = np.ones(75) __lowerCAmelCase = np.zeros((75,)) # 1. Union = max(µA(x), µB(x)) __lowerCAmelCase = fuzz.fuzzy_or(X, young, X, middle_aged)[1] # 2. Intersection = min(µA(x), µB(x)) __lowerCAmelCase = fuzz.fuzzy_and(X, young, X, middle_aged)[1] # 3. Complement (A) = (1- min(µA(x)) __lowerCAmelCase = fuzz.fuzzy_not(young) # 4. Difference (A/B) = min(µA(x),(1- µB(x))) __lowerCAmelCase = fuzz.fuzzy_and(X, young, X, fuzz.fuzzy_not(middle_aged)[1])[1] # 5. Algebraic Sum = [µA(x) + µB(x) – (µA(x) * µB(x))] __lowerCAmelCase = young + middle_aged - (young * middle_aged) # 6. Algebraic Product = (µA(x) * µB(x)) __lowerCAmelCase = young * middle_aged # 7. Bounded Sum = min[1,(µA(x), µB(x))] __lowerCAmelCase = fuzz.fuzzy_and(X, one, X, young + middle_aged)[1] # 8. Bounded difference = min[0,(µA(x), µB(x))] __lowerCAmelCase = fuzz.fuzzy_or(X, zero, X, young - middle_aged)[1] # max-min composition # max-product composition # Plot each set A, set B and each operation result using plot() and subplot(). from matplotlib import pyplot as plt plt.figure() plt.subplot(4, 3, 1) plt.plot(X, young) plt.title('''Young''') plt.grid(True) plt.subplot(4, 3, 2) plt.plot(X, middle_aged) plt.title('''Middle aged''') plt.grid(True) plt.subplot(4, 3, 3) plt.plot(X, union) plt.title('''union''') plt.grid(True) plt.subplot(4, 3, 4) plt.plot(X, intersection) plt.title('''intersection''') plt.grid(True) plt.subplot(4, 3, 5) plt.plot(X, complement_a) plt.title('''complement_a''') plt.grid(True) plt.subplot(4, 3, 6) plt.plot(X, difference) plt.title('''difference a/b''') plt.grid(True) plt.subplot(4, 3, 7) plt.plot(X, alg_sum) plt.title('''alg_sum''') plt.grid(True) plt.subplot(4, 3, 8) plt.plot(X, alg_product) plt.title('''alg_product''') plt.grid(True) plt.subplot(4, 3, 9) plt.plot(X, bdd_sum) plt.title('''bdd_sum''') plt.grid(True) plt.subplot(4, 3, 10) plt.plot(X, bdd_difference) plt.title('''bdd_difference''') plt.grid(True) plt.subplots_adjust(hspace=0.5) plt.show()
335
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto.configuration_auto import CONFIG_MAPPING __lowerCAmelCase = logging.get_logger(__name__) class __a ( __UpperCamelCase ): __lowercase : Union[str, Any] = 'upernet' def __init__( self , lowerCAmelCase__=None , lowerCAmelCase__=512 , lowerCAmelCase__=0.0_2 , lowerCAmelCase__=[1, 2, 3, 6] , lowerCAmelCase__=True , lowerCAmelCase__=0.4 , lowerCAmelCase__=384 , lowerCAmelCase__=256 , lowerCAmelCase__=1 , lowerCAmelCase__=False , lowerCAmelCase__=255 , **lowerCAmelCase__ , ) -> Optional[Any]: '''simple docstring''' super().__init__(**lowerCAmelCase__ ) if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.' ) lowercase__: str = CONFIG_MAPPING['resnet'](out_features=['stage1', 'stage2', 'stage3', 'stage4'] ) elif isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): lowercase__: str = backbone_config.get('model_type' ) lowercase__: Union[str, Any] = CONFIG_MAPPING[backbone_model_type] lowercase__: Dict = config_class.from_dict(lowerCAmelCase__ ) lowercase__: List[Any] = backbone_config lowercase__: Union[str, Any] = hidden_size lowercase__: Tuple = initializer_range lowercase__: Optional[int] = pool_scales lowercase__: Union[str, Any] = use_auxiliary_head lowercase__: Any = auxiliary_loss_weight lowercase__: Tuple = auxiliary_in_channels lowercase__: Optional[Any] = auxiliary_channels lowercase__: List[Any] = auxiliary_num_convs lowercase__: List[str] = auxiliary_concat_input lowercase__: Any = loss_ignore_index def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple: '''simple docstring''' lowercase__: Tuple = copy.deepcopy(self.__dict__ ) lowercase__: List[Any] = self.backbone_config.to_dict() lowercase__: str = self.__class__.model_type return output
335
1
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConfig, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaForCTC, WavaVecaForPreTraining, WavaVecaProcessor, logging, ) from transformers.models.wavaveca.modeling_wavaveca import WavaVecaForSequenceClassification logging.set_verbosity_info() lowerCamelCase__ : Optional[int] = logging.get_logger(__name__) lowerCamelCase__ : Any = { """post_extract_proj""": """feature_projection.projection""", """encoder.pos_conv.0""": """encoder.pos_conv_embed.conv""", """self_attn.k_proj""": """encoder.layers.*.attention.k_proj""", """self_attn.v_proj""": """encoder.layers.*.attention.v_proj""", """self_attn.q_proj""": """encoder.layers.*.attention.q_proj""", """self_attn.out_proj""": """encoder.layers.*.attention.out_proj""", """self_attn_layer_norm""": """encoder.layers.*.layer_norm""", """fc1""": """encoder.layers.*.feed_forward.intermediate_dense""", """fc2""": """encoder.layers.*.feed_forward.output_dense""", """final_layer_norm""": """encoder.layers.*.final_layer_norm""", """encoder.layer_norm""": """encoder.layer_norm""", """adapter_layer""": """encoder.layers.*.adapter_layer""", """w2v_model.layer_norm""": """feature_projection.layer_norm""", """quantizer.weight_proj""": """quantizer.weight_proj""", """quantizer.vars""": """quantizer.codevectors""", """project_q""": """project_q""", """final_proj""": """project_hid""", """w2v_encoder.proj""": """lm_head""", """mask_emb""": """masked_spec_embed""", """pooling_layer.linear""": """projector""", """pooling_layer.projection""": """classifier""", } lowerCamelCase__ : Union[str, Any] = [ """lm_head""", """quantizer.weight_proj""", """quantizer.codevectors""", """project_q""", """project_hid""", """projector""", """classifier""", ] def SCREAMING_SNAKE_CASE ( __lowerCAmelCase ) -> List[str]: snake_case__ = {} with open(__lowerCAmelCase , '''r''' ) as file: for line_number, line in enumerate(__lowerCAmelCase ): snake_case__ = line.strip() if line: snake_case__ = line.split() snake_case__ = line_number snake_case__ = words[0] snake_case__ = value return result def SCREAMING_SNAKE_CASE ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Any: for attribute in key.split('''.''' ): snake_case__ = getattr(__lowerCAmelCase , __lowerCAmelCase ) snake_case__ = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(__lowerCAmelCase ): snake_case__ = PARAM_MAPPING[full_name.split('''.''' )[-1]] snake_case__ = '''param''' if weight_type is not None and weight_type != "param": snake_case__ = getattr(__lowerCAmelCase , __lowerCAmelCase ).shape elif weight_type is not None and weight_type == "param": snake_case__ = hf_pointer for attribute in hf_param_name.split('''.''' ): snake_case__ = getattr(__lowerCAmelCase , __lowerCAmelCase ) snake_case__ = shape_pointer.shape # let's reduce dimension snake_case__ = value[0] else: snake_case__ = hf_pointer.shape if hf_shape != value.shape: raise ValueError( F"""Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be""" F""" {value.shape} for {full_name}""" ) if weight_type == "weight": snake_case__ = value elif weight_type == "weight_g": snake_case__ = value elif weight_type == "weight_v": snake_case__ = value elif weight_type == "bias": snake_case__ = value elif weight_type == "param": for attribute in hf_param_name.split('''.''' ): snake_case__ = getattr(__lowerCAmelCase , __lowerCAmelCase ) snake_case__ = value else: snake_case__ = value logger.info(F"""{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.""" ) def SCREAMING_SNAKE_CASE ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> str: snake_case__ = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(__lowerCAmelCase ): snake_case__ = PARAM_MAPPING[full_name.split('''.''' )[-1]] snake_case__ = '''param''' if weight_type is not None and weight_type != "param": snake_case__ = '''.'''.join([key, weight_type] ) elif weight_type is not None and weight_type == "param": snake_case__ = '''.'''.join([key, hf_param_name] ) else: snake_case__ = key snake_case__ = value if '''lm_head''' in full_key else value[0] lowerCamelCase__ : Optional[int] = { """W_a""": """linear_1.weight""", """W_b""": """linear_2.weight""", """b_a""": """linear_1.bias""", """b_b""": """linear_2.bias""", """ln_W""": """norm.weight""", """ln_b""": """norm.bias""", } def SCREAMING_SNAKE_CASE ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase=None , __lowerCAmelCase=None ) -> Tuple: snake_case__ = False for key, mapped_key in MAPPING.items(): snake_case__ = '''wav2vec2.''' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0]: snake_case__ = True if "*" in mapped_key: snake_case__ = name.split(__lowerCAmelCase )[0].split('''.''' )[-2] snake_case__ = mapped_key.replace('''*''' , __lowerCAmelCase ) if "weight_g" in name: snake_case__ = '''weight_g''' elif "weight_v" in name: snake_case__ = '''weight_v''' elif "bias" in name: snake_case__ = '''bias''' elif "weight" in name: # TODO: don't match quantizer.weight_proj snake_case__ = '''weight''' else: snake_case__ = None if hf_dict is not None: rename_dict(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) else: set_recursively(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) return is_used return is_used def SCREAMING_SNAKE_CASE ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> str: snake_case__ = [] snake_case__ = fairseq_model.state_dict() snake_case__ = hf_model.wavaveca.feature_extractor for name, value in fairseq_dict.items(): snake_case__ = False if "conv_layers" in name: load_conv_layer( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , hf_model.config.feat_extract_norm == '''group''' , ) snake_case__ = True else: snake_case__ = load_wavaveca_layer(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) if not is_used: unused_weights.append(__lowerCAmelCase ) logger.warning(F"""Unused weights: {unused_weights}""" ) def SCREAMING_SNAKE_CASE ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Dict: snake_case__ = full_name.split('''conv_layers.''' )[-1] snake_case__ = name.split('''.''' ) snake_case__ = int(items[0] ) snake_case__ = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) snake_case__ = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) snake_case__ = 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: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.""" ) snake_case__ = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.""" ) snake_case__ = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(__lowerCAmelCase ) @torch.no_grad() def SCREAMING_SNAKE_CASE ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase=None , __lowerCAmelCase=None , __lowerCAmelCase=True , __lowerCAmelCase=False ) -> List[str]: if config_path is not None: snake_case__ = WavaVecaConfig.from_pretrained(__lowerCAmelCase ) else: snake_case__ = WavaVecaConfig() if is_seq_class: snake_case__ = read_txt_into_dict(__lowerCAmelCase ) snake_case__ = idalabel snake_case__ = WavaVecaForSequenceClassification(__lowerCAmelCase ) snake_case__ = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6000 , padding_value=0 , do_normalize=__lowerCAmelCase , return_attention_mask=__lowerCAmelCase , ) feature_extractor.save_pretrained(__lowerCAmelCase ) elif is_finetuned: if dict_path: snake_case__ = Dictionary.load(__lowerCAmelCase ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq snake_case__ = target_dict.pad_index snake_case__ = target_dict.bos_index snake_case__ = target_dict.eos_index snake_case__ = len(target_dict.symbols ) snake_case__ = os.path.join(__lowerCAmelCase , '''vocab.json''' ) if not os.path.isdir(__lowerCAmelCase ): logger.error('''--pytorch_dump_folder_path ({}) should be a directory'''.format(__lowerCAmelCase ) ) return os.makedirs(__lowerCAmelCase , exist_ok=__lowerCAmelCase ) snake_case__ = target_dict.indices # fairseq has the <pad> and <s> switched snake_case__ = 0 snake_case__ = 1 with open(__lowerCAmelCase , '''w''' , encoding='''utf-8''' ) as vocab_handle: json.dump(__lowerCAmelCase , __lowerCAmelCase ) snake_case__ = WavaVecaCTCTokenizer( __lowerCAmelCase , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token='''|''' , do_lower_case=__lowerCAmelCase , ) snake_case__ = True if config.feat_extract_norm == '''layer''' else False snake_case__ = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6000 , padding_value=0 , do_normalize=__lowerCAmelCase , return_attention_mask=__lowerCAmelCase , ) snake_case__ = WavaVecaProcessor(feature_extractor=__lowerCAmelCase , tokenizer=__lowerCAmelCase ) processor.save_pretrained(__lowerCAmelCase ) snake_case__ = WavaVecaForCTC(__lowerCAmelCase ) else: snake_case__ = WavaVecaForPreTraining(__lowerCAmelCase ) if is_finetuned or is_seq_class: snake_case__ = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'''data''': '''/'''.join(dict_path.split('''/''' )[:-1] )} ) else: snake_case__ = argparse.Namespace(task='''audio_pretraining''' ) snake_case__ = fairseq.tasks.setup_task(__lowerCAmelCase ) snake_case__ = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] , task=__lowerCAmelCase ) snake_case__ = model[0].eval() recursively_load_weights(__lowerCAmelCase , __lowerCAmelCase , not is_finetuned ) hf_wavavec.save_pretrained(__lowerCAmelCase ) if __name__ == "__main__": lowerCamelCase__ : str = argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to fairseq checkpoint""") parser.add_argument("""--dict_path""", default=None, type=str, help="""Path to dict of fine-tuned model""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") parser.add_argument( """--not_finetuned""", action="""store_true""", help="""Whether the model to convert is a fine-tuned model or not""" ) parser.add_argument( """--is_seq_class""", action="""store_true""", help="""Whether the model to convert is a fine-tuned sequence classification model or not""", ) lowerCamelCase__ : Tuple = parser.parse_args() lowerCamelCase__ : str = not args.not_finetuned and not args.is_seq_class convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, is_finetuned, args.is_seq_class, )
33
'''simple docstring''' from math import factorial def _a ( __lowerCAmelCase : int , __lowerCAmelCase : int , __lowerCAmelCase : float ): """simple docstring""" if successes > trials: raise ValueError('''successes must be lower or equal to trials''' ) if trials < 0 or successes < 0: raise ValueError('''the function is defined for non-negative integers''' ) if not isinstance(__lowerCAmelCase , __lowerCAmelCase ) or not isinstance(__lowerCAmelCase , __lowerCAmelCase ): raise ValueError('''the function is defined for non-negative integers''' ) if not 0 < prob < 1: raise ValueError('''prob has to be in range of 1 - 0''' ) snake_case__ : Dict = (prob**successes) * ((1 - prob) ** (trials - successes)) # Calculate the binomial coefficient: n! / k!(n-k)! snake_case__ : str = float(factorial(__lowerCAmelCase ) ) coefficient /= factorial(__lowerCAmelCase ) * factorial(trials - successes ) return probability * coefficient if __name__ == "__main__": from doctest import testmod testmod() print("""Probability of 2 successes out of 4 trails""") print("""with probability of 0.75 is:""", end=""" """) print(binomial_distribution(2, 4, 0.75))
347
0
"""simple docstring""" from __future__ import annotations from collections import Counter from random import random class A__ : '''simple docstring''' def __init__( self: Optional[Any]) -> Optional[int]: """simple docstring""" __lowerCAmelCase : Optional[Any] = {} def _SCREAMING_SNAKE_CASE ( self: Optional[Any] , _SCREAMING_SNAKE_CASE: str) -> None: """simple docstring""" __lowerCAmelCase : Union[str, Any] = {} def _SCREAMING_SNAKE_CASE ( self: List[Any] , _SCREAMING_SNAKE_CASE: str , _SCREAMING_SNAKE_CASE: str , _SCREAMING_SNAKE_CASE: float) -> None: """simple docstring""" if nodea not in self.connections: self.add_node(_SCREAMING_SNAKE_CASE) if nodea not in self.connections: self.add_node(_SCREAMING_SNAKE_CASE) __lowerCAmelCase : Dict = probability def _SCREAMING_SNAKE_CASE ( self: Tuple) -> list[str]: """simple docstring""" return list(self.connections) def _SCREAMING_SNAKE_CASE ( self: List[str] , _SCREAMING_SNAKE_CASE: str) -> str: """simple docstring""" __lowerCAmelCase : List[str] = 0 __lowerCAmelCase : str = random() for dest in self.connections[node]: current_probability += self.connections[node][dest] if current_probability > random_value: return dest return "" def _lowercase ( __snake_case ,__snake_case ,__snake_case ) -> dict[str, int]: __lowerCAmelCase : List[Any] = MarkovChainGraphUndirectedUnweighted() for nodea, nodea, probability in transitions: graph.add_transition_probability(__snake_case ,__snake_case ,__snake_case ) __lowerCAmelCase : List[Any] = Counter(graph.get_nodes() ) __lowerCAmelCase : Tuple = start for _ in range(__snake_case ): __lowerCAmelCase : Union[str, Any] = graph.transition(__snake_case ) visited[node] += 1 return visited if __name__ == "__main__": import doctest doctest.testmod()
615
"""simple docstring""" def _lowercase ( __snake_case ,__snake_case ) -> list: __lowerCAmelCase : List[str] = len(__snake_case ) __lowerCAmelCase : Dict = [] for i in range(len(__snake_case ) - pat_len + 1 ): __lowerCAmelCase : List[Any] = True for j in range(__snake_case ): if s[i + j] != pattern[j]: __lowerCAmelCase : Union[str, Any] = False break if match_found: position.append(__snake_case ) return position if __name__ == "__main__": assert naive_pattern_search('ABCDEFG', 'DE') == [3] print(naive_pattern_search('ABAAABCDBBABCDDEBCABC', 'ABC'))
615
1
from argparse import ArgumentParser, Namespace from ..utils import logging from . import BaseTransformersCLICommand def __lowerCAmelCase ( UpperCamelCase ) -> Dict: return ConvertCommand( args.model_type , args.tf_checkpoint , args.pytorch_dump_output , args.config , args.finetuning_task_name ) lowerCAmelCase_ = """ transformers can only be used from the commandline to convert TensorFlow models in PyTorch, In that case, it requires TensorFlow to be installed. Please see https://www.tensorflow.org/install/ for installation instructions. """ class _lowerCAmelCase ( _lowercase ): @staticmethod def __magic_name__( __UpperCAmelCase ): lowerCAmelCase__ : int = parser.add_parser( '''convert''' , help='''CLI tool to run convert model from original author checkpoints to Transformers PyTorch checkpoints.''' , ) train_parser.add_argument('''--model_type''' , type=__UpperCAmelCase , required=__UpperCAmelCase , help='''Model\'s type.''' ) train_parser.add_argument( '''--tf_checkpoint''' , type=__UpperCAmelCase , required=__UpperCAmelCase , help='''TensorFlow checkpoint path or folder.''' ) train_parser.add_argument( '''--pytorch_dump_output''' , type=__UpperCAmelCase , required=__UpperCAmelCase , help='''Path to the PyTorch saved model output.''' ) train_parser.add_argument('''--config''' , type=__UpperCAmelCase , default='''''' , help='''Configuration file path or folder.''' ) train_parser.add_argument( '''--finetuning_task_name''' , type=__UpperCAmelCase , default=__UpperCAmelCase , help='''Optional fine-tuning task name if the TF model was a finetuned model.''' , ) train_parser.set_defaults(func=__UpperCAmelCase ) def __init__( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , *__UpperCAmelCase , ): lowerCAmelCase__ : str = logging.get_logger('''transformers-cli/converting''' ) self._logger.info(f"""Loading model {model_type}""" ) lowerCAmelCase__ : Any = model_type lowerCAmelCase__ : Dict = tf_checkpoint lowerCAmelCase__ : Optional[Any] = pytorch_dump_output lowerCAmelCase__ : Tuple = config lowerCAmelCase__ : List[str] = finetuning_task_name def __magic_name__( self ): if self._model_type == "albert": try: from ..models.albert.convert_albert_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(__UpperCAmelCase ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "bert": try: from ..models.bert.convert_bert_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(__UpperCAmelCase ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "funnel": try: from ..models.funnel.convert_funnel_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(__UpperCAmelCase ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "t5": try: from ..models.ta.convert_ta_original_tf_checkpoint_to_pytorch import convert_tf_checkpoint_to_pytorch except ImportError: raise ImportError(__UpperCAmelCase ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "gpt": from ..models.openai.convert_openai_original_tf_checkpoint_to_pytorch import ( convert_openai_checkpoint_to_pytorch, ) convert_openai_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "transfo_xl": try: from ..models.transfo_xl.convert_transfo_xl_original_tf_checkpoint_to_pytorch import ( convert_transfo_xl_checkpoint_to_pytorch, ) except ImportError: raise ImportError(__UpperCAmelCase ) if "ckpt" in self._tf_checkpoint.lower(): lowerCAmelCase__ : Dict = self._tf_checkpoint lowerCAmelCase__ : Any = '''''' else: lowerCAmelCase__ : List[Any] = self._tf_checkpoint lowerCAmelCase__ : Union[str, Any] = '''''' convert_transfo_xl_checkpoint_to_pytorch( __UpperCAmelCase , self._config , self._pytorch_dump_output , __UpperCAmelCase ) elif self._model_type == "gpt2": try: from ..models.gpta.convert_gpta_original_tf_checkpoint_to_pytorch import ( convert_gpta_checkpoint_to_pytorch, ) except ImportError: raise ImportError(__UpperCAmelCase ) convert_gpta_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "xlnet": try: from ..models.xlnet.convert_xlnet_original_tf_checkpoint_to_pytorch import ( convert_xlnet_checkpoint_to_pytorch, ) except ImportError: raise ImportError(__UpperCAmelCase ) convert_xlnet_checkpoint_to_pytorch( self._tf_checkpoint , self._config , self._pytorch_dump_output , self._finetuning_task_name ) elif self._model_type == "xlm": from ..models.xlm.convert_xlm_original_pytorch_checkpoint_to_pytorch import ( convert_xlm_checkpoint_to_pytorch, ) convert_xlm_checkpoint_to_pytorch(self._tf_checkpoint , self._pytorch_dump_output ) elif self._model_type == "lxmert": from ..models.lxmert.convert_lxmert_original_tf_checkpoint_to_pytorch import ( convert_lxmert_checkpoint_to_pytorch, ) convert_lxmert_checkpoint_to_pytorch(self._tf_checkpoint , self._pytorch_dump_output ) elif self._model_type == "rembert": from ..models.rembert.convert_rembert_tf_checkpoint_to_pytorch import ( convert_rembert_tf_checkpoint_to_pytorch, ) convert_rembert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) else: raise ValueError( '''--model_type should be selected in the list [bert, gpt, gpt2, t5, transfo_xl, xlnet, xlm, lxmert]''' )
678
import unittest from transformers import ( MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING, TextGenerationPipeline, logging, pipeline, ) from transformers.testing_utils import ( CaptureLogger, is_pipeline_test, require_accelerate, require_tf, require_torch, require_torch_gpu, require_torch_or_tf, ) from .test_pipelines_common import ANY @is_pipeline_test @require_torch_or_tf class _lowerCAmelCase ( unittest.TestCase ): A__ = MODEL_FOR_CAUSAL_LM_MAPPING A__ = TF_MODEL_FOR_CAUSAL_LM_MAPPING @require_torch def __magic_name__( self ): lowerCAmelCase__ : Tuple = pipeline(task='''text-generation''' , model='''sshleifer/tiny-ctrl''' , framework='''pt''' ) # Using `do_sample=False` to force deterministic output lowerCAmelCase__ : Optional[int] = text_generator('''This is a test''' , do_sample=__UpperCAmelCase ) self.assertEqual( __UpperCAmelCase , [ { '''generated_text''': ( '''This is a test ☃ ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy oscope.''' ''' oscope. FiliFili@@''' ) } ] , ) lowerCAmelCase__ : List[str] = text_generator(['''This is a test''', '''This is a second test'''] ) self.assertEqual( __UpperCAmelCase , [ [ { '''generated_text''': ( '''This is a test ☃ ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy oscope.''' ''' oscope. FiliFili@@''' ) } ], [ { '''generated_text''': ( '''This is a second test ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy''' ''' oscope. oscope. FiliFili@@''' ) } ], ] , ) lowerCAmelCase__ : str = text_generator('''This is a test''' , do_sample=__UpperCAmelCase , num_return_sequences=2 , return_tensors=__UpperCAmelCase ) self.assertEqual( __UpperCAmelCase , [ {'''generated_token_ids''': ANY(__UpperCAmelCase )}, {'''generated_token_ids''': ANY(__UpperCAmelCase )}, ] , ) lowerCAmelCase__ : List[Any] = text_generator.model.config.eos_token_id lowerCAmelCase__ : List[Any] = '''<pad>''' lowerCAmelCase__ : List[Any] = text_generator( ['''This is a test''', '''This is a second test'''] , do_sample=__UpperCAmelCase , num_return_sequences=2 , batch_size=2 , return_tensors=__UpperCAmelCase , ) self.assertEqual( __UpperCAmelCase , [ [ {'''generated_token_ids''': ANY(__UpperCAmelCase )}, {'''generated_token_ids''': ANY(__UpperCAmelCase )}, ], [ {'''generated_token_ids''': ANY(__UpperCAmelCase )}, {'''generated_token_ids''': ANY(__UpperCAmelCase )}, ], ] , ) @require_tf def __magic_name__( self ): lowerCAmelCase__ : int = pipeline(task='''text-generation''' , model='''sshleifer/tiny-ctrl''' , framework='''tf''' ) # Using `do_sample=False` to force deterministic output lowerCAmelCase__ : List[Any] = text_generator('''This is a test''' , do_sample=__UpperCAmelCase ) self.assertEqual( __UpperCAmelCase , [ { '''generated_text''': ( '''This is a test FeyFeyFey(Croatis.), s.), Cannes Cannes Cannes 閲閲Cannes Cannes Cannes 攵''' ''' please,''' ) } ] , ) lowerCAmelCase__ : List[str] = text_generator(['''This is a test''', '''This is a second test'''] , do_sample=__UpperCAmelCase ) self.assertEqual( __UpperCAmelCase , [ [ { '''generated_text''': ( '''This is a test FeyFeyFey(Croatis.), s.), Cannes Cannes Cannes 閲閲Cannes Cannes Cannes 攵''' ''' please,''' ) } ], [ { '''generated_text''': ( '''This is a second test Chieftain Chieftain prefecture prefecture prefecture Cannes Cannes''' ''' Cannes 閲閲Cannes Cannes Cannes 攵 please,''' ) } ], ] , ) def __magic_name__( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ : Dict = TextGenerationPipeline(model=__UpperCAmelCase , tokenizer=__UpperCAmelCase ) return text_generator, ["This is a test", "Another test"] def __magic_name__( self ): lowerCAmelCase__ : Any = '''Hello I believe in''' lowerCAmelCase__ : List[Any] = pipeline('''text-generation''' , model='''hf-internal-testing/tiny-random-gpt2''' ) lowerCAmelCase__ : Optional[int] = text_generator(__UpperCAmelCase ) self.assertEqual( __UpperCAmelCase , [{'''generated_text''': '''Hello I believe in fe fe fe fe fe fe fe fe fe fe fe fe'''}] , ) lowerCAmelCase__ : List[str] = text_generator(__UpperCAmelCase , stop_sequence=''' fe''' ) self.assertEqual(__UpperCAmelCase , [{'''generated_text''': '''Hello I believe in fe'''}] ) def __magic_name__( self , __UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ : str = text_generator.model lowerCAmelCase__ : Optional[int] = text_generator.tokenizer lowerCAmelCase__ : Tuple = text_generator('''This is a test''' ) self.assertEqual(__UpperCAmelCase , [{'''generated_text''': ANY(__UpperCAmelCase )}] ) self.assertTrue(outputs[0]['''generated_text'''].startswith('''This is a test''' ) ) lowerCAmelCase__ : Optional[int] = text_generator('''This is a test''' , return_full_text=__UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , [{'''generated_text''': ANY(__UpperCAmelCase )}] ) self.assertNotIn('''This is a test''' , outputs[0]['''generated_text'''] ) lowerCAmelCase__ : Dict = pipeline(task='''text-generation''' , model=__UpperCAmelCase , tokenizer=__UpperCAmelCase , return_full_text=__UpperCAmelCase ) lowerCAmelCase__ : Dict = text_generator('''This is a test''' ) self.assertEqual(__UpperCAmelCase , [{'''generated_text''': ANY(__UpperCAmelCase )}] ) self.assertNotIn('''This is a test''' , outputs[0]['''generated_text'''] ) lowerCAmelCase__ : List[str] = text_generator('''This is a test''' , return_full_text=__UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , [{'''generated_text''': ANY(__UpperCAmelCase )}] ) self.assertTrue(outputs[0]['''generated_text'''].startswith('''This is a test''' ) ) lowerCAmelCase__ : Optional[int] = text_generator(['''This is great !''', '''Something else'''] , num_return_sequences=2 , do_sample=__UpperCAmelCase ) self.assertEqual( __UpperCAmelCase , [ [{'''generated_text''': ANY(__UpperCAmelCase )}, {'''generated_text''': ANY(__UpperCAmelCase )}], [{'''generated_text''': ANY(__UpperCAmelCase )}, {'''generated_text''': ANY(__UpperCAmelCase )}], ] , ) if text_generator.tokenizer.pad_token is not None: lowerCAmelCase__ : List[str] = text_generator( ['''This is great !''', '''Something else'''] , num_return_sequences=2 , batch_size=2 , do_sample=__UpperCAmelCase ) self.assertEqual( __UpperCAmelCase , [ [{'''generated_text''': ANY(__UpperCAmelCase )}, {'''generated_text''': ANY(__UpperCAmelCase )}], [{'''generated_text''': ANY(__UpperCAmelCase )}, {'''generated_text''': ANY(__UpperCAmelCase )}], ] , ) with self.assertRaises(__UpperCAmelCase ): lowerCAmelCase__ : Any = text_generator('''test''' , return_full_text=__UpperCAmelCase , return_text=__UpperCAmelCase ) with self.assertRaises(__UpperCAmelCase ): lowerCAmelCase__ : Optional[int] = text_generator('''test''' , return_full_text=__UpperCAmelCase , return_tensors=__UpperCAmelCase ) with self.assertRaises(__UpperCAmelCase ): lowerCAmelCase__ : str = text_generator('''test''' , return_text=__UpperCAmelCase , return_tensors=__UpperCAmelCase ) # Empty prompt is slighly special # it requires BOS token to exist. # Special case for Pegasus which will always append EOS so will # work even without BOS. if ( text_generator.tokenizer.bos_token_id is not None or "Pegasus" in tokenizer.__class__.__name__ or "Git" in model.__class__.__name__ ): lowerCAmelCase__ : str = text_generator('''''' ) self.assertEqual(__UpperCAmelCase , [{'''generated_text''': ANY(__UpperCAmelCase )}] ) else: with self.assertRaises((ValueError, AssertionError) ): lowerCAmelCase__ : List[str] = text_generator('''''' ) if text_generator.framework == "tf": # TF generation does not support max_new_tokens, and it's impossible # to control long generation with only max_length without # fancy calculation, dismissing tests for now. return # We don't care about infinite range models. # They already work. # Skip this test for XGLM, since it uses sinusoidal positional embeddings which are resized on-the-fly. lowerCAmelCase__ : Optional[Any] = ['''RwkvForCausalLM''', '''XGLMForCausalLM''', '''GPTNeoXForCausalLM'''] if ( tokenizer.model_max_length < 1_0000 and text_generator.model.__class__.__name__ not in EXTRA_MODELS_CAN_HANDLE_LONG_INPUTS ): # Handling of large generations with self.assertRaises((RuntimeError, IndexError, ValueError, AssertionError) ): text_generator('''This is a test''' * 500 , max_new_tokens=20 ) lowerCAmelCase__ : Optional[Any] = text_generator('''This is a test''' * 500 , handle_long_generation='''hole''' , max_new_tokens=20 ) # Hole strategy cannot work with self.assertRaises(__UpperCAmelCase ): text_generator( '''This is a test''' * 500 , handle_long_generation='''hole''' , max_new_tokens=tokenizer.model_max_length + 10 , ) @require_torch @require_accelerate @require_torch_gpu def __magic_name__( self ): import torch # Classic `model_kwargs` lowerCAmelCase__ : List[str] = pipeline( model='''hf-internal-testing/tiny-random-bloom''' , model_kwargs={'''device_map''': '''auto''', '''torch_dtype''': torch.bfloataa} , ) self.assertEqual(pipe.model.device , torch.device(0 ) ) self.assertEqual(pipe.model.lm_head.weight.dtype , torch.bfloataa ) lowerCAmelCase__ : Any = pipe('''This is a test''' ) self.assertEqual( __UpperCAmelCase , [ { '''generated_text''': ( '''This is a test test test test test test test test test test test test test test test test''' ''' test''' ) } ] , ) # Upgraded those two to real pipeline arguments (they just get sent for the model as they're unlikely to mean anything else.) lowerCAmelCase__ : Dict = pipeline(model='''hf-internal-testing/tiny-random-bloom''' , device_map='''auto''' , torch_dtype=torch.bfloataa ) self.assertEqual(pipe.model.device , torch.device(0 ) ) self.assertEqual(pipe.model.lm_head.weight.dtype , torch.bfloataa ) lowerCAmelCase__ : Union[str, Any] = pipe('''This is a test''' ) self.assertEqual( __UpperCAmelCase , [ { '''generated_text''': ( '''This is a test test test test test test test test test test test test test test test test''' ''' test''' ) } ] , ) # torch_dtype will be automatically set to float32 if not provided - check: https://github.com/huggingface/transformers/pull/20602 lowerCAmelCase__ : str = pipeline(model='''hf-internal-testing/tiny-random-bloom''' , device_map='''auto''' ) self.assertEqual(pipe.model.device , torch.device(0 ) ) self.assertEqual(pipe.model.lm_head.weight.dtype , torch.floataa ) lowerCAmelCase__ : Any = pipe('''This is a test''' ) self.assertEqual( __UpperCAmelCase , [ { '''generated_text''': ( '''This is a test test test test test test test test test test test test test test test test''' ''' test''' ) } ] , ) @require_torch @require_torch_gpu def __magic_name__( self ): import torch lowerCAmelCase__ : List[str] = pipeline(model='''hf-internal-testing/tiny-random-bloom''' , device=0 , torch_dtype=torch.floataa ) pipe('''This is a test''' ) @require_torch @require_accelerate @require_torch_gpu def __magic_name__( self ): import torch lowerCAmelCase__ : Any = pipeline(model='''hf-internal-testing/tiny-random-bloom''' , device_map='''auto''' , torch_dtype=torch.floataa ) pipe('''This is a test''' , do_sample=__UpperCAmelCase , top_p=0.5 ) def __magic_name__( self ): lowerCAmelCase__ : int = '''Hello world''' lowerCAmelCase__ : Union[str, Any] = pipeline('''text-generation''' , model='''hf-internal-testing/tiny-random-gpt2''' ) if text_generator.model.framework == "tf": lowerCAmelCase__ : List[Any] = logging.get_logger('''transformers.generation.tf_utils''' ) else: lowerCAmelCase__ : Dict = logging.get_logger('''transformers.generation.utils''' ) lowerCAmelCase__ : Optional[Any] = '''Both `max_new_tokens`''' # The beggining of the message to be checked in this test # Both are set by the user -> log warning with CaptureLogger(__UpperCAmelCase ) as cl: lowerCAmelCase__ : List[str] = text_generator(__UpperCAmelCase , max_length=10 , max_new_tokens=1 ) self.assertIn(__UpperCAmelCase , cl.out ) # The user only sets one -> no warning with CaptureLogger(__UpperCAmelCase ) as cl: lowerCAmelCase__ : Any = text_generator(__UpperCAmelCase , max_new_tokens=1 ) self.assertNotIn(__UpperCAmelCase , cl.out ) with CaptureLogger(__UpperCAmelCase ) as cl: lowerCAmelCase__ : Union[str, Any] = text_generator(__UpperCAmelCase , max_length=10 ) self.assertNotIn(__UpperCAmelCase , cl.out )
678
1
'''simple docstring''' import argparse import torch from transformers import ( WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaForAudioFrameClassification, WavaVecaForSequenceClassification, WavaVecaForXVector, logging, ) logging.set_verbosity_info() snake_case_ = logging.get_logger(__name__) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : str ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = WavaVecaForSequenceClassification.from_pretrained(SCREAMING_SNAKE_CASE_ , config=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Any = downstream_dict["projector.weight"] SCREAMING_SNAKE_CASE_ : List[str] = downstream_dict["projector.bias"] SCREAMING_SNAKE_CASE_ : List[str] = downstream_dict["model.post_net.linear.weight"] SCREAMING_SNAKE_CASE_ : List[Any] = downstream_dict["model.post_net.linear.bias"] return model def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : List[Any] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = WavaVecaForAudioFrameClassification.from_pretrained(SCREAMING_SNAKE_CASE_ , config=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : str = downstream_dict["model.linear.weight"] SCREAMING_SNAKE_CASE_ : List[Any] = downstream_dict["model.linear.bias"] return model def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = WavaVecaForXVector.from_pretrained(SCREAMING_SNAKE_CASE_ , config=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Dict = downstream_dict["connector.weight"] SCREAMING_SNAKE_CASE_ : int = downstream_dict["connector.bias"] for i, kernel_size in enumerate(hf_config.tdnn_kernel ): SCREAMING_SNAKE_CASE_ : List[Any] = downstream_dict[ F"model.framelevel_feature_extractor.module.{i}.kernel.weight" ] SCREAMING_SNAKE_CASE_ : int = downstream_dict[F"model.framelevel_feature_extractor.module.{i}.kernel.bias"] SCREAMING_SNAKE_CASE_ : List[Any] = downstream_dict["model.utterancelevel_feature_extractor.linear1.weight"] SCREAMING_SNAKE_CASE_ : List[str] = downstream_dict["model.utterancelevel_feature_extractor.linear1.bias"] SCREAMING_SNAKE_CASE_ : Optional[Any] = downstream_dict["model.utterancelevel_feature_extractor.linear2.weight"] SCREAMING_SNAKE_CASE_ : str = downstream_dict["model.utterancelevel_feature_extractor.linear2.bias"] SCREAMING_SNAKE_CASE_ : Dict = downstream_dict["objective.W"] return model @torch.no_grad() def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Dict ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.load(SCREAMING_SNAKE_CASE_ , map_location="cpu" ) SCREAMING_SNAKE_CASE_ : Optional[Any] = checkpoint["Downstream"] SCREAMING_SNAKE_CASE_ : Optional[Any] = WavaVecaConfig.from_pretrained(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : List[str] = WavaVecaFeatureExtractor.from_pretrained( SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , do_normalize=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Optional[int] = hf_config.architectures[0] if arch.endswith("ForSequenceClassification" ): SCREAMING_SNAKE_CASE_ : int = convert_classification(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) elif arch.endswith("ForAudioFrameClassification" ): SCREAMING_SNAKE_CASE_ : List[Any] = convert_diarization(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) elif arch.endswith("ForXVector" ): SCREAMING_SNAKE_CASE_ : Any = convert_xvector(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else: raise NotImplementedError(F"S3PRL weights conversion is not supported for {arch}" ) if hf_config.use_weighted_layer_sum: SCREAMING_SNAKE_CASE_ : Tuple = checkpoint["Featurizer"]["weights"] hf_feature_extractor.save_pretrained(SCREAMING_SNAKE_CASE_ ) hf_model.save_pretrained(SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": snake_case_ = argparse.ArgumentParser() parser.add_argument( '--base_model_name', default=None, type=str, help='Name of the huggingface pretrained base model.' ) parser.add_argument('--config_path', default=None, type=str, help='Path to the huggingface classifier config.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to the s3prl checkpoint.') parser.add_argument('--model_dump_path', default=None, type=str, help='Path to the final converted model.') snake_case_ = parser.parse_args() convert_saprl_checkpoint(args.base_model_name, args.config_path, args.checkpoint_path, args.model_dump_path)
68
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging snake_case_ = logging.get_logger(__name__) snake_case_ = { 'facebook/xmod-base': 'https://huggingface.co/facebook/xmod-base/resolve/main/config.json', 'facebook/xmod-large-prenorm': 'https://huggingface.co/facebook/xmod-large-prenorm/resolve/main/config.json', 'facebook/xmod-base-13-125k': 'https://huggingface.co/facebook/xmod-base-13-125k/resolve/main/config.json', 'facebook/xmod-base-30-125k': 'https://huggingface.co/facebook/xmod-base-30-125k/resolve/main/config.json', 'facebook/xmod-base-30-195k': 'https://huggingface.co/facebook/xmod-base-30-195k/resolve/main/config.json', 'facebook/xmod-base-60-125k': 'https://huggingface.co/facebook/xmod-base-60-125k/resolve/main/config.json', 'facebook/xmod-base-60-265k': 'https://huggingface.co/facebook/xmod-base-60-265k/resolve/main/config.json', 'facebook/xmod-base-75-125k': 'https://huggingface.co/facebook/xmod-base-75-125k/resolve/main/config.json', 'facebook/xmod-base-75-269k': 'https://huggingface.co/facebook/xmod-base-75-269k/resolve/main/config.json', } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = "xmod" def __init__( self , lowercase__=3_0522 , lowercase__=768 , lowercase__=12 , lowercase__=12 , lowercase__=3072 , lowercase__="gelu" , lowercase__=0.1 , lowercase__=0.1 , lowercase__=512 , lowercase__=2 , lowercase__=0.02 , lowercase__=1e-12 , lowercase__=1 , lowercase__=0 , lowercase__=2 , lowercase__="absolute" , lowercase__=True , lowercase__=None , lowercase__=False , lowercase__=2 , lowercase__=False , lowercase__=True , lowercase__=True , lowercase__=("en_XX",) , lowercase__=None , **lowercase__ , ): """simple docstring""" super().__init__(pad_token_id=lowercase__ , bos_token_id=lowercase__ , eos_token_id=lowercase__ , **lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = vocab_size SCREAMING_SNAKE_CASE_ : Optional[Any] = hidden_size SCREAMING_SNAKE_CASE_ : Tuple = num_hidden_layers SCREAMING_SNAKE_CASE_ : Optional[int] = num_attention_heads SCREAMING_SNAKE_CASE_ : List[str] = hidden_act SCREAMING_SNAKE_CASE_ : Optional[int] = intermediate_size SCREAMING_SNAKE_CASE_ : Tuple = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : int = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE_ : Dict = type_vocab_size SCREAMING_SNAKE_CASE_ : str = initializer_range SCREAMING_SNAKE_CASE_ : List[str] = layer_norm_eps SCREAMING_SNAKE_CASE_ : Tuple = position_embedding_type SCREAMING_SNAKE_CASE_ : str = use_cache SCREAMING_SNAKE_CASE_ : Optional[int] = classifier_dropout SCREAMING_SNAKE_CASE_ : int = pre_norm SCREAMING_SNAKE_CASE_ : Optional[int] = adapter_reduction_factor SCREAMING_SNAKE_CASE_ : List[str] = adapter_layer_norm SCREAMING_SNAKE_CASE_ : List[str] = adapter_reuse_layer_norm SCREAMING_SNAKE_CASE_ : int = ln_before_adapter SCREAMING_SNAKE_CASE_ : List[Any] = list(lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = default_language class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): @property def __lowerCamelCase ( self ): """simple docstring""" if self.task == "multiple-choice": SCREAMING_SNAKE_CASE_ : Tuple = {0: "batch", 1: "choice", 2: "sequence"} else: SCREAMING_SNAKE_CASE_ : Optional[int] = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
68
1
import json import os import shutil import tempfile import unittest from transformers import BatchEncoding, CanineTokenizer from transformers.testing_utils import require_tokenizers, require_torch from transformers.tokenization_utils import AddedToken from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin class __A ( UpperCamelCase__ , unittest.TestCase ): UpperCamelCase = CanineTokenizer UpperCamelCase = False def A__ ( self :Tuple ): '''simple docstring''' super().setUp() __magic_name__ : Optional[int] =CanineTokenizer() tokenizer.save_pretrained(self.tmpdirname ) @cached_property def A__ ( self :Optional[Any] ): '''simple docstring''' return CanineTokenizer.from_pretrained("""google/canine-s""" ) def A__ ( self :Optional[int] , **__snake_case :Any ): '''simple docstring''' __magic_name__ : Any =self.tokenizer_class.from_pretrained(self.tmpdirname , **__snake_case ) __magic_name__ : Optional[int] =10_24 return tokenizer @require_torch def A__ ( self :int ): '''simple docstring''' __magic_name__ : str =self.canine_tokenizer __magic_name__ : Any =["""Life is like a box of chocolates.""", """You never know what you're gonna get."""] # fmt: off __magic_name__ : Optional[int] =[5_73_44, 76, 1_05, 1_02, 1_01, 32, 1_05, 1_15, 32, 1_08, 1_05, 1_07, 1_01, 32, 97, 32, 98, 1_11, 1_20, 32, 1_11, 1_02, 32, 99, 1_04, 1_11, 99, 1_11, 1_08, 97, 1_16, 1_01, 1_15, 46, 5_73_45, 0, 0, 0, 0] # fmt: on __magic_name__ : Dict =tokenizer(__snake_case , padding=__snake_case , return_tensors="""pt""" ) self.assertIsInstance(__snake_case , __snake_case ) __magic_name__ : Optional[int] =list(batch.input_ids.numpy()[0] ) self.assertListEqual(__snake_case , __snake_case ) self.assertEqual((2, 39) , batch.input_ids.shape ) self.assertEqual((2, 39) , batch.attention_mask.shape ) @require_torch def A__ ( self :Union[str, Any] ): '''simple docstring''' __magic_name__ : Union[str, Any] =self.canine_tokenizer __magic_name__ : Optional[Any] =["""Once there was a man.""", """He wrote a test in HuggingFace Tranformers."""] __magic_name__ : int =tokenizer(__snake_case , padding=__snake_case , return_tensors="""pt""" ) # check if input_ids, attention_mask and token_type_ids are returned self.assertIn("""input_ids""" , __snake_case ) self.assertIn("""attention_mask""" , __snake_case ) self.assertIn("""token_type_ids""" , __snake_case ) @require_torch def A__ ( self :int ): '''simple docstring''' __magic_name__ : Dict =self.canine_tokenizer __magic_name__ : List[Any] =[ """What's the weater?""", """It's about 25 degrees.""", ] __magic_name__ : Any =tokenizer( text_target=__snake_case , max_length=32 , padding="""max_length""" , truncation=__snake_case , return_tensors="""pt""" ) self.assertEqual(32 , targets["""input_ids"""].shape[1] ) def A__ ( self :Any ): '''simple docstring''' __magic_name__ : Optional[Any] =self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f"{tokenizer.__class__.__name__}" ): self.assertNotEqual(tokenizer.model_max_length , 42 ) # Now let's start the test __magic_name__ : Tuple =self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f"{tokenizer.__class__.__name__}" ): # Isolate this from the other tests because we save additional tokens/etc __magic_name__ : Any =tempfile.mkdtemp() __magic_name__ : Union[str, Any] =""" He is very happy, UNwant\u00E9d,running""" __magic_name__ : List[str] =tokenizer.encode(__snake_case , add_special_tokens=__snake_case ) tokenizer.save_pretrained(__snake_case ) __magic_name__ : Optional[Any] =tokenizer.__class__.from_pretrained(__snake_case ) __magic_name__ : str =after_tokenizer.encode(__snake_case , add_special_tokens=__snake_case ) self.assertListEqual(__snake_case , __snake_case ) shutil.rmtree(__snake_case ) __magic_name__ : int =self.get_tokenizers(model_max_length=42 ) for tokenizer in tokenizers: with self.subTest(f"{tokenizer.__class__.__name__}" ): # Isolate this from the other tests because we save additional tokens/etc __magic_name__ : str =tempfile.mkdtemp() __magic_name__ : Optional[int] =""" He is very happy, UNwant\u00E9d,running""" __magic_name__ : Optional[Any] =tokenizer.additional_special_tokens # We can add a new special token for Canine as follows: __magic_name__ : Optional[int] =chr(0xE_0_0_7 ) additional_special_tokens.append(__snake_case ) tokenizer.add_special_tokens({"""additional_special_tokens""": additional_special_tokens} ) __magic_name__ : List[Any] =tokenizer.encode(__snake_case , add_special_tokens=__snake_case ) tokenizer.save_pretrained(__snake_case ) __magic_name__ : Optional[Any] =tokenizer.__class__.from_pretrained(__snake_case ) __magic_name__ : List[Any] =after_tokenizer.encode(__snake_case , add_special_tokens=__snake_case ) self.assertListEqual(__snake_case , __snake_case ) self.assertIn(__snake_case , after_tokenizer.additional_special_tokens ) self.assertEqual(after_tokenizer.model_max_length , 42 ) __magic_name__ : Optional[int] =tokenizer.__class__.from_pretrained(__snake_case , model_max_length=43 ) self.assertEqual(tokenizer.model_max_length , 43 ) shutil.rmtree(__snake_case ) def A__ ( self :Optional[Any] ): '''simple docstring''' __magic_name__ : Optional[int] =self.get_tokenizers(do_lower_case=__snake_case ) for tokenizer in tokenizers: with self.subTest(f"{tokenizer.__class__.__name__}" ): __magic_name__ , __magic_name__ : List[str] =self.get_clean_sequence(__snake_case ) # a special token for Canine can be defined as follows: __magic_name__ : Tuple =0xE_0_0_5 __magic_name__ : Tuple =chr(__snake_case ) tokenizer.add_special_tokens({"""cls_token""": special_token} ) __magic_name__ : Optional[int] =tokenizer.encode(__snake_case , add_special_tokens=__snake_case ) self.assertEqual(len(__snake_case ) , 1 ) __magic_name__ : Any =tokenizer.decode(ids + encoded_special_token , clean_up_tokenization_spaces=__snake_case ) __magic_name__ : Union[str, Any] =tokenizer.encode(__snake_case , add_special_tokens=__snake_case ) __magic_name__ : Optional[int] =tokenizer.encode(__snake_case , add_special_tokens=__snake_case ) __magic_name__ : Union[str, Any] =tokenizer.encode(__snake_case , add_special_tokens=__snake_case ) self.assertEqual(__snake_case , input_encoded + special_token_id ) __magic_name__ : List[str] =tokenizer.decode(__snake_case , skip_special_tokens=__snake_case ) self.assertTrue(special_token not in decoded ) def A__ ( self :Dict ): '''simple docstring''' __magic_name__ : Dict =self.get_tokenizers(do_lower_case=__snake_case ) for tokenizer in tokenizers: with self.subTest(f"{tokenizer.__class__.__name__}" ): __magic_name__ : Tuple =chr(0xE_0_0_5 ) __magic_name__ : Union[str, Any] =chr(0xE_0_0_6 ) # `add_tokens` method stores special tokens only in `tokenizer.unique_no_split_tokens`. (in tokenization_utils.py) tokenizer.add_tokens([SPECIAL_TOKEN_1] , special_tokens=__snake_case ) # `add_special_tokens` method stores special tokens in `tokenizer.additional_special_tokens`, # which also occur in `tokenizer.all_special_tokens`. (in tokenization_utils_base.py) tokenizer.add_special_tokens({"""additional_special_tokens""": [SPECIAL_TOKEN_2]} ) __magic_name__ : List[Any] =tokenizer.tokenize(__snake_case ) __magic_name__ : Union[str, Any] =tokenizer.tokenize(__snake_case ) self.assertEqual(len(__snake_case ) , 1 ) self.assertEqual(len(__snake_case ) , 1 ) self.assertEqual(token_a[0] , __snake_case ) self.assertEqual(token_a[0] , __snake_case ) @require_tokenizers def A__ ( self :int ): '''simple docstring''' __magic_name__ : Dict =self.get_tokenizers(do_lower_case=__snake_case ) for tokenizer in tokenizers: with self.subTest(f"{tokenizer.__class__.__name__}" ): # a special token for Canine can be defined as follows: __magic_name__ : Dict =0xE_0_0_6 __magic_name__ : Tuple =chr(__snake_case ) __magic_name__ : str =AddedToken(__snake_case , lstrip=__snake_case ) tokenizer.add_special_tokens({"""additional_special_tokens""": [new_token]} ) with tempfile.TemporaryDirectory() as tmp_dir_name: tokenizer.save_pretrained(__snake_case ) tokenizer.from_pretrained(__snake_case ) def A__ ( self :int ): '''simple docstring''' __magic_name__ : str =[] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(__snake_case ) with open(os.path.join(__snake_case , """special_tokens_map.json""" ) , encoding="""utf-8""" ) as json_file: __magic_name__ : List[Any] =json.load(__snake_case ) with open(os.path.join(__snake_case , """tokenizer_config.json""" ) , encoding="""utf-8""" ) as json_file: __magic_name__ : str =json.load(__snake_case ) # a special token for Canine can be defined as follows: __magic_name__ : int =0xE_0_0_6 __magic_name__ : List[str] =chr(__snake_case ) __magic_name__ : Union[str, Any] =[new_token_a] __magic_name__ : List[Any] =[new_token_a] with open(os.path.join(__snake_case , """special_tokens_map.json""" ) , """w""" , encoding="""utf-8""" ) as outfile: json.dump(__snake_case , __snake_case ) with open(os.path.join(__snake_case , """tokenizer_config.json""" ) , """w""" , encoding="""utf-8""" ) as outfile: json.dump(__snake_case , __snake_case ) # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and # "special_tokens_map.json" files __magic_name__ : Union[str, Any] =tokenizer_class.from_pretrained(__snake_case , extra_ids=0 ) self.assertIn(__snake_case , tokenizer_without_change_in_init.additional_special_tokens ) # self.assertIn("an_additional_special_token",tokenizer_without_change_in_init.get_vocab()) # ByT5Tokenization no vocab self.assertEqual( [new_token_a] , tokenizer_without_change_in_init.convert_ids_to_tokens( tokenizer_without_change_in_init.convert_tokens_to_ids([new_token_a] ) ) , ) __magic_name__ : str =0xE_0_0_7 __magic_name__ : Optional[int] =chr(__snake_case ) # Now we test that we can change the value of additional_special_tokens in the from_pretrained __magic_name__ : List[Any] =[AddedToken(__snake_case , lstrip=__snake_case )] __magic_name__ : str =tokenizer_class.from_pretrained( __snake_case , additional_special_tokens=__snake_case , extra_ids=0 ) self.assertIn(__snake_case , tokenizer.additional_special_tokens ) # self.assertIn(new_token_2,tokenizer.get_vocab()) # ByT5Tokenization no vocab self.assertEqual( [new_token_a] , tokenizer.convert_ids_to_tokens(tokenizer.convert_tokens_to_ids([new_token_a] ) ) ) @require_tokenizers def A__ ( self :str ): '''simple docstring''' __magic_name__ : List[str] =self.get_tokenizers(do_lower_case=__snake_case ) for tokenizer in tokenizers: with self.subTest(f"{tokenizer.__class__.__name__}" ): __magic_name__ : Dict ="""hello world""" if self.space_between_special_tokens: __magic_name__ : Dict ="""[CLS] hello world [SEP]""" else: __magic_name__ : int =input __magic_name__ : Any =tokenizer.encode(__snake_case , add_special_tokens=__snake_case ) __magic_name__ : List[Any] =tokenizer.decode(__snake_case , spaces_between_special_tokens=self.space_between_special_tokens ) self.assertIn(__snake_case , [output, output.lower()] ) def A__ ( self :List[str] ): '''simple docstring''' __magic_name__ : str =self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f"{tokenizer.__class__.__name__}" ): __magic_name__ : str =[ """bos_token""", """eos_token""", """unk_token""", """sep_token""", """pad_token""", """cls_token""", """mask_token""", ] __magic_name__ : Union[str, Any] ="""a""" __magic_name__ : int =ord(__snake_case ) for attr in attributes_list: setattr(__snake_case , attr + """_id""" , __snake_case ) self.assertEqual(getattr(__snake_case , __snake_case ) , __snake_case ) self.assertEqual(getattr(__snake_case , attr + """_id""" ) , __snake_case ) setattr(__snake_case , attr + """_id""" , __snake_case ) self.assertEqual(getattr(__snake_case , __snake_case ) , __snake_case ) self.assertEqual(getattr(__snake_case , attr + """_id""" ) , __snake_case ) setattr(__snake_case , """additional_special_tokens_ids""" , [] ) self.assertListEqual(getattr(__snake_case , """additional_special_tokens""" ) , [] ) self.assertListEqual(getattr(__snake_case , """additional_special_tokens_ids""" ) , [] ) __magic_name__ : Optional[int] =0xE_0_0_6 __magic_name__ : Any =chr(__snake_case ) setattr(__snake_case , """additional_special_tokens_ids""" , [additional_special_token_id] ) self.assertListEqual(getattr(__snake_case , """additional_special_tokens""" ) , [additional_special_token] ) self.assertListEqual(getattr(__snake_case , """additional_special_tokens_ids""" ) , [additional_special_token_id] ) def A__ ( self :int ): '''simple docstring''' pass def A__ ( self :str ): '''simple docstring''' pass def A__ ( self :str ): '''simple docstring''' pass def A__ ( self :Tuple ): '''simple docstring''' pass def A__ ( self :Tuple ): '''simple docstring''' pass def A__ ( self :Any ): '''simple docstring''' pass def A__ ( self :Optional[int] ): '''simple docstring''' pass def A__ ( self :int ): '''simple docstring''' pass
21
import collections import gzip import os import urllib import numpy from tensorflow.python.framework import dtypes, random_seed from tensorflow.python.platform import gfile from tensorflow.python.util.deprecation import deprecated _snake_case = collections.namedtuple("""_Datasets""", ["""train""", """validation""", """test"""]) # CVDF mirror of http://yann.lecun.com/exdb/mnist/ _snake_case = """https://storage.googleapis.com/cvdf-datasets/mnist/""" def _A ( __magic_name__ ): lowercase__ = numpy.dtype(numpy.uintaa ).newbyteorder(">" ) return numpy.frombuffer(bytestream.read(4 ) , dtype=__magic_name__ )[0] @deprecated(__magic_name__ , "Please use tf.data to implement this functionality." ) def _A ( __magic_name__ ): print("Extracting" , f.name ) with gzip.GzipFile(fileobj=__magic_name__ ) as bytestream: lowercase__ = _readaa(__magic_name__ ) if magic != 2051: raise ValueError( "Invalid magic number %d in MNIST image file: %s" % (magic, f.name) ) lowercase__ = _readaa(__magic_name__ ) lowercase__ = _readaa(__magic_name__ ) lowercase__ = _readaa(__magic_name__ ) lowercase__ = bytestream.read(rows * cols * num_images ) lowercase__ = numpy.frombuffer(__magic_name__ , dtype=numpy.uinta ) lowercase__ = data.reshape(__magic_name__ , __magic_name__ , __magic_name__ , 1 ) return data @deprecated(__magic_name__ , "Please use tf.one_hot on tensors." ) def _A ( __magic_name__ , __magic_name__ ): lowercase__ = labels_dense.shape[0] lowercase__ = numpy.arange(__magic_name__ ) * num_classes lowercase__ = numpy.zeros((num_labels, num_classes) ) lowercase__ = 1 return labels_one_hot @deprecated(__magic_name__ , "Please use tf.data to implement this functionality." ) def _A ( __magic_name__ , __magic_name__=False , __magic_name__=10 ): print("Extracting" , f.name ) with gzip.GzipFile(fileobj=__magic_name__ ) as bytestream: lowercase__ = _readaa(__magic_name__ ) if magic != 2049: raise ValueError( "Invalid magic number %d in MNIST label file: %s" % (magic, f.name) ) lowercase__ = _readaa(__magic_name__ ) lowercase__ = bytestream.read(__magic_name__ ) lowercase__ = numpy.frombuffer(__magic_name__ , dtype=numpy.uinta ) if one_hot: return _dense_to_one_hot(__magic_name__ , __magic_name__ ) return labels class lowerCAmelCase : @deprecated( _lowercase , "Please use alternatives such as official/mnist/_DataSet.py" " from tensorflow/models." , ) def __init__( self :List[str] , _lowercase :Optional[Any] , _lowercase :Union[str, Any] , _lowercase :Tuple=False , _lowercase :str=False , _lowercase :Dict=dtypes.floataa , _lowercase :Optional[Any]=True , _lowercase :Any=None , ): '''simple docstring''' lowercase__ , lowercase__ = random_seed.get_seed(_lowercase ) # If op level seed is not set, use whatever graph level seed is returned numpy.random.seed(seeda if seed is None else seeda ) lowercase__ = dtypes.as_dtype(_lowercase ).base_dtype if dtype not in (dtypes.uinta, dtypes.floataa): raise TypeError("Invalid image dtype %r, expected uint8 or float32" % dtype ) if fake_data: lowercase__ = 1_00_00 lowercase__ = one_hot else: assert ( images.shape[0] == labels.shape[0] ), f'''images.shape: {images.shape} labels.shape: {labels.shape}''' lowercase__ = images.shape[0] # Convert shape from [num examples, rows, columns, depth] # to [num examples, rows*columns] (assuming depth == 1) if reshape: assert images.shape[3] == 1 lowercase__ = images.reshape( images.shape[0] , images.shape[1] * images.shape[2] ) if dtype == dtypes.floataa: # Convert from [0, 255] -> [0.0, 1.0]. lowercase__ = images.astype(numpy.floataa ) lowercase__ = numpy.multiply(_lowercase , 1.0 / 255.0 ) lowercase__ = images lowercase__ = labels lowercase__ = 0 lowercase__ = 0 @property def UpperCAmelCase ( self :Tuple ): '''simple docstring''' return self._images @property def UpperCAmelCase ( self :Union[str, Any] ): '''simple docstring''' return self._labels @property def UpperCAmelCase ( self :Dict ): '''simple docstring''' return self._num_examples @property def UpperCAmelCase ( self :Tuple ): '''simple docstring''' return self._epochs_completed def UpperCAmelCase ( self :str , _lowercase :Union[str, Any] , _lowercase :Any=False , _lowercase :Union[str, Any]=True ): '''simple docstring''' if fake_data: lowercase__ = [1] * 7_84 lowercase__ = [1] + [0] * 9 if self.one_hot else 0 return ( [fake_image for _ in range(_lowercase )], [fake_label for _ in range(_lowercase )], ) lowercase__ = self._index_in_epoch # Shuffle for the first epoch if self._epochs_completed == 0 and start == 0 and shuffle: lowercase__ = numpy.arange(self._num_examples ) numpy.random.shuffle(_lowercase ) lowercase__ = self.images[perma] lowercase__ = self.labels[perma] # Go to the next epoch if start + batch_size > self._num_examples: # Finished epoch self._epochs_completed += 1 # Get the rest examples in this epoch lowercase__ = self._num_examples - start lowercase__ = self._images[start : self._num_examples] lowercase__ = self._labels[start : self._num_examples] # Shuffle the data if shuffle: lowercase__ = numpy.arange(self._num_examples ) numpy.random.shuffle(_lowercase ) lowercase__ = self.images[perm] lowercase__ = self.labels[perm] # Start next epoch lowercase__ = 0 lowercase__ = batch_size - rest_num_examples lowercase__ = self._index_in_epoch lowercase__ = self._images[start:end] lowercase__ = self._labels[start:end] return ( numpy.concatenate((images_rest_part, images_new_part) , axis=0 ), numpy.concatenate((labels_rest_part, labels_new_part) , axis=0 ), ) else: self._index_in_epoch += batch_size lowercase__ = self._index_in_epoch return self._images[start:end], self._labels[start:end] @deprecated(__magic_name__ , "Please write your own downloading logic." ) def _A ( __magic_name__ , __magic_name__ , __magic_name__ ): if not gfile.Exists(__magic_name__ ): gfile.MakeDirs(__magic_name__ ) lowercase__ = os.path.join(__magic_name__ , __magic_name__ ) if not gfile.Exists(__magic_name__ ): urllib.request.urlretrieve(__magic_name__ , __magic_name__ ) # noqa: S310 with gfile.GFile(__magic_name__ ) as f: lowercase__ = f.size() print("Successfully downloaded" , __magic_name__ , __magic_name__ , "bytes." ) return filepath @deprecated( __magic_name__ , "Please use alternatives such as:" " tensorflow_datasets.load('mnist')" ) def _A ( __magic_name__ , __magic_name__=False , __magic_name__=False , __magic_name__=dtypes.floataa , __magic_name__=True , __magic_name__=5000 , __magic_name__=None , __magic_name__=DEFAULT_SOURCE_URL , ): if fake_data: def fake(): return _DataSet( [] , [] , fake_data=__magic_name__ , one_hot=__magic_name__ , dtype=__magic_name__ , seed=__magic_name__ ) lowercase__ = fake() lowercase__ = fake() lowercase__ = fake() return _Datasets(train=__magic_name__ , validation=__magic_name__ , test=__magic_name__ ) if not source_url: # empty string check lowercase__ = DEFAULT_SOURCE_URL lowercase__ = "train-images-idx3-ubyte.gz" lowercase__ = "train-labels-idx1-ubyte.gz" lowercase__ = "t10k-images-idx3-ubyte.gz" lowercase__ = "t10k-labels-idx1-ubyte.gz" lowercase__ = _maybe_download( __magic_name__ , __magic_name__ , source_url + train_images_file ) with gfile.Open(__magic_name__ , "rb" ) as f: lowercase__ = _extract_images(__magic_name__ ) lowercase__ = _maybe_download( __magic_name__ , __magic_name__ , source_url + train_labels_file ) with gfile.Open(__magic_name__ , "rb" ) as f: lowercase__ = _extract_labels(__magic_name__ , one_hot=__magic_name__ ) lowercase__ = _maybe_download( __magic_name__ , __magic_name__ , source_url + test_images_file ) with gfile.Open(__magic_name__ , "rb" ) as f: lowercase__ = _extract_images(__magic_name__ ) lowercase__ = _maybe_download( __magic_name__ , __magic_name__ , source_url + test_labels_file ) with gfile.Open(__magic_name__ , "rb" ) as f: lowercase__ = _extract_labels(__magic_name__ , one_hot=__magic_name__ ) if not 0 <= validation_size <= len(__magic_name__ ): lowercase__ = ( "Validation size should be between 0 and " f'''{len(__magic_name__ )}. Received: {validation_size}.''' ) raise ValueError(__magic_name__ ) lowercase__ = train_images[:validation_size] lowercase__ = train_labels[:validation_size] lowercase__ = train_images[validation_size:] lowercase__ = train_labels[validation_size:] lowercase__ = {"dtype": dtype, "reshape": reshape, "seed": seed} lowercase__ = _DataSet(__magic_name__ , __magic_name__ , **__magic_name__ ) lowercase__ = _DataSet(__magic_name__ , __magic_name__ , **__magic_name__ ) lowercase__ = _DataSet(__magic_name__ , __magic_name__ , **__magic_name__ ) return _Datasets(train=__magic_name__ , validation=__magic_name__ , test=__magic_name__ )
655
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_torch_available, ) lowercase_ = { '''configuration_trocr''': ['''TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''TrOCRConfig'''], '''processing_trocr''': ['''TrOCRProcessor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ '''TROCR_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TrOCRForCausalLM''', '''TrOCRPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig from .processing_trocr import TrOCRProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel else: import sys lowercase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
336
def lowerCAmelCase ( UpperCAmelCase ) ->list[int]: """simple docstring""" __magic_name__ : Optional[int] = len(UpperCAmelCase ) for i in range(UpperCAmelCase ): for j in range(i + 1, UpperCAmelCase ): if numbers[j] < numbers[i]: __magic_name__ , __magic_name__ : Dict = numbers[j], numbers[i] return numbers if __name__ == "__main__": lowercase_ = input('''Enter numbers separated by a comma:\n''').strip() lowercase_ = [int(item) for item in user_input.split(''',''')] print(exchange_sort(unsorted))
336
1
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( HubertConfig, HubertForCTC, HubertModel, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() __a = logging.get_logger(__name__) __a = { '''post_extract_proj''': '''feature_projection.projection''', '''encoder.pos_conv.0''': '''encoder.pos_conv_embed.conv''', '''self_attn.k_proj''': '''encoder.layers.*.attention.k_proj''', '''self_attn.v_proj''': '''encoder.layers.*.attention.v_proj''', '''self_attn.q_proj''': '''encoder.layers.*.attention.q_proj''', '''self_attn.out_proj''': '''encoder.layers.*.attention.out_proj''', '''self_attn_layer_norm''': '''encoder.layers.*.layer_norm''', '''fc1''': '''encoder.layers.*.feed_forward.intermediate_dense''', '''fc2''': '''encoder.layers.*.feed_forward.output_dense''', '''final_layer_norm''': '''encoder.layers.*.final_layer_norm''', '''encoder.layer_norm''': '''encoder.layer_norm''', '''w2v_model.layer_norm''': '''feature_projection.layer_norm''', '''w2v_encoder.proj''': '''lm_head''', '''mask_emb''': '''masked_spec_embed''', } def __lowercase ( _UpperCamelCase, _UpperCamelCase, _UpperCamelCase, _UpperCamelCase, _UpperCamelCase ) ->str: """simple docstring""" for attribute in key.split('''.''' ): lowercase : Union[str, Any] = getattr(_UpperCamelCase, _UpperCamelCase ) if weight_type is not None: lowercase : Union[str, Any] = getattr(_UpperCamelCase, _UpperCamelCase ).shape else: lowercase : List[Any] = hf_pointer.shape assert hf_shape == value.shape, ( f"""Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be""" f""" {value.shape} for {full_name}""" ) if weight_type == "weight": lowercase : str = value elif weight_type == "weight_g": lowercase : Optional[Any] = value elif weight_type == "weight_v": lowercase : Any = value elif weight_type == "bias": lowercase : Union[str, Any] = value else: lowercase : List[str] = value logger.info(f"""{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.""" ) def __lowercase ( _UpperCamelCase, _UpperCamelCase, _UpperCamelCase ) ->Optional[int]: """simple docstring""" lowercase : int = [] lowercase : str = fairseq_model.state_dict() lowercase : Any = hf_model.hubert.feature_extractor if is_finetuned else hf_model.feature_extractor for name, value in fairseq_dict.items(): lowercase : Optional[int] = False if "conv_layers" in name: load_conv_layer( _UpperCamelCase, _UpperCamelCase, _UpperCamelCase, _UpperCamelCase, hf_model.config.feat_extract_norm == '''group''', ) lowercase : Dict = True else: for key, mapped_key in MAPPING.items(): lowercase : Tuple = '''hubert.''' + mapped_key if (is_finetuned and mapped_key != '''lm_head''') else mapped_key if key in name or (key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0] and not is_finetuned): lowercase : List[str] = True if "*" in mapped_key: lowercase : str = name.split(_UpperCamelCase )[0].split('''.''' )[-2] lowercase : Optional[int] = mapped_key.replace('''*''', _UpperCamelCase ) if "weight_g" in name: lowercase : Union[str, Any] = '''weight_g''' elif "weight_v" in name: lowercase : Optional[Any] = '''weight_v''' elif "weight" in name: lowercase : Optional[int] = '''weight''' elif "bias" in name: lowercase : List[Any] = '''bias''' else: lowercase : List[Any] = None set_recursively(_UpperCamelCase, _UpperCamelCase, _UpperCamelCase, _UpperCamelCase, _UpperCamelCase ) continue if not is_used: unused_weights.append(_UpperCamelCase ) logger.warning(f"""Unused weights: {unused_weights}""" ) def __lowercase ( _UpperCamelCase, _UpperCamelCase, _UpperCamelCase, _UpperCamelCase, _UpperCamelCase ) ->Dict: """simple docstring""" lowercase : str = full_name.split('''conv_layers.''' )[-1] lowercase : str = name.split('''.''' ) lowercase : Dict = int(items[0] ) lowercase : Any = 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.""" ) lowercase : int = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) lowercase : Optional[int] = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( f"""{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was""" " found." ) lowercase : Dict = 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.""" ) lowercase : Dict = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(_UpperCamelCase ) @torch.no_grad() def __lowercase ( _UpperCamelCase, _UpperCamelCase, _UpperCamelCase=None, _UpperCamelCase=None, _UpperCamelCase=True ) ->int: """simple docstring""" if config_path is not None: lowercase : Optional[Any] = HubertConfig.from_pretrained(_UpperCamelCase ) else: lowercase : int = HubertConfig() if is_finetuned: if dict_path: lowercase : Any = Dictionary.load(_UpperCamelCase ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq lowercase : List[str] = target_dict.pad_index lowercase : Dict = target_dict.bos_index lowercase : List[str] = target_dict.eos_index lowercase : int = len(target_dict.symbols ) lowercase : Any = os.path.join(_UpperCamelCase, '''vocab.json''' ) if not os.path.isdir(_UpperCamelCase ): logger.error('''--pytorch_dump_folder_path ({}) should be a directory'''.format(_UpperCamelCase ) ) return os.makedirs(_UpperCamelCase, exist_ok=_UpperCamelCase ) with open(_UpperCamelCase, '''w''', encoding='''utf-8''' ) as vocab_handle: json.dump(target_dict.indices, _UpperCamelCase ) lowercase : Dict = WavaVecaCTCTokenizer( _UpperCamelCase, 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=_UpperCamelCase, ) lowercase : Tuple = True if config.feat_extract_norm == '''layer''' else False lowercase : Optional[Any] = WavaVecaFeatureExtractor( feature_size=1, sampling_rate=16000, padding_value=0, do_normalize=_UpperCamelCase, return_attention_mask=_UpperCamelCase, ) lowercase : Any = WavaVecaProcessor(feature_extractor=_UpperCamelCase, tokenizer=_UpperCamelCase ) processor.save_pretrained(_UpperCamelCase ) lowercase : Optional[Any] = HubertForCTC(_UpperCamelCase ) else: lowercase : Tuple = HubertModel(_UpperCamelCase ) if is_finetuned: lowercase , lowercase , lowercase : Optional[int] = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path], arg_overrides={'''data''': '''/'''.join(dict_path.split('''/''' )[:-1] )} ) else: lowercase , lowercase , lowercase : int = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ) lowercase : str = model[0].eval() recursively_load_weights(_UpperCamelCase, _UpperCamelCase, _UpperCamelCase ) hf_wavavec.save_pretrained(_UpperCamelCase ) if __name__ == "__main__": __a = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--dict_path''', default=None, type=str, help='''Path to dict of fine-tuned model''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument( '''--not_finetuned''', action='''store_true''', help='''Whether the model to convert is a fine-tuned model or not''' ) __a = parser.parse_args() convert_hubert_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
319
import os from typing import List, Optional, Union from ...tokenization_utils import PreTrainedTokenizer from ...tokenization_utils_base import AddedToken from ...utils import logging __a = logging.get_logger(__name__) __a = {'''vocab_file''': '''vocab.txt'''} __a = { '''vocab_file''': { '''facebook/esm2_t6_8M_UR50D''': '''https://huggingface.co/facebook/esm2_t6_8M_UR50D/resolve/main/vocab.txt''', '''facebook/esm2_t12_35M_UR50D''': '''https://huggingface.co/facebook/esm2_t12_35M_UR50D/resolve/main/vocab.txt''', }, } __a = { '''facebook/esm2_t6_8M_UR50D''': 10_24, '''facebook/esm2_t12_35M_UR50D''': 10_24, } def __lowercase ( _UpperCamelCase ) ->Tuple: """simple docstring""" with open(_UpperCamelCase, '''r''' ) as f: lowercase : List[Any] = f.read().splitlines() return [l.strip() for l in lines] class __SCREAMING_SNAKE_CASE ( A__ ): A : Dict = VOCAB_FILES_NAMES A : List[str] = PRETRAINED_VOCAB_FILES_MAP A : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A : List[str] = ['input_ids', 'attention_mask'] def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__="<unk>" , SCREAMING_SNAKE_CASE__="<cls>" , SCREAMING_SNAKE_CASE__="<pad>" , SCREAMING_SNAKE_CASE__="<mask>" , SCREAMING_SNAKE_CASE__="<eos>" , **SCREAMING_SNAKE_CASE__ , ): super().__init__(**SCREAMING_SNAKE_CASE__ ) lowercase : str = load_vocab_file(SCREAMING_SNAKE_CASE__ ) lowercase : List[Any] = dict(enumerate(self.all_tokens ) ) lowercase : Tuple = {tok: ind for ind, tok in enumerate(self.all_tokens )} lowercase : Tuple = unk_token lowercase : Optional[Any] = cls_token lowercase : Union[str, Any] = pad_token lowercase : Dict = mask_token lowercase : Dict = eos_token lowercase : Any = self.all_tokens self._create_trie(self.unique_no_split_tokens ) def __lowerCamelCase ( self , SCREAMING_SNAKE_CASE__ ): return self._id_to_token.get(SCREAMING_SNAKE_CASE__ , self.unk_token ) def __lowerCamelCase ( self , SCREAMING_SNAKE_CASE__ ): return self._token_to_id.get(SCREAMING_SNAKE_CASE__ , self._token_to_id.get(self.unk_token ) ) def __lowerCamelCase ( self , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ): return text.split() def __lowerCamelCase ( self , SCREAMING_SNAKE_CASE__=False ): return len(self._id_to_token ) def __lowerCamelCase ( self ): return {token: i for i, token in enumerate(self.all_tokens )} def __lowerCamelCase ( self , SCREAMING_SNAKE_CASE__ ): return self._token_to_id.get(SCREAMING_SNAKE_CASE__ , self._token_to_id.get(self.unk_token ) ) def __lowerCamelCase ( self , SCREAMING_SNAKE_CASE__ ): return self._id_to_token.get(SCREAMING_SNAKE_CASE__ , self.unk_token ) def __lowerCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None ): lowercase : List[str] = [self.cls_token_id] lowercase : Dict = [self.eos_token_id] # No sep token in ESM vocabulary if token_ids_a is None: if self.eos_token_id is None: return cls + token_ids_a else: return cls + token_ids_a + sep elif self.eos_token_id is None: raise ValueError('''Cannot tokenize multiple sequences when EOS token is not set!''' ) return cls + token_ids_a + sep + token_ids_a + sep # Multiple inputs always have an EOS token def __lowerCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = False ): 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 token in self.all_special_ids else 0 for token in token_ids_a] lowercase : Tuple = [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] if token_ids_a is not None: mask += [0] * len(SCREAMING_SNAKE_CASE__ ) + [1] return mask def __lowerCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): lowercase : List[str] = os.path.join(SCREAMING_SNAKE_CASE__ , (filename_prefix + '''-''' if filename_prefix else '''''') + '''vocab.txt''' ) with open(SCREAMING_SNAKE_CASE__ , '''w''' ) as f: f.write('''\n'''.join(self.all_tokens ) ) return (vocab_file,) @property def __lowerCamelCase ( self ): return self.get_vocab_size(with_added_tokens=SCREAMING_SNAKE_CASE__ ) def __lowerCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = False ): return super()._add_tokens(SCREAMING_SNAKE_CASE__ , special_tokens=SCREAMING_SNAKE_CASE__ )
319
1
from argparse import ArgumentParser, Namespace from typing import Any, List, Optional from ..pipelines import Pipeline, get_supported_tasks, pipeline from ..utils import logging from . import BaseTransformersCLICommand try: from fastapi import Body, FastAPI, HTTPException from fastapi.routing import APIRoute from pydantic import BaseModel from starlette.responses import JSONResponse from uvicorn import run SCREAMING_SNAKE_CASE_ = True except (ImportError, AttributeError): SCREAMING_SNAKE_CASE_ = object def __lowercase ( *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> Tuple: '''simple docstring''' pass SCREAMING_SNAKE_CASE_ = False SCREAMING_SNAKE_CASE_ = logging.get_logger("""transformers-cli/serving""") def __lowercase ( _SCREAMING_SNAKE_CASE ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = pipeline( task=args.task , model=args.model if args.model else None , config=args.config , tokenizer=args.tokenizer , device=args.device , ) return ServeCommand(_SCREAMING_SNAKE_CASE , args.host , args.port , args.workers ) class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : dict class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : List[str] __snake_case : Optional[List[int]] class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : str class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : Any class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' @staticmethod def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ : ArgumentParser ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = parser.add_parser( """serve""" ,help="""CLI tool to run inference requests through REST and GraphQL endpoints.""" ) serve_parser.add_argument( """--task""" ,type=lowerCamelCase__ ,choices=get_supported_tasks() ,help="""The task to run the pipeline on""" ,) serve_parser.add_argument("""--host""" ,type=lowerCamelCase__ ,default="""localhost""" ,help="""Interface the server will listen on.""" ) serve_parser.add_argument("""--port""" ,type=lowerCamelCase__ ,default=8888 ,help="""Port the serving will listen to.""" ) serve_parser.add_argument("""--workers""" ,type=lowerCamelCase__ ,default=1 ,help="""Number of http workers""" ) serve_parser.add_argument("""--model""" ,type=lowerCamelCase__ ,help="""Model's name or path to stored model.""" ) serve_parser.add_argument("""--config""" ,type=lowerCamelCase__ ,help="""Model's config name or path to stored model.""" ) serve_parser.add_argument("""--tokenizer""" ,type=lowerCamelCase__ ,help="""Tokenizer name to use.""" ) serve_parser.add_argument( """--device""" ,type=lowerCamelCase__ ,default=-1 ,help="""Indicate the device to run onto, -1 indicates CPU, >= 0 indicates GPU (default: -1)""" ,) serve_parser.set_defaults(func=lowerCamelCase__ ) def __init__( self : List[str] ,lowerCamelCase__ : Pipeline ,lowerCamelCase__ : str ,lowerCamelCase__ : int ,lowerCamelCase__ : int ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE = pipeline SCREAMING_SNAKE_CASE = host SCREAMING_SNAKE_CASE = port SCREAMING_SNAKE_CASE = workers if not _serve_dependencies_installed: raise RuntimeError( """Using serve command requires FastAPI and uvicorn. """ """Please install transformers with [serving]: pip install \"transformers[serving]\".""" """Or install FastAPI and uvicorn separately.""" ) else: logger.info(F"""Serving model over {host}:{port}""" ) SCREAMING_SNAKE_CASE = FastAPI( routes=[ APIRoute( """/""" ,self.model_info ,response_model=lowerCamelCase__ ,response_class=lowerCamelCase__ ,methods=["""GET"""] ,), APIRoute( """/tokenize""" ,self.tokenize ,response_model=lowerCamelCase__ ,response_class=lowerCamelCase__ ,methods=["""POST"""] ,), APIRoute( """/detokenize""" ,self.detokenize ,response_model=lowerCamelCase__ ,response_class=lowerCamelCase__ ,methods=["""POST"""] ,), APIRoute( """/forward""" ,self.forward ,response_model=lowerCamelCase__ ,response_class=lowerCamelCase__ ,methods=["""POST"""] ,), ] ,timeout=600 ,) def SCREAMING_SNAKE_CASE__ ( self : List[Any] ) -> str: '''simple docstring''' run(self._app ,host=self.host ,port=self.port ,workers=self.workers ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> List[str]: '''simple docstring''' return ServeModelInfoResult(infos=vars(self._pipeline.model.config ) ) def SCREAMING_SNAKE_CASE__ ( self : Dict ,lowerCamelCase__ : str = Body(lowerCamelCase__ ,embed=lowerCamelCase__ ) ,lowerCamelCase__ : bool = Body(lowerCamelCase__ ,embed=lowerCamelCase__ ) ) -> Any: '''simple docstring''' try: SCREAMING_SNAKE_CASE = self._pipeline.tokenizer.tokenize(lowerCamelCase__ ) if return_ids: SCREAMING_SNAKE_CASE = self._pipeline.tokenizer.convert_tokens_to_ids(lowerCamelCase__ ) return ServeTokenizeResult(tokens=lowerCamelCase__ ,tokens_ids=lowerCamelCase__ ) else: return ServeTokenizeResult(tokens=lowerCamelCase__ ) except Exception as e: raise HTTPException(status_code=500 ,detail={"""model""": """""", """error""": str(lowerCamelCase__ )} ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] ,lowerCamelCase__ : List[int] = Body(lowerCamelCase__ ,embed=lowerCamelCase__ ) ,lowerCamelCase__ : bool = Body(lowerCamelCase__ ,embed=lowerCamelCase__ ) ,lowerCamelCase__ : bool = Body(lowerCamelCase__ ,embed=lowerCamelCase__ ) ,) -> int: '''simple docstring''' try: SCREAMING_SNAKE_CASE = self._pipeline.tokenizer.decode(lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ) return ServeDeTokenizeResult(model="""""" ,text=lowerCamelCase__ ) except Exception as e: raise HTTPException(status_code=500 ,detail={"""model""": """""", """error""": str(lowerCamelCase__ )} ) async def SCREAMING_SNAKE_CASE__ ( self : int ,lowerCamelCase__ : str=Body(lowerCamelCase__ ,embed=lowerCamelCase__ ) ) -> Optional[Any]: '''simple docstring''' if len(lowerCamelCase__ ) == 0: return ServeForwardResult(output=[] ,attention=[] ) try: # Forward through the model SCREAMING_SNAKE_CASE = self._pipeline(lowerCamelCase__ ) return ServeForwardResult(output=lowerCamelCase__ ) except Exception as e: raise HTTPException(500 ,{"""error""": str(lowerCamelCase__ )} )
116
import warnings from ...utils import logging from .image_processing_deformable_detr import DeformableDetrImageProcessor SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' def __init__( self : int ,*lowerCamelCase__ : int ,**lowerCamelCase__ : List[Any] ) -> None: '''simple docstring''' warnings.warn( """The class DeformableDetrFeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use DeformableDetrImageProcessor instead.""" ,lowerCamelCase__ ,) super().__init__(*lowerCamelCase__ ,**lowerCamelCase__ )
116
1
from sympy import diff, lambdify, symbols from sympy.functions import * # noqa: F403 def SCREAMING_SNAKE_CASE__ ( lowerCAmelCase_ : Union[str, Any] ,lowerCAmelCase_ : str ,lowerCAmelCase_ : List[str] = "x" ,lowerCAmelCase_ : Tuple = 10**-10 ,lowerCAmelCase_ : Optional[int] = 1 ,) -> complex: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] =symbols(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] =lambdify(lowerCAmelCase_ ,lowerCAmelCase_ ) SCREAMING_SNAKE_CASE_ : Optional[int] =lambdify(lowerCAmelCase_ ,diff(lowerCAmelCase_ ,lowerCAmelCase_ ) ) SCREAMING_SNAKE_CASE_ : int =starting_point while True: if diff_function(lowerCAmelCase_ ) != 0: SCREAMING_SNAKE_CASE_ : Dict =prev_guess - multiplicity * func(lowerCAmelCase_ ) / diff_function( lowerCAmelCase_ ) else: raise ZeroDivisionError('Could not find root' ) from None # Precision is checked by comparing the difference of consecutive guesses if abs(next_guess - prev_guess ) < precision: return next_guess SCREAMING_SNAKE_CASE_ : Union[str, Any] =next_guess # Let's Execute if __name__ == "__main__": # Find root of trigonometric function # Find value of pi print(f"""The root of sin(x) = 0 is {newton_raphson('sin(x)', 2)}""") # Find root of polynomial # Find fourth Root of 5 print(f"""The root of x**4 - 5 = 0 is {newton_raphson('x**4 -5', 0.4 +5J)}""") # Find value of e print( 'The root of log(y) - 1 = 0 is ', f"""{newton_raphson('log(y) - 1', 2, variable='y')}""", ) # Exponential Roots print( 'The root of exp(x) - 1 = 0 is', f"""{newton_raphson('exp(x) - 1', 10, precision=0.005)}""", ) # Find root of cos(x) print(f"""The root of cos(x) = 0 is {newton_raphson('cos(x)', 0)}""")
220
import argparse import gc import json import os import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler lowerCamelCase_ : int = 16 lowerCamelCase_ : str = 32 def A__ ( lowerCamelCase ) -> int: return int(x / 2**20 ) class _UpperCamelCase : '''simple docstring''' def __enter__( self : int ): gc.collect() torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() # reset the peak gauge to zero UpperCamelCase_: str = torch.cuda.memory_allocated() return self def __exit__( self : List[Any] , *snake_case_ : Union[str, Any] ): gc.collect() torch.cuda.empty_cache() UpperCamelCase_: List[str] = torch.cuda.memory_allocated() UpperCamelCase_: int = torch.cuda.max_memory_allocated() UpperCamelCase_: Optional[int] = bamb(self.end - self.begin ) UpperCamelCase_: Tuple = bamb(self.peak - self.begin ) # print(f"delta used/peak {self.used:4d}/{self.peaked:4d}") def A__ ( lowerCamelCase , lowerCamelCase = 16 , lowerCamelCase = "bert-base-cased" , lowerCamelCase = 3_20 , lowerCamelCase = 1_60 , ) -> Dict: UpperCamelCase_: str = AutoTokenizer.from_pretrained(lowerCamelCase ) UpperCamelCase_: List[str] = load_dataset( """glue""" , """mrpc""" , split={"""train""": F'''train[:{n_train}]''', """validation""": F'''validation[:{n_val}]'''} ) def tokenize_function(lowerCamelCase ): # max_length=None => use the model max length (it's actually the default) UpperCamelCase_: Optional[Any] = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=lowerCamelCase , max_length=lowerCamelCase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset UpperCamelCase_: Dict = datasets.map( lowerCamelCase , batched=lowerCamelCase , remove_columns=["""idx""", """sentence1""", """sentence2"""] , load_from_cache_file=lowerCamelCase ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library UpperCamelCase_: int = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(lowerCamelCase ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(lowerCamelCase , padding="""max_length""" , max_length=1_28 , return_tensors="""pt""" ) return tokenizer.pad(lowerCamelCase , padding="""longest""" , return_tensors="""pt""" ) # Instantiate dataloaders. UpperCamelCase_: List[str] = DataLoader( tokenized_datasets["""train"""] , shuffle=lowerCamelCase , collate_fn=lowerCamelCase , batch_size=lowerCamelCase ) UpperCamelCase_: Optional[Any] = DataLoader( tokenized_datasets["""validation"""] , shuffle=lowerCamelCase , collate_fn=lowerCamelCase , batch_size=lowerCamelCase ) return train_dataloader, eval_dataloader def A__ ( lowerCamelCase , lowerCamelCase ) -> Union[str, Any]: # Initialize accelerator UpperCamelCase_: Any = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs UpperCamelCase_: str = config["""lr"""] UpperCamelCase_: Any = int(config["""num_epochs"""] ) UpperCamelCase_: Tuple = int(config["""seed"""] ) UpperCamelCase_: Dict = int(config["""batch_size"""] ) UpperCamelCase_: Dict = args.model_name_or_path set_seed(lowerCamelCase ) UpperCamelCase_, UpperCamelCase_: int = get_dataloaders(lowerCamelCase , lowerCamelCase , lowerCamelCase , args.n_train , args.n_val ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) UpperCamelCase_: Any = AutoModelForSequenceClassification.from_pretrained(lowerCamelCase , return_dict=lowerCamelCase ) # Instantiate optimizer UpperCamelCase_: Tuple = ( AdamW if accelerator.state.deepspeed_plugin is None or """optimizer""" not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) UpperCamelCase_: List[Any] = optimizer_cls(params=model.parameters() , lr=lowerCamelCase ) if accelerator.state.deepspeed_plugin is not None: UpperCamelCase_: Any = accelerator.state.deepspeed_plugin.deepspeed_config[ """gradient_accumulation_steps""" ] else: UpperCamelCase_: List[Any] = 1 UpperCamelCase_: Optional[int] = (len(lowerCamelCase ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): UpperCamelCase_: List[Any] = get_linear_schedule_with_warmup( optimizer=lowerCamelCase , num_warmup_steps=0 , num_training_steps=lowerCamelCase , ) else: UpperCamelCase_: Dict = DummyScheduler(lowerCamelCase , total_num_steps=lowerCamelCase , warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. UpperCamelCase_, UpperCamelCase_, UpperCamelCase_, UpperCamelCase_, UpperCamelCase_: str = accelerator.prepare( lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ) # We need to keep track of how many total steps we have iterated over UpperCamelCase_: str = 0 # We also need to keep track of the stating epoch so files are named properly UpperCamelCase_: Dict = 0 # Now we train the model UpperCamelCase_: Dict = {} for epoch in range(lowerCamelCase , lowerCamelCase ): with TorchTracemalloc() as tracemalloc: model.train() for step, batch in enumerate(lowerCamelCase ): UpperCamelCase_: Union[str, Any] = model(**lowerCamelCase ) UpperCamelCase_: str = outputs.loss UpperCamelCase_: List[str] = loss / gradient_accumulation_steps accelerator.backward(lowerCamelCase ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 # Printing the GPU memory usage details such as allocated memory, peak memory, and total memory usage accelerator.print("""Memory before entering the train : {}""".format(bamb(tracemalloc.begin ) ) ) accelerator.print("""Memory consumed at the end of the train (end-begin): {}""".format(tracemalloc.used ) ) accelerator.print("""Peak Memory consumed during the train (max-begin): {}""".format(tracemalloc.peaked ) ) accelerator.print( """Total Peak Memory consumed during the train (max): {}""".format( tracemalloc.peaked + bamb(tracemalloc.begin ) ) ) UpperCamelCase_: Optional[Any] = tracemalloc.peaked + bamb(tracemalloc.begin ) if args.peak_memory_upper_bound is not None: assert ( train_total_peak_memory[F'''epoch-{epoch}'''] <= args.peak_memory_upper_bound ), "Peak memory usage exceeded the upper bound" accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir , """peak_memory_utilization.json""" ) , """w""" ) as f: json.dump(lowerCamelCase , lowerCamelCase ) def A__ ( ) -> Optional[Any]: UpperCamelCase_: Any = argparse.ArgumentParser(description="""Simple example of training script tracking peak GPU memory usage.""" ) parser.add_argument( """--model_name_or_path""" , type=lowerCamelCase , default="""bert-base-cased""" , help="""Path to pretrained model or model identifier from huggingface.co/models.""" , required=lowerCamelCase , ) parser.add_argument( """--output_dir""" , type=lowerCamelCase , default=""".""" , help="""Optional save directory where all checkpoint folders will be stored. Default is the current working directory.""" , ) parser.add_argument( """--peak_memory_upper_bound""" , type=lowerCamelCase , default=lowerCamelCase , help="""The upper bound of peak memory usage in MB. If set, the training will throw an error if the peak memory usage exceeds this value.""" , ) parser.add_argument( """--n_train""" , type=lowerCamelCase , default=3_20 , help="""Number of training examples to use.""" , ) parser.add_argument( """--n_val""" , type=lowerCamelCase , default=1_60 , help="""Number of validation examples to use.""" , ) parser.add_argument( """--num_epochs""" , type=lowerCamelCase , default=1 , help="""Number of train epochs.""" , ) UpperCamelCase_: Optional[int] = parser.parse_args() UpperCamelCase_: Union[str, Any] = {"""lr""": 2E-5, """num_epochs""": args.num_epochs, """seed""": 42, """batch_size""": 16} training_function(lowerCamelCase , lowerCamelCase ) if __name__ == "__main__": main()
548
0
def __lowerCamelCase ( __a :str ) -> bool: """simple docstring""" if not all(x.isalpha() for x in string ): raise ValueError("""String must only contain alphabetic characters.""" ) A__ = sorted(string.lower() ) return len(__a ) == len(set(__a ) ) if __name__ == "__main__": A : Union[str, Any] = input('''Enter a string ''').strip() A : str = is_isogram(input_str) print(F'''{input_str} is {"an" if isogram else "not an"} isogram.''')
706
# 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. import torch from accelerate import PartialState from accelerate.utils.operations import broadcast, gather, gather_object, pad_across_processes, reduce def __lowerCamelCase ( __a :Dict ) -> List[Any]: """simple docstring""" return (torch.arange(state.num_processes ) + 1.0 + (state.num_processes * state.process_index)).to(state.device ) def __lowerCamelCase ( __a :str ) -> int: """simple docstring""" A__ = create_tensor(__a ) A__ = gather(__a ) assert gathered_tensor.tolist() == list(range(1 , state.num_processes**2 + 1 ) ) def __lowerCamelCase ( __a :Optional[Any] ) -> Optional[int]: """simple docstring""" A__ = [state.process_index] A__ = gather_object(__a ) assert len(__a ) == state.num_processes, F'{gathered_obj}, {len(__a )} != {state.num_processes}' assert gathered_obj == list(range(state.num_processes ) ), F'{gathered_obj} != {list(range(state.num_processes ) )}' def __lowerCamelCase ( __a :Optional[int] ) -> Dict: """simple docstring""" A__ = create_tensor(__a ) A__ = broadcast(__a ) assert broadcasted_tensor.shape == torch.Size([state.num_processes] ) assert broadcasted_tensor.tolist() == list(range(1 , state.num_processes + 1 ) ) def __lowerCamelCase ( __a :List[str] ) -> Tuple: """simple docstring""" if state.is_main_process: A__ = torch.arange(state.num_processes + 1 ).to(state.device ) else: A__ = torch.arange(state.num_processes ).to(state.device ) A__ = pad_across_processes(__a ) assert padded_tensor.shape == torch.Size([state.num_processes + 1] ) if not state.is_main_process: assert padded_tensor.tolist() == list(range(0 , state.num_processes ) ) + [0] def __lowerCamelCase ( __a :Optional[int] ) -> Tuple: """simple docstring""" if state.num_processes != 2: return A__ = create_tensor(__a ) A__ = reduce(__a , """sum""" ) A__ = torch.tensor([4.0, 6] ).to(state.device ) assert torch.allclose(__a , __a ), F'{reduced_tensor} != {truth_tensor}' def __lowerCamelCase ( __a :str ) -> List[str]: """simple docstring""" if state.num_processes != 2: return A__ = create_tensor(__a ) A__ = reduce(__a , """mean""" ) A__ = torch.tensor([2.0, 3] ).to(state.device ) assert torch.allclose(__a , __a ), F'{reduced_tensor} != {truth_tensor}' def __lowerCamelCase ( __a :List[Any] ) -> Union[str, Any]: """simple docstring""" main() def __lowerCamelCase ( ) -> List[str]: """simple docstring""" A__ = PartialState() state.print(F'State: {state}' ) state.print("""testing gather""" ) test_gather(__a ) state.print("""testing gather_object""" ) test_gather_object(__a ) state.print("""testing broadcast""" ) test_broadcast(__a ) state.print("""testing pad_across_processes""" ) test_pad_across_processes(__a ) state.print("""testing reduce_sum""" ) test_reduce_sum(__a ) state.print("""testing reduce_mean""" ) test_reduce_mean(__a ) if __name__ == "__main__": main()
247
0
'''simple docstring''' from __future__ import annotations from collections import deque from collections.abc import Sequence from dataclasses import dataclass from typing import Any @dataclass class UpperCAmelCase_ : """simple docstring""" UpperCamelCase_ = 42 UpperCamelCase_ = None UpperCamelCase_ = None def lowercase_ ( ) -> Node | None: """simple docstring""" lowercase : Tuple =Node(1 ) lowercase : List[Any] =Node(2 ) lowercase : str =Node(3 ) lowercase : Union[str, Any] =Node(4 ) lowercase : List[Any] =Node(5 ) return tree def lowercase_ ( __A : Node | None ) -> list[int]: """simple docstring""" return [root.data, *preorder(root.left ), *preorder(root.right )] if root else [] def lowercase_ ( __A : Node | None ) -> list[int]: """simple docstring""" return postorder(root.left ) + postorder(root.right ) + [root.data] if root else [] def lowercase_ ( __A : Node | None ) -> list[int]: """simple docstring""" return [*inorder(root.left ), root.data, *inorder(root.right )] if root else [] def lowercase_ ( __A : Node | None ) -> int: """simple docstring""" return (max(height(root.left ) , height(root.right ) ) + 1) if root else 0 def lowercase_ ( __A : Node | None ) -> Sequence[Node | None]: """simple docstring""" lowercase : list[Any] =[] if root is None: return output lowercase : Dict =deque([root] ) while process_queue: lowercase : int =process_queue.popleft() output.append(node.data ) if node.left: process_queue.append(node.left ) if node.right: process_queue.append(node.right ) return output def lowercase_ ( __A : Node | None , __A : int ) -> Sequence[Node | None]: """simple docstring""" lowercase : list[Any] =[] def populate_output(__A : Node | None , __A : int ) -> None: if not root: return if level == 1: output.append(root.data ) elif level > 1: populate_output(root.left , level - 1 ) populate_output(root.right , level - 1 ) populate_output(__A , __A ) return output def lowercase_ ( __A : Node | None , __A : int ) -> Sequence[Node | None]: """simple docstring""" lowercase : list[Any] =[] def populate_output(__A : Node | None , __A : int ) -> None: if root is None: return if level == 1: output.append(root.data ) elif level > 1: populate_output(root.right , level - 1 ) populate_output(root.left , level - 1 ) populate_output(__A , __A ) return output def lowercase_ ( __A : Node | None ) -> Sequence[Node | None] | list[Any]: """simple docstring""" if root is None: return [] lowercase : list[Sequence[Node | None]] =[] lowercase : str =0 lowercase : int =height(__A ) for h in range(1 , height_tree + 1 ): if not flag: output.append(get_nodes_from_left_to_right(__A , __A ) ) lowercase : Optional[Any] =1 else: output.append(get_nodes_from_right_to_left(__A , __A ) ) lowercase : Dict =0 return output def lowercase_ ( ) -> None: # Main function for testing. """simple docstring""" lowercase : int =make_tree() print(F'In-order Traversal: {inorder(__A )}' ) print(F'Pre-order Traversal: {preorder(__A )}' ) print(F'Post-order Traversal: {postorder(__A )}' , '''\n''' ) print(F'Height of Tree: {height(__A )}' , '''\n''' ) print('''Complete Level Order Traversal: ''' ) print(level_order(__A ) , '''\n''' ) print('''Level-wise order Traversal: ''' ) for level in range(1 , height(__A ) + 1 ): print(F'Level {level}:' , get_nodes_from_left_to_right(__A , level=__A ) ) print('''\nZigZag order Traversal: ''' ) print(zigzag(__A ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
94
from importlib import import_module from .logging import get_logger SCREAMING_SNAKE_CASE__ : Union[str, Any] = get_logger(__name__) class UpperCAmelCase_ : def __init__( self , _lowerCAmelCase , _lowerCAmelCase=None ): UpperCAmelCase__ : List[str] = attrs or [] if module is not None: for key in module.__dict__: if key in attrs or not key.startswith("""__""" ): setattr(self , _lowerCAmelCase , getattr(_lowerCAmelCase , _lowerCAmelCase ) ) UpperCAmelCase__ : Tuple = module._original_module if isinstance(_lowerCAmelCase , _PatchedModuleObj ) else module class UpperCAmelCase_ : __lowerCamelCase = [] def __init__( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase=None ): UpperCAmelCase__ : str = obj UpperCAmelCase__ : List[str] = target UpperCAmelCase__ : List[str] = new UpperCAmelCase__ : Any = target.split(""".""" )[0] UpperCAmelCase__ : Union[str, Any] = {} UpperCAmelCase__ : str = attrs or [] def __enter__( self ): *UpperCAmelCase__ , UpperCAmelCase__ : List[Any] = self.target.split(""".""" ) # Patch modules: # it's used to patch attributes of submodules like "os.path.join"; # in this case we need to patch "os" and "os.path" for i in range(len(_lowerCAmelCase ) ): try: UpperCAmelCase__ : Optional[int] = import_module(""".""".join(submodules[: i + 1] ) ) except ModuleNotFoundError: continue # We iterate over all the globals in self.obj in case we find "os" or "os.path" for attr in self.obj.__dir__(): UpperCAmelCase__ : Any = getattr(self.obj , _lowerCAmelCase ) # We don't check for the name of the global, but rather if its value *is* "os" or "os.path". # This allows to patch renamed modules like "from os import path as ospath". if obj_attr is submodule or ( (isinstance(_lowerCAmelCase , _PatchedModuleObj ) and obj_attr._original_module is submodule) ): UpperCAmelCase__ : List[Any] = obj_attr # patch at top level setattr(self.obj , _lowerCAmelCase , _PatchedModuleObj(_lowerCAmelCase , attrs=self.attrs ) ) UpperCAmelCase__ : Optional[Any] = getattr(self.obj , _lowerCAmelCase ) # construct lower levels patches for key in submodules[i + 1 :]: setattr(_lowerCAmelCase , _lowerCAmelCase , _PatchedModuleObj(getattr(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) , attrs=self.attrs ) ) UpperCAmelCase__ : Union[str, Any] = getattr(_lowerCAmelCase , _lowerCAmelCase ) # finally set the target attribute setattr(_lowerCAmelCase , _lowerCAmelCase , self.new ) # Patch attribute itself: # it's used for builtins like "open", # and also to patch "os.path.join" we may also need to patch "join" # itself if it was imported as "from os.path import join". if submodules: # if it's an attribute of a submodule like "os.path.join" try: UpperCAmelCase__ : Union[str, Any] = getattr(import_module(""".""".join(_lowerCAmelCase ) ) , _lowerCAmelCase ) except (AttributeError, ModuleNotFoundError): return # We iterate over all the globals in self.obj in case we find "os.path.join" for attr in self.obj.__dir__(): # We don't check for the name of the global, but rather if its value *is* "os.path.join". # This allows to patch renamed attributes like "from os.path import join as pjoin". if getattr(self.obj , _lowerCAmelCase ) is attr_value: UpperCAmelCase__ : Optional[int] = getattr(self.obj , _lowerCAmelCase ) setattr(self.obj , _lowerCAmelCase , self.new ) elif target_attr in globals()["__builtins__"]: # if it'a s builtin like "open" UpperCAmelCase__ : Dict = globals()["""__builtins__"""][target_attr] setattr(self.obj , _lowerCAmelCase , self.new ) else: raise RuntimeError(f"Tried to patch attribute {target_attr} instead of a submodule." ) def __exit__( self , *_lowerCAmelCase ): for attr in list(self.original ): setattr(self.obj , _lowerCAmelCase , self.original.pop(_lowerCAmelCase ) ) def __UpperCAmelCase ( self ): self.__enter__() self._active_patches.append(self ) def __UpperCAmelCase ( self ): try: self._active_patches.remove(self ) except ValueError: # If the patch hasn't been started this will fail return None return self.__exit__()
79
0
def A__ ( lowerCamelCase , lowerCamelCase ) -> int: while a != 0: UpperCamelCase_, UpperCamelCase_: Dict = b % a, a return b def A__ ( lowerCamelCase , lowerCamelCase ) -> int: if gcd(lowerCamelCase , lowerCamelCase ) != 1: UpperCamelCase_: str = F'''mod inverse of {a!r} and {m!r} does not exist''' raise ValueError(lowerCamelCase ) UpperCamelCase_, UpperCamelCase_, UpperCamelCase_: List[str] = 1, 0, a UpperCamelCase_, UpperCamelCase_, UpperCamelCase_: Dict = 0, 1, m while va != 0: UpperCamelCase_: List[str] = ua // va UpperCamelCase_, UpperCamelCase_, UpperCamelCase_, UpperCamelCase_, UpperCamelCase_, UpperCamelCase_: List[str] = (ua - q * va), (ua - q * va), (ua - q * va), va, va, va return ua % m
670
import os import unittest from huggingface_hub.utils import are_progress_bars_disabled import transformers.models.bart.tokenization_bart from transformers import logging from transformers.testing_utils import CaptureLogger, mockenv, mockenv_context from transformers.utils.logging import disable_progress_bar, enable_progress_bar class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' def lowerCAmelCase__ ( self : str ): UpperCamelCase_: Optional[int] = logging.get_logger() # the current default level is logging.WARNING UpperCamelCase_: Dict = logging.get_verbosity() logging.set_verbosity_error() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_warning() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_info() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_debug() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) # restore to the original level logging.set_verbosity(snake_case_ ) def lowerCAmelCase__ ( self : Optional[int] ): UpperCamelCase_: Union[str, Any] = logging.get_verbosity() UpperCamelCase_: int = logging.get_logger("""transformers.models.bart.tokenization_bart""" ) UpperCamelCase_: Union[str, Any] = """Testing 1, 2, 3""" # should be able to log warnings (if default settings weren't overridden by `pytest --log-level-all`) if level_origin <= logging.WARNING: with CaptureLogger(snake_case_ ) as cl: logger.warning(snake_case_ ) self.assertEqual(cl.out , msg + """\n""" ) # this is setting the level for all of `transformers.*` loggers logging.set_verbosity_error() # should not be able to log warnings with CaptureLogger(snake_case_ ) as cl: logger.warning(snake_case_ ) self.assertEqual(cl.out , """""" ) # should be able to log warnings again logging.set_verbosity_warning() with CaptureLogger(snake_case_ ) as cl: logger.warning(snake_case_ ) self.assertEqual(cl.out , msg + """\n""" ) # restore to the original level logging.set_verbosity(snake_case_ ) @mockenv(TRANSFORMERS_VERBOSITY="""error""" ) def lowerCAmelCase__ ( self : Optional[int] ): # reset for the env var to take effect, next time some logger call is made transformers.utils.logging._reset_library_root_logger() # this action activates the env var UpperCamelCase_: List[str] = logging.get_logger("""transformers.models.bart.tokenization_bart""" ) UpperCamelCase_: str = os.getenv("""TRANSFORMERS_VERBOSITY""" , snake_case_ ) UpperCamelCase_: Any = logging.log_levels[env_level_str] UpperCamelCase_: Dict = logging.get_verbosity() self.assertEqual( snake_case_ , snake_case_ , f'''TRANSFORMERS_VERBOSITY={env_level_str}/{env_level}, but internal verbosity is {current_level}''' , ) # restore to the original level UpperCamelCase_: str = """""" transformers.utils.logging._reset_library_root_logger() @mockenv(TRANSFORMERS_VERBOSITY="""super-error""" ) def lowerCAmelCase__ ( self : List[Any] ): # reset for the env var to take effect, next time some logger call is made transformers.utils.logging._reset_library_root_logger() UpperCamelCase_: str = logging.logging.getLogger() with CaptureLogger(snake_case_ ) as cl: # this action activates the env var logging.get_logger("""transformers.models.bart.tokenization_bart""" ) self.assertIn("""Unknown option TRANSFORMERS_VERBOSITY=super-error""" , cl.out ) # no need to restore as nothing was changed def lowerCAmelCase__ ( self : List[Any] ): # testing `logger.warning_advice()` transformers.utils.logging._reset_library_root_logger() UpperCamelCase_: List[str] = logging.get_logger("""transformers.models.bart.tokenization_bart""" ) UpperCamelCase_: Any = """Testing 1, 2, 3""" with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS="""1""" ): # nothing should be logged as env var disables this method with CaptureLogger(snake_case_ ) as cl: logger.warning_advice(snake_case_ ) self.assertEqual(cl.out , """""" ) with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS="""""" ): # should log normally as TRANSFORMERS_NO_ADVISORY_WARNINGS is unset with CaptureLogger(snake_case_ ) as cl: logger.warning_advice(snake_case_ ) self.assertEqual(cl.out , msg + """\n""" ) def A__ ( ) -> Union[str, Any]: disable_progress_bar() assert are_progress_bars_disabled() enable_progress_bar() assert not are_progress_bars_disabled()
670
1
'''simple docstring''' import time import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch, torch_device from ..test_modeling_common import ids_tensor if is_torch_available(): import torch from transformers.generation import ( MaxLengthCriteria, MaxNewTokensCriteria, MaxTimeCriteria, StoppingCriteriaList, validate_stopping_criteria, ) @require_torch class UpperCamelCase__ (unittest.TestCase ): '''simple docstring''' def UpperCamelCase_ ( self ,_lowerCAmelCase ): lowerCamelCase__ = 3 lowerCamelCase__ = 2_50 lowerCamelCase__ = ids_tensor((batch_size, length) ,_lowerCAmelCase ) lowerCamelCase__ = torch.ones((batch_size, length) ,device=_lowerCAmelCase ,dtype=torch.float ) / length return input_ids, scores def UpperCamelCase_ ( self ): lowerCamelCase__ , lowerCamelCase__ = self._get_tensors(5 ) lowerCamelCase__ = StoppingCriteriaList( [ MaxLengthCriteria(max_length=10 ), MaxTimeCriteria(max_time=0.1 ), ] ) self.assertFalse(criteria(_lowerCAmelCase ,_lowerCAmelCase ) ) lowerCamelCase__ , lowerCamelCase__ = self._get_tensors(9 ) self.assertFalse(criteria(_lowerCAmelCase ,_lowerCAmelCase ) ) lowerCamelCase__ , lowerCamelCase__ = self._get_tensors(10 ) self.assertTrue(criteria(_lowerCAmelCase ,_lowerCAmelCase ) ) def UpperCamelCase_ ( self ): lowerCamelCase__ = MaxLengthCriteria(max_length=10 ) lowerCamelCase__ , lowerCamelCase__ = self._get_tensors(5 ) self.assertFalse(criteria(_lowerCAmelCase ,_lowerCAmelCase ) ) lowerCamelCase__ , lowerCamelCase__ = self._get_tensors(9 ) self.assertFalse(criteria(_lowerCAmelCase ,_lowerCAmelCase ) ) lowerCamelCase__ , lowerCamelCase__ = self._get_tensors(10 ) self.assertTrue(criteria(_lowerCAmelCase ,_lowerCAmelCase ) ) def UpperCamelCase_ ( self ): lowerCamelCase__ = MaxNewTokensCriteria(start_length=5 ,max_new_tokens=5 ) lowerCamelCase__ , lowerCamelCase__ = self._get_tensors(5 ) self.assertFalse(criteria(_lowerCAmelCase ,_lowerCAmelCase ) ) lowerCamelCase__ , lowerCamelCase__ = self._get_tensors(9 ) self.assertFalse(criteria(_lowerCAmelCase ,_lowerCAmelCase ) ) lowerCamelCase__ , lowerCamelCase__ = self._get_tensors(10 ) self.assertTrue(criteria(_lowerCAmelCase ,_lowerCAmelCase ) ) lowerCamelCase__ = StoppingCriteriaList([criteria] ) self.assertEqual(criteria_list.max_length ,10 ) def UpperCamelCase_ ( self ): lowerCamelCase__ , lowerCamelCase__ = self._get_tensors(5 ) lowerCamelCase__ = MaxTimeCriteria(max_time=0.1 ) self.assertFalse(criteria(_lowerCAmelCase ,_lowerCAmelCase ) ) lowerCamelCase__ = MaxTimeCriteria(max_time=0.1 ,initial_timestamp=time.time() - 0.2 ) self.assertTrue(criteria(_lowerCAmelCase ,_lowerCAmelCase ) ) def UpperCamelCase_ ( self ): validate_stopping_criteria(StoppingCriteriaList([MaxLengthCriteria(10 )] ) ,10 ) with self.assertWarns(_lowerCAmelCase ): validate_stopping_criteria(StoppingCriteriaList([MaxLengthCriteria(10 )] ) ,11 ) lowerCamelCase__ = validate_stopping_criteria(StoppingCriteriaList() ,11 ) self.assertEqual(len(_lowerCAmelCase ) ,1 )
50
# flake8: noqa # Lint as: python3 from typing import Dict, List, Optional, Type from .. import config from ..utils import logging from .formatting import ( ArrowFormatter, CustomFormatter, Formatter, PandasFormatter, PythonFormatter, TensorFormatter, format_table, query_table, ) from .np_formatter import NumpyFormatter lowerCAmelCase__ : Tuple =logging.get_logger(__name__) lowerCAmelCase__ : Dict[Optional[str], Type[Formatter]] ={} lowerCAmelCase__ : Dict[Optional[str], str] ={} lowerCAmelCase__ : Dict[Optional[str], Exception] ={} def __lowercase ( a__ , a__ , a__ = None , ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = aliases if aliases is not None else [] if format_type in _FORMAT_TYPES: logger.warning( f"""Overwriting format type '{format_type}' ({_FORMAT_TYPES[format_type].__name__} -> {formatter_cls.__name__})""" ) __SCREAMING_SNAKE_CASE = formatter_cls for alias in set(aliases + [format_type] ): if alias in _FORMAT_TYPES_ALIASES: logger.warning( f"""Overwriting format type alias '{alias}' ({_FORMAT_TYPES_ALIASES[alias]} -> {format_type})""" ) __SCREAMING_SNAKE_CASE = format_type def __lowercase ( a__ , a__ , a__ = None ) -> List[str]: __SCREAMING_SNAKE_CASE = aliases if aliases is not None else [] for alias in set(aliases + [format_type] ): __SCREAMING_SNAKE_CASE = unavailable_error # Here we define all the available formatting functions that can be used by `Dataset.set_format` _register_formatter(PythonFormatter, None, aliases=['''python''']) _register_formatter(ArrowFormatter, '''arrow''', aliases=['''pa''', '''pyarrow''']) _register_formatter(NumpyFormatter, '''numpy''', aliases=['''np''']) _register_formatter(PandasFormatter, '''pandas''', aliases=['''pd''']) _register_formatter(CustomFormatter, '''custom''') if config.TORCH_AVAILABLE: from .torch_formatter import TorchFormatter _register_formatter(TorchFormatter, '''torch''', aliases=['''pt''', '''pytorch''']) else: lowerCAmelCase__ : List[Any] =ValueError('''PyTorch needs to be installed to be able to return PyTorch tensors.''') _register_unavailable_formatter(_torch_error, '''torch''', aliases=['''pt''', '''pytorch''']) if config.TF_AVAILABLE: from .tf_formatter import TFFormatter _register_formatter(TFFormatter, '''tensorflow''', aliases=['''tf''']) else: lowerCAmelCase__ : Optional[Any] =ValueError('''Tensorflow needs to be installed to be able to return Tensorflow tensors.''') _register_unavailable_formatter(_tf_error, '''tensorflow''', aliases=['''tf''']) if config.JAX_AVAILABLE: from .jax_formatter import JaxFormatter _register_formatter(JaxFormatter, '''jax''', aliases=[]) else: lowerCAmelCase__ : Optional[int] =ValueError('''JAX needs to be installed to be able to return JAX arrays.''') _register_unavailable_formatter(_jax_error, '''jax''', aliases=[]) def __lowercase ( a__ ) -> Optional[str]: if format_type in _FORMAT_TYPES_ALIASES: return _FORMAT_TYPES_ALIASES[format_type] else: return format_type def __lowercase ( a__ , **a__ ) -> Formatter: __SCREAMING_SNAKE_CASE = get_format_type_from_alias(a__ ) if format_type in _FORMAT_TYPES: return _FORMAT_TYPES[format_type](**a__ ) if format_type in _FORMAT_TYPES_ALIASES_UNAVAILABLE: raise _FORMAT_TYPES_ALIASES_UNAVAILABLE[format_type] else: raise ValueError( f"""Return type should be None or selected in {list(type for type in _FORMAT_TYPES.keys() if type != None )}, but got '{format_type}'""" )
148
0
'''simple docstring''' def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: int = 5_0 ) -> int: '''simple docstring''' A__ = [1] * (length + 1) for row_length in range(length + 1 ): for tile_length in range(2 , 5 ): for tile_start in range(row_length - tile_length + 1 ): ways_number[row_length] += ways_number[ row_length - tile_start - tile_length ] return ways_number[length] if __name__ == "__main__": print(f"""{solution() = }""")
709
import collections import importlib.util import os import re from pathlib import Path lowerCAmelCase__ = """src/transformers""" # Matches is_xxx_available() lowerCAmelCase__ = re.compile(R"""is\_([a-z_]*)_available()""") # Catches a one-line _import_struct = {xxx} lowerCAmelCase__ = re.compile(R"""^_import_structure\s+=\s+\{([^\}]+)\}""") # Catches a line with a key-values pattern: "bla": ["foo", "bar"] lowerCAmelCase__ = re.compile(R"""\s+\"\S*\":\s+\[([^\]]*)\]""") # Catches a line if not is_foo_available lowerCAmelCase__ = re.compile(R"""^\s*if\s+not\s+is\_[a-z_]*\_available\(\)""") # Catches a line _import_struct["bla"].append("foo") lowerCAmelCase__ = re.compile(R"""^\s*_import_structure\[\"\S*\"\]\.append\(\"(\S*)\"\)""") # Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"] lowerCAmelCase__ = re.compile(R"""^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]""") # Catches a line with an object between quotes and a comma: "MyModel", lowerCAmelCase__ = re.compile("""^\s+\"([^\"]+)\",""") # Catches a line with objects between brackets only: ["foo", "bar"], lowerCAmelCase__ = re.compile("""^\s+\[([^\]]+)\]""") # Catches a line with from foo import bar, bla, boo lowerCAmelCase__ = re.compile(R"""\s+from\s+\S*\s+import\s+([^\(\s].*)\n""") # Catches a line with try: lowerCAmelCase__ = re.compile(R"""^\s*try:""") # Catches a line with else: lowerCAmelCase__ = re.compile(R"""^\s*else:""") def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Any ) -> int: '''simple docstring''' if _re_test_backend.search(SCREAMING_SNAKE_CASE_ ) is None: return None A__ = [b[0] for b in _re_backend.findall(SCREAMING_SNAKE_CASE_ )] backends.sort() return "_and_".join(SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Union[str, Any] ) -> Optional[Any]: '''simple docstring''' with open(SCREAMING_SNAKE_CASE_ , "r" , encoding="utf-8" , newline="\n" ) as f: A__ = f.readlines() A__ = 0 while line_index < len(SCREAMING_SNAKE_CASE_ ) and not lines[line_index].startswith("_import_structure = {" ): line_index += 1 # If this is a traditional init, just return. if line_index >= len(SCREAMING_SNAKE_CASE_ ): return None # First grab the objects without a specific backend in _import_structure A__ = [] while not lines[line_index].startswith("if TYPE_CHECKING" ) and find_backend(lines[line_index] ) is None: A__ = lines[line_index] # If we have everything on a single line, let's deal with it. if _re_one_line_import_struct.search(SCREAMING_SNAKE_CASE_ ): A__ = _re_one_line_import_struct.search(SCREAMING_SNAKE_CASE_ ).groups()[0] A__ = re.findall("\[([^\]]+)\]" , SCREAMING_SNAKE_CASE_ ) for imp in imports: objects.extend([obj[1:-1] for obj in imp.split(", " )] ) line_index += 1 continue A__ = _re_import_struct_key_value.search(SCREAMING_SNAKE_CASE_ ) if single_line_import_search is not None: A__ = [obj[1:-1] for obj in single_line_import_search.groups()[0].split(", " ) if len(SCREAMING_SNAKE_CASE_ ) > 0] objects.extend(SCREAMING_SNAKE_CASE_ ) elif line.startswith(" " * 8 + "\"" ): objects.append(line[9:-3] ) line_index += 1 A__ = {"none": objects} # Let's continue with backend-specific objects in _import_structure while not lines[line_index].startswith("if TYPE_CHECKING" ): # If the line is an if not is_backend_available, we grab all objects associated. A__ = find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: A__ = None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 A__ = [] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(" " * 4 ): A__ = lines[line_index] if _re_import_struct_add_one.search(SCREAMING_SNAKE_CASE_ ) is not None: objects.append(_re_import_struct_add_one.search(SCREAMING_SNAKE_CASE_ ).groups()[0] ) elif _re_import_struct_add_many.search(SCREAMING_SNAKE_CASE_ ) is not None: A__ = _re_import_struct_add_many.search(SCREAMING_SNAKE_CASE_ ).groups()[0].split(", " ) A__ = [obj[1:-1] for obj in imports if len(SCREAMING_SNAKE_CASE_ ) > 0] objects.extend(SCREAMING_SNAKE_CASE_ ) elif _re_between_brackets.search(SCREAMING_SNAKE_CASE_ ) is not None: A__ = _re_between_brackets.search(SCREAMING_SNAKE_CASE_ ).groups()[0].split(", " ) A__ = [obj[1:-1] for obj in imports if len(SCREAMING_SNAKE_CASE_ ) > 0] objects.extend(SCREAMING_SNAKE_CASE_ ) elif _re_quote_object.search(SCREAMING_SNAKE_CASE_ ) is not None: objects.append(_re_quote_object.search(SCREAMING_SNAKE_CASE_ ).groups()[0] ) elif line.startswith(" " * 8 + "\"" ): objects.append(line[9:-3] ) elif line.startswith(" " * 1_2 + "\"" ): objects.append(line[1_3:-3] ) line_index += 1 A__ = objects else: line_index += 1 # At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend A__ = [] while ( line_index < len(SCREAMING_SNAKE_CASE_ ) and find_backend(lines[line_index] ) is None and not lines[line_index].startswith("else" ) ): A__ = lines[line_index] A__ = _re_import.search(SCREAMING_SNAKE_CASE_ ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(", " ) ) elif line.startswith(" " * 8 ): objects.append(line[8:-2] ) line_index += 1 A__ = {"none": objects} # Let's continue with backend-specific objects while line_index < len(SCREAMING_SNAKE_CASE_ ): # If the line is an if is_backend_available, we grab all objects associated. A__ = find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: A__ = None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 A__ = [] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(" " * 8 ): A__ = lines[line_index] A__ = _re_import.search(SCREAMING_SNAKE_CASE_ ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(", " ) ) elif line.startswith(" " * 1_2 ): objects.append(line[1_2:-2] ) line_index += 1 A__ = objects else: line_index += 1 return import_dict_objects, type_hint_objects def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Dict , SCREAMING_SNAKE_CASE_: List[Any] ) -> Optional[int]: '''simple docstring''' def find_duplicates(SCREAMING_SNAKE_CASE_: str ): return [k for k, v in collections.Counter(SCREAMING_SNAKE_CASE_ ).items() if v > 1] if list(import_dict_objects.keys() ) != list(type_hint_objects.keys() ): return ["Both sides of the init do not have the same backends!"] A__ = [] for key in import_dict_objects.keys(): A__ = find_duplicates(import_dict_objects[key] ) if duplicate_imports: errors.append(F'Duplicate _import_structure definitions for: {duplicate_imports}' ) A__ = find_duplicates(type_hint_objects[key] ) if duplicate_type_hints: errors.append(F'Duplicate TYPE_CHECKING objects for: {duplicate_type_hints}' ) if sorted(set(import_dict_objects[key] ) ) != sorted(set(type_hint_objects[key] ) ): A__ = "base imports" if key == "none" else F'{key} backend' errors.append(F'Differences for {name}:' ) for a in type_hint_objects[key]: if a not in import_dict_objects[key]: errors.append(F' {a} in TYPE_HINT but not in _import_structure.' ) for a in import_dict_objects[key]: if a not in type_hint_objects[key]: errors.append(F' {a} in _import_structure but not in TYPE_HINT.' ) return errors def lowerCAmelCase__ ( ) -> Dict: '''simple docstring''' A__ = [] for root, _, files in os.walk(SCREAMING_SNAKE_CASE_ ): if "__init__.py" in files: A__ = os.path.join(SCREAMING_SNAKE_CASE_ , "__init__.py" ) A__ = parse_init(SCREAMING_SNAKE_CASE_ ) if objects is not None: A__ = analyze_results(*SCREAMING_SNAKE_CASE_ ) if len(SCREAMING_SNAKE_CASE_ ) > 0: A__ = F'Problem in {fname}, both halves do not define the same objects.\n{errors[0]}' failures.append("\n".join(SCREAMING_SNAKE_CASE_ ) ) if len(SCREAMING_SNAKE_CASE_ ) > 0: raise ValueError("\n\n".join(SCREAMING_SNAKE_CASE_ ) ) def lowerCAmelCase__ ( ) -> Optional[Any]: '''simple docstring''' A__ = [] for path, directories, files in os.walk(SCREAMING_SNAKE_CASE_ ): for folder in directories: # Ignore private modules if folder.startswith("_" ): directories.remove(SCREAMING_SNAKE_CASE_ ) continue # Ignore leftovers from branches (empty folders apart from pycache) if len(list((Path(SCREAMING_SNAKE_CASE_ ) / folder).glob("*.py" ) ) ) == 0: continue A__ = str((Path(SCREAMING_SNAKE_CASE_ ) / folder).relative_to(SCREAMING_SNAKE_CASE_ ) ) A__ = short_path.replace(os.path.sep , "." ) submodules.append(SCREAMING_SNAKE_CASE_ ) for fname in files: if fname == "__init__.py": continue A__ = str((Path(SCREAMING_SNAKE_CASE_ ) / fname).relative_to(SCREAMING_SNAKE_CASE_ ) ) A__ = short_path.replace(".py" , "" ).replace(os.path.sep , "." ) if len(submodule.split("." ) ) == 1: submodules.append(SCREAMING_SNAKE_CASE_ ) return submodules lowerCAmelCase__ = [ """convert_pytorch_checkpoint_to_tf2""", """modeling_flax_pytorch_utils""", ] def lowerCAmelCase__ ( ) -> Optional[int]: '''simple docstring''' A__ = importlib.util.spec_from_file_location( "transformers" , os.path.join(SCREAMING_SNAKE_CASE_ , "__init__.py" ) , submodule_search_locations=[PATH_TO_TRANSFORMERS] , ) A__ = spec.loader.load_module() A__ = [ module for module in get_transformers_submodules() if module not in IGNORE_SUBMODULES and module not in transformers._import_structure.keys() ] if len(SCREAMING_SNAKE_CASE_ ) > 0: A__ = "\n".join(F'- {module}' for module in module_not_registered ) raise ValueError( "The following submodules are not properly registered in the main init of Transformers:\n" F'{list_of_modules}\n' "Make sure they appear somewhere in the keys of `_import_structure` with an empty list as value." ) if __name__ == "__main__": check_all_inits() check_submodules()
626
0
'''simple docstring''' def A__ ( __lowerCAmelCase : int ): lowerCamelCase__ = (1 + 24 * n) ** 0.5 return ((1 + root) / 6) % 1 == 0 def A__ ( __lowerCAmelCase : int = 5000 ): lowerCamelCase__ = [(i * (3 * i - 1)) // 2 for i in range(1 , __lowerCAmelCase )] for i, pentagonal_i in enumerate(__lowerCAmelCase ): for j in range(__lowerCAmelCase , len(__lowerCAmelCase ) ): lowerCamelCase__ = pentagonal_nums[j] lowerCamelCase__ = pentagonal_i + pentagonal_j lowerCamelCase__ = pentagonal_j - pentagonal_i if is_pentagonal(__lowerCAmelCase ) and is_pentagonal(__lowerCAmelCase ): return b return -1 if __name__ == "__main__": print(F'{solution() = }')
50
"""simple docstring""" def UpperCamelCase ( _A ) -> int: lowercase : Dict = 0 while num > 0: digit_sum += num % 10 num //= 10 return digit_sum def UpperCamelCase ( _A = 100 ) -> int: lowercase : Union[str, Any] = 1 lowercase : Tuple = 2 for i in range(2 , max_n + 1 ): lowercase : Any = pre_numerator lowercase : Dict = 2 * i // 3 if i % 3 == 0 else 1 lowercase : Optional[Any] = cur_numerator lowercase : str = e_cont * pre_numerator + temp return sum_digits(_A ) if __name__ == "__main__": print(F'{solution() = }')
264
0
from typing import List, Optional, Union import torch from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) UpperCAmelCase = logging.get_logger(__name__) # pylint: disable=invalid-name UpperCAmelCase = """ Examples: ```py >>> import torch >>> import numpy as np >>> from diffusers import KandinskyV22PriorPipeline, KandinskyV22ControlnetPipeline >>> from transformers import pipeline >>> from diffusers.utils import load_image >>> def make_hint(image, depth_estimator): ... image = depth_estimator(image)[\"depth\"] ... image = np.array(image) ... image = image[:, :, None] ... image = np.concatenate([image, image, image], axis=2) ... detected_map = torch.from_numpy(image).float() / 255.0 ... hint = detected_map.permute(2, 0, 1) ... return hint >>> depth_estimator = pipeline(\"depth-estimation\") >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained( ... \"kandinsky-community/kandinsky-2-2-prior\", torch_dtype=torch.float16 ... ) >>> pipe_prior = pipe_prior.to(\"cuda\") >>> pipe = KandinskyV22ControlnetPipeline.from_pretrained( ... \"kandinsky-community/kandinsky-2-2-controlnet-depth\", torch_dtype=torch.float16 ... ) >>> pipe = pipe.to(\"cuda\") >>> img = load_image( ... \"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main\" ... \"/kandinsky/cat.png\" ... ).resize((768, 768)) >>> hint = make_hint(img, depth_estimator).unsqueeze(0).half().to(\"cuda\") >>> prompt = \"A robot, 4k photo\" >>> negative_prior_prompt = \"lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature\" >>> generator = torch.Generator(device=\"cuda\").manual_seed(43) >>> image_emb, zero_image_emb = pipe_prior( ... prompt=prompt, negative_prompt=negative_prior_prompt, generator=generator ... ).to_tuple() >>> images = pipe( ... image_embeds=image_emb, ... negative_image_embeds=zero_image_emb, ... hint=hint, ... num_inference_steps=50, ... generator=generator, ... height=768, ... width=768, ... ).images >>> images[0].save(\"robot_cat.png\") ``` """ def A_ ( __a : str , __a : int , __a : Dict=8 ): """simple docstring""" a__ = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 a__ = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor class __snake_case ( SCREAMING_SNAKE_CASE): '''simple docstring''' def __init__( self , a_ , a_ , a_ , ): super().__init__() self.register_modules( unet=__UpperCamelCase , scheduler=__UpperCamelCase , movq=__UpperCamelCase , ) a__ = 2 ** (len(self.movq.config.block_out_channels ) - 1) def _a ( self , a_ , a_ , a_ , a_ , a_ , a_ ): if latents is None: a__ = randn_tensor(__UpperCamelCase , generator=__UpperCamelCase , device=__UpperCamelCase , dtype=__UpperCamelCase ) else: if latents.shape != shape: raise ValueError(F'''Unexpected latents shape, got {latents.shape}, expected {shape}''' ) a__ = latents.to(__UpperCamelCase ) a__ = latents * scheduler.init_noise_sigma return latents def _a ( self , a_=0 ): if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("""Please install accelerate via `pip install accelerate`""" ) a__ = torch.device(F'''cuda:{gpu_id}''' ) a__ = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(__UpperCamelCase , __UpperCamelCase ) def _a ( self , a_=0 ): if is_accelerate_available() and is_accelerate_version(""">=""" , """0.17.0.dev0""" ): from accelerate import cpu_offload_with_hook else: raise ImportError("""`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.""" ) a__ = torch.device(F'''cuda:{gpu_id}''' ) if self.device.type != "cpu": self.to("""cpu""" , silence_dtype_warnings=__UpperCamelCase ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) a__ = None for cpu_offloaded_model in [self.unet, self.movq]: a__ , a__ = cpu_offload_with_hook(__UpperCamelCase , __UpperCamelCase , prev_module_hook=__UpperCamelCase ) # We'll offload the last model manually. a__ = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def _a ( self ): if not hasattr(self.unet , """_hf_hook""" ): return self.device for module in self.unet.modules(): if ( hasattr(__UpperCamelCase , """_hf_hook""" ) and hasattr(module._hf_hook , """execution_device""" ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(__UpperCamelCase ) def __call__( self , a_ , a_ , a_ , a_ = 512 , a_ = 512 , a_ = 100 , a_ = 4.0 , a_ = 1 , a_ = None , a_ = None , a_ = "pil" , a_ = True , ): a__ = self._execution_device a__ = guidance_scale > 1.0 if isinstance(__UpperCamelCase , __UpperCamelCase ): a__ = torch.cat(__UpperCamelCase , dim=0 ) if isinstance(__UpperCamelCase , __UpperCamelCase ): a__ = torch.cat(__UpperCamelCase , dim=0 ) if isinstance(__UpperCamelCase , __UpperCamelCase ): a__ = torch.cat(__UpperCamelCase , dim=0 ) a__ = image_embeds.shape[0] * num_images_per_prompt if do_classifier_free_guidance: a__ = image_embeds.repeat_interleave(__UpperCamelCase , dim=0 ) a__ = negative_image_embeds.repeat_interleave(__UpperCamelCase , dim=0 ) a__ = hint.repeat_interleave(__UpperCamelCase , dim=0 ) a__ = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=__UpperCamelCase ) a__ = torch.cat([hint, hint] , dim=0 ).to(dtype=self.unet.dtype , device=__UpperCamelCase ) self.scheduler.set_timesteps(__UpperCamelCase , device=__UpperCamelCase ) a__ = self.scheduler.timesteps a__ = self.movq.config.latent_channels a__ , a__ = downscale_height_and_width(__UpperCamelCase , __UpperCamelCase , self.movq_scale_factor ) # create initial latent a__ = self.prepare_latents( (batch_size, num_channels_latents, height, width) , image_embeds.dtype , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , self.scheduler , ) for i, t in enumerate(self.progress_bar(__UpperCamelCase ) ): # expand the latents if we are doing classifier free guidance a__ = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents a__ = {"""image_embeds""": image_embeds, """hint""": hint} a__ = self.unet( sample=__UpperCamelCase , timestep=__UpperCamelCase , encoder_hidden_states=__UpperCamelCase , added_cond_kwargs=__UpperCamelCase , return_dict=__UpperCamelCase , )[0] if do_classifier_free_guidance: a__ , a__ = noise_pred.split(latents.shape[1] , dim=1 ) a__ , a__ = noise_pred.chunk(2 ) a__ , a__ = variance_pred.chunk(2 ) a__ = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) a__ = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , """variance_type""" ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): a__ , a__ = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 a__ = self.scheduler.step( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , generator=__UpperCamelCase , )[0] # post-processing a__ = self.movq.decode(__UpperCamelCase , force_not_quantize=__UpperCamelCase )["""sample"""] if output_type not in ["pt", "np", "pil"]: raise ValueError(F'''Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}''' ) if output_type in ["np", "pil"]: a__ = image * 0.5 + 0.5 a__ = image.clamp(0 , 1 ) a__ = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": a__ = self.numpy_to_pil(__UpperCamelCase ) if not return_dict: return (image,) return ImagePipelineOutput(images=__UpperCamelCase )
715
import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.local_sgd import LocalSGD ######################################################################## # This is a fully working simple example to use Accelerate # with LocalSGD, which is a method to synchronize model # parameters every K batches. It is different, but complementary # to gradient accumulation. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## UpperCAmelCase = 16 UpperCAmelCase = 32 def A_ ( __a : Accelerator , __a : int = 16 ): """simple docstring""" a__ = AutoTokenizer.from_pretrained("""bert-base-cased""" ) a__ = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(__a : int ): # max_length=None => use the model max length (it's actually the default) a__ = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=__a , max_length=__a ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): a__ = datasets.map( __a , batched=__a , remove_columns=["""idx""", """sentence1""", """sentence2"""] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library a__ = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(__a : Optional[int] ): # On TPU it's best to pad everything to the same length or training will be very slow. a__ = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": a__ = 16 elif accelerator.mixed_precision != "no": a__ = 8 else: a__ = None return tokenizer.pad( __a , padding="""longest""" , max_length=__a , pad_to_multiple_of=__a , return_tensors="""pt""" , ) # Instantiate dataloaders. a__ = DataLoader( tokenized_datasets["""train"""] , shuffle=__a , collate_fn=__a , batch_size=__a ) a__ = DataLoader( tokenized_datasets["""validation"""] , shuffle=__a , collate_fn=__a , batch_size=__a ) return train_dataloader, eval_dataloader # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""", None) == "1": from accelerate.test_utils.training import mocked_dataloaders UpperCAmelCase = mocked_dataloaders # noqa: F811 def A_ ( __a : List[Any] , __a : Tuple ): """simple docstring""" # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""" , __a ) == "1": a__ = 2 # New Code # a__ = int(args.gradient_accumulation_steps ) a__ = int(args.local_sgd_steps ) # Initialize accelerator a__ = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , gradient_accumulation_steps=__a ) if accelerator.distributed_type not in [DistributedType.NO, DistributedType.MULTI_CPU, DistributedType.MULTI_GPU]: raise NotImplementedError("""LocalSGD is supported only for CPUs and GPUs (no DeepSpeed or MegatronLM)""" ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs a__ = config["""lr"""] a__ = int(config["""num_epochs"""] ) a__ = int(config["""seed"""] ) a__ = int(config["""batch_size"""] ) a__ = evaluate.load("""glue""" , """mrpc""" ) set_seed(__a ) a__ , a__ = get_dataloaders(__a , __a ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) a__ = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" , return_dict=__a ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). a__ = model.to(accelerator.device ) # Instantiate optimizer a__ = AdamW(params=model.parameters() , lr=__a ) # Instantiate scheduler a__ = get_linear_schedule_with_warmup( optimizer=__a , num_warmup_steps=100 , num_training_steps=(len(__a ) * num_epochs) , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. a__ , a__ , a__ , a__ , a__ = accelerator.prepare( __a , __a , __a , __a , __a ) # Now we train the model for epoch in range(__a ): model.train() with LocalSGD( accelerator=__a , model=__a , local_sgd_steps=__a , enabled=local_sgd_steps is not None ) as local_sgd: for step, batch in enumerate(__a ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) # New code # # We use the new `accumulate` context manager to perform gradient accumulation # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. with accelerator.accumulate(__a ): a__ = model(**__a ) a__ = output.loss accelerator.backward(__a ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() # LocalSGD-specific line local_sgd.step() model.eval() for step, batch in enumerate(__a ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): a__ = model(**__a ) a__ = outputs.logits.argmax(dim=-1 ) a__ , a__ = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=__a , references=__a , ) a__ = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'''epoch {epoch}:''' , __a ) def A_ ( ): """simple docstring""" a__ = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" , type=__a , default=__a , choices=["""no""", """fp16""", """bf16""", """fp8"""] , help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" , ) # New Code # parser.add_argument( """--gradient_accumulation_steps""" , type=__a , default=1 , help="""The number of minibatches to be ran before gradients are accumulated.""" , ) parser.add_argument( """--local_sgd_steps""" , type=__a , default=8 , help="""Number of local SGD steps or None to disable local SGD""" ) parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" ) a__ = parser.parse_args() a__ = {"""lr""": 2e-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16} training_function(__a , __a ) if __name__ == "__main__": main()
351
0
"""simple docstring""" import math class __A : '''simple docstring''' def __init__( self : List[Any] ,_snake_case : Optional[int]=0 ) -> List[str]: # a graph with Node 0,1,...,N-1 """simple docstring""" lowercase__ : Optional[Any] = n lowercase__ : Tuple = [ [math.inf for j in range(0 ,_snake_case )] for i in range(0 ,_snake_case ) ] # adjacency matrix for weight lowercase__ : List[Any] = [ [math.inf for j in range(0 ,_snake_case )] for i in range(0 ,_snake_case ) ] # dp[i][j] stores minimum distance from i to j def UpperCAmelCase ( self : Union[str, Any] ,_snake_case : Any ,_snake_case : Union[str, Any] ,_snake_case : Union[str, Any] ) -> Optional[Any]: """simple docstring""" lowercase__ : List[str] = w def UpperCAmelCase ( self : Dict ) -> Optional[Any]: """simple docstring""" for k in range(0 ,self.n ): for i in range(0 ,self.n ): for j in range(0 ,self.n ): lowercase__ : int = min(self.dp[i][j] ,self.dp[i][k] + self.dp[k][j] ) def UpperCAmelCase ( self : Dict ,_snake_case : Optional[int] ,_snake_case : Tuple ) -> Tuple: """simple docstring""" return self.dp[u][v] if __name__ == "__main__": lowerCAmelCase_ = Graph(5) graph.add_edge(0, 2, 9) graph.add_edge(0, 4, 10) graph.add_edge(1, 3, 5) graph.add_edge(2, 3, 7) graph.add_edge(3, 0, 10) graph.add_edge(3, 1, 2) graph.add_edge(3, 2, 1) graph.add_edge(3, 4, 6) graph.add_edge(4, 1, 3) graph.add_edge(4, 2, 4) graph.add_edge(4, 3, 9) graph.floyd_warshall() graph.show_min(1, 4) graph.show_min(0, 3)
560
"""simple docstring""" import argparse import os import pickle import sys import torch from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() # We do this to be able to load python 2 datasets pickles # See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918 lowerCAmelCase_ = data_utils.TransfoXLTokenizer lowerCAmelCase_ = data_utils.TransfoXLCorpus lowerCAmelCase_ = data_utils lowerCAmelCase_ = data_utils def __UpperCAmelCase ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> List[Any]: if transfo_xl_dataset_file: # Convert a pre-processed corpus (see original TensorFlow repo) with open(__lowerCamelCase , '''rb''' ) as fp: lowercase__ : Dict = pickle.load(__lowerCamelCase , encoding='''latin1''' ) # Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term) lowercase__ : int = pytorch_dump_folder_path + '''/''' + VOCAB_FILES_NAMES['''pretrained_vocab_file'''] print(f"""Save vocabulary to {pytorch_vocab_dump_path}""" ) lowercase__ : List[Any] = corpus.vocab.__dict__ torch.save(__lowerCamelCase , __lowerCamelCase ) lowercase__ : int = corpus.__dict__ corpus_dict_no_vocab.pop('''vocab''' , __lowerCamelCase ) lowercase__ : List[str] = pytorch_dump_folder_path + '''/''' + CORPUS_NAME print(f"""Save dataset to {pytorch_dataset_dump_path}""" ) torch.save(__lowerCamelCase , __lowerCamelCase ) if tf_checkpoint_path: # Convert a pre-trained TensorFlow model lowercase__ : Tuple = os.path.abspath(__lowerCamelCase ) lowercase__ : List[Any] = os.path.abspath(__lowerCamelCase ) print(f"""Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.""" ) # Initialise PyTorch model if transfo_xl_config_file == "": lowercase__ : Tuple = TransfoXLConfig() else: lowercase__ : List[str] = TransfoXLConfig.from_json_file(__lowerCamelCase ) print(f"""Building PyTorch model from configuration: {config}""" ) lowercase__ : Union[str, Any] = TransfoXLLMHeadModel(__lowerCamelCase ) lowercase__ : List[Any] = load_tf_weights_in_transfo_xl(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # Save pytorch-model lowercase__ : Optional[int] = os.path.join(__lowerCamelCase , __lowerCamelCase ) lowercase__ : Dict = os.path.join(__lowerCamelCase , __lowerCamelCase ) print(f"""Save PyTorch model to {os.path.abspath(__lowerCamelCase )}""" ) torch.save(model.state_dict() , __lowerCamelCase ) print(f"""Save configuration file to {os.path.abspath(__lowerCamelCase )}""" ) with open(__lowerCamelCase , '''w''' , encoding='''utf-8''' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": lowerCAmelCase_ = argparse.ArgumentParser() parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the folder to store the PyTorch model or dataset/vocab.', ) parser.add_argument( '--tf_checkpoint_path', default='', type=str, help='An optional path to a TensorFlow checkpoint path to be converted.', ) parser.add_argument( '--transfo_xl_config_file', default='', type=str, help=( 'An optional config json file corresponding to the pre-trained BERT model. \n' 'This specifies the model architecture.' ), ) parser.add_argument( '--transfo_xl_dataset_file', default='', type=str, help='An optional dataset file to be converted in a vocabulary.', ) lowerCAmelCase_ = parser.parse_args() convert_transfo_xl_checkpoint_to_pytorch( args.tf_checkpoint_path, args.transfo_xl_config_file, args.pytorch_dump_folder_path, args.transfo_xl_dataset_file, )
560
1
"""simple docstring""" import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging __lowercase : Any = logging.get_logger(__name__) __lowercase : List[Any] = { "facebook/wav2vec2-base-960h": "https://huggingface.co/facebook/wav2vec2-base-960h/resolve/main/config.json", # See all Wav2Vec2 models at https://huggingface.co/models?filter=wav2vec2 } class _A ( _UpperCAmelCase ): """simple docstring""" UpperCamelCase_ : Optional[int] = '''wav2vec2''' def __init__( self : Any , A_ : str=32 , A_ : Dict=768 , A_ : int=12 , A_ : Tuple=12 , A_ : Optional[Any]=3_072 , A_ : List[Any]="gelu" , A_ : int=0.1 , A_ : Any=0.1 , A_ : Optional[int]=0.1 , A_ : Optional[Any]=0.0 , A_ : Union[str, Any]=0.0 , A_ : List[Any]=0.1 , A_ : List[Any]=0.1 , A_ : Union[str, Any]=0.02 , A_ : List[str]=1E-5 , A_ : Optional[int]="group" , A_ : str="gelu" , A_ : Union[str, Any]=(512, 512, 512, 512, 512, 512, 512) , A_ : Union[str, Any]=(5, 2, 2, 2, 2, 2, 2) , A_ : int=(10, 3, 3, 3, 3, 2, 2) , A_ : str=False , A_ : Union[str, Any]=128 , A_ : str=16 , A_ : str=False , A_ : str=True , A_ : List[Any]=0.05 , A_ : List[Any]=10 , A_ : Any=2 , A_ : Optional[int]=0.0 , A_ : Dict=10 , A_ : Optional[int]=0 , A_ : int=320 , A_ : Optional[int]=2 , A_ : Tuple=0.1 , A_ : Optional[Any]=100 , A_ : Tuple=256 , A_ : Dict=256 , A_ : Union[str, Any]=0.1 , A_ : Tuple="sum" , A_ : Any=False , A_ : List[str]=False , A_ : Union[str, Any]=256 , A_ : Optional[Any]=(512, 512, 512, 512, 1_500) , A_ : List[Any]=(5, 3, 3, 1, 1) , A_ : Dict=(1, 2, 3, 1, 1) , A_ : Tuple=512 , A_ : List[str]=0 , A_ : Any=1 , A_ : Dict=2 , A_ : Optional[Any]=False , A_ : List[Any]=3 , A_ : str=2 , A_ : Tuple=3 , A_ : Dict=None , A_ : Tuple=None , **A_ : Any , ) -> Union[str, Any]: super().__init__(**A_ , pad_token_id=A_ , bos_token_id=A_ , eos_token_id=A_ ) __snake_case = hidden_size __snake_case = feat_extract_norm __snake_case = feat_extract_activation __snake_case = list(A_ ) __snake_case = list(A_ ) __snake_case = list(A_ ) __snake_case = conv_bias __snake_case = num_conv_pos_embeddings __snake_case = num_conv_pos_embedding_groups __snake_case = len(self.conv_dim ) __snake_case = num_hidden_layers __snake_case = intermediate_size __snake_case = hidden_act __snake_case = num_attention_heads __snake_case = hidden_dropout __snake_case = attention_dropout __snake_case = activation_dropout __snake_case = feat_proj_dropout __snake_case = final_dropout __snake_case = layerdrop __snake_case = layer_norm_eps __snake_case = initializer_range __snake_case = vocab_size __snake_case = do_stable_layer_norm __snake_case = use_weighted_layer_sum if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( '''Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==''' ''' `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =''' f" {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`," f" `len(config.conv_kernel) = {len(self.conv_kernel )}`." ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 __snake_case = apply_spec_augment __snake_case = mask_time_prob __snake_case = mask_time_length __snake_case = mask_time_min_masks __snake_case = mask_feature_prob __snake_case = mask_feature_length __snake_case = mask_feature_min_masks # parameters for pretraining with codevector quantized representations __snake_case = num_codevectors_per_group __snake_case = num_codevector_groups __snake_case = contrastive_logits_temperature __snake_case = feat_quantizer_dropout __snake_case = num_negatives __snake_case = codevector_dim __snake_case = proj_codevector_dim __snake_case = diversity_loss_weight # ctc loss __snake_case = ctc_loss_reduction __snake_case = ctc_zero_infinity # adapter __snake_case = add_adapter __snake_case = adapter_kernel_size __snake_case = adapter_stride __snake_case = num_adapter_layers __snake_case = output_hidden_size or hidden_size __snake_case = adapter_attn_dim # SequenceClassification-specific parameter. Feel free to ignore for other classes. __snake_case = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. __snake_case = list(A_ ) __snake_case = list(A_ ) __snake_case = list(A_ ) __snake_case = xvector_output_dim @property def lowercase ( self : Optional[Any] ) -> str: return functools.reduce(operator.mul , self.conv_stride , 1 )
93
"""simple docstring""" import qiskit def SCREAMING_SNAKE_CASE ( snake_case, snake_case): __snake_case = qiskit.Aer.get_backend('''aer_simulator''') # Create a Quantum Circuit acting on the q register __snake_case = qiskit.QuantumCircuit(snake_case, snake_case) # Map the quantum measurement to the classical bits circuit.measure([0], [0]) # Execute the circuit on the simulator __snake_case = qiskit.execute(snake_case, snake_case, shots=10_00) # Return the histogram data of the results of the experiment. return job.result().get_counts(snake_case) if __name__ == "__main__": print(F"""Total count for various states are: {single_qubit_measure(1, 1)}""")
93
1
"""simple docstring""" import re def lowerCamelCase ( _snake_case ): if len(re.findall('[ATCG]' ,_snake_case ) ) != len(_snake_case ): raise ValueError('Invalid Strand' ) return dna.translate(dna.maketrans('ATCG' ,'TAGC' ) ) if __name__ == "__main__": import doctest doctest.testmod()
110
"""simple docstring""" import argparse import os import torch from transformers import FlavaConfig, FlavaForPreTraining from transformers.models.flava.convert_dalle_to_flava_codebook import convert_dalle_checkpoint def __UpperCAmelCase ( __UpperCamelCase ): # encoder.embeddings are double copied in original FLAVA return sum(param.float().sum() if '''encoder.embeddings''' not in key else 0 for key, param in state_dict.items() ) def __UpperCAmelCase ( __UpperCamelCase , __UpperCamelCase ): __lowercase : Any = {} for key, value in state_dict.items(): if "text_encoder.embeddings" in key or "image_encoder.embeddings" in key: continue __lowercase : Dict = key.replace('''heads.cmd.mim_head.cls.predictions''' , '''mmm_image_head''' ) __lowercase : Dict = key.replace('''heads.cmd.mlm_head.cls.predictions''' , '''mmm_text_head''' ) __lowercase : Dict = key.replace('''heads.cmd.itm_head.cls''' , '''itm_head''' ) __lowercase : Tuple = key.replace('''heads.cmd.itm_head.pooler''' , '''itm_head.pooler''' ) __lowercase : Dict = key.replace('''heads.cmd.clip_head.logit_scale''' , '''flava.logit_scale''' ) __lowercase : Optional[int] = key.replace('''heads.fairseq_mlm.cls.predictions''' , '''mlm_head''' ) __lowercase : Optional[int] = key.replace('''heads.imagenet.mim_head.cls.predictions''' , '''mim_head''' ) __lowercase : Union[str, Any] = key.replace('''mm_text_projection''' , '''flava.text_to_mm_projection''' ) __lowercase : str = key.replace('''mm_image_projection''' , '''flava.image_to_mm_projection''' ) __lowercase : Dict = key.replace('''image_encoder.module''' , '''flava.image_model''' ) __lowercase : str = key.replace('''text_encoder.module''' , '''flava.text_model''' ) __lowercase : Dict = key.replace('''mm_encoder.module.encoder.cls_token''' , '''flava.multimodal_model.cls_token''' ) __lowercase : Union[str, Any] = key.replace('''mm_encoder.module''' , '''flava.multimodal_model''' ) __lowercase : List[str] = key.replace('''text_projection''' , '''flava.text_projection''' ) __lowercase : Any = key.replace('''image_projection''' , '''flava.image_projection''' ) __lowercase : Tuple = value.float() for key, value in codebook_state_dict.items(): __lowercase : int = value return upgrade @torch.no_grad() def __UpperCAmelCase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase=None ): if config_path is not None: __lowercase : Union[str, Any] = FlavaConfig.from_pretrained(__UpperCamelCase ) else: __lowercase : Union[str, Any] = FlavaConfig() __lowercase : Any = FlavaForPreTraining(__UpperCamelCase ).eval() __lowercase : Any = convert_dalle_checkpoint(__UpperCamelCase , __UpperCamelCase , save_checkpoint=__UpperCamelCase ) if os.path.exists(__UpperCamelCase ): __lowercase : Optional[Any] = torch.load(__UpperCamelCase , map_location='''cpu''' ) else: __lowercase : List[Any] = torch.hub.load_state_dict_from_url(__UpperCamelCase , map_location='''cpu''' ) __lowercase : Optional[int] = upgrade_state_dict(__UpperCamelCase , __UpperCamelCase ) hf_model.load_state_dict(__UpperCamelCase ) __lowercase : Union[str, Any] = hf_model.state_dict() __lowercase : Optional[Any] = count_parameters(__UpperCamelCase ) __lowercase : List[Any] = count_parameters(__UpperCamelCase ) + count_parameters(__UpperCamelCase ) assert torch.allclose(__UpperCamelCase , __UpperCamelCase , atol=1e-3 ) hf_model.save_pretrained(__UpperCamelCase ) if __name__ == "__main__": a_ = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to flava checkpoint') parser.add_argument('--codebook_path', default=None, type=str, help='Path to flava codebook checkpoint') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') a_ = parser.parse_args() convert_flava_checkpoint(args.checkpoint_path, args.codebook_path, args.pytorch_dump_folder_path, args.config_path)
76
0
'''simple docstring''' import pytest import datasets.config from datasets.utils.info_utils import is_small_dataset @pytest.mark.parametrize('''dataset_size''' , [None, 400 * 2**20, 600 * 2**20] ) @pytest.mark.parametrize('''input_in_memory_max_size''' , ['''default''', 0, 100 * 2**20, 900 * 2**20] ) def _a ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> List[str]: """simple docstring""" if input_in_memory_max_size != "default": monkeypatch.setattr(datasets.config , '''IN_MEMORY_MAX_SIZE''' , UpperCAmelCase ) lowerCamelCase__ : Dict = datasets.config.IN_MEMORY_MAX_SIZE if input_in_memory_max_size == "default": assert in_memory_max_size == 0 else: assert in_memory_max_size == input_in_memory_max_size if dataset_size and in_memory_max_size: lowerCamelCase__ : int = dataset_size < in_memory_max_size else: lowerCamelCase__ : List[str] = False lowerCamelCase__ : str = is_small_dataset(UpperCAmelCase ) assert result == expected
700
import json from typing import Iterator, List, Union from tokenizers import AddedToken, Regex, Tokenizer, decoders, normalizers, pre_tokenizers, trainers from tokenizers.implementations.base_tokenizer import BaseTokenizer from tokenizers.models import Unigram from tokenizers.processors import TemplateProcessing class __SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ): def __init__( self : Tuple , A : str = "▁" , A : bool = True , A : Union[str, AddedToken] = "<unk>" , A : Union[str, AddedToken] = "</s>" , A : Union[str, AddedToken] = "<pad>" , ) ->Optional[int]: lowerCamelCase__ : str = { '''pad''': {'''id''': 0, '''token''': pad_token}, '''eos''': {'''id''': 1, '''token''': eos_token}, '''unk''': {'''id''': 2, '''token''': unk_token}, } lowerCamelCase__ : Optional[int] = [None] * len(self.special_tokens ) for token_dict in self.special_tokens.values(): lowerCamelCase__ : Optional[Any] = token_dict['''token'''] lowerCamelCase__ : int = Tokenizer(Unigram() ) lowerCamelCase__ : List[Any] = normalizers.Sequence( [ normalizers.Nmt(), normalizers.NFKC(), normalizers.Replace(Regex(''' {2,}''' ) , ''' ''' ), normalizers.Lowercase(), ] ) lowerCamelCase__ : Dict = pre_tokenizers.Sequence( [ pre_tokenizers.Metaspace(replacement=A , add_prefix_space=A ), pre_tokenizers.Digits(individual_digits=A ), pre_tokenizers.Punctuation(), ] ) lowerCamelCase__ : Optional[int] = decoders.Metaspace(replacement=A , add_prefix_space=A ) lowerCamelCase__ : Any = TemplateProcessing( single=F"$A {self.special_tokens['eos']['token']}" , special_tokens=[(self.special_tokens['''eos''']['''token'''], self.special_tokens['''eos''']['''id'''])] , ) lowerCamelCase__ : List[str] = { '''model''': '''SentencePieceUnigram''', '''replacement''': replacement, '''add_prefix_space''': add_prefix_space, } super().__init__(A , A ) def __lowerCamelCase ( self : List[str] , A : Union[str, List[str]] , A : int = 8_0_0_0 , A : bool = True , ) ->Optional[int]: lowerCamelCase__ : Optional[int] = trainers.UnigramTrainer( vocab_size=A , special_tokens=self.special_tokens_list , show_progress=A , ) if isinstance(A , A ): lowerCamelCase__ : Union[str, Any] = [files] self._tokenizer.train(A , trainer=A ) self.add_unk_id() def __lowerCamelCase ( self : Union[str, Any] , A : Union[Iterator[str], Iterator[Iterator[str]]] , A : int = 8_0_0_0 , A : bool = True , ) ->List[Any]: lowerCamelCase__ : str = trainers.UnigramTrainer( vocab_size=A , special_tokens=self.special_tokens_list , show_progress=A , ) self._tokenizer.train_from_iterator(A , trainer=A ) self.add_unk_id() def __lowerCamelCase ( self : int ) ->Union[str, Any]: lowerCamelCase__ : Union[str, Any] = json.loads(self._tokenizer.to_str() ) lowerCamelCase__ : str = self.special_tokens['''unk''']['''id'''] lowerCamelCase__ : List[Any] = Tokenizer.from_str(json.dumps(A ) )
130
0
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Image from .base import TaskTemplate @dataclass(frozen=snake_case ) class _A ( snake_case ): '''simple docstring''' __lowerCamelCase : str = field(default='''image-classification''' , metadata={'''include_in_asdict_even_if_is_default''': True} ) __lowerCamelCase : ClassVar[Features] = Features({'''image''': Image()} ) __lowerCamelCase : ClassVar[Features] = Features({'''labels''': ClassLabel} ) __lowerCamelCase : str = "image" __lowerCamelCase : str = "labels" def snake_case_ ( self ,SCREAMING_SNAKE_CASE_ ): '''simple docstring''' if self.label_column not in features: raise ValueError(F"""Column {self.label_column} is not present in features.""" ) if not isinstance(features[self.label_column] ,SCREAMING_SNAKE_CASE_ ): raise ValueError(F"""Column {self.label_column} is not a ClassLabel.""" ) snake_case : Any = copy.deepcopy(self ) snake_case : List[str] = self.label_schema.copy() snake_case : Union[str, Any] = features[self.label_column] snake_case : List[str] = label_schema return task_template @property def snake_case_ ( self ): '''simple docstring''' return { self.image_column: "image", self.label_column: "labels", }
36
"""simple docstring""" from collections import deque from math import floor from random import random from time import time class A__ : """simple docstring""" def __init__( self: Union[str, Any] )-> List[str]: lowerCamelCase : Optional[int] = {} def a__ ( self: Any , __a: int , __a: List[Any] , __a: Optional[int]=1 )-> Optional[Any]: if self.graph.get(__a ): if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: lowerCamelCase : Tuple = [[w, v]] if not self.graph.get(__a ): lowerCamelCase : Optional[Any] = [] def a__ ( self: str )-> str: return list(self.graph ) def a__ ( self: Any , __a: int , __a: Any )-> int: if self.graph.get(__a ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(__a ) def a__ ( self: Optional[int] , __a: str=-2 , __a: Optional[Any]=-1 )-> int: if s == d: return [] lowerCamelCase : Union[str, Any] = [] lowerCamelCase : str = [] if s == -2: lowerCamelCase : List[Any] = list(self.graph )[0] stack.append(__a ) visited.append(__a ) lowerCamelCase : int = s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase : Optional[Any] = s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(__a ) return visited else: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase : Any = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(__a ) != 0: lowerCamelCase : int = stack[len(__a ) - 1] else: lowerCamelCase : Dict = ss # check if se have reached the starting point if len(__a ) == 0: return visited def a__ ( self: str , __a: str=-1 )-> Optional[Any]: if c == -1: lowerCamelCase : List[str] = floor(random() * 10_000 ) + 10 for i in range(__a ): # every vertex has max 100 edges for _ in range(floor(random() * 102 ) + 1 ): lowerCamelCase : Optional[int] = floor(random() * c ) + 1 if n != i: self.add_pair(__a , __a , 1 ) def a__ ( self: Any , __a: int=-2 )-> List[str]: lowerCamelCase : List[Any] = deque() lowerCamelCase : List[str] = [] if s == -2: lowerCamelCase : str = list(self.graph )[0] d.append(__a ) visited.append(__a ) while d: lowerCamelCase : Dict = d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def a__ ( self: Tuple , __a: Union[str, Any] )-> Union[str, Any]: lowerCamelCase : Optional[int] = 0 for x in self.graph: for y in self.graph[x]: if y[1] == u: count += 1 return count def a__ ( self: Optional[Any] , __a: Any )-> Optional[int]: return len(self.graph[u] ) def a__ ( self: Optional[int] , __a: Tuple=-2 )-> List[Any]: lowerCamelCase : Any = [] lowerCamelCase : Optional[Any] = [] if s == -2: lowerCamelCase : List[Any] = list(self.graph )[0] stack.append(__a ) visited.append(__a ) lowerCamelCase : Tuple = s lowerCamelCase : List[Any] = [] while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase : List[str] = s for node in self.graph[s]: if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase : List[str] = node[1] break # check if all the children are visited if s == ss: sorted_nodes.append(stack.pop() ) if len(__a ) != 0: lowerCamelCase : Dict = stack[len(__a ) - 1] else: lowerCamelCase : Tuple = ss # check if se have reached the starting point if len(__a ) == 0: return sorted_nodes def a__ ( self: Dict )-> Tuple: lowerCamelCase : Any = [] lowerCamelCase : Union[str, Any] = [] lowerCamelCase : List[str] = list(self.graph )[0] stack.append(__a ) visited.append(__a ) lowerCamelCase : Union[str, Any] = -2 lowerCamelCase : Optional[int] = [] lowerCamelCase : Optional[int] = s lowerCamelCase : str = False lowerCamelCase : Optional[Any] = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase : Any = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): lowerCamelCase : List[Any] = len(__a ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase : Union[str, Any] = node[1] break # check if all the children are visited if s == ss: stack.pop() lowerCamelCase : Optional[int] = True if len(__a ) != 0: lowerCamelCase : Tuple = stack[len(__a ) - 1] else: lowerCamelCase : List[str] = False indirect_parents.append(__a ) lowerCamelCase : Any = s lowerCamelCase : int = ss # check if se have reached the starting point if len(__a ) == 0: return list(__a ) def a__ ( self: Any )-> int: lowerCamelCase : str = [] lowerCamelCase : Any = [] lowerCamelCase : List[Any] = list(self.graph )[0] stack.append(__a ) visited.append(__a ) lowerCamelCase : Any = -2 lowerCamelCase : Optional[int] = [] lowerCamelCase : Tuple = s lowerCamelCase : Tuple = False lowerCamelCase : Tuple = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase : Union[str, Any] = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): lowerCamelCase : str = len(__a ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase : Optional[Any] = node[1] break # check if all the children are visited if s == ss: stack.pop() lowerCamelCase : List[Any] = True if len(__a ) != 0: lowerCamelCase : List[str] = stack[len(__a ) - 1] else: lowerCamelCase : str = False indirect_parents.append(__a ) lowerCamelCase : Any = s lowerCamelCase : List[str] = ss # check if se have reached the starting point if len(__a ) == 0: return False def a__ ( self: Optional[int] , __a: Tuple=-2 , __a: List[Any]=-1 )-> Optional[Any]: lowerCamelCase : Union[str, Any] = time() self.dfs(__a , __a ) lowerCamelCase : Tuple = time() return end - begin def a__ ( self: List[str] , __a: Optional[Any]=-2 )-> List[Any]: lowerCamelCase : str = time() self.bfs(__a ) lowerCamelCase : Tuple = time() return end - begin class A__ : """simple docstring""" def __init__( self: Any )-> Tuple: lowerCamelCase : List[Any] = {} def a__ ( self: Tuple , __a: Any , __a: int , __a: List[Any]=1 )-> Union[str, Any]: # check if the u exists if self.graph.get(__a ): # if there already is a edge if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: # if u does not exist lowerCamelCase : Any = [[w, v]] # add the other way if self.graph.get(__a ): # if there already is a edge if self.graph[v].count([w, u] ) == 0: self.graph[v].append([w, u] ) else: # if u does not exist lowerCamelCase : Dict = [[w, u]] def a__ ( self: Tuple , __a: List[str] , __a: List[str] )-> Any: if self.graph.get(__a ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(__a ) # the other way round if self.graph.get(__a ): for _ in self.graph[v]: if _[1] == u: self.graph[v].remove(__a ) def a__ ( self: Any , __a: str=-2 , __a: str=-1 )-> Tuple: if s == d: return [] lowerCamelCase : Dict = [] lowerCamelCase : List[Any] = [] if s == -2: lowerCamelCase : Tuple = list(self.graph )[0] stack.append(__a ) visited.append(__a ) lowerCamelCase : Any = s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase : Any = s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(__a ) return visited else: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase : List[str] = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(__a ) != 0: lowerCamelCase : List[str] = stack[len(__a ) - 1] else: lowerCamelCase : Union[str, Any] = ss # check if se have reached the starting point if len(__a ) == 0: return visited def a__ ( self: Any , __a: Tuple=-1 )-> List[Any]: if c == -1: lowerCamelCase : Any = floor(random() * 10_000 ) + 10 for i in range(__a ): # every vertex has max 100 edges for _ in range(floor(random() * 102 ) + 1 ): lowerCamelCase : Union[str, Any] = floor(random() * c ) + 1 if n != i: self.add_pair(__a , __a , 1 ) def a__ ( self: Tuple , __a: int=-2 )-> str: lowerCamelCase : Dict = deque() lowerCamelCase : int = [] if s == -2: lowerCamelCase : str = list(self.graph )[0] d.append(__a ) visited.append(__a ) while d: lowerCamelCase : Optional[Any] = d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def a__ ( self: str , __a: str )-> Any: return len(self.graph[u] ) def a__ ( self: Any )-> List[str]: lowerCamelCase : int = [] lowerCamelCase : Tuple = [] lowerCamelCase : str = list(self.graph )[0] stack.append(__a ) visited.append(__a ) lowerCamelCase : List[str] = -2 lowerCamelCase : Optional[Any] = [] lowerCamelCase : Optional[Any] = s lowerCamelCase : List[Any] = False lowerCamelCase : List[str] = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase : Optional[Any] = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): lowerCamelCase : Any = len(__a ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase : List[Any] = node[1] break # check if all the children are visited if s == ss: stack.pop() lowerCamelCase : Any = True if len(__a ) != 0: lowerCamelCase : Tuple = stack[len(__a ) - 1] else: lowerCamelCase : Dict = False indirect_parents.append(__a ) lowerCamelCase : str = s lowerCamelCase : Any = ss # check if se have reached the starting point if len(__a ) == 0: return list(__a ) def a__ ( self: Any )-> Union[str, Any]: lowerCamelCase : str = [] lowerCamelCase : str = [] lowerCamelCase : str = list(self.graph )[0] stack.append(__a ) visited.append(__a ) lowerCamelCase : List[str] = -2 lowerCamelCase : List[str] = [] lowerCamelCase : Optional[int] = s lowerCamelCase : Tuple = False lowerCamelCase : List[Any] = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowerCamelCase : Optional[Any] = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): lowerCamelCase : Tuple = len(__a ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) lowerCamelCase : Optional[int] = node[1] break # check if all the children are visited if s == ss: stack.pop() lowerCamelCase : str = True if len(__a ) != 0: lowerCamelCase : Optional[int] = stack[len(__a ) - 1] else: lowerCamelCase : Tuple = False indirect_parents.append(__a ) lowerCamelCase : List[str] = s lowerCamelCase : List[Any] = ss # check if se have reached the starting point if len(__a ) == 0: return False def a__ ( self: Tuple )-> Optional[int]: return list(self.graph ) def a__ ( self: Optional[Any] , __a: Dict=-2 , __a: Optional[Any]=-1 )-> Optional[int]: lowerCamelCase : List[str] = time() self.dfs(__a , __a ) lowerCamelCase : Optional[int] = time() return end - begin def a__ ( self: Union[str, Any] , __a: Optional[Any]=-2 )-> Any: lowerCamelCase : Tuple = time() self.bfs(__a ) lowerCamelCase : Optional[int] = time() return end - begin
222
0
import flax.linen as nn import jax import jax.numpy as jnp class __magic_name__ ( nn.Module): A: int A: jnp.dtype = jnp.floataa def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: '''simple docstring''' UpperCamelCase__ : Dict = nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__( self : int , lowerCamelCase__ : List[Any] ) -> Optional[int]: '''simple docstring''' UpperCamelCase__ : Optional[Any] = hidden_states.shape UpperCamelCase__ : List[Any] = jax.image.resize( lowerCamelCase__ , shape=(batch, height * 2, width * 2, channels) , method='''nearest''' , ) UpperCamelCase__ : Any = self.conv(lowerCamelCase__ ) return hidden_states class __magic_name__ ( nn.Module): A: int A: jnp.dtype = jnp.floataa def UpperCAmelCase__ ( self : Optional[int] ) -> str: '''simple docstring''' UpperCamelCase__ : List[str] = nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(2, 2) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__( self : Union[str, Any] , lowerCamelCase__ : Union[str, Any] ) -> int: '''simple docstring''' UpperCamelCase__ : List[str] = self.conv(lowerCamelCase__ ) return hidden_states class __magic_name__ ( nn.Module): A: int A: int = None A: float = 0.0 A: bool = None A: jnp.dtype = jnp.floataa def UpperCAmelCase__ ( self : List[str] ) -> Dict: '''simple docstring''' UpperCamelCase__ : str = self.in_channels if self.out_channels is None else self.out_channels UpperCamelCase__ : Any = nn.GroupNorm(num_groups=32 , epsilon=1E-5 ) UpperCamelCase__ : Tuple = nn.Conv( lowerCamelCase__ , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) UpperCamelCase__ : Union[str, Any] = nn.Dense(lowerCamelCase__ , dtype=self.dtype ) UpperCamelCase__ : Optional[Any] = nn.GroupNorm(num_groups=32 , epsilon=1E-5 ) UpperCamelCase__ : Tuple = nn.Dropout(self.dropout_prob ) UpperCamelCase__ : List[str] = nn.Conv( lowerCamelCase__ , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) UpperCamelCase__ : Optional[int] = self.in_channels != out_channels if self.use_nin_shortcut is None else self.use_nin_shortcut UpperCamelCase__ : Optional[Any] = None if use_nin_shortcut: UpperCamelCase__ : List[str] = nn.Conv( lowerCamelCase__ , kernel_size=(1, 1) , strides=(1, 1) , padding='''VALID''' , dtype=self.dtype , ) def __call__( self : Any , lowerCamelCase__ : Union[str, Any] , lowerCamelCase__ : Union[str, Any] , lowerCamelCase__ : List[str]=True ) -> Union[str, Any]: '''simple docstring''' UpperCamelCase__ : Optional[int] = hidden_states UpperCamelCase__ : int = self.norma(lowerCamelCase__ ) UpperCamelCase__ : List[str] = nn.swish(lowerCamelCase__ ) UpperCamelCase__ : Tuple = self.conva(lowerCamelCase__ ) UpperCamelCase__ : List[str] = self.time_emb_proj(nn.swish(lowerCamelCase__ ) ) UpperCamelCase__ : str = jnp.expand_dims(jnp.expand_dims(lowerCamelCase__ , 1 ) , 1 ) UpperCamelCase__ : Tuple = hidden_states + temb UpperCamelCase__ : Dict = self.norma(lowerCamelCase__ ) UpperCamelCase__ : int = nn.swish(lowerCamelCase__ ) UpperCamelCase__ : str = self.dropout(lowerCamelCase__ , lowerCamelCase__ ) UpperCamelCase__ : int = self.conva(lowerCamelCase__ ) if self.conv_shortcut is not None: UpperCamelCase__ : str = self.conv_shortcut(lowerCamelCase__ ) return hidden_states + residual
706
__UpperCamelCase : List[Any] = 256 # Modulus to hash a string __UpperCamelCase : Union[str, Any] = 100_0003 def _a ( SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : str ): """simple docstring""" UpperCamelCase__ : Optional[int] = len(SCREAMING_SNAKE_CASE ) UpperCamelCase__ : List[Any] = len(SCREAMING_SNAKE_CASE ) if p_len > t_len: return False UpperCamelCase__ : Any = 0 UpperCamelCase__ : str = 0 UpperCamelCase__ : List[Any] = 1 # Calculating the hash of pattern and substring of text for i in range(SCREAMING_SNAKE_CASE ): UpperCamelCase__ : Any = (ord(pattern[i] ) + p_hash * alphabet_size) % modulus UpperCamelCase__ : List[str] = (ord(text[i] ) + text_hash * alphabet_size) % modulus if i == p_len - 1: continue UpperCamelCase__ : Dict = (modulus_power * alphabet_size) % modulus for i in range(0 , t_len - p_len + 1 ): if text_hash == p_hash and text[i : i + p_len] == pattern: return True if i == t_len - p_len: continue # Calculate the https://en.wikipedia.org/wiki/Rolling_hash UpperCamelCase__ : Optional[int] = ( (text_hash - ord(text[i] ) * modulus_power) * alphabet_size + ord(text[i + p_len] ) ) % modulus return False def _a ( ): """simple docstring""" UpperCamelCase__ : Tuple = '''abc1abc12''' UpperCamelCase__ : Dict = '''alskfjaldsabc1abc1abc12k23adsfabcabc''' UpperCamelCase__ : List[str] = '''alskfjaldsk23adsfabcabc''' assert rabin_karp(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) and not rabin_karp(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # Test 2) UpperCamelCase__ : Optional[int] = '''ABABX''' UpperCamelCase__ : int = '''ABABZABABYABABX''' assert rabin_karp(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # Test 3) UpperCamelCase__ : int = '''AAAB''' UpperCamelCase__ : str = '''ABAAAAAB''' assert rabin_karp(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # Test 4) UpperCamelCase__ : Union[str, Any] = '''abcdabcy''' UpperCamelCase__ : List[str] = '''abcxabcdabxabcdabcdabcy''' assert rabin_karp(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # Test 5) UpperCamelCase__ : Tuple = '''Lü''' UpperCamelCase__ : Any = '''Lüsai''' assert rabin_karp(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) UpperCamelCase__ : Dict = '''Lue''' assert not rabin_karp(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) print('''Success.''' ) if __name__ == "__main__": test_rabin_karp()
106
0
import logging import os import sys from dataclasses import dataclass, field from itertools import chain from typing import Optional, Union import datasets import numpy as np import torch from datasets import load_dataset import transformers from transformers import ( AutoConfig, AutoModelForMultipleChoice, AutoTokenizer, HfArgumentParser, Trainer, TrainingArguments, default_data_collator, set_seed, ) from transformers.tokenization_utils_base import PreTrainedTokenizerBase from transformers.trainer_utils import get_last_checkpoint from transformers.utils import PaddingStrategy, check_min_version, send_example_telemetry # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("4.31.0") __A : str = logging.getLogger(__name__) @dataclass class A_ : UpperCAmelCase__ = field( metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''} ) UpperCAmelCase__ = field( default=a_ , metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} ) UpperCAmelCase__ = field( default=a_ , metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''} ) UpperCAmelCase__ = field( default=a_ , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''} , ) UpperCAmelCase__ = field( default=a_ , metadata={'''help''': '''Whether to use one of the fast tokenizer (backed by the tokenizers library) or not.'''} , ) UpperCAmelCase__ = field( default='''main''' , metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''} , ) UpperCAmelCase__ = field( default=a_ , metadata={ '''help''': ( '''Will use the token generated when running `huggingface-cli login` (necessary to use this script ''' '''with private models).''' ) } , ) @dataclass class A_ : UpperCAmelCase__ = field(default=a_ , metadata={'''help''': '''The input training data file (a text file).'''} ) UpperCAmelCase__ = field( default=a_ , metadata={'''help''': '''An optional input evaluation data file to evaluate the perplexity on (a text file).'''} , ) UpperCAmelCase__ = field( default=a_ , metadata={'''help''': '''Overwrite the cached training and evaluation sets'''} ) UpperCAmelCase__ = field( default=a_ , metadata={'''help''': '''The number of processes to use for the preprocessing.'''} , ) UpperCAmelCase__ = field( default=a_ , metadata={ '''help''': ( '''The maximum total input sequence length after tokenization. If passed, sequences longer ''' '''than this will be truncated, sequences shorter will be padded.''' ) } , ) UpperCAmelCase__ = field( default=a_ , metadata={ '''help''': ( '''Whether to pad all samples to the maximum sentence length. ''' '''If False, will pad the samples dynamically when batching to the maximum length in the batch. More ''' '''efficient on GPU but very bad for TPU.''' ) } , ) UpperCAmelCase__ = field( default=a_ , metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of training examples to this ''' '''value if set.''' ) } , ) UpperCAmelCase__ = field( default=a_ , metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of evaluation examples to this ''' '''value if set.''' ) } , ) def _lowercase ( self ): '''simple docstring''' if self.train_file is not None: UpperCAmelCase = self.train_file.split('''.''' )[-1] assert extension in ["csv", "json"], "`train_file` should be a csv or a json file." if self.validation_file is not None: UpperCAmelCase = self.validation_file.split('''.''' )[-1] assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file." @dataclass class A_ : UpperCAmelCase__ = 42 UpperCAmelCase__ = True UpperCAmelCase__ = None UpperCAmelCase__ = None def __call__( self , _A ): '''simple docstring''' UpperCAmelCase = '''label''' if '''label''' in features[0].keys() else '''labels''' UpperCAmelCase = [feature.pop(_A ) for feature in features] UpperCAmelCase = len(_A ) UpperCAmelCase = len(features[0]['''input_ids'''] ) UpperCAmelCase = [ [{k: v[i] for k, v in feature.items()} for i in range(_A )] for feature in features ] UpperCAmelCase = list(chain(*_A ) ) UpperCAmelCase = self.tokenizer.pad( _A , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors='''pt''' , ) # Un-flatten UpperCAmelCase = {k: v.view(_A , _A , -1 ) for k, v in batch.items()} # Add back labels UpperCAmelCase = torch.tensor(_A , dtype=torch.intaa ) return batch def __SCREAMING_SNAKE_CASE ( ) -> Union[str, Any]: '''simple docstring''' UpperCAmelCase = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('''.json''' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry('''run_swag''' , UpperCamelCase__ , UpperCamelCase__ ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() UpperCAmelCase = training_args.get_process_log_level() logger.setLevel(UpperCamelCase__ ) datasets.utils.logging.set_verbosity(UpperCamelCase__ ) transformers.utils.logging.set_verbosity(UpperCamelCase__ ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}""" + F"""distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}""" ) logger.info(F"""Training/evaluation parameters {training_args}""" ) # Detecting last checkpoint. UpperCAmelCase = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: UpperCAmelCase = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F"""Output directory ({training_args.output_dir}) already exists and is not empty. """ '''Use --overwrite_output_dir to overcome.''' ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( F"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """ '''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.''' ) # 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.train_file is not None or data_args.validation_file is not None: UpperCAmelCase = {} if data_args.train_file is not None: UpperCAmelCase = data_args.train_file if data_args.validation_file is not None: UpperCAmelCase = data_args.validation_file UpperCAmelCase = data_args.train_file.split('''.''' )[-1] UpperCAmelCase = load_dataset( UpperCamelCase__ , data_files=UpperCamelCase__ , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) else: # Downloading and loading the swag dataset from the hub. UpperCAmelCase = load_dataset( '''swag''' , '''regular''' , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) # 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. UpperCAmelCase = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) UpperCAmelCase = 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_tokenizer , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) UpperCAmelCase = AutoModelForMultipleChoice.from_pretrained( model_args.model_name_or_path , from_tf=bool('''.ckpt''' in model_args.model_name_or_path ) , config=UpperCamelCase__ , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # When using your own dataset or a different dataset from swag, you will probably need to change this. UpperCAmelCase = [F"""ending{i}""" for i in range(4 )] UpperCAmelCase = '''sent1''' UpperCAmelCase = '''sent2''' if data_args.max_seq_length is None: UpperCAmelCase = tokenizer.model_max_length if max_seq_length > 1024: logger.warning( '''The chosen tokenizer supports a `model_max_length` that is longer than the default `block_size` value''' ''' of 1024. If you would like to use a longer `block_size` up to `tokenizer.model_max_length` you can''' ''' override this default with `--block_size xxx`.''' ) UpperCAmelCase = 1024 else: if data_args.max_seq_length > tokenizer.model_max_length: logger.warning( F"""The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the""" F"""model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.""" ) UpperCAmelCase = min(data_args.max_seq_length , tokenizer.model_max_length ) # Preprocessing the datasets. def preprocess_function(UpperCamelCase__ ): UpperCAmelCase = [[context] * 4 for context in examples[context_name]] UpperCAmelCase = examples[question_header_name] UpperCAmelCase = [ [F"""{header} {examples[end][i]}""" for end in ending_names] for i, header in enumerate(UpperCamelCase__ ) ] # Flatten out UpperCAmelCase = list(chain(*UpperCamelCase__ ) ) UpperCAmelCase = list(chain(*UpperCamelCase__ ) ) # Tokenize UpperCAmelCase = tokenizer( UpperCamelCase__ , UpperCamelCase__ , truncation=UpperCamelCase__ , max_length=UpperCamelCase__ , padding='''max_length''' if data_args.pad_to_max_length else False , ) # Un-flatten return {k: [v[i : i + 4] for i in range(0 , len(UpperCamelCase__ ) , 4 )] for k, v in tokenized_examples.items()} if training_args.do_train: if "train" not in raw_datasets: raise ValueError('''--do_train requires a train dataset''' ) UpperCAmelCase = raw_datasets['''train'''] if data_args.max_train_samples is not None: UpperCAmelCase = min(len(UpperCamelCase__ ) , data_args.max_train_samples ) UpperCAmelCase = train_dataset.select(range(UpperCamelCase__ ) ) with training_args.main_process_first(desc='''train dataset map pre-processing''' ): UpperCAmelCase = train_dataset.map( UpperCamelCase__ , batched=UpperCamelCase__ , num_proc=data_args.preprocessing_num_workers , load_from_cache_file=not data_args.overwrite_cache , ) if training_args.do_eval: if "validation" not in raw_datasets: raise ValueError('''--do_eval requires a validation dataset''' ) UpperCAmelCase = raw_datasets['''validation'''] if data_args.max_eval_samples is not None: UpperCAmelCase = min(len(UpperCamelCase__ ) , data_args.max_eval_samples ) UpperCAmelCase = eval_dataset.select(range(UpperCamelCase__ ) ) with training_args.main_process_first(desc='''validation dataset map pre-processing''' ): UpperCAmelCase = eval_dataset.map( UpperCamelCase__ , batched=UpperCamelCase__ , num_proc=data_args.preprocessing_num_workers , load_from_cache_file=not data_args.overwrite_cache , ) # Data collator UpperCAmelCase = ( default_data_collator if data_args.pad_to_max_length else DataCollatorForMultipleChoice(tokenizer=UpperCamelCase__ , pad_to_multiple_of=8 if training_args.fpaa else None ) ) # Metric def compute_metrics(UpperCamelCase__ ): UpperCAmelCase , UpperCAmelCase = eval_predictions UpperCAmelCase = np.argmax(UpperCamelCase__ , axis=1 ) return {"accuracy": (preds == label_ids).astype(np.floataa ).mean().item()} # Initialize our Trainer UpperCAmelCase = Trainer( model=UpperCamelCase__ , args=UpperCamelCase__ , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , tokenizer=UpperCamelCase__ , data_collator=UpperCamelCase__ , compute_metrics=UpperCamelCase__ , ) # Training if training_args.do_train: UpperCAmelCase = None if training_args.resume_from_checkpoint is not None: UpperCAmelCase = training_args.resume_from_checkpoint elif last_checkpoint is not None: UpperCAmelCase = last_checkpoint UpperCAmelCase = trainer.train(resume_from_checkpoint=UpperCamelCase__ ) trainer.save_model() # Saves the tokenizer too for easy upload UpperCAmelCase = train_result.metrics UpperCAmelCase = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(UpperCamelCase__ ) ) UpperCAmelCase = min(UpperCamelCase__ , len(UpperCamelCase__ ) ) trainer.log_metrics('''train''' , UpperCamelCase__ ) trainer.save_metrics('''train''' , UpperCamelCase__ ) trainer.save_state() # Evaluation if training_args.do_eval: logger.info('''*** Evaluate ***''' ) UpperCAmelCase = trainer.evaluate() UpperCAmelCase = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(UpperCamelCase__ ) UpperCAmelCase = min(UpperCamelCase__ , len(UpperCamelCase__ ) ) trainer.log_metrics('''eval''' , UpperCamelCase__ ) trainer.save_metrics('''eval''' , UpperCamelCase__ ) UpperCAmelCase = { '''finetuned_from''': model_args.model_name_or_path, '''tasks''': '''multiple-choice''', '''dataset_tags''': '''swag''', '''dataset_args''': '''regular''', '''dataset''': '''SWAG''', '''language''': '''en''', } if training_args.push_to_hub: trainer.push_to_hub(**UpperCamelCase__ ) else: trainer.create_model_card(**UpperCamelCase__ ) def __SCREAMING_SNAKE_CASE ( UpperCamelCase__ ) -> List[str]: '''simple docstring''' main() if __name__ == "__main__": main()
130
import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation __A : Optional[Any] = logging.get_logger(__name__) __A : Dict = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"} __A : Tuple = { "tokenizer_file": { "EleutherAI/gpt-neox-20b": "https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/tokenizer.json", }, } __A : Dict = { "gpt-neox-20b": 2_048, } class A_ (a_ ): UpperCAmelCase__ = VOCAB_FILES_NAMES UpperCAmelCase__ = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase__ = ['''input_ids''', '''attention_mask'''] def __init__( self , _A=None , _A=None , _A=None , _A="<|endoftext|>" , _A="<|endoftext|>" , _A="<|endoftext|>" , _A=False , **_A , ): '''simple docstring''' super().__init__( _A , _A , tokenizer_file=_A , unk_token=_A , bos_token=_A , eos_token=_A , add_prefix_space=_A , **_A , ) UpperCAmelCase = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get('''add_prefix_space''' , _A ) != add_prefix_space: UpperCAmelCase = getattr(_A , pre_tok_state.pop('''type''' ) ) UpperCAmelCase = add_prefix_space UpperCAmelCase = pre_tok_class(**_A ) UpperCAmelCase = add_prefix_space def _lowercase ( self , _A , _A = None ): '''simple docstring''' UpperCAmelCase = self._tokenizer.model.save(_A , name=_A ) return tuple(_A ) def _lowercase ( self , _A ): '''simple docstring''' UpperCAmelCase = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(_A , add_special_tokens=_A ) + [self.eos_token_id] ) if len(_A ) > self.model_max_length: UpperCAmelCase = input_ids[-self.model_max_length :] return input_ids
130
1
import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing the experiment tracking capability, # and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To help focus on the differences in the code, building `DataLoaders` # was refactored into its own function. # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## lowercase__ : Union[str, Any] = 1_6 lowercase__ : Tuple = 3_2 def A_ ( snake_case : Accelerator , snake_case : int = 16 ) -> List[Any]: '''simple docstring''' __UpperCamelCase = AutoTokenizer.from_pretrained('''bert-base-cased''' ) __UpperCamelCase = load_dataset('''glue''' , '''mrpc''' ) def tokenize_function(snake_case : Tuple ): # max_length=None => use the model max length (it's actually the default) __UpperCamelCase = tokenizer(examples['''sentence1'''] , examples['''sentence2'''] , truncation=snake_case , max_length=snake_case ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): __UpperCamelCase = datasets.map( snake_case , batched=snake_case , remove_columns=['''idx''', '''sentence1''', '''sentence2'''] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library __UpperCamelCase = tokenized_datasets.rename_column('''label''' , '''labels''' ) def collate_fn(snake_case : Union[str, Any] ): # On TPU it's best to pad everything to the same length or training will be very slow. __UpperCamelCase = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": __UpperCamelCase = 16 elif accelerator.mixed_precision != "no": __UpperCamelCase = 8 else: __UpperCamelCase = None return tokenizer.pad( snake_case , padding='''longest''' , max_length=snake_case , pad_to_multiple_of=snake_case , return_tensors='''pt''' , ) # Instantiate dataloaders. __UpperCamelCase = DataLoader( tokenized_datasets['''train'''] , shuffle=snake_case , collate_fn=snake_case , batch_size=snake_case ) __UpperCamelCase = DataLoader( tokenized_datasets['''validation'''] , shuffle=snake_case , collate_fn=snake_case , batch_size=snake_case ) return train_dataloader, eval_dataloader # For testing only if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": from accelerate.test_utils.training import mocked_dataloaders lowercase__ : List[str] = mocked_dataloaders # noqa: F811 def A_ ( snake_case : str , snake_case : Optional[Any] ) -> Optional[int]: '''simple docstring''' if os.environ.get('''TESTING_MOCKED_DATALOADERS''' , snake_case ) == "1": __UpperCamelCase = 2 # Initialize Accelerator # New Code # # We pass in "all" to `log_with` to grab all available trackers in the environment # Note: If using a custom `Tracker` class, should be passed in here such as: # >>> log_with = ["all", MyCustomTrackerClassInstance()] if args.with_tracking: __UpperCamelCase = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , log_with='''all''' , project_dir=args.project_dir ) else: __UpperCamelCase = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs __UpperCamelCase = config['''lr'''] __UpperCamelCase = int(config['''num_epochs'''] ) __UpperCamelCase = int(config['''seed'''] ) __UpperCamelCase = int(config['''batch_size'''] ) set_seed(snake_case ) __UpperCamelCase , __UpperCamelCase = get_dataloaders(snake_case , snake_case ) __UpperCamelCase = evaluate.load('''glue''' , '''mrpc''' ) # If the batch size is too big we use gradient accumulation __UpperCamelCase = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: __UpperCamelCase = batch_size // MAX_GPU_BATCH_SIZE __UpperCamelCase = MAX_GPU_BATCH_SIZE # Instantiate the model (we build the model here so that the seed also control new weights initialization) __UpperCamelCase = AutoModelForSequenceClassification.from_pretrained('''bert-base-cased''' , return_dict=snake_case ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). __UpperCamelCase = model.to(accelerator.device ) # Instantiate optimizer __UpperCamelCase = AdamW(params=model.parameters() , lr=snake_case ) # Instantiate scheduler __UpperCamelCase = get_linear_schedule_with_warmup( optimizer=snake_case , num_warmup_steps=100 , num_training_steps=(len(snake_case ) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = accelerator.prepare( snake_case , snake_case , snake_case , snake_case , snake_case ) # New Code # # We need to initialize the trackers we use. Overall configurations can also be stored if args.with_tracking: __UpperCamelCase = os.path.split(snake_case )[-1].split('''.''' )[0] accelerator.init_trackers(snake_case , snake_case ) # Now we train the model for epoch in range(snake_case ): model.train() # New Code # # For our tracking example, we will log the total loss of each epoch if args.with_tracking: __UpperCamelCase = 0 for step, batch in enumerate(snake_case ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) __UpperCamelCase = model(**snake_case ) __UpperCamelCase = outputs.loss # New Code # if args.with_tracking: total_loss += loss.detach().float() __UpperCamelCase = loss / gradient_accumulation_steps accelerator.backward(snake_case ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(snake_case ): # We could avoid this line since we set the accelerator with `device_placement=True` (the default). batch.to(accelerator.device ) with torch.no_grad(): __UpperCamelCase = model(**snake_case ) __UpperCamelCase = outputs.logits.argmax(dim=-1 ) __UpperCamelCase , __UpperCamelCase = accelerator.gather_for_metrics((predictions, batch['''labels''']) ) metric.add_batch( predictions=snake_case , references=snake_case , ) __UpperCamelCase = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f"epoch {epoch}:" , snake_case ) # New Code # # To actually log, we call `Accelerator.log` # The values passed can be of `str`, `int`, `float` or `dict` of `str` to `float`/`int` if args.with_tracking: accelerator.log( { '''accuracy''': eval_metric['''accuracy'''], '''f1''': eval_metric['''f1'''], '''train_loss''': total_loss.item() / len(snake_case ), '''epoch''': epoch, } , step=snake_case , ) # New Code # # When a run is finished, you should call `accelerator.end_training()` # to close all of the open trackers if args.with_tracking: accelerator.end_training() def A_ ( ) -> int: '''simple docstring''' __UpperCamelCase = argparse.ArgumentParser(description='''Simple example of training script.''' ) parser.add_argument( '''--mixed_precision''' , type=snake_case , default=snake_case , choices=['''no''', '''fp16''', '''bf16''', '''fp8'''] , help='''Whether to use mixed precision. Choose''' '''between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.''' '''and an Nvidia Ampere GPU.''' , ) parser.add_argument('''--cpu''' , action='''store_true''' , help='''If passed, will train on the CPU.''' ) parser.add_argument( '''--with_tracking''' , action='''store_true''' , help='''Whether to load in all available experiment trackers from the environment and use them for logging.''' , ) parser.add_argument( '''--project_dir''' , type=snake_case , default='''logs''' , help='''Location on where to store experiment tracking logs` and relevent project information''' , ) __UpperCamelCase = parser.parse_args() __UpperCamelCase = {'''lr''': 2e-5, '''num_epochs''': 3, '''seed''': 42, '''batch_size''': 16} training_function(snake_case , snake_case ) if __name__ == "__main__": main()
451
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowercase__ : int = { "configuration_git": ["GIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "GitConfig", "GitVisionConfig"], "processing_git": ["GitProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ : Tuple = [ "GIT_PRETRAINED_MODEL_ARCHIVE_LIST", "GitForCausalLM", "GitModel", "GitPreTrainedModel", "GitVisionModel", ] if TYPE_CHECKING: from .configuration_git import GIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GitConfig, GitVisionConfig from .processing_git import GitProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_git import ( GIT_PRETRAINED_MODEL_ARCHIVE_LIST, GitForCausalLM, GitModel, GitPreTrainedModel, GitVisionModel, ) else: import sys lowercase__ : Optional[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
451
1
'''simple docstring''' import unittest from transformers.testing_utils import require_bsa from transformers.utils import is_bsa_available from ...test_feature_extraction_common import FeatureExtractionSavingTestMixin if is_bsa_available(): from transformers import MarkupLMFeatureExtractor class _SCREAMING_SNAKE_CASE( unittest.TestCase ): def __init__( self : Optional[int] , UpperCamelCase_ : Dict ) -> Any: SCREAMING_SNAKE_CASE__ :Union[str, Any] = parent def __lowerCamelCase ( self : Union[str, Any] ) -> str: return {} def lowerCamelCase ( ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE__ :Dict = '<HTML>\n\n <HEAD>\n <TITLE>sample document</TITLE>\n </HEAD>\n\n <BODY BGCOLOR=\"FFFFFF\">\n <HR>\n <a href=\"http://google.com\">Goog</a>\n <H1>This is one header</H1>\n <H2>This is a another Header</H2>\n <P>Travel from\n <P>\n <B>SFO to JFK</B>\n <BR>\n <B><I>on May 2, 2015 at 2:00 pm. For details go to confirm.com </I></B>\n <HR>\n <div style=\"color:#0000FF\">\n <h3>Traveler <b> name </b> is\n <p> John Doe </p>\n </div>' SCREAMING_SNAKE_CASE__ :List[Any] = '\n <!DOCTYPE html>\n <html>\n <body>\n\n <h1>My First Heading</h1>\n <p>My first paragraph.</p>\n\n </body>\n </html>\n ' return [html_string_a, html_string_a] @require_bsa class _SCREAMING_SNAKE_CASE( __a , unittest.TestCase ): A_ : Union[str, Any] = MarkupLMFeatureExtractor if is_bsa_available() else None def __lowerCamelCase ( self : Tuple ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ :Optional[Any] = MarkupLMFeatureExtractionTester(self ) @property def __lowerCamelCase ( self : Optional[int] ) -> Optional[Any]: return self.feature_extract_tester.prepare_feat_extract_dict() def __lowerCamelCase ( self : str ) -> Dict: SCREAMING_SNAKE_CASE__ :Union[str, Any] = self.feature_extraction_class() # Test not batched input SCREAMING_SNAKE_CASE__ :List[Any] = get_html_strings()[0] SCREAMING_SNAKE_CASE__ :Optional[Any] = feature_extractor(lowercase_ ) # fmt: off SCREAMING_SNAKE_CASE__ :List[Any] = [['sample document', 'Goog', 'This is one header', 'This is a another Header', 'Travel from', 'SFO to JFK', 'on May 2, 2015 at 2:00 pm. For details go to confirm.com', 'Traveler', 'name', 'is', 'John Doe']] SCREAMING_SNAKE_CASE__ :List[Any] = [['/html/head/title', '/html/body/a', '/html/body/h1', '/html/body/h2', '/html/body/p', '/html/body/p/p/b[1]', '/html/body/p/p/b[2]/i', '/html/body/p/p/div/h3', '/html/body/p/p/div/h3/b', '/html/body/p/p/div/h3', '/html/body/p/p/div/h3/p']] # fmt: on self.assertEqual(encoding.nodes , lowercase_ ) self.assertEqual(encoding.xpaths , lowercase_ ) # Test batched SCREAMING_SNAKE_CASE__ :Optional[Any] = get_html_strings() SCREAMING_SNAKE_CASE__ :Union[str, Any] = feature_extractor(lowercase_ ) # fmt: off SCREAMING_SNAKE_CASE__ :Union[str, Any] = expected_nodes + [['My First Heading', 'My first paragraph.']] SCREAMING_SNAKE_CASE__ :str = expected_xpaths + [['/html/body/h1', '/html/body/p']] self.assertEqual(len(encoding.nodes ) , 2 ) self.assertEqual(len(encoding.xpaths ) , 2 ) self.assertEqual(encoding.nodes , lowercase_ ) self.assertEqual(encoding.xpaths , lowercase_ )
209
'''simple docstring''' def A_ ( SCREAMING_SNAKE_CASE_ ) ->bool: if num < 0: return False lowercase_ = num lowercase_ = 0 while num > 0: lowercase_ = rev_num * 10 + (num % 10) num //= 10 return num_copy == rev_num if __name__ == "__main__": import doctest doctest.testmod()
451
0
import argparse import json import math import os import time import traceback import zipfile from collections import Counter import requests def lowercase_ (A : Optional[int] , A : Any=None ): snake_case__ : Any = None if token is not None: snake_case__ : List[Any] = {'Accept': 'application/vnd.github+json', 'Authorization': F'''Bearer {token}'''} snake_case__ : Union[str, Any] = F'''https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100''' snake_case__ : Any = requests.get(A , headers=A ).json() snake_case__ : int = {} try: job_links.update({job['name']: job['html_url'] for job in result['jobs']} ) snake_case__ : Optional[Any] = math.ceil((result['total_count'] - 1_0_0) / 1_0_0 ) for i in range(A ): snake_case__ : Any = requests.get(url + F'''&page={i + 2}''' , headers=A ).json() job_links.update({job['name']: job['html_url'] for job in result['jobs']} ) return job_links except Exception: print(F'''Unknown error, could not fetch links:\n{traceback.format_exc()}''' ) return {} def lowercase_ (A : Optional[int] , A : Optional[Any]=None ): snake_case__ : str = None if token is not None: snake_case__ : Union[str, Any] = {'Accept': 'application/vnd.github+json', 'Authorization': F'''Bearer {token}'''} snake_case__ : Union[str, Any] = F'''https://api.github.com/repos/huggingface/transformers/actions/runs/{worflow_run_id}/artifacts?per_page=100''' snake_case__ : Union[str, Any] = requests.get(A , headers=A ).json() snake_case__ : List[str] = {} try: artifacts.update({artifact['name']: artifact['archive_download_url'] for artifact in result['artifacts']} ) snake_case__ : Optional[int] = math.ceil((result['total_count'] - 1_0_0) / 1_0_0 ) for i in range(A ): snake_case__ : List[Any] = requests.get(url + F'''&page={i + 2}''' , headers=A ).json() artifacts.update({artifact['name']: artifact['archive_download_url'] for artifact in result['artifacts']} ) return artifacts except Exception: print(F'''Unknown error, could not fetch links:\n{traceback.format_exc()}''' ) return {} def lowercase_ (A : str , A : Optional[Any] , A : Optional[Any] , A : Optional[int] ): snake_case__ : Union[str, Any] = None if token is not None: snake_case__ : Tuple = {'Accept': 'application/vnd.github+json', 'Authorization': F'''Bearer {token}'''} snake_case__ : Tuple = requests.get(A , headers=A , allow_redirects=A ) snake_case__ : Any = result.headers['Location'] snake_case__ : Union[str, Any] = requests.get(A , allow_redirects=A ) snake_case__ : str = os.path.join(A , F'''{artifact_name}.zip''' ) with open(A , 'wb' ) as fp: fp.write(response.content ) def lowercase_ (A : Optional[Any] , A : Any=None ): snake_case__ : Tuple = [] snake_case__ : Tuple = [] snake_case__ : Optional[int] = None with zipfile.ZipFile(A ) as z: for filename in z.namelist(): if not os.path.isdir(A ): # read the file if filename in ["failures_line.txt", "summary_short.txt", "job_name.txt"]: with z.open(A ) as f: for line in f: snake_case__ : int = line.decode('UTF-8' ).strip() if filename == "failures_line.txt": try: # `error_line` is the place where `error` occurs snake_case__ : Optional[int] = line[: line.index(': ' )] snake_case__ : Optional[Any] = line[line.index(': ' ) + len(': ' ) :] errors.append([error_line, error] ) except Exception: # skip un-related lines pass elif filename == "summary_short.txt" and line.startswith('FAILED ' ): # `test` is the test method that failed snake_case__ : Optional[Any] = line[len('FAILED ' ) :] failed_tests.append(A ) elif filename == "job_name.txt": snake_case__ : List[Any] = line if len(A ) != len(A ): raise ValueError( F'''`errors` and `failed_tests` should have the same number of elements. Got {len(A )} for `errors` ''' F'''and {len(A )} for `failed_tests` instead. The test reports in {artifact_zip_path} have some''' ' problem.' ) snake_case__ : Union[str, Any] = None if job_name and job_links: snake_case__ : Any = job_links.get(A , A ) # A list with elements of the form (line of error, error, failed test) snake_case__ : Union[str, Any] = [x + [y] + [job_link] for x, y in zip(A , A )] return result def lowercase_ (A : Optional[int] , A : List[str]=None ): snake_case__ : Union[str, Any] = [] snake_case__ : Optional[Any] = [os.path.join(A , A ) for p in os.listdir(A ) if p.endswith('.zip' )] for p in paths: errors.extend(get_errors_from_single_artifact(A , job_links=A ) ) return errors def lowercase_ (A : Optional[Any] , A : Optional[int]=None ): snake_case__ : Dict = Counter() counter.update([x[1] for x in logs] ) snake_case__ : Any = counter.most_common() snake_case__ : Optional[int] = {} for error, count in counts: if error_filter is None or error not in error_filter: snake_case__ : List[str] = {'count': count, 'failed_tests': [(x[2], x[0]) for x in logs if x[1] == error]} snake_case__ : int = dict(sorted(r.items() , key=lambda A : item[1]["count"] , reverse=A ) ) return r def lowercase_ (A : List[Any] ): snake_case__ : Any = test.split('::' )[0] if test.startswith('tests/models/' ): snake_case__ : Tuple = test.split('/' )[2] else: snake_case__ : Tuple = None return test def lowercase_ (A : Tuple , A : List[Any]=None ): snake_case__ : List[Any] = [(x[0], x[1], get_model(x[2] )) for x in logs] snake_case__ : int = [x for x in logs if x[2] is not None] snake_case__ : Dict = {x[2] for x in logs} snake_case__ : List[Any] = {} for test in tests: snake_case__ : List[Any] = Counter() # count by errors in `test` counter.update([x[1] for x in logs if x[2] == test] ) snake_case__ : Tuple = counter.most_common() snake_case__ : List[str] = {error: count for error, count in counts if (error_filter is None or error not in error_filter)} snake_case__ : List[Any] = sum(error_counts.values() ) if n_errors > 0: snake_case__ : Optional[Any] = {'count': n_errors, 'errors': error_counts} snake_case__ : List[str] = dict(sorted(r.items() , key=lambda A : item[1]["count"] , reverse=A ) ) return r def lowercase_ (A : Tuple ): snake_case__ : Tuple = '| no. | error | status |' snake_case__ : Dict = '|-:|:-|:-|' snake_case__ : Dict = [header, sep] for error in reduced_by_error: snake_case__ : List[str] = reduced_by_error[error]['count'] snake_case__ : Tuple = F'''| {count} | {error[:1_0_0]} | |''' lines.append(A ) return "\n".join(A ) def lowercase_ (A : Optional[int] ): snake_case__ : Dict = '| model | no. of errors | major error | count |' snake_case__ : Optional[Any] = '|-:|-:|-:|-:|' snake_case__ : Any = [header, sep] for model in reduced_by_model: snake_case__ : List[Any] = reduced_by_model[model]['count'] snake_case__ : int = list(reduced_by_model[model]['errors'].items() )[0] snake_case__ : List[str] = F'''| {model} | {count} | {error[:6_0]} | {_count} |''' lines.append(A ) return "\n".join(A ) if __name__ == "__main__": a_ :str = argparse.ArgumentParser() # Required parameters parser.add_argument("--workflow_run_id", type=str, required=True, help="A GitHub Actions workflow run id.") parser.add_argument( "--output_dir", type=str, required=True, help="Where to store the downloaded artifacts and other result files.", ) parser.add_argument("--token", default=None, type=str, help="A token that has actions:read permission.") a_ :int = parser.parse_args() os.makedirs(args.output_dir, exist_ok=True) a_ :List[Any] = get_job_links(args.workflow_run_id, token=args.token) a_ :Optional[Any] = {} # To deal with `workflow_call` event, where a job name is the combination of the job names in the caller and callee. # For example, `PyTorch 1.11 / Model tests (models/albert, single-gpu)`. if _job_links: for k, v in _job_links.items(): # This is how GitHub actions combine job names. if " / " in k: a_ :List[Any] = k.find(" / ") a_ :int = k[index + len(" / ") :] a_ :Dict = v with open(os.path.join(args.output_dir, "job_links.json"), "w", encoding="UTF-8") as fp: json.dump(job_links, fp, ensure_ascii=False, indent=4) a_ :Dict = get_artifacts_links(args.workflow_run_id, token=args.token) with open(os.path.join(args.output_dir, "artifacts.json"), "w", encoding="UTF-8") as fp: json.dump(artifacts, fp, ensure_ascii=False, indent=4) for idx, (name, url) in enumerate(artifacts.items()): download_artifact(name, url, args.output_dir, args.token) # Be gentle to GitHub time.sleep(1) a_ :Optional[Any] = get_all_errors(args.output_dir, job_links=job_links) # `e[1]` is the error a_ :Optional[int] = Counter() counter.update([e[1] for e in errors]) # print the top 30 most common test errors a_ :Tuple = counter.most_common(30) for item in most_common: print(item) with open(os.path.join(args.output_dir, "errors.json"), "w", encoding="UTF-8") as fp: json.dump(errors, fp, ensure_ascii=False, indent=4) a_ :List[str] = reduce_by_error(errors) a_ :Union[str, Any] = reduce_by_model(errors) a_ :Optional[Any] = make_github_table(reduced_by_error) a_ :Optional[Any] = make_github_table_per_model(reduced_by_model) with open(os.path.join(args.output_dir, "reduced_by_error.txt"), "w", encoding="UTF-8") as fp: fp.write(sa) with open(os.path.join(args.output_dir, "reduced_by_model.txt"), "w", encoding="UTF-8") as fp: fp.write(sa)
704
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a_ :str = { "configuration_instructblip": [ "INSTRUCTBLIP_PRETRAINED_CONFIG_ARCHIVE_MAP", "InstructBlipConfig", "InstructBlipQFormerConfig", "InstructBlipVisionConfig", ], "processing_instructblip": ["InstructBlipProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ :Optional[int] = [ "INSTRUCTBLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "InstructBlipQFormerModel", "InstructBlipPreTrainedModel", "InstructBlipForConditionalGeneration", "InstructBlipVisionModel", ] if TYPE_CHECKING: from .configuration_instructblip import ( INSTRUCTBLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, InstructBlipConfig, InstructBlipQFormerConfig, InstructBlipVisionConfig, ) from .processing_instructblip import InstructBlipProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_instructblip import ( INSTRUCTBLIP_PRETRAINED_MODEL_ARCHIVE_LIST, InstructBlipForConditionalGeneration, InstructBlipPreTrainedModel, InstructBlipQFormerModel, InstructBlipVisionModel, ) else: import sys a_ :Dict = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
243
0
'''simple docstring''' def __UpperCamelCase ( UpperCAmelCase , UpperCAmelCase ): if discount_rate < 0: raise ValueError('''Discount rate cannot be negative''' ) if not cash_flows: raise ValueError('''Cash flows list cannot be empty''' ) lowercase__ : str = sum( cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(A__ ) ) return round(A__ , ndigits=2 ) if __name__ == "__main__": import doctest doctest.testmod()
152
'''simple docstring''' 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 lowercase_ (lowerCamelCase__ ): """simple docstring""" SCREAMING_SNAKE_CASE : Dict = 'blenderbot-small' SCREAMING_SNAKE_CASE : int = ['past_key_values'] SCREAMING_SNAKE_CASE : List[str] = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self : Optional[int] ,lowercase__ : List[str]=5_0_2_6_5 ,lowercase__ : Optional[Any]=5_1_2 ,lowercase__ : Optional[int]=8 ,lowercase__ : List[Any]=2_0_4_8 ,lowercase__ : List[str]=1_6 ,lowercase__ : str=8 ,lowercase__ : Any=2_0_4_8 ,lowercase__ : Tuple=1_6 ,lowercase__ : Tuple=0.0 ,lowercase__ : List[str]=0.0 ,lowercase__ : Any=True ,lowercase__ : str=True ,lowercase__ : int="gelu" ,lowercase__ : Tuple=5_1_2 ,lowercase__ : List[Any]=0.1 ,lowercase__ : Tuple=0.0 ,lowercase__ : str=0.0 ,lowercase__ : Any=0.0_2 ,lowercase__ : Union[str, Any]=1 ,lowercase__ : List[Any]=False ,lowercase__ : Optional[int]=0 ,lowercase__ : Optional[int]=1 ,lowercase__ : str=2 ,lowercase__ : int=2 ,**lowercase__ : List[str] ,): __lowercase = vocab_size __lowercase = max_position_embeddings __lowercase = d_model __lowercase = encoder_ffn_dim __lowercase = encoder_layers __lowercase = encoder_attention_heads __lowercase = decoder_ffn_dim __lowercase = decoder_layers __lowercase = decoder_attention_heads __lowercase = dropout __lowercase = attention_dropout __lowercase = activation_dropout __lowercase = activation_function __lowercase = init_std __lowercase = encoder_layerdrop __lowercase = decoder_layerdrop __lowercase = use_cache __lowercase = encoder_layers __lowercase = 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 lowercase_ (lowerCamelCase__ ): """simple docstring""" @property def SCREAMING_SNAKE_CASE ( self : Dict ): if self.task in ["default", "seq2seq-lm"]: __lowercase = OrderedDict( [ ('''input_ids''', {0: '''batch''', 1: '''encoder_sequence'''}), ('''attention_mask''', {0: '''batch''', 1: '''encoder_sequence'''}), ] ) if self.use_past: __lowercase = {0: '''batch'''} __lowercase = {0: '''batch''', 1: '''past_decoder_sequence + sequence'''} else: __lowercase = {0: '''batch''', 1: '''decoder_sequence'''} __lowercase = {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. __lowercase = OrderedDict( [ ('''input_ids''', {0: '''batch''', 1: '''encoder_sequence'''}), ('''attention_mask''', {0: '''batch''', 1: '''encoder_sequence'''}), ] ) if self.use_past: __lowercase , __lowercase = self.num_layers for i in range(lowercase__ ): __lowercase = {0: '''batch''', 2: '''past_sequence + sequence'''} __lowercase = {0: '''batch''', 2: '''past_sequence + sequence'''} else: __lowercase = 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 SCREAMING_SNAKE_CASE ( self : List[Any] ): if self.task in ["default", "seq2seq-lm"]: __lowercase = super().outputs else: __lowercase = super(lowercase__ ,self ).outputs if self.use_past: __lowercase , __lowercase = self.num_layers for i in range(lowercase__ ): __lowercase = {0: '''batch''', 2: '''past_sequence + sequence'''} __lowercase = {0: '''batch''', 2: '''past_sequence + sequence'''} return common_outputs def SCREAMING_SNAKE_CASE ( self : Dict ,lowercase__ : PreTrainedTokenizer ,lowercase__ : int = -1 ,lowercase__ : int = -1 ,lowercase__ : bool = False ,lowercase__ : Optional[TensorType] = None ,): __lowercase = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( lowercase__ ,lowercase__ ,lowercase__ ,lowercase__ ,lowercase__ ) # Generate decoder inputs __lowercase = seq_length if not self.use_past else 1 __lowercase = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( lowercase__ ,lowercase__ ,lowercase__ ,lowercase__ ,lowercase__ ) __lowercase = {F"decoder_{name}": tensor for name, tensor in decoder_inputs.items()} __lowercase = 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 __lowercase , __lowercase = common_inputs['''input_ids'''].shape __lowercase = common_inputs['''decoder_input_ids'''].shape[1] __lowercase , __lowercase = self.num_attention_heads __lowercase = ( batch, num_encoder_attention_heads, encoder_seq_length, self._config.hidden_size // num_encoder_attention_heads, ) __lowercase = decoder_seq_length + 3 __lowercase = ( batch, num_decoder_attention_heads, decoder_past_length, self._config.hidden_size // num_decoder_attention_heads, ) __lowercase = torch.cat( [common_inputs['''decoder_attention_mask'''], torch.ones(lowercase__ ,lowercase__ )] ,dim=1 ) __lowercase = [] # If the number of encoder and decoder layers are present in the model configuration, both are considered __lowercase , __lowercase = self.num_layers __lowercase = min(lowercase__ ,lowercase__ ) __lowercase = max(lowercase__ ,lowercase__ ) - min_num_layers __lowercase = '''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. __lowercase = 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 SCREAMING_SNAKE_CASE ( self : Any ,lowercase__ : PreTrainedTokenizer ,lowercase__ : int = -1 ,lowercase__ : int = -1 ,lowercase__ : bool = False ,lowercase__ : Optional[TensorType] = None ,): __lowercase = 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 __lowercase , __lowercase = common_inputs['''input_ids'''].shape # Not using the same length for past_key_values __lowercase = seqlen + 2 __lowercase , __lowercase = self.num_layers __lowercase , __lowercase = self.num_attention_heads __lowercase = ( batch, num_encoder_attention_heads, past_key_values_length, self._config.hidden_size // num_encoder_attention_heads, ) __lowercase = common_inputs['''attention_mask'''].dtype __lowercase = torch.cat( [common_inputs['''attention_mask'''], torch.ones(lowercase__ ,lowercase__ ,dtype=lowercase__ )] ,dim=1 ) __lowercase = [ (torch.zeros(lowercase__ ), torch.zeros(lowercase__ )) for _ in range(lowercase__ ) ] return common_inputs def SCREAMING_SNAKE_CASE ( self : List[str] ,lowercase__ : PreTrainedTokenizer ,lowercase__ : int = -1 ,lowercase__ : int = -1 ,lowercase__ : bool = False ,lowercase__ : Optional[TensorType] = None ,): # 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 __lowercase = 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 __lowercase = tokenizer.num_special_tokens_to_add(lowercase__ ) __lowercase = 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 __lowercase = [''' '''.join([tokenizer.unk_token] ) * seq_length] * batch_size __lowercase = dict(tokenizer(lowercase__ ,return_tensors=lowercase__ ) ) return common_inputs def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,lowercase__ : PreTrainedTokenizer ,lowercase__ : int = -1 ,lowercase__ : int = -1 ,lowercase__ : bool = False ,lowercase__ : Optional[TensorType] = None ,): if self.task in ["default", "seq2seq-lm"]: __lowercase = 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": __lowercase = self._generate_dummy_inputs_for_causal_lm( lowercase__ ,batch_size=lowercase__ ,seq_length=lowercase__ ,is_pair=lowercase__ ,framework=lowercase__ ) else: __lowercase = 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 SCREAMING_SNAKE_CASE ( self : Tuple ,lowercase__ : List[Any] ,lowercase__ : Tuple ,lowercase__ : List[Any] ,lowercase__ : Optional[Any] ): if self.task in ["default", "seq2seq-lm"]: __lowercase = super()._flatten_past_key_values_(lowercase__ ,lowercase__ ,lowercase__ ,lowercase__ ) else: __lowercase = super(lowercase__ ,self )._flatten_past_key_values_( lowercase__ ,lowercase__ ,lowercase__ ,lowercase__ )
41
0
def _UpperCAmelCase ( a : str ): return " ".join(input_str.split()[::-1] ) if __name__ == "__main__": import doctest doctest.testmod()
99
from collections.abc import Callable def _UpperCAmelCase ( a : Callable[[float], float] , a : float , a : float ): snake_case__ = a snake_case__ = b if function(a ) == 0: # one of the a or b is a root for the function return a elif function(a ) == 0: return b elif ( function(a ) * function(a ) > 0 ): # if none of these are root and they are both positive or negative, # then this algorithm can't find the root raise ValueError("""could not find root in given interval.""" ) else: snake_case__ = start + (end - start) / 2.0 while abs(start - mid ) > 10**-7: # until precisely equals to 10^-7 if function(a ) == 0: return mid elif function(a ) * function(a ) < 0: snake_case__ = mid else: snake_case__ = mid snake_case__ = start + (end - start) / 2.0 return mid def _UpperCAmelCase ( a : float ): return x**3 - 2 * x - 5 if __name__ == "__main__": print(bisection(f, 1, 1_0_0_0)) import doctest doctest.testmod()
99
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _UpperCAmelCase = { """configuration_roberta""": ["""ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP""", """RobertaConfig""", """RobertaOnnxConfig"""], """tokenization_roberta""": ["""RobertaTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = ["""RobertaTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = [ """ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST""", """RobertaForCausalLM""", """RobertaForMaskedLM""", """RobertaForMultipleChoice""", """RobertaForQuestionAnswering""", """RobertaForSequenceClassification""", """RobertaForTokenClassification""", """RobertaModel""", """RobertaPreTrainedModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = [ """TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFRobertaForCausalLM""", """TFRobertaForMaskedLM""", """TFRobertaForMultipleChoice""", """TFRobertaForQuestionAnswering""", """TFRobertaForSequenceClassification""", """TFRobertaForTokenClassification""", """TFRobertaMainLayer""", """TFRobertaModel""", """TFRobertaPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = [ """FlaxRobertaForCausalLM""", """FlaxRobertaForMaskedLM""", """FlaxRobertaForMultipleChoice""", """FlaxRobertaForQuestionAnswering""", """FlaxRobertaForSequenceClassification""", """FlaxRobertaForTokenClassification""", """FlaxRobertaModel""", """FlaxRobertaPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_roberta import ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, RobertaConfig, RobertaOnnxConfig from .tokenization_roberta import RobertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roberta_fast import RobertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roberta import ( ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, RobertaForCausalLM, RobertaForMaskedLM, RobertaForMultipleChoice, RobertaForQuestionAnswering, RobertaForSequenceClassification, RobertaForTokenClassification, RobertaModel, RobertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roberta import ( TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFRobertaForCausalLM, TFRobertaForMaskedLM, TFRobertaForMultipleChoice, TFRobertaForQuestionAnswering, TFRobertaForSequenceClassification, TFRobertaForTokenClassification, TFRobertaMainLayer, TFRobertaModel, TFRobertaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roberta import ( FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaModel, FlaxRobertaPreTrainedModel, ) else: import sys _UpperCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
558
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() _UpperCAmelCase = logging.get_logger(__name__) _UpperCAmelCase = { """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 UpperCamelCase ( __lowercase : int ,__lowercase : List[str] ,__lowercase : str ,__lowercase : Optional[Any] ,__lowercase : Any ): '''simple docstring''' for attribute in key.split('.' ): A_ : Dict = getattr(__lowercase ,__lowercase ) if weight_type is not None: A_ : Any = getattr(__lowercase ,__lowercase ).shape else: A_ : Optional[Any] = hf_pointer.shape assert hf_shape == value.shape, ( f'''Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be''' f''' {value.shape} for {full_name}''' ) if weight_type == "weight": A_ : int = value elif weight_type == "weight_g": A_ : Tuple = value elif weight_type == "weight_v": A_ : Union[str, Any] = value elif weight_type == "bias": A_ : Any = value else: A_ : str = value logger.info(f'''{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.''' ) def UpperCamelCase ( __lowercase : str ,__lowercase : Dict ,__lowercase : Tuple ): '''simple docstring''' A_ : Optional[Any] = [] A_ : Tuple = fairseq_model.state_dict() A_ : Any = hf_model.sew.feature_extractor if is_finetuned else hf_model.feature_extractor for name, value in fairseq_dict.items(): A_ : Union[str, Any] = False if "conv_layers" in name: load_conv_layer( __lowercase ,__lowercase ,__lowercase ,__lowercase ,hf_model.config.feat_extract_norm == 'group' ,) A_ : List[str] = True else: for key, mapped_key in MAPPING.items(): A_ : str = '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_ : int = True if "*" in mapped_key: A_ : str = name.split(__lowercase )[0].split('.' )[-2] A_ : Optional[Any] = mapped_key.replace('*' ,__lowercase ) if "weight_g" in name: A_ : Dict = 'weight_g' elif "weight_v" in name: A_ : Tuple = 'weight_v' elif "weight" in name: A_ : Union[str, Any] = 'weight' elif "bias" in name: A_ : Optional[Any] = 'bias' else: A_ : Union[str, Any] = None set_recursively(__lowercase ,__lowercase ,__lowercase ,__lowercase ,__lowercase ) continue if not is_used: unused_weights.append(__lowercase ) logger.warning(f'''Unused weights: {unused_weights}''' ) def UpperCamelCase ( __lowercase : Optional[Any] ,__lowercase : Union[str, Any] ,__lowercase : Any ,__lowercase : List[Any] ,__lowercase : Union[str, Any] ): '''simple docstring''' A_ : Optional[int] = full_name.split('conv_layers.' )[-1] A_ : Any = name.split('.' ) A_ : Dict = int(items[0] ) A_ : Optional[int] = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( f'''{full_name} has size {value.shape}, but''' f''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.''' ) A_ : Optional[int] = value logger.info(f'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( f'''{full_name} has size {value.shape}, but''' f''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.''' ) A_ : Union[str, Any] = value logger.info(f'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( f'''{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was''' " found." ) A_ : Any = value logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( f'''{full_name} has size {value.shape}, but''' f''' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.''' ) A_ : Tuple = value logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) else: unused_weights.append(__lowercase ) def UpperCamelCase ( __lowercase : List[str] ,__lowercase : str ): '''simple docstring''' A_ : Union[str, Any] = SEWConfig() if is_finetuned: A_ : Any = model.wav_encoder.wav_model.cfg else: A_ : int = model.cfg A_ : Any = fs_config.conv_bias A_ : Dict = eval(fs_config.conv_feature_layers ) A_ : List[Any] = [x[0] for x in conv_layers] A_ : Optional[Any] = [x[1] for x in conv_layers] A_ : List[Any] = [x[2] for x in conv_layers] A_ : Optional[int] = 'gelu' A_ : Union[str, Any] = 'layer' if fs_config.extractor_mode == 'layer_norm' else 'group' A_ : Tuple = 0.0 A_ : Dict = fs_config.activation_fn.name A_ : List[Any] = fs_config.encoder_embed_dim A_ : int = 0.02 A_ : List[str] = fs_config.encoder_ffn_embed_dim A_ : Any = 1e-5 A_ : Optional[Any] = fs_config.encoder_layerdrop A_ : Optional[int] = fs_config.encoder_attention_heads A_ : Any = fs_config.conv_pos_groups A_ : int = fs_config.conv_pos A_ : Tuple = len(__lowercase ) A_ : List[Any] = fs_config.encoder_layers A_ : Any = fs_config.squeeze_factor # take care of any params that are overridden by the Wav2VecCtc model if is_finetuned: A_ : Union[str, Any] = model.cfg A_ : str = fs_config.final_dropout A_ : Any = fs_config.layerdrop A_ : str = fs_config.activation_dropout A_ : Any = fs_config.mask_prob > 0 or fs_config.mask_channel_prob > 0 A_ : str = fs_config.attention_dropout A_ : Any = fs_config.dropout_input A_ : Dict = fs_config.dropout A_ : Optional[Any] = fs_config.mask_channel_length A_ : List[str] = fs_config.mask_channel_prob A_ : Tuple = fs_config.mask_length A_ : Dict = fs_config.mask_prob A_ : Any = 'Wav2Vec2FeatureExtractor' A_ : Union[str, Any] = 'Wav2Vec2CTCTokenizer' return config @torch.no_grad() def UpperCamelCase ( __lowercase : List[Any] ,__lowercase : int ,__lowercase : Optional[int]=None ,__lowercase : Optional[Any]=None ,__lowercase : str=True ): '''simple docstring''' if is_finetuned: A_ , A_ , A_ : List[Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] ,arg_overrides={'data': '/'.join(dict_path.split('/' )[:-1] )} ) else: A_ , A_ , A_ : Union[str, Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ) if config_path is not None: A_ : Union[str, Any] = SEWConfig.from_pretrained(__lowercase ) else: A_ : Dict = convert_config(model[0] ,__lowercase ) A_ : Union[str, Any] = model[0].eval() A_ : Optional[int] = True if config.feat_extract_norm == 'layer' else False A_ : List[Any] = WavaVecaFeatureExtractor( feature_size=1 ,sampling_rate=1_60_00 ,padding_value=0 ,do_normalize=__lowercase ,return_attention_mask=__lowercase ,) if is_finetuned: if dict_path: A_ : Optional[int] = Dictionary.load(__lowercase ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq A_ : int = target_dict.pad_index A_ : List[Any] = target_dict.bos_index A_ : Optional[Any] = target_dict.pad_index A_ : str = target_dict.bos_index A_ : str = target_dict.eos_index A_ : str = len(target_dict.symbols ) A_ : Union[str, Any] = os.path.join(__lowercase ,'vocab.json' ) if not os.path.isdir(__lowercase ): logger.error('--pytorch_dump_folder_path ({}) should be a directory'.format(__lowercase ) ) return os.makedirs(__lowercase ,exist_ok=__lowercase ) with open(__lowercase ,'w' ,encoding='utf-8' ) as vocab_handle: json.dump(target_dict.indices ,__lowercase ) A_ : Any = WavaVecaCTCTokenizer( __lowercase ,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=__lowercase ,) A_ : Tuple = WavaVecaProcessor(feature_extractor=__lowercase ,tokenizer=__lowercase ) processor.save_pretrained(__lowercase ) A_ : Dict = SEWForCTC(__lowercase ) else: A_ : Tuple = SEWModel(__lowercase ) feature_extractor.save_pretrained(__lowercase ) recursively_load_weights(__lowercase ,__lowercase ,__lowercase ) hf_model.save_pretrained(__lowercase ) if __name__ == "__main__": _UpperCAmelCase = 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""" ) _UpperCAmelCase = parser.parse_args() convert_sew_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, args.is_finetuned )
558
1
# DISCLAIMER: This file is strongly influenced by https://github.com/yang-song/score_sde_pytorch import math from typing import Union import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import randn_tensor from .scheduling_utils import SchedulerMixin class lowerCAmelCase__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = 1 @register_to_config def __init__( self , lowercase__=2_0_0_0 , lowercase__=0.1 , lowercase__=2_0 , lowercase__=1E-3 ): '''simple docstring''' __A =None __A =None __A =None def __UpperCamelCase ( self , lowercase__ , lowercase__ = None ): '''simple docstring''' __A =torch.linspace(1 , self.config.sampling_eps , __snake_case , device=__snake_case ) def __UpperCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__=None ): '''simple docstring''' if self.timesteps is None: raise ValueError( '''`self.timesteps` is not set, you need to run \'set_timesteps\' after creating the scheduler''' ) # TODO(Patrick) better comments + non-PyTorch # postprocess model score __A =( -0.25 * t**2 * (self.config.beta_max - self.config.beta_min) - 0.5 * t * self.config.beta_min ) __A =torch.sqrt(1.0 - torch.exp(2.0 * log_mean_coeff ) ) __A =std.flatten() while len(std.shape ) < len(score.shape ): __A =std.unsqueeze(-1 ) __A =-score / std # compute __A =-1.0 / len(self.timesteps ) __A =self.config.beta_min + t * (self.config.beta_max - self.config.beta_min) __A =beta_t.flatten() while len(beta_t.shape ) < len(x.shape ): __A =beta_t.unsqueeze(-1 ) __A =-0.5 * beta_t * x __A =torch.sqrt(__snake_case ) __A =drift - diffusion**2 * score __A =x + drift * dt # add noise __A =randn_tensor(x.shape , layout=x.layout , generator=__snake_case , device=x.device , dtype=x.dtype ) __A =x_mean + diffusion * math.sqrt(-dt ) * noise return x, x_mean def __len__( self ): '''simple docstring''' return self.config.num_train_timesteps
705
from ..utils import DummyObject, requires_backends class lowerCAmelCase__ ( metaclass=__magic_name__ ): '''simple docstring''' lowercase_ = ["""torch"""] def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(self , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) class lowerCAmelCase__ ( metaclass=__magic_name__ ): '''simple docstring''' lowercase_ = ["""torch"""] def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(self , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) class lowerCAmelCase__ ( metaclass=__magic_name__ ): '''simple docstring''' lowercase_ = ["""torch"""] def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(self , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) class lowerCAmelCase__ ( metaclass=__magic_name__ ): '''simple docstring''' lowercase_ = ["""torch"""] def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(self , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) class lowerCAmelCase__ ( metaclass=__magic_name__ ): '''simple docstring''' lowercase_ = ["""torch"""] def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(self , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) class lowerCAmelCase__ ( metaclass=__magic_name__ ): '''simple docstring''' lowercase_ = ["""torch"""] def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(self , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) class lowerCAmelCase__ ( metaclass=__magic_name__ ): '''simple docstring''' lowercase_ = ["""torch"""] def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(self , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) class lowerCAmelCase__ ( metaclass=__magic_name__ ): '''simple docstring''' lowercase_ = ["""torch"""] def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(self , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) class lowerCAmelCase__ ( metaclass=__magic_name__ ): '''simple docstring''' lowercase_ = ["""torch"""] def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(self , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) class lowerCAmelCase__ ( metaclass=__magic_name__ ): '''simple docstring''' lowercase_ = ["""torch"""] def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(self , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) class lowerCAmelCase__ ( metaclass=__magic_name__ ): '''simple docstring''' lowercase_ = ["""torch"""] def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(self , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) def A__ ( *__A : Optional[int] , **__A : Union[str, Any] ) ->Dict: requires_backends(__A , ['''torch'''] ) def A__ ( *__A : str , **__A : int ) ->List[Any]: requires_backends(__A , ['''torch'''] ) def A__ ( *__A : Dict , **__A : str ) ->Tuple: requires_backends(__A , ['''torch'''] ) def A__ ( *__A : Optional[Any] , **__A : Dict ) ->Optional[Any]: requires_backends(__A , ['''torch'''] ) def A__ ( *__A : str , **__A : str ) ->Any: requires_backends(__A , ['''torch'''] ) def A__ ( *__A : List[Any] , **__A : Dict ) ->Union[str, Any]: requires_backends(__A , ['''torch'''] ) def A__ ( *__A : Optional[int] , **__A : Optional[int] ) ->Any: requires_backends(__A , ['''torch'''] ) class lowerCAmelCase__ ( metaclass=__magic_name__ ): '''simple docstring''' lowercase_ = ["""torch"""] def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(self , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) class lowerCAmelCase__ ( metaclass=__magic_name__ ): '''simple docstring''' lowercase_ = ["""torch"""] def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(self , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) class lowerCAmelCase__ ( metaclass=__magic_name__ ): '''simple docstring''' lowercase_ = ["""torch"""] def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(self , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) class lowerCAmelCase__ ( metaclass=__magic_name__ ): '''simple docstring''' lowercase_ = ["""torch"""] def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(self , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) class lowerCAmelCase__ ( metaclass=__magic_name__ ): '''simple docstring''' lowercase_ = ["""torch"""] def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(self , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) class lowerCAmelCase__ ( metaclass=__magic_name__ ): '''simple docstring''' lowercase_ = ["""torch"""] def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(self , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) class lowerCAmelCase__ ( metaclass=__magic_name__ ): '''simple docstring''' lowercase_ = ["""torch"""] def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(self , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) class lowerCAmelCase__ ( metaclass=__magic_name__ ): '''simple docstring''' lowercase_ = ["""torch"""] def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(self , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) class lowerCAmelCase__ ( metaclass=__magic_name__ ): '''simple docstring''' lowercase_ = ["""torch"""] def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(self , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) class lowerCAmelCase__ ( metaclass=__magic_name__ ): '''simple docstring''' lowercase_ = ["""torch"""] def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(self , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) class lowerCAmelCase__ ( metaclass=__magic_name__ ): '''simple docstring''' lowercase_ = ["""torch"""] def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(self , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) class lowerCAmelCase__ ( metaclass=__magic_name__ ): '''simple docstring''' lowercase_ = ["""torch"""] def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(self , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) class lowerCAmelCase__ ( metaclass=__magic_name__ ): '''simple docstring''' lowercase_ = ["""torch"""] def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(self , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) class lowerCAmelCase__ ( metaclass=__magic_name__ ): '''simple docstring''' lowercase_ = ["""torch"""] def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(self , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) class lowerCAmelCase__ ( metaclass=__magic_name__ ): '''simple docstring''' lowercase_ = ["""torch"""] def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(self , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) class lowerCAmelCase__ ( metaclass=__magic_name__ ): '''simple docstring''' lowercase_ = ["""torch"""] def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(self , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) class lowerCAmelCase__ ( metaclass=__magic_name__ ): '''simple docstring''' lowercase_ = ["""torch"""] def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(self , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) class lowerCAmelCase__ ( metaclass=__magic_name__ ): '''simple docstring''' lowercase_ = ["""torch"""] def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(self , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) class lowerCAmelCase__ ( metaclass=__magic_name__ ): '''simple docstring''' lowercase_ = ["""torch"""] def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(self , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) class lowerCAmelCase__ ( metaclass=__magic_name__ ): '''simple docstring''' lowercase_ = ["""torch"""] def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(self , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) class lowerCAmelCase__ ( metaclass=__magic_name__ ): '''simple docstring''' lowercase_ = ["""torch"""] def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(self , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) class lowerCAmelCase__ ( metaclass=__magic_name__ ): '''simple docstring''' lowercase_ = ["""torch"""] def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(self , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) class lowerCAmelCase__ ( metaclass=__magic_name__ ): '''simple docstring''' lowercase_ = ["""torch"""] def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(self , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) class lowerCAmelCase__ ( metaclass=__magic_name__ ): '''simple docstring''' lowercase_ = ["""torch"""] def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(self , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) class lowerCAmelCase__ ( metaclass=__magic_name__ ): '''simple docstring''' lowercase_ = ["""torch"""] def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(self , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) class lowerCAmelCase__ ( metaclass=__magic_name__ ): '''simple docstring''' lowercase_ = ["""torch"""] def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(self , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) class lowerCAmelCase__ ( metaclass=__magic_name__ ): '''simple docstring''' lowercase_ = ["""torch"""] def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(self , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) class lowerCAmelCase__ ( metaclass=__magic_name__ ): '''simple docstring''' lowercase_ = ["""torch"""] def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(self , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) class lowerCAmelCase__ ( metaclass=__magic_name__ ): '''simple docstring''' lowercase_ = ["""torch"""] def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(self , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) class lowerCAmelCase__ ( metaclass=__magic_name__ ): '''simple docstring''' lowercase_ = ["""torch"""] def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(self , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) class lowerCAmelCase__ ( metaclass=__magic_name__ ): '''simple docstring''' lowercase_ = ["""torch"""] def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(self , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) class lowerCAmelCase__ ( metaclass=__magic_name__ ): '''simple docstring''' lowercase_ = ["""torch"""] def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(self , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) class lowerCAmelCase__ ( metaclass=__magic_name__ ): '''simple docstring''' lowercase_ = ["""torch"""] def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(self , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) class lowerCAmelCase__ ( metaclass=__magic_name__ ): '''simple docstring''' lowercase_ = ["""torch"""] def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(self , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) class lowerCAmelCase__ ( metaclass=__magic_name__ ): '''simple docstring''' lowercase_ = ["""torch"""] def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(self , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) class lowerCAmelCase__ ( metaclass=__magic_name__ ): '''simple docstring''' lowercase_ = ["""torch"""] def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(self , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) class lowerCAmelCase__ ( metaclass=__magic_name__ ): '''simple docstring''' lowercase_ = ["""torch"""] def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(self , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) class lowerCAmelCase__ ( metaclass=__magic_name__ ): '''simple docstring''' lowercase_ = ["""torch"""] def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(self , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) class lowerCAmelCase__ ( metaclass=__magic_name__ ): '''simple docstring''' lowercase_ = ["""torch"""] def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(self , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] ) @classmethod def __UpperCamelCase ( cls , *lowercase__ , **lowercase__ ): '''simple docstring''' requires_backends(cls , ['''torch'''] )
516
0
"""simple docstring""" import inspect from typing import Callable, List, Optional, Union import torch from transformers import ( CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, WhisperForConditionalGeneration, WhisperProcessor, ) from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.utils import logging UpperCAmelCase = logging.get_logger(__name__) # pylint: disable=invalid-name class lowercase__ ( A_ ): def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , ) -> Union[str, Any]: super().__init__() if safety_checker is None: logger.warning( F'You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure' """ that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered""" """ results in services or applications open to the public. Both the diffusers team and Hugging Face""" """ strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling""" """ it only for use-cases that involve analyzing network behavior or auditing its results. For more""" """ information, please have a look at https://github.com/huggingface/diffusers/pull/254 .""") self.register_modules( speech_model=SCREAMING_SNAKE_CASE , speech_processor=SCREAMING_SNAKE_CASE , vae=SCREAMING_SNAKE_CASE , text_encoder=SCREAMING_SNAKE_CASE , tokenizer=SCREAMING_SNAKE_CASE , unet=SCREAMING_SNAKE_CASE , scheduler=SCREAMING_SNAKE_CASE , feature_extractor=SCREAMING_SNAKE_CASE , ) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE = "auto") -> Dict: if slice_size == "auto": _lowerCamelCase : int = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Any: self.enable_attention_slicing(SCREAMING_SNAKE_CASE) @torch.no_grad() def __call__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=1_6000 , SCREAMING_SNAKE_CASE = 512 , SCREAMING_SNAKE_CASE = 512 , SCREAMING_SNAKE_CASE = 50 , SCREAMING_SNAKE_CASE = 7.5 , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = 1 , SCREAMING_SNAKE_CASE = 0.0 , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = "pil" , SCREAMING_SNAKE_CASE = True , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = 1 , **SCREAMING_SNAKE_CASE , ) -> Dict: _lowerCamelCase : Dict = self.speech_processor.feature_extractor( SCREAMING_SNAKE_CASE , return_tensors="""pt""" , sampling_rate=SCREAMING_SNAKE_CASE).input_features.to(self.device) _lowerCamelCase : Union[str, Any] = self.speech_model.generate(SCREAMING_SNAKE_CASE , max_length=48_0000) _lowerCamelCase : Optional[int] = self.speech_processor.tokenizer.batch_decode(SCREAMING_SNAKE_CASE , skip_special_tokens=SCREAMING_SNAKE_CASE , normalize=SCREAMING_SNAKE_CASE)[ 0 ] if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE): _lowerCamelCase : Tuple = 1 elif isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE): _lowerCamelCase : Union[str, Any] = len(SCREAMING_SNAKE_CASE) else: raise ValueError(F'`prompt` has to be of type `str` or `list` but is {type(SCREAMING_SNAKE_CASE)}') if height % 8 != 0 or width % 8 != 0: raise ValueError(F'`height` and `width` have to be divisible by 8 but are {height} and {width}.') if (callback_steps is None) or ( callback_steps is not None and (not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) or callback_steps <= 0) ): raise ValueError( F'`callback_steps` has to be a positive integer but is {callback_steps} of type' F' {type(SCREAMING_SNAKE_CASE)}.') # get prompt text embeddings _lowerCamelCase : Tuple = self.tokenizer( SCREAMING_SNAKE_CASE , padding="""max_length""" , max_length=self.tokenizer.model_max_length , return_tensors="""pt""" , ) _lowerCamelCase : Any = text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: _lowerCamelCase : Union[str, Any] = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :]) logger.warning( """The following part of your input was truncated because CLIP can only handle sequences up to""" F' {self.tokenizer.model_max_length} tokens: {removed_text}') _lowerCamelCase : int = text_input_ids[:, : self.tokenizer.model_max_length] _lowerCamelCase : Union[str, Any] = self.text_encoder(text_input_ids.to(self.device))[0] # duplicate text embeddings for each generation per prompt, using mps friendly method _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : int = text_embeddings.shape _lowerCamelCase : Optional[int] = text_embeddings.repeat(1 , SCREAMING_SNAKE_CASE , 1) _lowerCamelCase : Optional[int] = text_embeddings.view(bs_embed * num_images_per_prompt , SCREAMING_SNAKE_CASE , -1) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. _lowerCamelCase : Optional[int] = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: _lowerCamelCase : List[str] if negative_prompt is None: _lowerCamelCase : List[Any] = [""""""] * batch_size elif type(SCREAMING_SNAKE_CASE) is not type(SCREAMING_SNAKE_CASE): raise TypeError( F'`negative_prompt` should be the same type to `prompt`, but got {type(SCREAMING_SNAKE_CASE)} !=' F' {type(SCREAMING_SNAKE_CASE)}.') elif isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE): _lowerCamelCase : Optional[Any] = [negative_prompt] elif batch_size != len(SCREAMING_SNAKE_CASE): raise ValueError( F'`negative_prompt`: {negative_prompt} has batch size {len(SCREAMING_SNAKE_CASE)}, but `prompt`:' F' {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches' """ the batch size of `prompt`.""") else: _lowerCamelCase : Any = negative_prompt _lowerCamelCase : int = text_input_ids.shape[-1] _lowerCamelCase : str = self.tokenizer( SCREAMING_SNAKE_CASE , padding="""max_length""" , max_length=SCREAMING_SNAKE_CASE , truncation=SCREAMING_SNAKE_CASE , return_tensors="""pt""" , ) _lowerCamelCase : List[Any] = self.text_encoder(uncond_input.input_ids.to(self.device))[0] # duplicate unconditional embeddings for each generation per prompt, using mps friendly method _lowerCamelCase : List[Any] = uncond_embeddings.shape[1] _lowerCamelCase : Optional[int] = uncond_embeddings.repeat(1 , SCREAMING_SNAKE_CASE , 1) _lowerCamelCase : List[Any] = uncond_embeddings.view(batch_size * num_images_per_prompt , SCREAMING_SNAKE_CASE , -1) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes _lowerCamelCase : Optional[Any] = torch.cat([uncond_embeddings, text_embeddings]) # get the initial random noise unless the user supplied it # Unlike in other pipelines, latents need to be generated in the target device # for 1-to-1 results reproducibility with the CompVis implementation. # However this currently doesn't work in `mps`. _lowerCamelCase : Optional[int] = (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8) _lowerCamelCase : Any = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not exist on mps _lowerCamelCase : str = torch.randn(SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE , device="""cpu""" , dtype=SCREAMING_SNAKE_CASE).to( self.device) else: _lowerCamelCase : List[str] = torch.randn(SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE , device=self.device , dtype=SCREAMING_SNAKE_CASE) else: if latents.shape != latents_shape: raise ValueError(F'Unexpected latents shape, got {latents.shape}, expected {latents_shape}') _lowerCamelCase : str = latents.to(self.device) # set timesteps self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand _lowerCamelCase : Union[str, Any] = self.scheduler.timesteps.to(self.device) # scale the initial noise by the standard deviation required by the scheduler _lowerCamelCase : Any = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] _lowerCamelCase : str = """eta""" in set(inspect.signature(self.scheduler.step).parameters.keys()) _lowerCamelCase : Dict = {} if accepts_eta: _lowerCamelCase : Any = eta for i, t in enumerate(self.progress_bar(SCREAMING_SNAKE_CASE)): # expand the latents if we are doing classifier free guidance _lowerCamelCase : Optional[int] = torch.cat([latents] * 2) if do_classifier_free_guidance else latents _lowerCamelCase : str = self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) # predict the noise residual _lowerCamelCase : str = self.unet(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , encoder_hidden_states=SCREAMING_SNAKE_CASE).sample # perform guidance if do_classifier_free_guidance: _lowerCamelCase , _lowerCamelCase : Dict = noise_pred.chunk(2) _lowerCamelCase : int = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # compute the previous noisy sample x_t -> x_t-1 _lowerCamelCase : Tuple = self.scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) _lowerCamelCase : Dict = 1 / 0.1_82_15 * latents _lowerCamelCase : Tuple = self.vae.decode(SCREAMING_SNAKE_CASE).sample _lowerCamelCase : int = (image / 2 + 0.5).clamp(0 , 1) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 _lowerCamelCase : Optional[Any] = image.cpu().permute(0 , 2 , 3 , 1).float().numpy() if output_type == "pil": _lowerCamelCase : Optional[Any] = self.numpy_to_pil(SCREAMING_SNAKE_CASE) if not return_dict: return image return StableDiffusionPipelineOutput(images=SCREAMING_SNAKE_CASE , nsfw_content_detected=SCREAMING_SNAKE_CASE)
88
'''simple docstring''' def __UpperCAmelCase ( _UpperCAmelCase : int = 1_00_00_00 ) -> int: __snake_case = 1 __snake_case = 1 __snake_case = {1: 1} for inputa in range(2 , _UpperCAmelCase ): __snake_case = 0 __snake_case = inputa while True: if number in counters: counter += counters[number] break if number % 2 == 0: number //= 2 counter += 1 else: __snake_case = (3 * number) + 1 counter += 1 if inputa not in counters: __snake_case = counter if counter > pre_counter: __snake_case = inputa __snake_case = counter return largest_number if __name__ == "__main__": print(solution(int(input().strip())))
69
0
'''simple docstring''' import os import shutil from pathlib import Path from typing import Optional, Union import numpy as np from huggingface_hub import hf_hub_download from ..utils import ONNX_EXTERNAL_WEIGHTS_NAME, ONNX_WEIGHTS_NAME, is_onnx_available, logging if is_onnx_available(): import onnxruntime as ort __SCREAMING_SNAKE_CASE =logging.get_logger(__name__) __SCREAMING_SNAKE_CASE ={ """tensor(bool)""": np.bool_, """tensor(int8)""": np.inta, """tensor(uint8)""": np.uinta, """tensor(int16)""": np.intaa, """tensor(uint16)""": np.uintaa, """tensor(int32)""": np.intaa, """tensor(uint32)""": np.uintaa, """tensor(int64)""": np.intaa, """tensor(uint64)""": np.uintaa, """tensor(float16)""": np.floataa, """tensor(float)""": np.floataa, """tensor(double)""": np.floataa, } class __magic_name__ : '''simple docstring''' def __init__( self: List[Any] , _lowerCamelCase: Tuple=None , **_lowerCamelCase: str ): logger.info('''`diffusers.OnnxRuntimeModel` is experimental and might change in the future.''' ) SCREAMING_SNAKE_CASE_ = model SCREAMING_SNAKE_CASE_ = kwargs.get('''model_save_dir''' , _lowerCamelCase ) SCREAMING_SNAKE_CASE_ = kwargs.get('''latest_model_name''' , _lowerCamelCase ) def __call__( self: List[Any] , **_lowerCamelCase: List[str] ): SCREAMING_SNAKE_CASE_ = {k: np.array(_lowerCamelCase ) for k, v in kwargs.items()} return self.model.run(_lowerCamelCase , _lowerCamelCase ) @staticmethod def _A ( _lowerCamelCase: Union[str, Path] , _lowerCamelCase: str=None , _lowerCamelCase: Tuple=None ): if provider is None: logger.info('''No onnxruntime provider specified, using CPUExecutionProvider''' ) SCREAMING_SNAKE_CASE_ = '''CPUExecutionProvider''' return ort.InferenceSession(_lowerCamelCase , providers=[provider] , sess_options=_lowerCamelCase ) def _A ( self: Optional[int] , _lowerCamelCase: Union[str, Path] , _lowerCamelCase: Optional[str] = None , **_lowerCamelCase: int ): SCREAMING_SNAKE_CASE_ = file_name if file_name is not None else ONNX_WEIGHTS_NAME SCREAMING_SNAKE_CASE_ = self.model_save_dir.joinpath(self.latest_model_name ) SCREAMING_SNAKE_CASE_ = Path(_lowerCamelCase ).joinpath(_lowerCamelCase ) try: shutil.copyfile(_lowerCamelCase , _lowerCamelCase ) except shutil.SameFileError: pass # copy external weights (for models >2GB) SCREAMING_SNAKE_CASE_ = self.model_save_dir.joinpath(_lowerCamelCase ) if src_path.exists(): SCREAMING_SNAKE_CASE_ = Path(_lowerCamelCase ).joinpath(_lowerCamelCase ) try: shutil.copyfile(_lowerCamelCase , _lowerCamelCase ) except shutil.SameFileError: pass def _A ( self: str , _lowerCamelCase: Union[str, os.PathLike] , **_lowerCamelCase: Dict , ): if os.path.isfile(_lowerCamelCase ): logger.error(f"Provided path ({save_directory}) should be a directory, not a file" ) return os.makedirs(_lowerCamelCase , exist_ok=_lowerCamelCase ) # saving model weights/files self._save_pretrained(_lowerCamelCase , **_lowerCamelCase ) @classmethod def _A ( cls: Optional[Any] , _lowerCamelCase: Union[str, Path] , _lowerCamelCase: Optional[Union[bool, str, None]] = None , _lowerCamelCase: Optional[Union[str, None]] = None , _lowerCamelCase: bool = False , _lowerCamelCase: Optional[str] = None , _lowerCamelCase: Optional[str] = None , _lowerCamelCase: Optional[str] = None , _lowerCamelCase: Optional["ort.SessionOptions"] = None , **_lowerCamelCase: Any , ): SCREAMING_SNAKE_CASE_ = file_name if file_name is not None else ONNX_WEIGHTS_NAME # load model from local directory if os.path.isdir(_lowerCamelCase ): SCREAMING_SNAKE_CASE_ = OnnxRuntimeModel.load_model( os.path.join(_lowerCamelCase , _lowerCamelCase ) , provider=_lowerCamelCase , sess_options=_lowerCamelCase ) SCREAMING_SNAKE_CASE_ = Path(_lowerCamelCase ) # load model from hub else: # download model SCREAMING_SNAKE_CASE_ = hf_hub_download( repo_id=_lowerCamelCase , filename=_lowerCamelCase , use_auth_token=_lowerCamelCase , revision=_lowerCamelCase , cache_dir=_lowerCamelCase , force_download=_lowerCamelCase , ) SCREAMING_SNAKE_CASE_ = Path(_lowerCamelCase ).parent SCREAMING_SNAKE_CASE_ = Path(_lowerCamelCase ).name SCREAMING_SNAKE_CASE_ = OnnxRuntimeModel.load_model(_lowerCamelCase , provider=_lowerCamelCase , sess_options=_lowerCamelCase ) return cls(model=_lowerCamelCase , **_lowerCamelCase ) @classmethod def _A ( cls: int , _lowerCamelCase: Union[str, Path] , _lowerCamelCase: bool = True , _lowerCamelCase: Optional[str] = None , _lowerCamelCase: Optional[str] = None , **_lowerCamelCase: Optional[int] , ): SCREAMING_SNAKE_CASE_ = None if len(str(_lowerCamelCase ).split('''@''' ) ) == 2: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = model_id.split('''@''' ) return cls._from_pretrained( model_id=_lowerCamelCase , revision=_lowerCamelCase , cache_dir=_lowerCamelCase , force_download=_lowerCamelCase , use_auth_token=_lowerCamelCase , **_lowerCamelCase , )
720
from __future__ import annotations __SCREAMING_SNAKE_CASE ={ """A""": ["""B""", """C""", """E"""], """B""": ["""A""", """D""", """E"""], """C""": ["""A""", """F""", """G"""], """D""": ["""B"""], """E""": ["""A""", """B""", """D"""], """F""": ["""C"""], """G""": ["""C"""], } class __magic_name__ : '''simple docstring''' def __init__( self: List[Any] , _lowerCamelCase: dict[str, list[str]] , _lowerCamelCase: str ): SCREAMING_SNAKE_CASE_ = graph # mapping node to its parent in resulting breadth first tree SCREAMING_SNAKE_CASE_ = {} SCREAMING_SNAKE_CASE_ = source_vertex def _A ( self: Tuple ): SCREAMING_SNAKE_CASE_ = {self.source_vertex} SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = [self.source_vertex] # first in first out queue while queue: SCREAMING_SNAKE_CASE_ = queue.pop(0 ) for adjacent_vertex in self.graph[vertex]: if adjacent_vertex not in visited: visited.add(_lowerCamelCase ) SCREAMING_SNAKE_CASE_ = vertex queue.append(_lowerCamelCase ) def _A ( self: List[str] , _lowerCamelCase: str ): if target_vertex == self.source_vertex: return self.source_vertex SCREAMING_SNAKE_CASE_ = self.parent.get(_lowerCamelCase ) if target_vertex_parent is None: SCREAMING_SNAKE_CASE_ = ( f"No path from vertex: {self.source_vertex} to vertex: {target_vertex}" ) raise ValueError(_lowerCamelCase ) return self.shortest_path(_lowerCamelCase ) + f"->{target_vertex}" if __name__ == "__main__": __SCREAMING_SNAKE_CASE =Graph(graph, """G""") g.breath_first_search() print(g.shortest_path("""D""")) print(g.shortest_path("""G""")) print(g.shortest_path("""Foo"""))
89
0
from __future__ import annotations def lowerCamelCase_ ( _UpperCamelCase ) -> list[int]: """simple docstring""" return [ord(_UpperCamelCase ) - 96 for elem in plain] def lowerCamelCase_ ( _UpperCamelCase ) -> str: """simple docstring""" return "".join(chr(elem + 96 ) for elem in encoded ) def lowerCamelCase_ ( ) -> None: """simple docstring""" snake_case_ : List[Any] = encode(input('''-> ''' ).strip().lower() ) print('''Encoded: ''' , _UpperCamelCase ) print('''Decoded:''' , decode(_UpperCamelCase ) ) if __name__ == "__main__": main()
60
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _snake_case : Union[str, Any] = {"configuration_wavlm": ["WAVLM_PRETRAINED_CONFIG_ARCHIVE_MAP", "WavLMConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case : Union[str, Any] = [ "WAVLM_PRETRAINED_MODEL_ARCHIVE_LIST", "WavLMForAudioFrameClassification", "WavLMForCTC", "WavLMForSequenceClassification", "WavLMForXVector", "WavLMModel", "WavLMPreTrainedModel", ] if TYPE_CHECKING: from .configuration_wavlm import WAVLM_PRETRAINED_CONFIG_ARCHIVE_MAP, WavLMConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_wavlm import ( WAVLM_PRETRAINED_MODEL_ARCHIVE_LIST, WavLMForAudioFrameClassification, WavLMForCTC, WavLMForSequenceClassification, WavLMForXVector, WavLMModel, WavLMPreTrainedModel, ) else: import sys _snake_case : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
441
0
'''simple docstring''' from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging if TYPE_CHECKING: from ... import FeatureExtractionMixin, TensorType _A : int = logging.get_logger(__name__) _A : Any = { '''openai/imagegpt-small''': '''''', '''openai/imagegpt-medium''': '''''', '''openai/imagegpt-large''': '''''', } class _lowercase ( __lowerCamelCase ): '''simple docstring''' _SCREAMING_SNAKE_CASE : List[Any] = """imagegpt""" _SCREAMING_SNAKE_CASE : Optional[Any] = ["""past_key_values"""] _SCREAMING_SNAKE_CASE : Optional[int] = { """hidden_size""": """n_embd""", """max_position_embeddings""": """n_positions""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : Dict=5_12 + 1 , SCREAMING_SNAKE_CASE__ : int=32 * 32 , SCREAMING_SNAKE_CASE__ : Optional[Any]=5_12 , SCREAMING_SNAKE_CASE__ : List[Any]=24 , SCREAMING_SNAKE_CASE__ : Any=8 , SCREAMING_SNAKE_CASE__ : int=None , SCREAMING_SNAKE_CASE__ : List[str]="quick_gelu" , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0.1 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0.1 , SCREAMING_SNAKE_CASE__ : Optional[int]=1e-5 , SCREAMING_SNAKE_CASE__ : Dict=0.0_2 , SCREAMING_SNAKE_CASE__ : List[str]=True , SCREAMING_SNAKE_CASE__ : List[str]=True , SCREAMING_SNAKE_CASE__ : List[Any]=False , SCREAMING_SNAKE_CASE__ : List[Any]=False , SCREAMING_SNAKE_CASE__ : Any=False , **SCREAMING_SNAKE_CASE__ : List[str] , ) -> Optional[Any]: __lowerCAmelCase = vocab_size __lowerCAmelCase = n_positions __lowerCAmelCase = n_embd __lowerCAmelCase = n_layer __lowerCAmelCase = n_head __lowerCAmelCase = n_inner __lowerCAmelCase = activation_function __lowerCAmelCase = resid_pdrop __lowerCAmelCase = embd_pdrop __lowerCAmelCase = attn_pdrop __lowerCAmelCase = layer_norm_epsilon __lowerCAmelCase = initializer_range __lowerCAmelCase = scale_attn_weights __lowerCAmelCase = use_cache __lowerCAmelCase = scale_attn_by_inverse_layer_idx __lowerCAmelCase = reorder_and_upcast_attn __lowerCAmelCase = tie_word_embeddings super().__init__(tie_word_embeddings=UpperCAmelCase_ , **UpperCAmelCase_ ) class _lowercase ( __lowerCamelCase ): '''simple docstring''' @property def a ( self : Optional[Any] ) -> Any: return OrderedDict( [ ("""input_ids""", {0: """batch""", 1: """sequence"""}), ] ) def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : "FeatureExtractionMixin" , SCREAMING_SNAKE_CASE__ : int = 1 , SCREAMING_SNAKE_CASE__ : int = -1 , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : Optional["TensorType"] = None , SCREAMING_SNAKE_CASE__ : int = 3 , SCREAMING_SNAKE_CASE__ : int = 32 , SCREAMING_SNAKE_CASE__ : int = 32 , ) -> List[Any]: __lowerCAmelCase = self._generate_dummy_images(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) __lowerCAmelCase = dict(preprocessor(images=UpperCAmelCase_ , return_tensors=UpperCAmelCase_ ) ) return inputs
706
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging _A : Union[str, Any] = logging.get_logger(__name__) _A : Union[str, Any] = { '''facebook/dpr-ctx_encoder-single-nq-base''': ( '''https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/config.json''' ), '''facebook/dpr-question_encoder-single-nq-base''': ( '''https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/config.json''' ), '''facebook/dpr-reader-single-nq-base''': ( '''https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/config.json''' ), '''facebook/dpr-ctx_encoder-multiset-base''': ( '''https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/config.json''' ), '''facebook/dpr-question_encoder-multiset-base''': ( '''https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/config.json''' ), '''facebook/dpr-reader-multiset-base''': ( '''https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/config.json''' ), } class _lowercase ( UpperCAmelCase__ ): '''simple docstring''' _SCREAMING_SNAKE_CASE : str = """dpr""" def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : Tuple=3_05_22 , SCREAMING_SNAKE_CASE__ : List[Any]=7_68 , SCREAMING_SNAKE_CASE__ : int=12 , SCREAMING_SNAKE_CASE__ : List[str]=12 , SCREAMING_SNAKE_CASE__ : Tuple=30_72 , SCREAMING_SNAKE_CASE__ : int="gelu" , SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 , SCREAMING_SNAKE_CASE__ : str=0.1 , SCREAMING_SNAKE_CASE__ : List[str]=5_12 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=2 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0.0_2 , SCREAMING_SNAKE_CASE__ : Optional[Any]=1e-1_2 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0 , SCREAMING_SNAKE_CASE__ : int="absolute" , SCREAMING_SNAKE_CASE__ : int = 0 , **SCREAMING_SNAKE_CASE__ : str , ) -> Tuple: super().__init__(pad_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = vocab_size __lowerCAmelCase = hidden_size __lowerCAmelCase = num_hidden_layers __lowerCAmelCase = num_attention_heads __lowerCAmelCase = hidden_act __lowerCAmelCase = intermediate_size __lowerCAmelCase = hidden_dropout_prob __lowerCAmelCase = attention_probs_dropout_prob __lowerCAmelCase = max_position_embeddings __lowerCAmelCase = type_vocab_size __lowerCAmelCase = initializer_range __lowerCAmelCase = layer_norm_eps __lowerCAmelCase = projection_dim __lowerCAmelCase = position_embedding_type
330
0
"""simple docstring""" from collections import namedtuple import requests from lxml import html # type: ignore __lowerCamelCase = namedtuple('covid_data', 'cases deaths recovered') def a ( __UpperCAmelCase : str = "https://www.worldometers.info/coronavirus/" ) -> covid_data: __magic_name__: Dict = """//div[@class = \"maincounter-number\"]/span/text()""" return covid_data(*html.fromstring(requests.get(__UpperCAmelCase ).content ).xpath(__UpperCAmelCase ) ) __lowerCamelCase = 'Total COVID-19 cases in the world: {}\nTotal deaths due to COVID-19 in the world: {}\nTotal COVID-19 patients recovered in the world: {}' print(fmt.format(*covid_stats()))
96
"""simple docstring""" import os import socket from contextlib import contextmanager import torch from ..commands.config.default import write_basic_config # noqa: F401 from ..state import PartialState from .dataclasses import DistributedType from .imports import is_deepspeed_available, is_tpu_available from .transformer_engine import convert_model from .versions import is_torch_version if is_deepspeed_available(): from deepspeed import DeepSpeedEngine if is_tpu_available(check_device=False): import torch_xla.core.xla_model as xm def lowercase (_lowerCAmelCase ): if is_torch_version("""<""" , """2.0.0""" ) or not hasattr(_lowerCAmelCase , """_dynamo""" ): return False return isinstance(_lowerCAmelCase , torch._dynamo.eval_frame.OptimizedModule ) def lowercase (_lowerCAmelCase , _lowerCAmelCase = True ): __lowerCAmelCase = (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel) __lowerCAmelCase = is_compiled_module(_lowerCAmelCase ) if is_compiled: __lowerCAmelCase = model __lowerCAmelCase = model._orig_mod if is_deepspeed_available(): options += (DeepSpeedEngine,) while isinstance(_lowerCAmelCase , _lowerCAmelCase ): __lowerCAmelCase = model.module if not keep_fpaa_wrapper: __lowerCAmelCase = getattr(_lowerCAmelCase , """forward""" ) __lowerCAmelCase = model.__dict__.pop("""_original_forward""" , _lowerCAmelCase ) if original_forward is not None: while hasattr(_lowerCAmelCase , """__wrapped__""" ): __lowerCAmelCase = forward.__wrapped__ if forward == original_forward: break __lowerCAmelCase = forward if getattr(_lowerCAmelCase , """_converted_to_transformer_engine""" , _lowerCAmelCase ): convert_model(_lowerCAmelCase , to_transformer_engine=_lowerCAmelCase ) if is_compiled: __lowerCAmelCase = model __lowerCAmelCase = compiled_model return model def lowercase (): PartialState().wait_for_everyone() def lowercase (_lowerCAmelCase , _lowerCAmelCase ): if PartialState().distributed_type == DistributedType.TPU: xm.save(_lowerCAmelCase , _lowerCAmelCase ) elif PartialState().local_process_index == 0: torch.save(_lowerCAmelCase , _lowerCAmelCase ) @contextmanager def lowercase (**_lowerCAmelCase ): for key, value in kwargs.items(): __lowerCAmelCase = str(_lowerCAmelCase ) yield for key in kwargs: if key.upper() in os.environ: del os.environ[key.upper()] def lowercase (_lowerCAmelCase ): if not hasattr(_lowerCAmelCase , """__qualname__""" ) and not hasattr(_lowerCAmelCase , """__name__""" ): __lowerCAmelCase = getattr(_lowerCAmelCase , """__class__""" , _lowerCAmelCase ) if hasattr(_lowerCAmelCase , """__qualname__""" ): return obj.__qualname__ if hasattr(_lowerCAmelCase , """__name__""" ): return obj.__name__ return str(_lowerCAmelCase ) def lowercase (_lowerCAmelCase , _lowerCAmelCase ): for key, value in source.items(): if isinstance(_lowerCAmelCase , _lowerCAmelCase ): __lowerCAmelCase = destination.setdefault(_lowerCAmelCase , {} ) merge_dicts(_lowerCAmelCase , _lowerCAmelCase ) else: __lowerCAmelCase = value return destination def lowercase (_lowerCAmelCase = None ): if port is None: __lowerCAmelCase = 2_9500 with socket.socket(socket.AF_INET , socket.SOCK_STREAM ) as s: return s.connect_ex(("""localhost""", port) ) == 0
465
0
def UpperCamelCase__ ( lowerCAmelCase__ ): return [ { 0: [1, 2], 1: [0, 2], 2: [0, 1, 3, 5], 3: [2, 4], 4: [3], 5: [2, 6, 8], 6: [5, 7], 7: [6, 8], 8: [5, 7], }, { 0: [6], 1: [9], 2: [4, 5], 3: [4], 4: [2, 3], 5: [2], 6: [0, 7], 7: [6], 8: [], 9: [1], }, { 0: [4], 1: [6], 2: [], 3: [5, 6, 7], 4: [0, 6], 5: [3, 8, 9], 6: [1, 3, 4, 7], 7: [3, 6, 8, 9], 8: [5, 7], 9: [5, 7], }, { 0: [1, 3], 1: [0, 2, 4], 2: [1, 3, 4], 3: [0, 2, 4], 4: [1, 2, 3], }, ][index] def UpperCamelCase__ ( lowerCAmelCase__ ): lowercase = 0 lowercase = len(__SCREAMING_SNAKE_CASE ) # No of vertices in graph lowercase = [0] * n lowercase = [False] * n def dfs(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ): lowercase = True lowercase = id_ id_ += 1 for to in graph[at]: if to == parent: pass elif not visited[to]: dfs(__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,id_ ) lowercase = min(low[at] ,low[to] ) if id_ <= low[to]: bridges.append((at, to) if at < to else (to, at) ) else: # This edge is a back edge and cannot be a bridge lowercase = min(low[at] ,low[to] ) lowercase = [] for i in range(__SCREAMING_SNAKE_CASE ): if not visited[i]: dfs(__SCREAMING_SNAKE_CASE ,-1 ,__SCREAMING_SNAKE_CASE ,id_ ) return bridges if __name__ == "__main__": import doctest doctest.testmod()
703
import math from ...configuration_utils import PretrainedConfig from ...utils import logging __SCREAMING_SNAKE_CASE : str =logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : str ={ '''facebook/data2vec-base-960h''': '''https://huggingface.co/facebook/data2vec-audio-base-960h/resolve/main/config.json''', # See all Data2VecAudio models at https://huggingface.co/models?filter=data2vec-audio } class A_ ( __a ): _A :Tuple = '''data2vec-audio''' def __init__( self : Optional[Any] , snake_case__ : List[Any]=32 , snake_case__ : List[Any]=7_68 , snake_case__ : int=12 , snake_case__ : Dict=12 , snake_case__ : List[str]=30_72 , snake_case__ : List[str]="gelu" , snake_case__ : Optional[int]=0.1 , snake_case__ : List[Any]=0.1 , snake_case__ : int=0.1 , snake_case__ : Tuple=0.0 , snake_case__ : Tuple=0.1 , snake_case__ : Any=0.1 , snake_case__ : Dict=0.02 , snake_case__ : List[str]=1E-5 , snake_case__ : Optional[Any]="gelu" , snake_case__ : Union[str, Any]=(5_12, 5_12, 5_12, 5_12, 5_12, 5_12, 5_12) , snake_case__ : List[str]=(5, 2, 2, 2, 2, 2, 2) , snake_case__ : str=(10, 3, 3, 3, 3, 2, 2) , snake_case__ : Any=False , snake_case__ : List[str]=16 , snake_case__ : Any=19 , snake_case__ : Optional[Any]=5 , snake_case__ : str=0.05 , snake_case__ : Tuple=10 , snake_case__ : Optional[Any]=2 , snake_case__ : Dict=0.0 , snake_case__ : int=10 , snake_case__ : Any=0 , snake_case__ : int="sum" , snake_case__ : str=False , snake_case__ : str=False , snake_case__ : Optional[int]=2_56 , snake_case__ : List[str]=(5_12, 5_12, 5_12, 5_12, 15_00) , snake_case__ : List[str]=(5, 3, 3, 1, 1) , snake_case__ : int=(1, 2, 3, 1, 1) , snake_case__ : Optional[Any]=5_12 , snake_case__ : Dict=0 , snake_case__ : Optional[Any]=1 , snake_case__ : Tuple=2 , snake_case__ : Tuple=False , snake_case__ : List[str]=3 , snake_case__ : List[str]=2 , snake_case__ : Tuple=3 , snake_case__ : List[str]=None , **snake_case__ : str , ): super().__init__(**snake_case__ , pad_token_id=snake_case__ , bos_token_id=snake_case__ , eos_token_id=snake_case__ ) lowercase = hidden_size lowercase = feat_extract_activation lowercase = list(snake_case__ ) lowercase = list(snake_case__ ) lowercase = list(snake_case__ ) lowercase = conv_bias lowercase = num_conv_pos_embeddings lowercase = num_conv_pos_embedding_groups lowercase = conv_pos_kernel_size lowercase = len(self.conv_dim ) lowercase = num_hidden_layers lowercase = intermediate_size lowercase = hidden_act lowercase = num_attention_heads lowercase = hidden_dropout lowercase = attention_dropout lowercase = activation_dropout lowercase = feat_proj_dropout lowercase = final_dropout lowercase = layerdrop lowercase = layer_norm_eps lowercase = initializer_range lowercase = vocab_size lowercase = use_weighted_layer_sum if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( """Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==""" """ `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =""" F""" {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`,""" F""" `len(config.conv_kernel) = {len(self.conv_kernel )}`.""" ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 lowercase = mask_time_prob lowercase = mask_time_length lowercase = mask_time_min_masks lowercase = mask_feature_prob lowercase = mask_feature_length lowercase = mask_feature_min_masks # ctc loss lowercase = ctc_loss_reduction lowercase = ctc_zero_infinity # adapter lowercase = add_adapter lowercase = adapter_kernel_size lowercase = adapter_stride lowercase = num_adapter_layers lowercase = output_hidden_size or hidden_size # SequenceClassification-specific parameter. Feel free to ignore for other classes. lowercase = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. lowercase = list(snake_case__ ) lowercase = list(snake_case__ ) lowercase = list(snake_case__ ) lowercase = xvector_output_dim @property def SCREAMING_SNAKE_CASE__ ( self : Dict ): return math.prod(self.conv_stride )
72
0
from argparse import ArgumentParser from .env import EnvironmentCommand def _UpperCAmelCase ( ): """simple docstring""" __lowerCAmelCase = ArgumentParser("Diffusers CLI tool" , usage="diffusers-cli <command> [<args>]" ) __lowerCAmelCase = parser.add_subparsers(help="diffusers-cli command helpers" ) # Register commands EnvironmentCommand.register_subcommand(UpperCamelCase ) # Let's go __lowerCAmelCase = parser.parse_args() if not hasattr(UpperCamelCase , "func" ): parser.print_help() exit(1 ) # Run __lowerCAmelCase = args.func(UpperCamelCase ) service.run() if __name__ == "__main__": main()
611
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...utils import logging if TYPE_CHECKING: from ...processing_utils import ProcessorMixin from ...utils import TensorType UpperCamelCase_ = logging.get_logger(__name__) UpperCamelCase_ = { "microsoft/layoutlmv3-base": "https://huggingface.co/microsoft/layoutlmv3-base/resolve/main/config.json", } class a ( __UpperCAmelCase ): lowercase_ : Optional[int] = 'layoutlmv3' def __init__( self : Dict , snake_case__ : Dict=50_265 , snake_case__ : Optional[Any]=768 , snake_case__ : Dict=12 , snake_case__ : List[Any]=12 , snake_case__ : int=3_072 , snake_case__ : Dict="gelu" , snake_case__ : Any=0.1 , snake_case__ : Optional[Any]=0.1 , snake_case__ : Tuple=512 , snake_case__ : str=2 , snake_case__ : Optional[int]=0.0_2 , snake_case__ : Optional[Any]=1E-5 , snake_case__ : Tuple=1 , snake_case__ : str=0 , snake_case__ : Dict=2 , snake_case__ : int=1_024 , snake_case__ : Optional[Any]=128 , snake_case__ : List[str]=128 , snake_case__ : Dict=True , snake_case__ : Optional[int]=32 , snake_case__ : str=128 , snake_case__ : Dict=64 , snake_case__ : Any=256 , snake_case__ : Union[str, Any]=True , snake_case__ : Union[str, Any]=True , snake_case__ : Tuple=True , snake_case__ : List[Any]=224 , snake_case__ : str=3 , snake_case__ : Dict=16 , snake_case__ : Tuple=None , **snake_case__ : Any , ): """simple docstring""" super().__init__( vocab_size=snake_case__ , hidden_size=snake_case__ , num_hidden_layers=snake_case__ , num_attention_heads=snake_case__ , intermediate_size=snake_case__ , hidden_act=snake_case__ , hidden_dropout_prob=snake_case__ , attention_probs_dropout_prob=snake_case__ , max_position_embeddings=snake_case__ , type_vocab_size=snake_case__ , initializer_range=snake_case__ , layer_norm_eps=snake_case__ , pad_token_id=snake_case__ , bos_token_id=snake_case__ , eos_token_id=snake_case__ , **snake_case__ , ) __lowerCAmelCase = max_ad_position_embeddings __lowerCAmelCase = coordinate_size __lowerCAmelCase = shape_size __lowerCAmelCase = has_relative_attention_bias __lowerCAmelCase = rel_pos_bins __lowerCAmelCase = max_rel_pos __lowerCAmelCase = has_spatial_attention_bias __lowerCAmelCase = rel_ad_pos_bins __lowerCAmelCase = max_rel_ad_pos __lowerCAmelCase = text_embed __lowerCAmelCase = visual_embed __lowerCAmelCase = input_size __lowerCAmelCase = num_channels __lowerCAmelCase = patch_size __lowerCAmelCase = classifier_dropout class a ( __UpperCAmelCase ): lowercase_ : int = version.parse('1.12' ) @property def UpperCAmelCase__ ( self : List[str] ): """simple docstring""" if self.task in ["question-answering", "sequence-classification"]: return OrderedDict( [ ("input_ids", {0: "batch", 1: "sequence"}), ("attention_mask", {0: "batch", 1: "sequence"}), ("bbox", {0: "batch", 1: "sequence"}), ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ] ) else: return OrderedDict( [ ("input_ids", {0: "batch", 1: "sequence"}), ("bbox", {0: "batch", 1: "sequence"}), ("attention_mask", {0: "batch", 1: "sequence"}), ("pixel_values", {0: "batch", 1: "num_channels"}), ] ) @property def UpperCAmelCase__ ( self : Tuple ): """simple docstring""" return 1E-5 @property def UpperCAmelCase__ ( self : List[str] ): """simple docstring""" return 12 def UpperCAmelCase__ ( self : Dict , snake_case__ : "ProcessorMixin" , snake_case__ : int = -1 , snake_case__ : int = -1 , snake_case__ : bool = False , snake_case__ : Optional["TensorType"] = None , snake_case__ : int = 3 , snake_case__ : int = 40 , snake_case__ : int = 40 , ): """simple docstring""" setattr(processor.image_processor , "apply_ocr" , snake_case__ ) # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX __lowerCAmelCase = compute_effective_axis_dimension( snake_case__ , 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 __lowerCAmelCase = processor.tokenizer.num_special_tokens_to_add(snake_case__ ) __lowerCAmelCase = compute_effective_axis_dimension( snake_case__ , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=snake_case__ ) # Generate dummy inputs according to compute batch and sequence __lowerCAmelCase = [[" ".join([processor.tokenizer.unk_token] ) * seq_length]] * batch_size # Generate dummy bounding boxes __lowerCAmelCase = [[[48, 84, 73, 128]]] * batch_size # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX # batch_size = compute_effective_axis_dimension(batch_size, fixed_dimension=OnnxConfig.default_fixed_batch) __lowerCAmelCase = self._generate_dummy_images(snake_case__ , snake_case__ , snake_case__ , snake_case__ ) __lowerCAmelCase = dict( processor( snake_case__ , text=snake_case__ , boxes=snake_case__ , return_tensors=snake_case__ , ) ) return inputs
611
1
import argparse import glob import importlib.util import os import re import black from doc_builder.style_doc import style_docstrings_in_code # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py __UpperCAmelCase = """src/diffusers""" __UpperCAmelCase = """.""" # This is to make sure the diffusers module imported is the one in the repo. __UpperCAmelCase = importlib.util.spec_from_file_location( """diffusers""", os.path.join(DIFFUSERS_PATH, """__init__.py"""), submodule_search_locations=[DIFFUSERS_PATH], ) __UpperCAmelCase = spec.loader.load_module() def _lowerCamelCase ( A_ : Union[str, Any] , A_ : Dict ) -> List[str]: '''simple docstring''' return line.startswith(A_ ) or len(A_ ) <= 1 or re.search(R"^\s*\)(\s*->.*:|:)\s*$" , A_ ) is not None def _lowerCamelCase ( A_ : Optional[Any] ) -> Tuple: '''simple docstring''' UpperCamelCase__ : Any =object_name.split("." ) UpperCamelCase__ : List[Any] =0 # First let's find the module where our object lives. UpperCamelCase__ : Optional[int] =parts[i] while i < len(A_ ) and not os.path.isfile(os.path.join(A_ , f'''{module}.py''' ) ): i += 1 if i < len(A_ ): UpperCamelCase__ : List[Any] =os.path.join(A_ , parts[i] ) if i >= len(A_ ): raise ValueError(f'''`object_name` should begin with the name of a module of diffusers but got {object_name}.''' ) with open(os.path.join(A_ , f'''{module}.py''' ) , "r" , encoding="utf-8" , newline="\n" ) as f: UpperCamelCase__ : Union[str, Any] =f.readlines() # Now let's find the class / func in the code! UpperCamelCase__ : str ="" UpperCamelCase__ : Optional[Any] =0 for name in parts[i + 1 :]: while ( line_index < len(A_ ) and re.search(Rf'''^{indent}(class|def)\s+{name}(\(|\:)''' , lines[line_index] ) is None ): line_index += 1 indent += " " line_index += 1 if line_index >= len(A_ ): raise ValueError(f''' {object_name} does not match any function or class in {module}.''' ) # We found the beginning of the class / func, now let's find the end (when the indent diminishes). UpperCamelCase__ : Union[str, Any] =line_index while line_index < len(A_ ) and _should_continue(lines[line_index] , A_ ): line_index += 1 # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 UpperCamelCase__ : Tuple =lines[start_index:line_index] return "".join(A_ ) __UpperCAmelCase = re.compile(r"""^(\s*)#\s*Copied from\s+diffusers\.(\S+\.\S+)\s*($|\S.*$)""") __UpperCAmelCase = re.compile(r"""^\s*(\S+)->(\S+)(\s+.*|$)""") __UpperCAmelCase = re.compile(r"""<FILL\s+[^>]*>""") def _lowerCamelCase ( A_ : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' UpperCamelCase__ : Optional[Any] =code.split("\n" ) UpperCamelCase__ : Any =0 while idx < len(A_ ) and len(lines[idx] ) == 0: idx += 1 if idx < len(A_ ): return re.search(R"^(\s*)\S" , lines[idx] ).groups()[0] return "" def _lowerCamelCase ( A_ : Optional[int] ) -> Any: '''simple docstring''' UpperCamelCase__ : int =len(get_indent(A_ ) ) > 0 if has_indent: UpperCamelCase__ : List[Any] =f'''class Bla:\n{code}''' UpperCamelCase__ : Optional[int] =black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=1_1_9 , preview=A_ ) UpperCamelCase__ : Tuple =black.format_str(A_ , mode=A_ ) UpperCamelCase__ , UpperCamelCase__ : List[Any] =style_docstrings_in_code(A_ ) return result[len("class Bla:\n" ) :] if has_indent else result def _lowerCamelCase ( A_ : Union[str, Any] , A_ : List[str]=False ) -> Union[str, Any]: '''simple docstring''' with open(A_ , "r" , encoding="utf-8" , newline="\n" ) as f: UpperCamelCase__ : List[Any] =f.readlines() UpperCamelCase__ : List[str] =[] UpperCamelCase__ : List[str] =0 # Not a for loop cause `lines` is going to change (if `overwrite=True`). while line_index < len(A_ ): UpperCamelCase__ : Dict =_re_copy_warning.search(lines[line_index] ) if search is None: line_index += 1 continue # There is some copied code here, let's retrieve the original. UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ : Optional[Any] =search.groups() UpperCamelCase__ : List[str] =find_code_in_diffusers(A_ ) UpperCamelCase__ : str =get_indent(A_ ) UpperCamelCase__ : Optional[int] =line_index + 1 if indent == theoretical_indent else line_index + 2 UpperCamelCase__ : str =theoretical_indent UpperCamelCase__ : int =start_index # Loop to check the observed code, stop when indentation diminishes or if we see a End copy comment. UpperCamelCase__ : List[str] =True while line_index < len(A_ ) and should_continue: line_index += 1 if line_index >= len(A_ ): break UpperCamelCase__ : int =lines[line_index] UpperCamelCase__ : List[str] =_should_continue(A_ , A_ ) and re.search(f'''^{indent}# End copy''' , A_ ) is None # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 UpperCamelCase__ : str =lines[start_index:line_index] UpperCamelCase__ : Dict ="".join(A_ ) # Remove any nested `Copied from` comments to avoid circular copies UpperCamelCase__ : Optional[int] =[line for line in theoretical_code.split("\n" ) if _re_copy_warning.search(A_ ) is None] UpperCamelCase__ : Dict ="\n".join(A_ ) # Before comparing, use the `replace_pattern` on the original code. if len(A_ ) > 0: UpperCamelCase__ : Any =replace_pattern.replace("with" , "" ).split("," ) UpperCamelCase__ : Union[str, Any] =[_re_replace_pattern.search(A_ ) for p in patterns] for pattern in patterns: if pattern is None: continue UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ : str =pattern.groups() UpperCamelCase__ : List[str] =re.sub(A_ , A_ , A_ ) if option.strip() == "all-casing": UpperCamelCase__ : Any =re.sub(obja.lower() , obja.lower() , A_ ) UpperCamelCase__ : List[str] =re.sub(obja.upper() , obja.upper() , A_ ) # Blackify after replacement. To be able to do that, we need the header (class or function definition) # from the previous line UpperCamelCase__ : Dict =blackify(lines[start_index - 1] + theoretical_code ) UpperCamelCase__ : int =theoretical_code[len(lines[start_index - 1] ) :] # Test for a diff and act accordingly. if observed_code != theoretical_code: diffs.append([object_name, start_index] ) if overwrite: UpperCamelCase__ : List[Any] =lines[:start_index] + [theoretical_code] + lines[line_index:] UpperCamelCase__ : List[Any] =start_index + 1 if overwrite and len(A_ ) > 0: # Warn the user a file has been modified. print(f'''Detected changes, rewriting {filename}.''' ) with open(A_ , "w" , encoding="utf-8" , newline="\n" ) as f: f.writelines(A_ ) return diffs def _lowerCamelCase ( A_ : bool = False ) -> int: '''simple docstring''' UpperCamelCase__ : List[str] =glob.glob(os.path.join(A_ , "**/*.py" ) , recursive=A_ ) UpperCamelCase__ : int =[] for filename in all_files: UpperCamelCase__ : str =is_copy_consistent(A_ , A_ ) diffs += [f'''- {filename}: copy does not match {d[0]} at line {d[1]}''' for d in new_diffs] if not overwrite and len(A_ ) > 0: UpperCamelCase__ : Any ="\n".join(A_ ) raise Exception( "Found the following copy inconsistencies:\n" + diff + "\nRun `make fix-copies` or `python utils/check_copies.py --fix_and_overwrite` to fix them." ) if __name__ == "__main__": __UpperCAmelCase = argparse.ArgumentParser() parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""") __UpperCAmelCase = parser.parse_args() check_copies(args.fix_and_overwrite)
582
import argparse import torch from transformers import GPTaLMHeadModel, RobertaForMaskedLM if __name__ == "__main__": __UpperCAmelCase = argparse.ArgumentParser( description=( """Extraction some layers of the full RobertaForMaskedLM or GPT2LMHeadModel for Transfer Learned""" """ Distillation""" ) ) parser.add_argument("""--model_type""", default="""roberta""", choices=["""roberta""", """gpt2"""]) parser.add_argument("""--model_name""", default="""roberta-large""", type=str) parser.add_argument("""--dump_checkpoint""", default="""serialization_dir/tf_roberta_048131723.pth""", type=str) parser.add_argument("""--vocab_transform""", action="""store_true""") __UpperCAmelCase = parser.parse_args() if args.model_type == "roberta": __UpperCAmelCase = RobertaForMaskedLM.from_pretrained(args.model_name) __UpperCAmelCase = """roberta""" elif args.model_type == "gpt2": __UpperCAmelCase = GPTaLMHeadModel.from_pretrained(args.model_name) __UpperCAmelCase = """transformer""" __UpperCAmelCase = model.state_dict() __UpperCAmelCase = {} # Embeddings # if args.model_type == "gpt2": for param_name in ["wte.weight", "wpe.weight"]: __UpperCAmelCase = state_dict[F"""{prefix}.{param_name}"""] else: for w in ["word_embeddings", "position_embeddings", "token_type_embeddings"]: __UpperCAmelCase = F"""{prefix}.embeddings.{w}.weight""" __UpperCAmelCase = state_dict[param_name] for w in ["weight", "bias"]: __UpperCAmelCase = F"""{prefix}.embeddings.LayerNorm.{w}""" __UpperCAmelCase = state_dict[param_name] # Transformer Blocks # __UpperCAmelCase = 0 for teacher_idx in [0, 2, 4, 7, 9, 11]: if args.model_type == "gpt2": for layer in ["ln_1", "attn.c_attn", "attn.c_proj", "ln_2", "mlp.c_fc", "mlp.c_proj"]: for w in ["weight", "bias"]: __UpperCAmelCase = state_dict[ F"""{prefix}.h.{teacher_idx}.{layer}.{w}""" ] __UpperCAmelCase = state_dict[F"""{prefix}.h.{teacher_idx}.attn.bias"""] else: for layer in [ "attention.self.query", "attention.self.key", "attention.self.value", "attention.output.dense", "attention.output.LayerNorm", "intermediate.dense", "output.dense", "output.LayerNorm", ]: for w in ["weight", "bias"]: __UpperCAmelCase = state_dict[ F"""{prefix}.encoder.layer.{teacher_idx}.{layer}.{w}""" ] std_idx += 1 # Language Modeling Head ###s if args.model_type == "roberta": for layer in ["lm_head.decoder.weight", "lm_head.bias"]: __UpperCAmelCase = state_dict[F"""{layer}"""] if args.vocab_transform: for w in ["weight", "bias"]: __UpperCAmelCase = state_dict[F"""lm_head.dense.{w}"""] __UpperCAmelCase = state_dict[F"""lm_head.layer_norm.{w}"""] elif args.model_type == "gpt2": for w in ["weight", "bias"]: __UpperCAmelCase = state_dict[F"""{prefix}.ln_f.{w}"""] __UpperCAmelCase = state_dict["""lm_head.weight"""] print(F"""N layers selected for distillation: {std_idx}""") print(F"""Number of params transferred for distillation: {len(compressed_sd.keys())}""") print(F"""Save transferred checkpoint to {args.dump_checkpoint}.""") torch.save(compressed_sd, args.dump_checkpoint)
582
1
import os import unittest from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import ( VOCAB_FILES_NAMES, BasicTokenizer, BertTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class SCREAMING_SNAKE_CASE ( a_ , unittest.TestCase ): """simple docstring""" lowerCamelCase : Union[str, Any] =BertTokenizer lowerCamelCase : List[Any] =BertTokenizerFast lowerCamelCase : List[str] =True lowerCamelCase : Any =True lowerCamelCase : Dict =filter_non_english def SCREAMING_SNAKE_CASE ( self : int ) -> Optional[Any]: """simple docstring""" super().setUp() __lowerCAmelCase : Any = [ """[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] __lowerCAmelCase : str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) def SCREAMING_SNAKE_CASE ( self : Optional[int] , lowerCAmelCase : str ) -> Any: """simple docstring""" __lowerCAmelCase : List[str] = """UNwant\u00E9d,running""" __lowerCAmelCase : Optional[int] = """unwanted, running""" return input_text, output_text def SCREAMING_SNAKE_CASE ( self : str ) -> str: """simple docstring""" __lowerCAmelCase : List[str] = self.tokenizer_class(self.vocab_file ) __lowerCAmelCase : List[str] = tokenizer.tokenize("""UNwant\u00E9d,running""" ) self.assertListEqual(lowerCAmelCase , ["""un""", """##want""", """##ed""", """,""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCAmelCase ) , [9, 6, 7, 12, 10, 11] ) def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Any: """simple docstring""" if not self.test_rust_tokenizer: return __lowerCAmelCase : List[str] = self.get_tokenizer() __lowerCAmelCase : Any = self.get_rust_tokenizer() __lowerCAmelCase : List[str] = """UNwant\u00E9d,running""" __lowerCAmelCase : str = tokenizer.tokenize(lowerCAmelCase ) __lowerCAmelCase : Optional[int] = rust_tokenizer.tokenize(lowerCAmelCase ) self.assertListEqual(lowerCAmelCase , lowerCAmelCase ) __lowerCAmelCase : Dict = tokenizer.encode(lowerCAmelCase , add_special_tokens=lowerCAmelCase ) __lowerCAmelCase : Any = rust_tokenizer.encode(lowerCAmelCase , add_special_tokens=lowerCAmelCase ) self.assertListEqual(lowerCAmelCase , lowerCAmelCase ) __lowerCAmelCase : str = self.get_rust_tokenizer() __lowerCAmelCase : Any = tokenizer.encode(lowerCAmelCase ) __lowerCAmelCase : List[Any] = rust_tokenizer.encode(lowerCAmelCase ) self.assertListEqual(lowerCAmelCase , lowerCAmelCase ) # With lower casing __lowerCAmelCase : int = self.get_tokenizer(do_lower_case=lowerCAmelCase ) __lowerCAmelCase : Optional[int] = self.get_rust_tokenizer(do_lower_case=lowerCAmelCase ) __lowerCAmelCase : Optional[Any] = """UNwant\u00E9d,running""" __lowerCAmelCase : Any = tokenizer.tokenize(lowerCAmelCase ) __lowerCAmelCase : Optional[int] = rust_tokenizer.tokenize(lowerCAmelCase ) self.assertListEqual(lowerCAmelCase , lowerCAmelCase ) __lowerCAmelCase : Tuple = tokenizer.encode(lowerCAmelCase , add_special_tokens=lowerCAmelCase ) __lowerCAmelCase : Optional[Any] = rust_tokenizer.encode(lowerCAmelCase , add_special_tokens=lowerCAmelCase ) self.assertListEqual(lowerCAmelCase , lowerCAmelCase ) __lowerCAmelCase : Any = self.get_rust_tokenizer() __lowerCAmelCase : str = tokenizer.encode(lowerCAmelCase ) __lowerCAmelCase : str = rust_tokenizer.encode(lowerCAmelCase ) self.assertListEqual(lowerCAmelCase , lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> List[str]: """simple docstring""" __lowerCAmelCase : Dict = BasicTokenizer() self.assertListEqual(tokenizer.tokenize("""ah\u535A\u63A8zz""" ) , ["""ah""", """\u535A""", """\u63A8""", """zz"""] ) def SCREAMING_SNAKE_CASE ( self : str ) -> Optional[int]: """simple docstring""" __lowerCAmelCase : int = BasicTokenizer(do_lower_case=lowerCAmelCase ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? """ ) , ["""hello""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[str]: """simple docstring""" __lowerCAmelCase : List[str] = BasicTokenizer(do_lower_case=lowerCAmelCase , strip_accents=lowerCAmelCase ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hällo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""h\u00E9llo"""] ) def SCREAMING_SNAKE_CASE ( self : int ) -> Dict: """simple docstring""" __lowerCAmelCase : Dict = BasicTokenizer(do_lower_case=lowerCAmelCase , strip_accents=lowerCAmelCase ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hallo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def SCREAMING_SNAKE_CASE ( self : List[str] ) -> int: """simple docstring""" __lowerCAmelCase : Tuple = BasicTokenizer(do_lower_case=lowerCAmelCase ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hallo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def SCREAMING_SNAKE_CASE ( self : Tuple ) -> str: """simple docstring""" __lowerCAmelCase : Any = BasicTokenizer(do_lower_case=lowerCAmelCase ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? """ ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def SCREAMING_SNAKE_CASE ( self : Dict ) -> int: """simple docstring""" __lowerCAmelCase : Union[str, Any] = BasicTokenizer(do_lower_case=lowerCAmelCase , strip_accents=lowerCAmelCase ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""HäLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def SCREAMING_SNAKE_CASE ( self : Dict ) -> List[Any]: """simple docstring""" __lowerCAmelCase : Union[str, Any] = BasicTokenizer(do_lower_case=lowerCAmelCase , strip_accents=lowerCAmelCase ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""HaLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def SCREAMING_SNAKE_CASE ( self : Tuple ) -> List[str]: """simple docstring""" __lowerCAmelCase : Tuple = BasicTokenizer(do_lower_case=lowerCAmelCase , never_split=["""[UNK]"""] ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? [UNK]""" ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?""", """[UNK]"""] ) def SCREAMING_SNAKE_CASE ( self : int ) -> List[Any]: """simple docstring""" __lowerCAmelCase : Tuple = BasicTokenizer() __lowerCAmelCase : Dict = """a\n'll !!to?'d of, can't.""" __lowerCAmelCase : int = ["""a""", """'""", """ll""", """!""", """!""", """to""", """?""", """'""", """d""", """of""", """,""", """can""", """'""", """t""", """."""] self.assertListEqual(tokenizer.tokenize(lowerCAmelCase ) , lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Dict ) -> str: """simple docstring""" __lowerCAmelCase : Tuple = ["""[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing"""] __lowerCAmelCase : Tuple = {} for i, token in enumerate(lowerCAmelCase ): __lowerCAmelCase : Optional[int] = i __lowerCAmelCase : Optional[int] = WordpieceTokenizer(vocab=lowerCAmelCase , unk_token="""[UNK]""" ) self.assertListEqual(tokenizer.tokenize("""""" ) , [] ) self.assertListEqual(tokenizer.tokenize("""unwanted running""" ) , ["""un""", """##want""", """##ed""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.tokenize("""unwantedX running""" ) , ["""[UNK]""", """runn""", """##ing"""] ) def SCREAMING_SNAKE_CASE ( self : int ) -> Any: """simple docstring""" self.assertTrue(_is_whitespace(""" """ ) ) self.assertTrue(_is_whitespace("""\t""" ) ) self.assertTrue(_is_whitespace("""\r""" ) ) self.assertTrue(_is_whitespace("""\n""" ) ) self.assertTrue(_is_whitespace("""\u00A0""" ) ) self.assertFalse(_is_whitespace("""A""" ) ) self.assertFalse(_is_whitespace("""-""" ) ) def SCREAMING_SNAKE_CASE ( self : Dict ) -> Tuple: """simple docstring""" self.assertTrue(_is_control("""\u0005""" ) ) self.assertFalse(_is_control("""A""" ) ) self.assertFalse(_is_control(""" """ ) ) self.assertFalse(_is_control("""\t""" ) ) self.assertFalse(_is_control("""\r""" ) ) def SCREAMING_SNAKE_CASE ( self : Dict ) -> Tuple: """simple docstring""" self.assertTrue(_is_punctuation("""-""" ) ) self.assertTrue(_is_punctuation("""$""" ) ) self.assertTrue(_is_punctuation("""`""" ) ) self.assertTrue(_is_punctuation(""".""" ) ) self.assertFalse(_is_punctuation("""A""" ) ) self.assertFalse(_is_punctuation(""" """ ) ) def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Optional[Any]: """simple docstring""" __lowerCAmelCase : Optional[Any] = self.get_tokenizer() __lowerCAmelCase : Dict = self.get_rust_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(lowerCAmelCase ) for t in ["""Test""", """\xad""", """test"""]] , [["""[UNK]"""], [], ["""[UNK]"""]] ) self.assertListEqual( [rust_tokenizer.tokenize(lowerCAmelCase ) for t in ["""Test""", """\xad""", """test"""]] , [["""[UNK]"""], [], ["""[UNK]"""]] ) @slow def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" __lowerCAmelCase : Union[str, Any] = self.tokenizer_class.from_pretrained("""bert-base-uncased""" ) __lowerCAmelCase : List[Any] = tokenizer.encode("""sequence builders""" , add_special_tokens=lowerCAmelCase ) __lowerCAmelCase : int = tokenizer.encode("""multi-sequence build""" , add_special_tokens=lowerCAmelCase ) __lowerCAmelCase : List[str] = tokenizer.build_inputs_with_special_tokens(lowerCAmelCase ) __lowerCAmelCase : Optional[int] = tokenizer.build_inputs_with_special_tokens(lowerCAmelCase , lowerCAmelCase ) assert encoded_sentence == [1_01] + text + [1_02] assert encoded_pair == [1_01] + text + [1_02] + text_a + [1_02] def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Dict: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): __lowerCAmelCase : List[str] = self.rust_tokenizer_class.from_pretrained(lowerCAmelCase , **lowerCAmelCase ) __lowerCAmelCase : Any = f'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.''' __lowerCAmelCase : List[Any] = tokenizer_r.encode_plus( lowerCAmelCase , return_attention_mask=lowerCAmelCase , return_token_type_ids=lowerCAmelCase , return_offsets_mapping=lowerCAmelCase , add_special_tokens=lowerCAmelCase , ) __lowerCAmelCase : List[Any] = tokenizer_r.do_lower_case if hasattr(lowerCAmelCase , """do_lower_case""" ) else False __lowerCAmelCase : Any = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), """A"""), ((1, 2), ""","""), ((3, 5), """na"""), ((5, 6), """##ï"""), ((6, 8), """##ve"""), ((9, 15), tokenizer_r.mask_token), ((16, 21), """Allen"""), ((21, 23), """##NL"""), ((23, 24), """##P"""), ((25, 33), """sentence"""), ((33, 34), """."""), ((0, 0), tokenizer_r.sep_token), ] if not do_lower_case else [ ((0, 0), tokenizer_r.cls_token), ((0, 1), """a"""), ((1, 2), ""","""), ((3, 8), """naive"""), ((9, 15), tokenizer_r.mask_token), ((16, 21), """allen"""), ((21, 23), """##nl"""), ((23, 24), """##p"""), ((25, 33), """sentence"""), ((33, 34), """."""), ((0, 0), tokenizer_r.sep_token), ] ) self.assertEqual( [e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens["""input_ids"""] ) ) self.assertEqual([e[0] for e in expected_results] , tokens["""offset_mapping"""] ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Union[str, Any]: """simple docstring""" __lowerCAmelCase : str = ["""的""", """人""", """有"""] __lowerCAmelCase : Tuple = """""".join(lowerCAmelCase ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): __lowerCAmelCase : Dict = True __lowerCAmelCase : Dict = self.tokenizer_class.from_pretrained(lowerCAmelCase , **lowerCAmelCase ) __lowerCAmelCase : Any = self.rust_tokenizer_class.from_pretrained(lowerCAmelCase , **lowerCAmelCase ) __lowerCAmelCase : Dict = tokenizer_p.encode(lowerCAmelCase , add_special_tokens=lowerCAmelCase ) __lowerCAmelCase : Union[str, Any] = tokenizer_r.encode(lowerCAmelCase , add_special_tokens=lowerCAmelCase ) __lowerCAmelCase : Optional[int] = tokenizer_r.convert_ids_to_tokens(lowerCAmelCase ) __lowerCAmelCase : int = tokenizer_p.convert_ids_to_tokens(lowerCAmelCase ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(lowerCAmelCase , lowerCAmelCase ) self.assertListEqual(lowerCAmelCase , lowerCAmelCase ) __lowerCAmelCase : Optional[Any] = False __lowerCAmelCase : Union[str, Any] = self.rust_tokenizer_class.from_pretrained(lowerCAmelCase , **lowerCAmelCase ) __lowerCAmelCase : Tuple = self.tokenizer_class.from_pretrained(lowerCAmelCase , **lowerCAmelCase ) __lowerCAmelCase : Any = tokenizer_r.encode(lowerCAmelCase , add_special_tokens=lowerCAmelCase ) __lowerCAmelCase : Tuple = tokenizer_p.encode(lowerCAmelCase , add_special_tokens=lowerCAmelCase ) __lowerCAmelCase : Tuple = tokenizer_r.convert_ids_to_tokens(lowerCAmelCase ) __lowerCAmelCase : List[Any] = tokenizer_p.convert_ids_to_tokens(lowerCAmelCase ) # it is expected that only the first Chinese character is not preceded by "##". __lowerCAmelCase : Tuple = [ f'''##{token}''' if idx != 0 else token for idx, token in enumerate(lowerCAmelCase ) ] self.assertListEqual(lowerCAmelCase , lowerCAmelCase ) self.assertListEqual(lowerCAmelCase , lowerCAmelCase )
651
import argparse import json import logging import os import sys from unittest.mock import patch from transformers.testing_utils import TestCasePlus, get_gpu_count, slow __UpperCAmelCase = [ os.path.join(os.path.dirname(__file__), dirname) for dirname in [ """text-classification""", """language-modeling""", """summarization""", """token-classification""", """question-answering""", ] ] sys.path.extend(SRC_DIRS) if SRC_DIRS is not None: import run_clm_flax import run_flax_glue import run_flax_ner import run_mlm_flax import run_qa import run_summarization_flax import run_ta_mlm_flax logging.basicConfig(level=logging.DEBUG) __UpperCAmelCase = logging.getLogger() def snake_case_ () -> Optional[Any]: __lowerCAmelCase : Tuple = argparse.ArgumentParser() parser.add_argument("""-f""" ) __lowerCAmelCase : Dict = parser.parse_args() return args.f def snake_case_ (__A : Dict , __A : List[str]="eval" ) -> int: __lowerCAmelCase : int = os.path.join(__A , f'''{split}_results.json''' ) if os.path.exists(__A ): with open(__A , """r""" ) as f: return json.load(__A ) raise ValueError(f'''can\'t find {path}''' ) __UpperCAmelCase = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class SCREAMING_SNAKE_CASE ( a_ ): """simple docstring""" def SCREAMING_SNAKE_CASE ( self : List[str] ) -> Tuple: """simple docstring""" __lowerCAmelCase : Tuple = self.get_auto_remove_tmp_dir() __lowerCAmelCase : Optional[Any] = f''' run_glue.py --model_name_or_path distilbert-base-uncased --output_dir {tmp_dir} --train_file ./tests/fixtures/tests_samples/MRPC/train.csv --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --learning_rate=1e-4 --eval_steps=2 --warmup_steps=2 --seed=42 --max_seq_length=128 '''.split() with patch.object(lowerCAmelCase , """argv""" , lowerCAmelCase ): run_flax_glue.main() __lowerCAmelCase : Dict = get_results(lowerCAmelCase ) self.assertGreaterEqual(result["""eval_accuracy"""] , 0.75 ) @slow def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Optional[int]: """simple docstring""" __lowerCAmelCase : Union[str, Any] = self.get_auto_remove_tmp_dir() __lowerCAmelCase : Any = f''' run_clm_flax.py --model_name_or_path distilgpt2 --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --do_train --do_eval --block_size 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --num_train_epochs 2 --logging_steps 2 --eval_steps 2 --output_dir {tmp_dir} --overwrite_output_dir '''.split() with patch.object(lowerCAmelCase , """argv""" , lowerCAmelCase ): run_clm_flax.main() __lowerCAmelCase : int = get_results(lowerCAmelCase ) self.assertLess(result["""eval_perplexity"""] , 1_00 ) @slow def SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[str]: """simple docstring""" __lowerCAmelCase : Tuple = self.get_auto_remove_tmp_dir() __lowerCAmelCase : int = f''' run_summarization.py --model_name_or_path t5-small --train_file tests/fixtures/tests_samples/xsum/sample.json --validation_file tests/fixtures/tests_samples/xsum/sample.json --test_file tests/fixtures/tests_samples/xsum/sample.json --output_dir {tmp_dir} --overwrite_output_dir --num_train_epochs=3 --warmup_steps=8 --do_train --do_eval --do_predict --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --predict_with_generate '''.split() with patch.object(lowerCAmelCase , """argv""" , lowerCAmelCase ): run_summarization_flax.main() __lowerCAmelCase : Union[str, Any] = get_results(lowerCAmelCase , split="""test""" ) self.assertGreaterEqual(result["""test_rouge1"""] , 10 ) self.assertGreaterEqual(result["""test_rouge2"""] , 2 ) self.assertGreaterEqual(result["""test_rougeL"""] , 7 ) self.assertGreaterEqual(result["""test_rougeLsum"""] , 7 ) @slow def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> List[Any]: """simple docstring""" __lowerCAmelCase : Tuple = self.get_auto_remove_tmp_dir() __lowerCAmelCase : List[str] = f''' run_mlm.py --model_name_or_path distilroberta-base --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --output_dir {tmp_dir} --overwrite_output_dir --max_seq_length 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --logging_steps 2 --eval_steps 2 --do_train --do_eval --num_train_epochs=1 '''.split() with patch.object(lowerCAmelCase , """argv""" , lowerCAmelCase ): run_mlm_flax.main() __lowerCAmelCase : List[Any] = get_results(lowerCAmelCase ) self.assertLess(result["""eval_perplexity"""] , 42 ) @slow def SCREAMING_SNAKE_CASE ( self : Any ) -> Optional[Any]: """simple docstring""" __lowerCAmelCase : Union[str, Any] = self.get_auto_remove_tmp_dir() __lowerCAmelCase : List[str] = f''' run_t5_mlm_flax.py --model_name_or_path t5-small --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --do_train --do_eval --max_seq_length 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --num_train_epochs 2 --logging_steps 2 --eval_steps 2 --output_dir {tmp_dir} --overwrite_output_dir '''.split() with patch.object(lowerCAmelCase , """argv""" , lowerCAmelCase ): run_ta_mlm_flax.main() __lowerCAmelCase : Union[str, Any] = get_results(lowerCAmelCase ) self.assertGreaterEqual(result["""eval_accuracy"""] , 0.42 ) @slow def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Dict: """simple docstring""" __lowerCAmelCase : List[Any] = 7 if get_gpu_count() > 1 else 2 __lowerCAmelCase : Optional[int] = self.get_auto_remove_tmp_dir() __lowerCAmelCase : List[Any] = f''' run_flax_ner.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/conll/sample.json --validation_file tests/fixtures/tests_samples/conll/sample.json --output_dir {tmp_dir} --overwrite_output_dir --do_train --do_eval --warmup_steps=2 --learning_rate=2e-4 --logging_steps 2 --eval_steps 2 --per_device_train_batch_size=2 --per_device_eval_batch_size=2 --num_train_epochs={epochs} --seed 7 '''.split() with patch.object(lowerCAmelCase , """argv""" , lowerCAmelCase ): run_flax_ner.main() __lowerCAmelCase : Dict = get_results(lowerCAmelCase ) self.assertGreaterEqual(result["""eval_accuracy"""] , 0.75 ) self.assertGreaterEqual(result["""eval_f1"""] , 0.3 ) @slow def SCREAMING_SNAKE_CASE ( self : int ) -> List[str]: """simple docstring""" __lowerCAmelCase : List[Any] = self.get_auto_remove_tmp_dir() __lowerCAmelCase : List[str] = f''' run_qa.py --model_name_or_path bert-base-uncased --version_2_with_negative --train_file tests/fixtures/tests_samples/SQUAD/sample.json --validation_file tests/fixtures/tests_samples/SQUAD/sample.json --output_dir {tmp_dir} --overwrite_output_dir --num_train_epochs=3 --warmup_steps=2 --do_train --do_eval --logging_steps 2 --eval_steps 2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 '''.split() with patch.object(lowerCAmelCase , """argv""" , lowerCAmelCase ): run_qa.main() __lowerCAmelCase : Union[str, Any] = get_results(lowerCAmelCase ) self.assertGreaterEqual(result["""eval_f1"""] , 30 ) self.assertGreaterEqual(result["""eval_exact"""] , 30 )
651
1
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING a__ = logging.get_logger(__name__) a__ = { """ut/deta""": """https://huggingface.co/ut/deta/resolve/main/config.json""", } class __magic_name__( SCREAMING_SNAKE_CASE__ ): UpperCAmelCase_ : Dict = """deta""" UpperCAmelCase_ : str = { """hidden_size""": """d_model""", """num_attention_heads""": """encoder_attention_heads""", } def __init__( self : Union[str, Any] , __UpperCamelCase : int=None , __UpperCamelCase : str=9_0_0 , __UpperCamelCase : Optional[int]=2_0_4_8 , __UpperCamelCase : Optional[Any]=6 , __UpperCamelCase : Union[str, Any]=2_0_4_8 , __UpperCamelCase : Union[str, Any]=8 , __UpperCamelCase : str=6 , __UpperCamelCase : Optional[int]=1_0_2_4 , __UpperCamelCase : Any=8 , __UpperCamelCase : Any=0.0 , __UpperCamelCase : Optional[int]=True , __UpperCamelCase : str="relu" , __UpperCamelCase : List[str]=2_5_6 , __UpperCamelCase : List[Any]=0.1 , __UpperCamelCase : str=0.0 , __UpperCamelCase : Union[str, Any]=0.0 , __UpperCamelCase : Union[str, Any]=0.02 , __UpperCamelCase : Optional[Any]=1.0 , __UpperCamelCase : List[Any]=True , __UpperCamelCase : Optional[Any]=False , __UpperCamelCase : Union[str, Any]="sine" , __UpperCamelCase : Optional[int]=5 , __UpperCamelCase : Dict=4 , __UpperCamelCase : Union[str, Any]=4 , __UpperCamelCase : Optional[int]=True , __UpperCamelCase : Dict=3_0_0 , __UpperCamelCase : int=True , __UpperCamelCase : str=True , __UpperCamelCase : Dict=1 , __UpperCamelCase : Dict=5 , __UpperCamelCase : Dict=2 , __UpperCamelCase : Union[str, Any]=1 , __UpperCamelCase : Any=1 , __UpperCamelCase : Optional[int]=5 , __UpperCamelCase : Optional[Any]=2 , __UpperCamelCase : List[str]=0.1 , __UpperCamelCase : List[str]=0.25 , **__UpperCamelCase : Dict , ): '''simple docstring''' if backbone_config is None: logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.""" ) snake_case__ = CONFIG_MAPPING["resnet"](out_features=["""stage2""", """stage3""", """stage4"""] ) else: if isinstance(snake_case__ , snake_case__ ): snake_case__ = backbone_config.pop("""model_type""" ) snake_case__ = CONFIG_MAPPING[backbone_model_type] snake_case__ = config_class.from_dict(snake_case__ ) snake_case__ = backbone_config snake_case__ = num_queries snake_case__ = max_position_embeddings snake_case__ = d_model snake_case__ = encoder_ffn_dim snake_case__ = encoder_layers snake_case__ = encoder_attention_heads snake_case__ = decoder_ffn_dim snake_case__ = decoder_layers snake_case__ = decoder_attention_heads snake_case__ = dropout snake_case__ = attention_dropout snake_case__ = activation_dropout snake_case__ = activation_function snake_case__ = init_std snake_case__ = init_xavier_std snake_case__ = encoder_layerdrop snake_case__ = auxiliary_loss snake_case__ = position_embedding_type # deformable attributes snake_case__ = num_feature_levels snake_case__ = encoder_n_points snake_case__ = decoder_n_points snake_case__ = two_stage snake_case__ = two_stage_num_proposals snake_case__ = with_box_refine snake_case__ = assign_first_stage if two_stage is True and with_box_refine is False: raise ValueError("""If two_stage is True, with_box_refine must be True.""" ) # Hungarian matcher snake_case__ = class_cost snake_case__ = bbox_cost snake_case__ = giou_cost # Loss coefficients snake_case__ = mask_loss_coefficient snake_case__ = dice_loss_coefficient snake_case__ = bbox_loss_coefficient snake_case__ = giou_loss_coefficient snake_case__ = eos_coefficient snake_case__ = focal_alpha super().__init__(is_encoder_decoder=snake_case__ , **snake_case__ ) @property def __lowerCAmelCase( self : str ): '''simple docstring''' return self.encoder_attention_heads @property def __lowerCAmelCase( self : str ): '''simple docstring''' return self.d_model def __lowerCAmelCase( self : Optional[int] ): '''simple docstring''' snake_case__ = copy.deepcopy(self.__dict__ ) snake_case__ = self.backbone_config.to_dict() snake_case__ = self.__class__.model_type return output
719
'''simple docstring''' import argparse import json import os import time import zipfile from get_ci_error_statistics import download_artifact, get_artifacts_links from transformers import logging a__ = logging.get_logger(__name__) def snake_case__ ( a , a ) -> Optional[int]: '''simple docstring''' snake_case__ = set() snake_case__ = [] def parse_line(a ): for line in fp: if isinstance(a , a ): snake_case__ = line.decode("""UTF-8""" ) if "warnings summary (final)" in line: continue # This means we are outside the body of a warning elif not line.startswith(""" """ ): # process a single warning and move it to `selected_warnings`. if len(a ) > 0: snake_case__ = """\n""".join(a ) # Only keep the warnings specified in `targets` if any(F""": {x}: """ in warning for x in targets ): selected_warnings.add(a ) buffer.clear() continue else: snake_case__ = line.strip() buffer.append(a ) if from_gh: for filename in os.listdir(a ): snake_case__ = os.path.join(a , a ) if not os.path.isdir(a ): # read the file if filename != "warnings.txt": continue with open(a ) as fp: parse_line(a ) else: try: with zipfile.ZipFile(a ) as z: for filename in z.namelist(): if not os.path.isdir(a ): # read the file if filename != "warnings.txt": continue with z.open(a ) as fp: parse_line(a ) except Exception: logger.warning( F"""{artifact_path} is either an invalid zip file or something else wrong. This file is skipped.""" ) return selected_warnings def snake_case__ ( a , a ) -> int: '''simple docstring''' snake_case__ = set() snake_case__ = [os.path.join(a , a ) for p in os.listdir(a ) if (p.endswith(""".zip""" ) or from_gh)] for p in paths: selected_warnings.update(extract_warnings_from_single_artifact(a , a ) ) return selected_warnings if __name__ == "__main__": def snake_case__ ( a ) -> int: '''simple docstring''' return values.split(""",""" ) a__ = argparse.ArgumentParser() # Required parameters parser.add_argument('''--workflow_run_id''', type=str, required=True, help='''A GitHub Actions workflow run id.''') parser.add_argument( '''--output_dir''', type=str, required=True, help='''Where to store the downloaded artifacts and other result files.''', ) parser.add_argument('''--token''', default=None, type=str, help='''A token that has actions:read permission.''') # optional parameters parser.add_argument( '''--targets''', default='''DeprecationWarning,UserWarning,FutureWarning''', type=list_str, help='''Comma-separated list of target warning(s) which we want to extract.''', ) parser.add_argument( '''--from_gh''', action='''store_true''', help='''If running from a GitHub action workflow and collecting warnings from its artifacts.''', ) a__ = parser.parse_args() a__ = args.from_gh if from_gh: # The artifacts have to be downloaded using `actions/download-artifact@v3` pass else: os.makedirs(args.output_dir, exist_ok=True) # get download links a__ = get_artifacts_links(args.workflow_run_id, token=args.token) with open(os.path.join(args.output_dir, '''artifacts.json'''), '''w''', encoding='''UTF-8''') as fp: json.dump(artifacts, fp, ensure_ascii=False, indent=4) # download artifacts for idx, (name, url) in enumerate(artifacts.items()): print(name) print(url) print('''=''' * 80) download_artifact(name, url, args.output_dir, args.token) # Be gentle to GitHub time.sleep(1) # extract warnings from artifacts a__ = extract_warnings(args.output_dir, args.targets) a__ = sorted(selected_warnings) with open(os.path.join(args.output_dir, '''selected_warnings.json'''), '''w''', encoding='''UTF-8''') as fp: json.dump(selected_warnings, fp, ensure_ascii=False, indent=4)
566
0
'''simple docstring''' 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 _UpperCamelCase (_lowerCamelCase : int , _lowerCamelCase : str )-> List[str]: '''simple docstring''' __snake_case = old_name if "patch_embed" in old_name: __snake_case , __snake_case , __snake_case = old_name.split('''.''' ) if layer == "0": __snake_case = old_name.replace('''0''' , '''convolution1''' ) elif layer == "1": __snake_case = old_name.replace('''1''' , '''batchnorm_before''' ) elif layer == "3": __snake_case = old_name.replace('''3''' , '''convolution2''' ) else: __snake_case = old_name.replace('''4''' , '''batchnorm_after''' ) if "network" in old_name and re.search(R'''\d\.\d''' , _lowerCamelCase ): __snake_case = R'''\b\d{2}\b''' if bool(re.search(_lowerCamelCase , _lowerCamelCase ) ): __snake_case = re.search(R'''\d\.\d\d.''' , _lowerCamelCase ).group() else: __snake_case = re.search(R'''\d\.\d.''' , _lowerCamelCase ).group() if int(match[0] ) < 6: __snake_case = old_name.replace(_lowerCamelCase , '''''' ) __snake_case = trimmed_name.replace('''network''' , match[0] + '''.meta4D_layers.blocks.''' + match[2:-1] ) __snake_case = '''intermediate_stages.''' + trimmed_name else: __snake_case = old_name.replace(_lowerCamelCase , '''''' ) if int(match[2] ) < num_meta4D_last_stage: __snake_case = trimmed_name.replace('''network''' , '''meta4D_layers.blocks.''' + match[2] ) else: __snake_case = str(int(match[2] ) - num_meta4D_last_stage ) __snake_case = trimmed_name.replace('''network''' , '''meta3D_layers.blocks.''' + layer_index ) if "norm1" in old_name: __snake_case = trimmed_name.replace('''norm1''' , '''layernorm1''' ) elif "norm2" in old_name: __snake_case = trimmed_name.replace('''norm2''' , '''layernorm2''' ) elif "fc1" in old_name: __snake_case = trimmed_name.replace('''fc1''' , '''linear_in''' ) elif "fc2" in old_name: __snake_case = trimmed_name.replace('''fc2''' , '''linear_out''' ) __snake_case = '''last_stage.''' + trimmed_name elif "network" in old_name and re.search(R'''.\d.''' , _lowerCamelCase ): __snake_case = old_name.replace('''network''' , '''intermediate_stages''' ) if "fc" in new_name: __snake_case = new_name.replace('''fc''' , '''convolution''' ) elif ("norm1" in new_name) and ("layernorm1" not in new_name): __snake_case = new_name.replace('''norm1''' , '''batchnorm_before''' ) elif ("norm2" in new_name) and ("layernorm2" not in new_name): __snake_case = new_name.replace('''norm2''' , '''batchnorm_after''' ) if "proj" in new_name: __snake_case = new_name.replace('''proj''' , '''projection''' ) if "dist_head" in new_name: __snake_case = new_name.replace('''dist_head''' , '''distillation_classifier''' ) elif "head" in new_name: __snake_case = new_name.replace('''head''' , '''classifier''' ) elif "patch_embed" in new_name: __snake_case = '''efficientformer.''' + new_name elif new_name == "norm.weight" or new_name == "norm.bias": __snake_case = new_name.replace('''norm''' , '''layernorm''' ) __snake_case = '''efficientformer.''' + new_name else: __snake_case = '''efficientformer.encoder.''' + new_name return new_name def _UpperCamelCase (_lowerCamelCase : str , _lowerCamelCase : Tuple )-> List[str]: '''simple docstring''' for key in checkpoint.copy().keys(): __snake_case = checkpoint.pop(_lowerCamelCase ) __snake_case = val return checkpoint def _UpperCamelCase ()-> Tuple: '''simple docstring''' __snake_case = '''http://images.cocodataset.org/val2017/000000039769.jpg''' __snake_case = Image.open(requests.get(_lowerCamelCase , stream=_lowerCamelCase ).raw ) return image def _UpperCamelCase (_lowerCamelCase : Path , _lowerCamelCase : Path , _lowerCamelCase : Path , _lowerCamelCase : bool )-> Optional[Any]: '''simple docstring''' __snake_case = torch.load(_lowerCamelCase , map_location='''cpu''' )['''model'''] __snake_case = EfficientFormerConfig.from_json_file(_lowerCamelCase ) __snake_case = EfficientFormerForImageClassificationWithTeacher(_lowerCamelCase ) __snake_case = '''_'''.join(checkpoint_path.split('''/''' )[-1].split('''.''' )[0].split('''_''' )[:-1] ) __snake_case = config.depths[-1] - config.num_metaad_blocks + 1 __snake_case = convert_torch_checkpoint(_lowerCamelCase , _lowerCamelCase ) model.load_state_dict(_lowerCamelCase ) model.eval() __snake_case = { '''bilinear''': PILImageResampling.BILINEAR, '''bicubic''': PILImageResampling.BICUBIC, '''nearest''': PILImageResampling.NEAREST, } # prepare image __snake_case = prepare_img() __snake_case = 2_56 __snake_case = 2_24 __snake_case = EfficientFormerImageProcessor( size={'''shortest_edge''': image_size} , crop_size={'''height''': crop_size, '''width''': crop_size} , resample=pillow_resamplings['''bicubic'''] , ) __snake_case = processor(images=_lowerCamelCase , return_tensors='''pt''' ).pixel_values # original processing pipeline __snake_case = Compose( [ Resize(_lowerCamelCase , interpolation=pillow_resamplings['''bicubic'''] ), CenterCrop(_lowerCamelCase ), ToTensor(), Normalize(_lowerCamelCase , _lowerCamelCase ), ] ) __snake_case = image_transforms(_lowerCamelCase ).unsqueeze(0 ) assert torch.allclose(_lowerCamelCase , _lowerCamelCase ) __snake_case = model(_lowerCamelCase ) __snake_case = outputs.logits __snake_case = (1, 10_00) if "l1" in model_name: __snake_case = 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] , _lowerCamelCase , atol=1E-3 ) assert logits.shape == expected_shape elif "l3" in model_name: __snake_case = 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] , _lowerCamelCase , atol=1E-3 ) assert logits.shape == expected_shape elif "l7" in model_name: __snake_case = 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(_lowerCamelCase ).mkdir(exist_ok=_lowerCamelCase ) model.save_pretrained(_lowerCamelCase ) print(f'''Checkpoint successfuly converted. Model saved at {pytorch_dump_path}''' ) processor.save_pretrained(_lowerCamelCase ) 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=_lowerCamelCase , ) processor.push_to_hub( repo_id=f'''Bearnardd/{pytorch_dump_path}''' , commit_message='''Add image processor''' , use_temp_dir=_lowerCamelCase , ) if __name__ == "__main__": UpperCAmelCase_ : Optional[int] = 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) UpperCAmelCase_ : Union[str, Any] = 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, )
24
"""simple docstring""" import os from datetime import datetime as dt from github import Github _snake_case = [ "good first issue", "good second issue", "good difficult issue", "enhancement", "new pipeline/model", "new scheduler", "wip", ] def snake_case ( )-> int: '''simple docstring''' lowerCamelCase__ = Github(os.environ['GITHUB_TOKEN'] ) lowerCamelCase__ = g.get_repo('huggingface/diffusers' ) lowerCamelCase__ = repo.get_issues(state='open' ) for issue in open_issues: lowerCamelCase__ = sorted(issue.get_comments() , key=lambda _a : i.created_at , reverse=_a ) lowerCamelCase__ = comments[0] if len(_a ) > 0 else None if ( last_comment is not None and last_comment.user.login == "github-actions[bot]" and (dt.utcnow() - issue.updated_at).days > 7 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Closes the issue after 7 days of inactivity since the Stalebot notification. issue.edit(state='closed' ) elif ( "stale" in issue.get_labels() and last_comment is not None and last_comment.user.login != "github-actions[bot]" ): # Opens the issue if someone other than Stalebot commented. issue.edit(state='open' ) issue.remove_from_labels('stale' ) elif ( (dt.utcnow() - issue.updated_at).days > 23 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Post a Stalebot notification after 23 days of inactivity. issue.create_comment( 'This issue has been automatically marked as stale because it has not had ' 'recent activity. If you think this still needs to be addressed ' 'please comment on this thread.\n\nPlease note that issues that do not follow the ' '[contributing guidelines](https://github.com/huggingface/diffusers/blob/main/CONTRIBUTING.md) ' 'are likely to be ignored.' ) issue.add_to_labels('stale' ) if __name__ == "__main__": main()
510
0
import inspect from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel, VQModel from ...schedulers import DDIMScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class __snake_case ( lowerCamelCase_ ): def __init__( self : Optional[int] , _lowercase : VQModel , _lowercase : UNetaDModel , _lowercase : DDIMScheduler ): """simple docstring""" super().__init__() self.register_modules(vqvae=_lowercase , unet=_lowercase , scheduler=_lowercase ) @torch.no_grad() def __call__( self : List[Any] , _lowercase : int = 1 , _lowercase : Optional[Union[torch.Generator, List[torch.Generator]]] = None , _lowercase : float = 0.0 , _lowercase : int = 50 , _lowercase : Optional[str] = "pil" , _lowercase : bool = True , **_lowercase : Optional[Any] , ): """simple docstring""" SCREAMING_SNAKE_CASE__ = randn_tensor( (batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , generator=_lowercase , ) SCREAMING_SNAKE_CASE__ = latents.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler SCREAMING_SNAKE_CASE__ = latents * self.scheduler.init_noise_sigma self.scheduler.set_timesteps(_lowercase ) # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature SCREAMING_SNAKE_CASE__ = """eta""" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) SCREAMING_SNAKE_CASE__ = {} if accepts_eta: SCREAMING_SNAKE_CASE__ = eta for t in self.progress_bar(self.scheduler.timesteps ): SCREAMING_SNAKE_CASE__ = self.scheduler.scale_model_input(_lowercase , _lowercase ) # predict the noise residual SCREAMING_SNAKE_CASE__ = self.unet(_lowercase , _lowercase ).sample # compute the previous noisy sample x_t -> x_t-1 SCREAMING_SNAKE_CASE__ = self.scheduler.step(_lowercase , _lowercase , _lowercase , **_lowercase ).prev_sample # decode the image latents with the VAE SCREAMING_SNAKE_CASE__ = self.vqvae.decode(_lowercase ).sample SCREAMING_SNAKE_CASE__ = (image / 2 + 0.5).clamp(0 , 1 ) SCREAMING_SNAKE_CASE__ = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": SCREAMING_SNAKE_CASE__ = self.numpy_to_pil(_lowercase ) if not return_dict: return (image,) return ImagePipelineOutput(images=_lowercase )
721
def __SCREAMING_SNAKE_CASE ( __UpperCamelCase : int ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = [1] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = 0, 0, 0 SCREAMING_SNAKE_CASE__ = ugly_nums[ia] * 2 SCREAMING_SNAKE_CASE__ = ugly_nums[ia] * 3 SCREAMING_SNAKE_CASE__ = ugly_nums[ia] * 5 for _ in range(1 , __UpperCamelCase ): SCREAMING_SNAKE_CASE__ = min(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) ugly_nums.append(__UpperCamelCase ) if next_num == next_a: ia += 1 SCREAMING_SNAKE_CASE__ = ugly_nums[ia] * 2 if next_num == next_a: ia += 1 SCREAMING_SNAKE_CASE__ = ugly_nums[ia] * 3 if next_num == next_a: ia += 1 SCREAMING_SNAKE_CASE__ = ugly_nums[ia] * 5 return ugly_nums[-1] if __name__ == "__main__": from doctest import testmod testmod(verbose=True) print(F"""{ugly_numbers(200) = }""")
379
0
UpperCAmelCase_ = """Alexander Joslin""" import operator as op from .stack import Stack def SCREAMING_SNAKE_CASE_ ( _snake_case :str ) -> int: _A = {'''*''': op.mul, '''/''': op.truediv, '''+''': op.add, '''-''': op.sub} _A = Stack() _A = Stack() for i in equation: if i.isdigit(): # RULE 1 operand_stack.push(int(_snake_case ) ) elif i in operators: # RULE 2 operator_stack.push(_snake_case ) elif i == ")": # RULE 4 _A = operator_stack.peek() operator_stack.pop() _A = operand_stack.peek() operand_stack.pop() _A = operand_stack.peek() operand_stack.pop() _A = operators[opr](_snake_case , _snake_case ) operand_stack.push(_snake_case ) # RULE 5 return operand_stack.peek() if __name__ == "__main__": UpperCAmelCase_ = """(5 + ((4 * 2) * (2 + 3)))""" # answer = 45 print(f'{equation} = {dijkstras_two_stack_algorithm(equation)}')
2
import warnings from diffusers import StableDiffusionInpaintPipeline as StableDiffusionInpaintPipeline # noqa F401 warnings.warn( 'The `inpainting.py` script is outdated. Please use directly `from diffusers import' ' StableDiffusionInpaintPipeline` instead.' )
408
0
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import GLPNImageProcessor class lowerCAmelCase ( unittest.TestCase ): def __init__( self , lowerCAmelCase__ , lowerCAmelCase__=7 , lowerCAmelCase__=3 , lowerCAmelCase__=18 , lowerCAmelCase__=30 , lowerCAmelCase__=400 , lowerCAmelCase__=True , lowerCAmelCase__=32 , lowerCAmelCase__=True , ): _A= parent _A= batch_size _A= num_channels _A= image_size _A= min_resolution _A= max_resolution _A= do_resize _A= size_divisor _A= do_rescale def a__ ( self ): return { "do_resize": self.do_resize, "size_divisor": self.size_divisor, "do_rescale": self.do_rescale, } @require_torch @require_vision class lowerCAmelCase ( _a , unittest.TestCase ): _SCREAMING_SNAKE_CASE : int =GLPNImageProcessor if is_vision_available() else None def a__ ( self ): _A= GLPNImageProcessingTester(self ) @property def a__ ( self ): return self.image_processor_tester.prepare_image_processor_dict() def a__ ( self ): _A= self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowerCAmelCase__ , 'do_resize' ) ) self.assertTrue(hasattr(lowerCAmelCase__ , 'size_divisor' ) ) self.assertTrue(hasattr(lowerCAmelCase__ , 'resample' ) ) self.assertTrue(hasattr(lowerCAmelCase__ , 'do_rescale' ) ) def a__ ( self ): pass def a__ ( self ): # Initialize image_processing _A= self.image_processing_class(**self.image_processor_dict ) # create random PIL images _A= prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCAmelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCAmelCase__ , Image.Image ) # Test not batched input (GLPNImageProcessor doesn't support batching) _A= image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 ) def a__ ( self ): # Initialize image_processing _A= self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _A= prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCAmelCase__ , numpify=lowerCAmelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCAmelCase__ , np.ndarray ) # Test not batched input (GLPNImageProcessor doesn't support batching) _A= image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 ) def a__ ( self ): # Initialize image_processing _A= self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _A= prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCAmelCase__ , torchify=lowerCAmelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCAmelCase__ , torch.Tensor ) # Test not batched input (GLPNImageProcessor doesn't support batching) _A= image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 )
476
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, XLMRobertaTokenizer from diffusers import AltDiffusionPipeline, AutoencoderKL, DDIMScheduler, PNDMScheduler, UNetaDConditionModel from diffusers.pipelines.alt_diffusion.modeling_roberta_series import ( RobertaSeriesConfig, RobertaSeriesModelWithTransformation, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowerCAmelCase ( _a , _a , _a , unittest.TestCase ): _SCREAMING_SNAKE_CASE : Optional[int] =AltDiffusionPipeline _SCREAMING_SNAKE_CASE : int =TEXT_TO_IMAGE_PARAMS _SCREAMING_SNAKE_CASE : List[Any] =TEXT_TO_IMAGE_BATCH_PARAMS _SCREAMING_SNAKE_CASE : Dict =TEXT_TO_IMAGE_IMAGE_PARAMS _SCREAMING_SNAKE_CASE : Any =TEXT_TO_IMAGE_IMAGE_PARAMS def a__ ( self ): 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 , ) _A= DDIMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule='scaled_linear' , clip_sample=lowerCAmelCase__ , set_alpha_to_one=lowerCAmelCase__ , ) 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 , ) # TODO: address the non-deterministic text encoder (fails for save-load tests) # torch.manual_seed(0) # text_encoder_config = RobertaSeriesConfig( # hidden_size=32, # project_dim=32, # intermediate_size=37, # layer_norm_eps=1e-05, # num_attention_heads=4, # num_hidden_layers=5, # vocab_size=5002, # ) # text_encoder = RobertaSeriesModelWithTransformation(text_encoder_config) torch.manual_seed(0 ) _A= CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , projection_dim=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=5002 , ) _A= CLIPTextModel(lowerCAmelCase__ ) _A= XLMRobertaTokenizer.from_pretrained('hf-internal-testing/tiny-xlm-roberta' ) _A= 77 _A= { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def a__ ( self , lowerCAmelCase__ , lowerCAmelCase__=0 ): if str(lowerCAmelCase__ ).startswith('mps' ): _A= torch.manual_seed(lowerCAmelCase__ ) else: _A= torch.Generator(device=lowerCAmelCase__ ).manual_seed(lowerCAmelCase__ ) _A= { 'prompt': 'A painting of a squirrel eating a burger', 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, 'output_type': 'numpy', } return inputs def a__ ( self ): super().test_attention_slicing_forward_pass(expected_max_diff=3E-3 ) def a__ ( self ): super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) def a__ ( self ): _A= 'cpu' # ensure determinism for the device-dependent torch.Generator _A= self.get_dummy_components() torch.manual_seed(0 ) _A= RobertaSeriesConfig( hidden_size=32 , project_dim=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=5002 , ) # TODO: remove after fixing the non-deterministic text encoder _A= RobertaSeriesModelWithTransformation(lowerCAmelCase__ ) _A= text_encoder _A= AltDiffusionPipeline(**lowerCAmelCase__ ) _A= alt_pipe.to(lowerCAmelCase__ ) alt_pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) _A= self.get_dummy_inputs(lowerCAmelCase__ ) _A= 'A photo of an astronaut' _A= alt_pipe(**lowerCAmelCase__ ) _A= output.images _A= image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _A= np.array( [0.5748162, 0.60447145, 0.48821217, 0.50100636, 0.5431185, 0.45763683, 0.49657696, 0.48132733, 0.47573093] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def a__ ( self ): _A= 'cpu' # ensure determinism for the device-dependent torch.Generator _A= self.get_dummy_components() _A= PNDMScheduler(skip_prk_steps=lowerCAmelCase__ ) torch.manual_seed(0 ) _A= RobertaSeriesConfig( hidden_size=32 , project_dim=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=5002 , ) # TODO: remove after fixing the non-deterministic text encoder _A= RobertaSeriesModelWithTransformation(lowerCAmelCase__ ) _A= text_encoder _A= AltDiffusionPipeline(**lowerCAmelCase__ ) _A= alt_pipe.to(lowerCAmelCase__ ) alt_pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) _A= self.get_dummy_inputs(lowerCAmelCase__ ) _A= alt_pipe(**lowerCAmelCase__ ) _A= output.images _A= image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _A= np.array( [0.51605093, 0.5707241, 0.47365507, 0.50578886, 0.5633877, 0.4642503, 0.5182081, 0.48763484, 0.49084237] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch_gpu class lowerCAmelCase ( unittest.TestCase ): def a__ ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def a__ ( self ): # make sure here that pndm scheduler skips prk _A= AltDiffusionPipeline.from_pretrained('BAAI/AltDiffusion' , safety_checker=lowerCAmelCase__ ) _A= alt_pipe.to(lowerCAmelCase__ ) alt_pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) _A= 'A painting of a squirrel eating a burger' _A= torch.manual_seed(0 ) _A= alt_pipe([prompt] , generator=lowerCAmelCase__ , guidance_scale=6.0 , num_inference_steps=20 , output_type='np' ) _A= output.images _A= image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) _A= np.array([0.1010, 0.0800, 0.0794, 0.0885, 0.0843, 0.0762, 0.0769, 0.0729, 0.0586] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def a__ ( self ): _A= DDIMScheduler.from_pretrained('BAAI/AltDiffusion' , subfolder='scheduler' ) _A= AltDiffusionPipeline.from_pretrained('BAAI/AltDiffusion' , scheduler=lowerCAmelCase__ , safety_checker=lowerCAmelCase__ ) _A= alt_pipe.to(lowerCAmelCase__ ) alt_pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) _A= 'A painting of a squirrel eating a burger' _A= torch.manual_seed(0 ) _A= alt_pipe([prompt] , generator=lowerCAmelCase__ , num_inference_steps=2 , output_type='numpy' ) _A= output.images _A= image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) _A= np.array([0.4019, 0.4052, 0.3810, 0.4119, 0.3916, 0.3982, 0.4651, 0.4195, 0.5323] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
476
1
'''simple docstring''' import argparse from pathlib import Path import torch from transformers import OPTConfig, OPTModel from transformers.utils import logging logging.set_verbosity_info() _a : str = logging.get_logger(__name__) def _a (lowercase__ : Tuple ) -> Optional[int]: """simple docstring""" __snake_case = torch.load(lowercase__ , map_location='cpu' ) if "model" in sd.keys(): __snake_case = torch.load(lowercase__ , map_location='cpu' )['model'] # pop unnecessary weights __snake_case = [ 'decoder.version', 'decoder.output_projection.weight', ] for key in keys_to_delete: if key in sd: sd.pop(lowercase__ ) __snake_case = { 'decoder.project_in_dim.weight': 'decoder.project_in.weight', 'decoder.project_out_dim.weight': 'decoder.project_out.weight', 'decoder.layer_norm.weight': 'decoder.final_layer_norm.weight', 'decoder.layer_norm.bias': 'decoder.final_layer_norm.bias', } for old_key, new_key in keys_to_rename.items(): if old_key in sd: __snake_case = sd.pop(lowercase__ ) __snake_case = list(sd.keys() ) for key in keys: if ".qkv_proj." in key: __snake_case = sd[key] # We split QKV in separate Q,K,V __snake_case = key.replace('.qkv_proj.' , '.q_proj.' ) __snake_case = key.replace('.qkv_proj.' , '.k_proj.' ) __snake_case = key.replace('.qkv_proj.' , '.v_proj.' ) __snake_case = value.shape[0] assert depth % 3 == 0 # `SequeuceParallelTransformerBlock` has QKV weight is separated in K,V,Q despite the naming: # https://cs.github.com/facebookresearch/metaseq/blob/51871bd73cd04c038f239ea2a26db1d7f6b37927/metaseq/modules/sequence_parallel_transformer_layer.py#L97 __snake_case , __snake_case , __snake_case = torch.split(lowercase__ , depth // 3 , dim=0 ) __snake_case = q __snake_case = k __snake_case = v del sd[key] return sd @torch.no_grad() def _a (lowercase__ : str , lowercase__ : Tuple , lowercase__ : List[Any]=None ) -> Optional[int]: """simple docstring""" __snake_case = load_checkpoint(lowercase__ ) if config is not None: __snake_case = OPTConfig.from_pretrained(lowercase__ ) else: __snake_case = OPTConfig() __snake_case = OPTModel(lowercase__ ).half().eval() model.load_state_dict(lowercase__ ) # Check results Path(lowercase__ ).mkdir(exist_ok=lowercase__ ) model.save_pretrained(lowercase__ ) if __name__ == "__main__": _a : List[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--fairseq_path", type=str, help=( "path to fairseq checkpoint in correct format. You can find all checkpoints in the correct format here:" " https://huggingface.co/models?other=opt_metasq" ), ) parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument("--hf_config", default=None, type=str, help="Define HF config.") _a : List[Any] = parser.parse_args() convert_opt_checkpoint(args.fairseq_path, args.pytorch_dump_folder_path, config=args.hf_config)
56
'''simple docstring''' from __future__ import annotations import math def _a (lowercase__ : int ) -> bool: """simple docstring""" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(lowercase__ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True _a : Dict = [num for num in range(3, 100_001, 2) if not is_prime(num)] def _a (lowercase__ : int ) -> list[int]: """simple docstring""" if not isinstance(lowercase__ , lowercase__ ): raise ValueError('n must be an integer' ) if n <= 0: raise ValueError('n must be >= 0' ) __snake_case = [] for num in range(len(lowercase__ ) ): __snake_case = 0 while 2 * i * i <= odd_composites[num]: __snake_case = odd_composites[num] - 2 * i * i if is_prime(lowercase__ ): break i += 1 else: list_nums.append(odd_composites[num] ) if len(lowercase__ ) == n: return list_nums return [] def _a () -> int: """simple docstring""" return compute_nums(1 )[0] if __name__ == "__main__": print(f'''{solution() = }''')
56
1
'''simple docstring''' import math import qiskit def lowerCAmelCase( a__ : int = 1 , a__ : int = 1 , a__ : int = 1 ): '''simple docstring''' if ( isinstance(a__ , a__ ) or isinstance(a__ , a__ ) or isinstance(a__ , a__ ) ): raise TypeError("inputs must be integers." ) if (input_a < 0) or (input_a < 0) or (carry_in < 0): raise ValueError("inputs must be positive." ) if ( (math.floor(a__ ) != input_a) or (math.floor(a__ ) != input_a) or (math.floor(a__ ) != carry_in) ): raise ValueError("inputs must be exact integers." ) if (input_a > 2) or (input_a > 2) or (carry_in > 2): raise ValueError("inputs must be less or equal to 2." ) # build registers lowerCamelCase__ = qiskit.QuantumRegister(4 , "qr" ) lowerCamelCase__ = qiskit.ClassicalRegister(2 , "cr" ) # list the entries lowerCamelCase__ = [input_a, input_a, carry_in] lowerCamelCase__ = qiskit.QuantumCircuit(a__ , a__ ) for i in range(0 , 3 ): if entry[i] == 2: quantum_circuit.h(a__ ) # for hadamard entries elif entry[i] == 1: quantum_circuit.x(a__ ) # for 1 entries elif entry[i] == 0: quantum_circuit.i(a__ ) # for 0 entries # build the circuit quantum_circuit.ccx(0 , 1 , 3 ) # ccx = toffoli gate quantum_circuit.cx(0 , 1 ) quantum_circuit.ccx(1 , 2 , 3 ) quantum_circuit.cx(1 , 2 ) quantum_circuit.cx(0 , 1 ) quantum_circuit.measure([2, 3] , a__ ) # measure the last two qbits lowerCamelCase__ = qiskit.Aer.get_backend("aer_simulator" ) lowerCamelCase__ = qiskit.execute(a__ , a__ , shots=1000 ) return job.result().get_counts(a__ ) if __name__ == "__main__": print(f'Total sum count for state is: {quantum_full_adder(1, 1, 1)}')
426
'''simple docstring''' def lowerCAmelCase( a__ : str ): '''simple docstring''' if not all(char in "01" for char in bin_string ): raise ValueError("Non-binary value was passed to the function" ) if not bin_string: raise ValueError("Empty string was passed to the function" ) lowerCamelCase__ = "" while len(a__ ) % 3 != 0: lowerCamelCase__ = "0" + bin_string lowerCamelCase__ = [ bin_string[index : index + 3] for index in range(len(a__ ) ) if index % 3 == 0 ] for bin_group in bin_string_in_3_list: lowerCamelCase__ = 0 for index, val in enumerate(a__ ): oct_val += int(2 ** (2 - index) * int(a__ ) ) oct_string += str(a__ ) return oct_string if __name__ == "__main__": from doctest import testmod testmod()
426
1
'''simple docstring''' def lowerCamelCase__ ( a__) -> str: """simple docstring""" if isinstance(a__ , a__): raise TypeError('\'float\' object cannot be interpreted as an integer') if isinstance(a__ , a__): raise TypeError('\'str\' object cannot be interpreted as an integer') if num == 0: return "0b0" _snake_case : Dict = False if num < 0: _snake_case : str = True _snake_case : int = -num _snake_case : list[int] = [] while num > 0: binary.insert(0 , num % 2) num >>= 1 if negative: return "-0b" + "".join(str(a__) for e in binary) return "0b" + "".join(str(a__) for e in binary) if __name__ == "__main__": import doctest doctest.testmod()
517
'''simple docstring''' from __future__ import annotations def lowerCamelCase__ ( a__) -> float: """simple docstring""" if not nums: raise ValueError('List is empty') return sum(a__) / len(a__) if __name__ == "__main__": import doctest doctest.testmod()
517
1
"""simple docstring""" from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL import torch from transformers import CLIPImageProcessor, CLIPVisionModel from ...models import PriorTransformer from ...pipelines import DiffusionPipeline from ...schedulers import HeunDiscreteScheduler from ...utils import ( BaseOutput, is_accelerate_available, logging, randn_tensor, replace_example_docstring, ) from .renderer import ShapERenderer __UpperCAmelCase =logging.get_logger(__name__) # pylint: disable=invalid-name __UpperCAmelCase =""" Examples: ```py >>> from PIL import Image >>> import torch >>> from diffusers import DiffusionPipeline >>> from diffusers.utils import export_to_gif, load_image >>> device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") >>> repo = \"openai/shap-e-img2img\" >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16) >>> pipe = pipe.to(device) >>> guidance_scale = 3.0 >>> image_url = \"https://hf.co/datasets/diffusers/docs-images/resolve/main/shap-e/corgi.png\" >>> image = load_image(image_url).convert(\"RGB\") >>> images = pipe( ... image, ... guidance_scale=guidance_scale, ... num_inference_steps=64, ... frame_size=256, ... ).images >>> gif_path = export_to_gif(images[0], \"corgi_3d.gif\") ``` """ @dataclass class lowerCAmelCase__ ( UpperCAmelCase_ ): lowercase__ : Union[PIL.Image.Image, np.ndarray] class lowerCAmelCase__ ( UpperCAmelCase_ ): def __init__( self , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , ): '''simple docstring''' super().__init__() self.register_modules( prior=UpperCamelCase__ , image_encoder=UpperCamelCase__ , image_processor=UpperCamelCase__ , scheduler=UpperCamelCase__ , renderer=UpperCamelCase__ , ) def lowercase_ ( self , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' if latents is None: A__ = randn_tensor(UpperCamelCase__ , generator=UpperCamelCase__ , device=UpperCamelCase__ , dtype=UpperCamelCase__ ) else: if latents.shape != shape: raise ValueError(f"""Unexpected latents shape, got {latents.shape}, expected {shape}""" ) A__ = latents.to(UpperCamelCase__ ) A__ = latents * scheduler.init_noise_sigma return latents def lowercase_ ( self , UpperCamelCase__=0 ): '''simple docstring''' if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("Please install accelerate via `pip install accelerate`" ) A__ = torch.device(f"""cuda:{gpu_id}""" ) A__ = [self.image_encoder, self.prior] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(UpperCamelCase__ , UpperCamelCase__ ) @property def lowercase_ ( self ): '''simple docstring''' if self.device != torch.device("meta" ) or not hasattr(self.image_encoder , "_hf_hook" ): return self.device for module in self.image_encoder.modules(): if ( hasattr(UpperCamelCase__ , "_hf_hook" ) and hasattr(module._hf_hook , "execution_device" ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device def lowercase_ ( self , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , ): '''simple docstring''' if isinstance(UpperCamelCase__ , UpperCamelCase__ ) and isinstance(image[0] , torch.Tensor ): A__ = torch.cat(UpperCamelCase__ , axis=0 ) if image[0].ndim == 4 else torch.stack(UpperCamelCase__ , axis=0 ) if not isinstance(UpperCamelCase__ , torch.Tensor ): A__ = self.image_processor(UpperCamelCase__ , return_tensors="pt" ).pixel_values[0].unsqueeze(0 ) A__ = image.to(dtype=self.image_encoder.dtype , device=UpperCamelCase__ ) A__ = self.image_encoder(UpperCamelCase__ )["last_hidden_state"] A__ = image_embeds[:, 1:, :].contiguous() # batch_size, dim, 256 A__ = image_embeds.repeat_interleave(UpperCamelCase__ , dim=0 ) if do_classifier_free_guidance: A__ = torch.zeros_like(UpperCamelCase__ ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes A__ = torch.cat([negative_image_embeds, image_embeds] ) return image_embeds @torch.no_grad() @replace_example_docstring(UpperCamelCase__ ) def __call__( self , UpperCamelCase__ , UpperCamelCase__ = 1 , UpperCamelCase__ = 25 , UpperCamelCase__ = None , UpperCamelCase__ = None , UpperCamelCase__ = 4.0 , UpperCamelCase__ = 64 , UpperCamelCase__ = "pil" , UpperCamelCase__ = True , ): '''simple docstring''' if isinstance(UpperCamelCase__ , PIL.Image.Image ): A__ = 1 elif isinstance(UpperCamelCase__ , torch.Tensor ): A__ = image.shape[0] elif isinstance(UpperCamelCase__ , UpperCamelCase__ ) and isinstance(image[0] , (torch.Tensor, PIL.Image.Image) ): A__ = len(UpperCamelCase__ ) else: raise ValueError( f"""`image` has to be of type `PIL.Image.Image`, `torch.Tensor`, `List[PIL.Image.Image]` or `List[torch.Tensor]` but is {type(UpperCamelCase__ )}""" ) A__ = self._execution_device A__ = batch_size * num_images_per_prompt A__ = guidance_scale > 1.0 A__ = self._encode_image(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # prior self.scheduler.set_timesteps(UpperCamelCase__ , device=UpperCamelCase__ ) A__ = self.scheduler.timesteps A__ = self.prior.config.num_embeddings A__ = self.prior.config.embedding_dim A__ = self.prepare_latents( (batch_size, num_embeddings * embedding_dim) , image_embeds.dtype , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , self.scheduler , ) # YiYi notes: for testing only to match ldm, we can directly create a latents with desired shape: batch_size, num_embeddings, embedding_dim A__ = latents.reshape(latents.shape[0] , UpperCamelCase__ , UpperCamelCase__ ) for i, t in enumerate(self.progress_bar(UpperCamelCase__ ) ): # expand the latents if we are doing classifier free guidance A__ = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents A__ = self.scheduler.scale_model_input(UpperCamelCase__ , UpperCamelCase__ ) A__ = self.prior( UpperCamelCase__ , timestep=UpperCamelCase__ , proj_embedding=UpperCamelCase__ , ).predicted_image_embedding # remove the variance A__ , A__ = noise_pred.split( scaled_model_input.shape[2] , dim=2 ) # batch_size, num_embeddings, embedding_dim if do_classifier_free_guidance is not None: A__ , A__ = noise_pred.chunk(2 ) A__ = noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond) A__ = self.scheduler.step( UpperCamelCase__ , timestep=UpperCamelCase__ , sample=UpperCamelCase__ , ).prev_sample if output_type == "latent": return ShapEPipelineOutput(images=UpperCamelCase__ ) A__ = [] for i, latent in enumerate(UpperCamelCase__ ): print() A__ = self.renderer.decode( latent[None, :] , UpperCamelCase__ , size=UpperCamelCase__ , ray_batch_size=40_96 , n_coarse_samples=64 , n_fine_samples=1_28 , ) images.append(UpperCamelCase__ ) A__ = torch.stack(UpperCamelCase__ ) if output_type not in ["np", "pil"]: raise ValueError(f"""Only the output types `pil` and `np` are supported not output_type={output_type}""" ) A__ = images.cpu().numpy() if output_type == "pil": A__ = [self.numpy_to_pil(UpperCamelCase__ ) for image in images] # Offload last model to CPU if hasattr(self , "final_offload_hook" ) and self.final_offload_hook is not None: self.final_offload_hook.offload() if not return_dict: return (images,) return ShapEPipelineOutput(images=UpperCamelCase__ )
261
"""simple docstring""" import sys import webbrowser import requests from bsa import BeautifulSoup from fake_useragent import UserAgent if __name__ == "__main__": print("""Googling.....""") __UpperCAmelCase ="""https://www.google.com/search?q=""" + """ """.join(sys.argv[1:]) __UpperCAmelCase =requests.get(url, headers={"""UserAgent""": UserAgent().random}) # res.raise_for_status() with open("""project1a.html""", """wb""") as out_file: # only for knowing the class for data in res.iter_content(1_0000): out_file.write(data) __UpperCAmelCase =BeautifulSoup(res.text, """html.parser""") __UpperCAmelCase =list(soup.select(""".eZt8xd"""))[:5] print(len(links)) for link in links: if link.text == "Maps": webbrowser.open(link.get("""href""")) else: webbrowser.open(F'''https://google.com{link.get("href")}''')
261
1
"""simple docstring""" import collections import json import math import os import re import time from fnmatch import fnmatch from typing import Dict import requests from slack_sdk import WebClient lowercase_ = WebClient(token=os.environ["CI_SLACK_BOT_TOKEN"]) def lowercase ( lowerCAmelCase__ : Optional[int] ) -> List[str]: __a = test_results.split(''' ''' ) __a = 0 __a = 0 # When the output is short enough, the output is surrounded by = signs: "== OUTPUT ==" # When it is too long, those signs are not present. __a = expressions[-2] if '''=''' in expressions[-1] else expressions[-1] for i, expression in enumerate(lowerCAmelCase__ ): if "failed" in expression: failed += int(expressions[i - 1] ) if "passed" in expression: success += int(expressions[i - 1] ) return failed, success, time_spent def lowercase ( lowerCAmelCase__ : int ) -> str: __a = {} __a = None __a = False for line in failures_short_lines.split('''\n''' ): if re.search(r'''_ \[doctest\]''' , lowerCAmelCase__ ): __a = True __a = line.split(''' ''' )[2] elif in_error and not line.split(''' ''' )[0].isdigit(): __a = line __a = False return failures class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a ): __a = title __a = doc_test_results['''time_spent'''].split(''',''' )[0] __a = doc_test_results['''success'''] __a = doc_test_results['''failures'''] __a = self.n_success + self.n_failures # Failures and success of the modeling tests __a = doc_test_results @property def __UpperCAmelCase ( self ): __a = [self._time_spent] __a = 0 for time in time_spent: __a = time.split(''':''' ) # Time can be formatted as xx:xx:xx, as .xx, or as x.xx if the time spent was less than a minute. if len(_a ) == 1: __a = [0, 0, time_parts[0]] __a , __a , __a = int(time_parts[0] ), int(time_parts[1] ), float(time_parts[2] ) total_secs += hours * 3_600 + minutes * 60 + seconds __a , __a , __a = total_secs // 3_600, (total_secs % 3_600) // 60, total_secs % 60 return f'''{int(_a )}h{int(_a )}m{int(_a )}s''' @property def __UpperCAmelCase ( self ): return {"type": "header", "text": {"type": "plain_text", "text": self.title}} @property def __UpperCAmelCase ( self ): return { "type": "section", "text": { "type": "plain_text", "text": f'''🌞 There were no failures: all {self.n_tests} tests passed. The suite ran in {self.time}.''', "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": f'''https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}''', }, } @property def __UpperCAmelCase ( self ): return { "type": "section", "text": { "type": "plain_text", "text": ( f'''There were {self.n_failures} failures, out of {self.n_tests} tests.\nThe suite ran in''' f''' {self.time}.''' ), "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": f'''https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}''', }, } @property def __UpperCAmelCase ( self ): __a = 40 __a = {k: v['''failed'''] for k, v in doc_test_results.items() if isinstance(_a , _a )} __a = '''''' for category, failures in category_failures.items(): if len(_a ) == 0: continue if report != "": report += "\n\n" report += f'''*{category} failures*:'''.ljust(line_length // 2 ).rjust(line_length // 2 ) + "\n" report += "`" report += "`\n`".join(_a ) report += "`" return { "type": "section", "text": { "type": "mrkdwn", "text": f'''The following examples had failures:\n\n\n{report}\n''', }, } @property def __UpperCAmelCase ( self ): __a = [self.header] if self.n_failures > 0: blocks.append(self.failures ) if self.n_failures > 0: blocks.extend([self.category_failures] ) if self.n_failures == 0: blocks.append(self.no_failures ) return json.dumps(_a ) @staticmethod def __UpperCAmelCase ( ): __a = [ { '''type''': '''section''', '''text''': { '''type''': '''plain_text''', '''text''': '''There was an issue running the tests.''', }, '''accessory''': { '''type''': '''button''', '''text''': {'''type''': '''plain_text''', '''text''': '''Check Action results''', '''emoji''': True}, '''url''': f'''https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}''', }, } ] print('''Sending the following payload''' ) print(json.dumps({'''blocks''': json.loads(_a )} ) ) client.chat_postMessage( channel=os.environ['''CI_SLACK_CHANNEL_ID_DAILY'''] , text='''There was an issue running the tests.''' , blocks=_a , ) def __UpperCAmelCase ( self ): print('''Sending the following payload''' ) print(json.dumps({'''blocks''': json.loads(self.payload )} ) ) __a = f'''{self.n_failures} failures out of {self.n_tests} tests,''' if self.n_failures else '''All tests passed.''' __a = client.chat_postMessage( channel=os.environ['''CI_SLACK_CHANNEL_ID_DAILY'''] , blocks=self.payload , text=_a , ) def __UpperCAmelCase ( self , _a , _a , _a , _a ): __a = '''''' for key, value in failures.items(): __a = value[:200] + ''' [Truncated]''' if len(_a ) > 250 else value failures_text += f'''*{key}*\n_{value}_\n\n''' __a = job_name __a = {'''type''': '''section''', '''text''': {'''type''': '''mrkdwn''', '''text''': text}} if job_link is not None: __a = { '''type''': '''button''', '''text''': {'''type''': '''plain_text''', '''text''': '''GitHub Action job''', '''emoji''': True}, '''url''': job_link, } return [ {"type": "header", "text": {"type": "plain_text", "text": title.upper(), "emoji": True}}, content, {"type": "section", "text": {"type": "mrkdwn", "text": failures_text}}, ] def __UpperCAmelCase ( self ): if self.thread_ts is None: raise ValueError('''Can only post reply if a post has been made.''' ) __a = self.doc_test_results.pop('''job_link''' ) self.doc_test_results.pop('''failures''' ) self.doc_test_results.pop('''success''' ) self.doc_test_results.pop('''time_spent''' ) __a = sorted(self.doc_test_results.items() , key=lambda _a : t[0] ) for job, job_result in sorted_dict: if len(job_result['''failures'''] ): __a = f'''*Num failures* :{len(job_result['failed'] )} \n''' __a = job_result['''failures'''] __a = self.get_reply_blocks(_a , _a , _a , text=_a ) print('''Sending the following reply''' ) print(json.dumps({'''blocks''': blocks} ) ) client.chat_postMessage( channel=os.environ['''CI_SLACK_CHANNEL_ID_DAILY'''] , text=f'''Results for {job}''' , blocks=_a , thread_ts=self.thread_ts['''ts'''] , ) time.sleep(1 ) def lowercase ( ) -> Any: __a = os.environ['''GITHUB_RUN_ID'''] __a = f'''https://api.github.com/repos/huggingface/transformers/actions/runs/{run_id}/jobs?per_page=100''' __a = requests.get(lowerCAmelCase__ ).json() __a = {} try: jobs.update({job['''name''']: job['''html_url'''] for job in result['''jobs''']} ) __a = math.ceil((result['''total_count'''] - 100) / 100 ) for i in range(lowerCAmelCase__ ): __a = requests.get(url + f'''&page={i + 2}''' ).json() jobs.update({job['''name''']: job['''html_url'''] for job in result['''jobs''']} ) return jobs except Exception as e: print('''Unknown error, could not fetch links.''' , lowerCAmelCase__ ) return {} def lowercase ( lowerCAmelCase__ : str ) -> Dict: __a = {} if os.path.exists(lowerCAmelCase__ ): __a = os.listdir(lowerCAmelCase__ ) for file in files: try: with open(os.path.join(lowerCAmelCase__ , lowerCAmelCase__ ) , encoding='''utf-8''' ) as f: __a = f.read() except UnicodeDecodeError as e: raise ValueError(f'''Could not open {os.path.join(lowerCAmelCase__ , lowerCAmelCase__ )}.''' ) from e return _artifact def lowercase ( ) -> Dict: class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a ): __a = name __a = [] def __str__( self ): return self.name def __UpperCAmelCase ( self , _a ): self.paths.append({'''name''': self.name, '''path''': path} ) __a = {} __a = filter(os.path.isdir , os.listdir() ) for directory in directories: __a = directory if artifact_name not in _available_artifacts: __a = Artifact(lowerCAmelCase__ ) _available_artifacts[artifact_name].add_path(lowerCAmelCase__ ) return _available_artifacts if __name__ == "__main__": lowercase_ = get_job_links() lowercase_ = retrieve_available_artifacts() lowercase_ = collections.OrderedDict( [ ("*.py", "API Examples"), ("*.md", "MD Examples"), ] ) # This dict will contain all the information relative to each doc test category: # - failed: list of failed tests # - failures: dict in the format 'test': 'error_message' lowercase_ = { v: { "failed": [], "failures": {}, } for v in docs.values() } # Link to the GitHub Action job lowercase_ = github_actions_job_links.get("run_doctests") lowercase_ = available_artifacts["doc_tests_gpu_test_reports"].paths[0] lowercase_ = retrieve_artifact(artifact_path["name"]) if "stats" in artifact: lowercase_ , lowercase_ , lowercase_ = handle_test_results(artifact["stats"]) lowercase_ = failed lowercase_ = success lowercase_ = time_spent[1:-1] + ", " lowercase_ = extract_first_line_failure(artifact["failures_short"]) for line in artifact["summary_short"].split("\n"): if re.search("FAILED", line): lowercase_ = line.replace("FAILED ", "") lowercase_ = line.split()[0].replace("\n", "") if "::" in line: lowercase_ , lowercase_ = line.split("::") else: lowercase_ , lowercase_ = line, line for file_regex in docs.keys(): if fnmatch(file_path, file_regex): lowercase_ = docs[file_regex] doc_test_results[category]["failed"].append(test) lowercase_ = all_failures[test] if test in all_failures else "N/A" lowercase_ = failure break lowercase_ = Message("🤗 Results of the doc tests.", doc_test_results) message.post() message.post_reply()
695
"""simple docstring""" from __future__ import annotations def lowercase ( lowerCAmelCase__ : float , lowerCAmelCase__ : float , lowerCAmelCase__ : float ) -> float: if days_between_payments <= 0: raise ValueError('''days_between_payments must be > 0''' ) if daily_interest_rate < 0: raise ValueError('''daily_interest_rate must be >= 0''' ) if principal <= 0: raise ValueError('''principal must be > 0''' ) return principal * daily_interest_rate * days_between_payments def lowercase ( lowerCAmelCase__ : float , lowerCAmelCase__ : float , lowerCAmelCase__ : float , ) -> float: if number_of_compounding_periods <= 0: raise ValueError('''number_of_compounding_periods must be > 0''' ) if nominal_annual_interest_rate_percentage < 0: raise ValueError('''nominal_annual_interest_rate_percentage must be >= 0''' ) if principal <= 0: raise ValueError('''principal must be > 0''' ) return principal * ( (1 + nominal_annual_interest_rate_percentage) ** number_of_compounding_periods - 1 ) def lowercase ( lowerCAmelCase__ : float , lowerCAmelCase__ : float , lowerCAmelCase__ : float , ) -> float: if number_of_years <= 0: raise ValueError('''number_of_years must be > 0''' ) if nominal_annual_percentage_rate < 0: raise ValueError('''nominal_annual_percentage_rate must be >= 0''' ) if principal <= 0: raise ValueError('''principal must be > 0''' ) return compound_interest( lowerCAmelCase__ , nominal_annual_percentage_rate / 365 , number_of_years * 365 ) if __name__ == "__main__": import doctest doctest.testmod()
695
1
import math from numpy import inf from scipy.integrate import quad def _UpperCamelCase ( lowerCAmelCase_ ) ->float: if num <= 0: raise ValueError("""math domain error""" ) return quad(lowerCAmelCase_ , 0 , lowerCAmelCase_ , args=(lowerCAmelCase_) )[0] def _UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) ->float: return math.pow(lowerCAmelCase_ , z - 1 ) * math.exp(-x ) if __name__ == "__main__": from doctest import testmod testmod()
627
import multiprocessing import time from arguments import PretokenizationArguments from datasets import load_dataset from transformers import AutoTokenizer, HfArgumentParser def _UpperCamelCase ( lowerCAmelCase_ ) ->int: UpperCAmelCase = {} UpperCAmelCase = tokenizer(example["""content"""] , truncation=lowerCAmelCase_ )["""input_ids"""] UpperCAmelCase = len(example["""content"""] ) / len(output["""input_ids"""] ) return output __a = HfArgumentParser(PretokenizationArguments) __a = parser.parse_args() if args.num_workers is None: __a = multiprocessing.cpu_count() __a = AutoTokenizer.from_pretrained(args.tokenizer_dir) __a = time.time() __a = load_dataset(args.dataset_name, split="""train""") print(F"""Dataset loaded in {time.time()-t_start:.2f}s""") __a = time.time() __a = ds.map( tokenize, num_proc=args.num_workers, remove_columns=[ """repo_name""", """path""", """copies""", """size""", """content""", """license""", """hash""", """line_mean""", """line_max""", """alpha_frac""", """autogenerated""", ], ) print(F"""Dataset tokenized in {time.time()-t_start:.2f}s""") __a = time.time() ds.push_to_hub(args.tokenized_data_repo) print(F"""Data pushed to the hub in {time.time()-t_start:.2f}s""")
627
1
from __future__ import annotations __lowerCAmelCase =[] def __UpperCamelCase ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): """simple docstring""" for i in range(len(_lowerCAmelCase ) ): if board[row][i] == 1: return False for i in range(len(_lowerCAmelCase ) ): if board[i][column] == 1: return False for i, j in zip(range(_lowerCAmelCase , -1 , -1 ) , range(_lowerCAmelCase , -1 , -1 ) ): if board[i][j] == 1: return False for i, j in zip(range(_lowerCAmelCase , -1 , -1 ) , range(_lowerCAmelCase , len(_lowerCAmelCase ) ) ): if board[i][j] == 1: return False return True def __UpperCamelCase ( _lowerCAmelCase , _lowerCAmelCase ): """simple docstring""" if row >= len(_lowerCAmelCase ): solution.append(_lowerCAmelCase ) printboard(_lowerCAmelCase ) print() return True for i in range(len(_lowerCAmelCase ) ): if is_safe(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): UpperCAmelCase = 1 solve(_lowerCAmelCase , row + 1 ) UpperCAmelCase = 0 return False def __UpperCamelCase ( _lowerCAmelCase ): """simple docstring""" for i in range(len(_lowerCAmelCase ) ): for j in range(len(_lowerCAmelCase ) ): if board[i][j] == 1: print("Q" , end=" " ) else: print("." , end=" " ) print() # n=int(input("The no. of queens")) __lowerCAmelCase =8 __lowerCAmelCase =[[0 for i in range(n)] for j in range(n)] solve(board, 0) print("The total no. of solutions are :", len(solution))
333
from __future__ import annotations import unittest import numpy as np from transformers import LayoutLMConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.layoutlm.modeling_tf_layoutlm import ( TF_LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFLayoutLMForMaskedLM, TFLayoutLMForQuestionAnswering, TFLayoutLMForSequenceClassification, TFLayoutLMForTokenClassification, TFLayoutLMModel, ) class __magic_name__ : def __init__( self : str ,__SCREAMING_SNAKE_CASE : Union[str, Any] ,__SCREAMING_SNAKE_CASE : str=1_3 ,__SCREAMING_SNAKE_CASE : Optional[Any]=7 ,__SCREAMING_SNAKE_CASE : Optional[Any]=True ,__SCREAMING_SNAKE_CASE : List[str]=True ,__SCREAMING_SNAKE_CASE : int=True ,__SCREAMING_SNAKE_CASE : int=True ,__SCREAMING_SNAKE_CASE : Tuple=9_9 ,__SCREAMING_SNAKE_CASE : str=3_2 ,__SCREAMING_SNAKE_CASE : Any=2 ,__SCREAMING_SNAKE_CASE : Union[str, Any]=4 ,__SCREAMING_SNAKE_CASE : Tuple=3_7 ,__SCREAMING_SNAKE_CASE : List[str]="gelu" ,__SCREAMING_SNAKE_CASE : List[Any]=0.1 ,__SCREAMING_SNAKE_CASE : Optional[int]=0.1 ,__SCREAMING_SNAKE_CASE : Tuple=5_1_2 ,__SCREAMING_SNAKE_CASE : Dict=1_6 ,__SCREAMING_SNAKE_CASE : Tuple=2 ,__SCREAMING_SNAKE_CASE : List[str]=0.02 ,__SCREAMING_SNAKE_CASE : Optional[Any]=3 ,__SCREAMING_SNAKE_CASE : Dict=4 ,__SCREAMING_SNAKE_CASE : Union[str, Any]=None ,__SCREAMING_SNAKE_CASE : Dict=1_0_0_0 ,): UpperCAmelCase = parent UpperCAmelCase = batch_size UpperCAmelCase = seq_length UpperCAmelCase = is_training UpperCAmelCase = use_input_mask UpperCAmelCase = use_token_type_ids UpperCAmelCase = use_labels UpperCAmelCase = vocab_size UpperCAmelCase = hidden_size UpperCAmelCase = num_hidden_layers UpperCAmelCase = num_attention_heads UpperCAmelCase = intermediate_size UpperCAmelCase = hidden_act UpperCAmelCase = hidden_dropout_prob UpperCAmelCase = attention_probs_dropout_prob UpperCAmelCase = max_position_embeddings UpperCAmelCase = type_vocab_size UpperCAmelCase = type_sequence_label_size UpperCAmelCase = initializer_range UpperCAmelCase = num_labels UpperCAmelCase = num_choices UpperCAmelCase = scope UpperCAmelCase = range_bbox def _UpperCAmelCase ( self : Dict ): UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) # convert bbox to numpy since TF does not support item assignment UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length, 4] ,self.range_bbox ).numpy() # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: UpperCAmelCase = bbox[i, j, 3] UpperCAmelCase = bbox[i, j, 1] UpperCAmelCase = t if bbox[i, j, 2] < bbox[i, j, 0]: UpperCAmelCase = bbox[i, j, 2] UpperCAmelCase = bbox[i, j, 0] UpperCAmelCase = t UpperCAmelCase = tf.convert_to_tensor(__SCREAMING_SNAKE_CASE ) UpperCAmelCase = None if self.use_input_mask: UpperCAmelCase = random_attention_mask([self.batch_size, self.seq_length] ) UpperCAmelCase = None if self.use_token_type_ids: UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] ,self.type_vocab_size ) UpperCAmelCase = None UpperCAmelCase = None UpperCAmelCase = None if self.use_labels: UpperCAmelCase = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) UpperCAmelCase = ids_tensor([self.batch_size] ,self.num_choices ) UpperCAmelCase = LayoutLMConfig( vocab_size=self.vocab_size ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,hidden_act=self.hidden_act ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,type_vocab_size=self.type_vocab_size ,initializer_range=self.initializer_range ,) return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _UpperCAmelCase ( self : Dict ,__SCREAMING_SNAKE_CASE : List[str] ,__SCREAMING_SNAKE_CASE : Optional[Any] ,__SCREAMING_SNAKE_CASE : Dict ,__SCREAMING_SNAKE_CASE : Union[str, Any] ,__SCREAMING_SNAKE_CASE : int ,__SCREAMING_SNAKE_CASE : int ,__SCREAMING_SNAKE_CASE : Optional[Any] ,__SCREAMING_SNAKE_CASE : str ): UpperCAmelCase = TFLayoutLMModel(config=__SCREAMING_SNAKE_CASE ) UpperCAmelCase = model(__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,attention_mask=__SCREAMING_SNAKE_CASE ,token_type_ids=__SCREAMING_SNAKE_CASE ) UpperCAmelCase = model(__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,token_type_ids=__SCREAMING_SNAKE_CASE ) UpperCAmelCase = model(__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape ,(self.batch_size, self.hidden_size) ) def _UpperCAmelCase ( self : Dict ,__SCREAMING_SNAKE_CASE : Tuple ,__SCREAMING_SNAKE_CASE : Tuple ,__SCREAMING_SNAKE_CASE : List[str] ,__SCREAMING_SNAKE_CASE : str ,__SCREAMING_SNAKE_CASE : Union[str, Any] ,__SCREAMING_SNAKE_CASE : Any ,__SCREAMING_SNAKE_CASE : List[Any] ,__SCREAMING_SNAKE_CASE : List[Any] ): UpperCAmelCase = TFLayoutLMForMaskedLM(config=__SCREAMING_SNAKE_CASE ) UpperCAmelCase = model(__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,attention_mask=__SCREAMING_SNAKE_CASE ,token_type_ids=__SCREAMING_SNAKE_CASE ,labels=__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def _UpperCAmelCase ( self : Union[str, Any] ,__SCREAMING_SNAKE_CASE : str ,__SCREAMING_SNAKE_CASE : List[Any] ,__SCREAMING_SNAKE_CASE : int ,__SCREAMING_SNAKE_CASE : Tuple ,__SCREAMING_SNAKE_CASE : List[str] ,__SCREAMING_SNAKE_CASE : Optional[int] ,__SCREAMING_SNAKE_CASE : Union[str, Any] ,__SCREAMING_SNAKE_CASE : Union[str, Any] ): UpperCAmelCase = self.num_labels UpperCAmelCase = TFLayoutLMForSequenceClassification(config=__SCREAMING_SNAKE_CASE ) UpperCAmelCase = model(__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,attention_mask=__SCREAMING_SNAKE_CASE ,token_type_ids=__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def _UpperCAmelCase ( self : List[str] ,__SCREAMING_SNAKE_CASE : List[str] ,__SCREAMING_SNAKE_CASE : int ,__SCREAMING_SNAKE_CASE : List[str] ,__SCREAMING_SNAKE_CASE : int ,__SCREAMING_SNAKE_CASE : Dict ,__SCREAMING_SNAKE_CASE : Dict ,__SCREAMING_SNAKE_CASE : str ,__SCREAMING_SNAKE_CASE : Union[str, Any] ): UpperCAmelCase = self.num_labels UpperCAmelCase = TFLayoutLMForTokenClassification(config=__SCREAMING_SNAKE_CASE ) UpperCAmelCase = model(__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,attention_mask=__SCREAMING_SNAKE_CASE ,token_type_ids=__SCREAMING_SNAKE_CASE ,labels=__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) ) def _UpperCAmelCase ( self : Optional[int] ,__SCREAMING_SNAKE_CASE : Union[str, Any] ,__SCREAMING_SNAKE_CASE : Optional[int] ,__SCREAMING_SNAKE_CASE : Optional[Any] ,__SCREAMING_SNAKE_CASE : Dict ,__SCREAMING_SNAKE_CASE : int ,__SCREAMING_SNAKE_CASE : Optional[Any] ,__SCREAMING_SNAKE_CASE : List[str] ,__SCREAMING_SNAKE_CASE : str ): UpperCAmelCase = TFLayoutLMForQuestionAnswering(config=__SCREAMING_SNAKE_CASE ) UpperCAmelCase = model(__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,attention_mask=__SCREAMING_SNAKE_CASE ,token_type_ids=__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.start_logits.shape ,(self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape ,(self.batch_size, self.seq_length) ) def _UpperCAmelCase ( self : List[Any] ): UpperCAmelCase = self.prepare_config_and_inputs() ( ( UpperCAmelCase ) , ( UpperCAmelCase ) , ( UpperCAmelCase ) , ( UpperCAmelCase ) , ( UpperCAmelCase ) , ( UpperCAmelCase ) , ( UpperCAmelCase ) , ( UpperCAmelCase ) , ) = config_and_inputs UpperCAmelCase = { "input_ids": input_ids, "bbox": bbox, "token_type_ids": token_type_ids, "attention_mask": input_mask, } return config, inputs_dict @require_tf class __magic_name__ ( _a , _a , unittest.TestCase): _UpperCAmelCase : Optional[int] = ( ( TFLayoutLMModel, TFLayoutLMForMaskedLM, TFLayoutLMForTokenClassification, TFLayoutLMForSequenceClassification, TFLayoutLMForQuestionAnswering, ) if is_tf_available() else () ) _UpperCAmelCase : str = ( { 'feature-extraction': TFLayoutLMModel, 'fill-mask': TFLayoutLMForMaskedLM, 'text-classification': TFLayoutLMForSequenceClassification, 'token-classification': TFLayoutLMForTokenClassification, 'zero-shot': TFLayoutLMForSequenceClassification, } if is_tf_available() else {} ) _UpperCAmelCase : Tuple = False _UpperCAmelCase : int = True _UpperCAmelCase : Union[str, Any] = 10 def _UpperCAmelCase ( self : Tuple ): UpperCAmelCase = TFLayoutLMModelTester(self ) UpperCAmelCase = ConfigTester(self ,config_class=__SCREAMING_SNAKE_CASE ,hidden_size=3_7 ) def _UpperCAmelCase ( self : List[str] ): self.config_tester.run_common_tests() def _UpperCAmelCase ( self : List[str] ): UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE ) def _UpperCAmelCase ( self : Dict ): UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*__SCREAMING_SNAKE_CASE ) def _UpperCAmelCase ( self : Dict ): UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*__SCREAMING_SNAKE_CASE ) def _UpperCAmelCase ( self : Any ): UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__SCREAMING_SNAKE_CASE ) def _UpperCAmelCase ( self : List[str] ): UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__SCREAMING_SNAKE_CASE ) @slow def _UpperCAmelCase ( self : List[str] ): for model_name in TF_LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase = TFLayoutLMModel.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertIsNotNone(__SCREAMING_SNAKE_CASE ) @unittest.skip("Onnx compliancy broke with TF 2.10" ) def _UpperCAmelCase ( self : List[str] ): pass def __UpperCamelCase ( ): """simple docstring""" UpperCAmelCase = tf.convert_to_tensor([[1_01,10_19,10_14,10_16,10_37,1_28_49,47_47,10_04,1_42_46,22_78,54_39,45_24,50_02,29_30,21_93,29_30,43_41,32_08,10_05,10_55,21_71,28_48,1_13_00,35_31,1_02],[1_01,40_70,40_34,70_20,10_24,30_58,10_15,10_13,28_61,10_13,60_70,1_92_74,27_72,62_05,2_78_14,1_61_47,1_61_47,43_43,20_47,1_02_83,1_09_69,1_43_89,10_12,23_38,1_02]] ) # noqa: E231 UpperCAmelCase = tf.convert_to_tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],] ) # noqa: E231 UpperCAmelCase = tf.convert_to_tensor([[[0,0,0,0],[4_23,2_37,4_40,2_51],[4_27,2_72,4_41,2_87],[4_19,1_15,4_37,1_29],[9_61,8_85,9_92,9_12],[2_56,38,3_30,58],[2_56,38,3_30,58],[3_36,42,3_53,57],[3_60,39,4_01,56],[3_60,39,4_01,56],[4_11,39,4_71,59],[4_79,41,5_28,59],[5_33,39,6_30,60],[67,1_13,1_34,1_31],[1_41,1_15,2_09,1_32],[68,1_49,1_33,1_66],[1_41,1_49,1_87,1_64],[1_95,1_48,2_87,1_65],[1_95,1_48,2_87,1_65],[1_95,1_48,2_87,1_65],[2_95,1_48,3_49,1_65],[4_41,1_49,4_92,1_66],[4_97,1_49,5_46,1_64],[64,2_01,1_25,2_18],[10_00,10_00,10_00,10_00]],[[0,0,0,0],[6_62,1_50,7_54,1_66],[6_65,1_99,7_42,2_11],[5_19,2_13,5_54,2_28],[5_19,2_13,5_54,2_28],[1_34,4_33,1_87,4_54],[1_30,4_67,2_04,4_80],[1_30,4_67,2_04,4_80],[1_30,4_67,2_04,4_80],[1_30,4_67,2_04,4_80],[1_30,4_67,2_04,4_80],[3_14,4_69,3_76,4_82],[5_04,6_84,5_82,7_06],[9_41,8_25,9_73,9_00],[9_41,8_25,9_73,9_00],[9_41,8_25,9_73,9_00],[9_41,8_25,9_73,9_00],[6_10,7_49,6_52,7_65],[1_30,6_59,1_68,6_72],[1_76,6_57,2_37,6_72],[2_38,6_57,3_12,6_72],[4_43,6_53,6_28,6_72],[4_43,6_53,6_28,6_72],[7_16,3_01,8_25,3_17],[10_00,10_00,10_00,10_00]]] ) # noqa: E231 UpperCAmelCase = tf.convert_to_tensor([[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]] ) # noqa: E231 # these are sequence labels (i.e. at the token level) UpperCAmelCase = tf.convert_to_tensor([[-1_00,10,10,10,9,1,-1_00,7,7,-1_00,7,7,4,2,5,2,8,8,-1_00,-1_00,5,0,3,2,-1_00],[-1_00,12,12,12,-1_00,12,10,-1_00,-1_00,-1_00,-1_00,10,12,9,-1_00,-1_00,-1_00,10,10,10,9,12,-1_00,10,-1_00]] ) # noqa: E231 # fmt: on return input_ids, attention_mask, bbox, token_type_ids, labels @require_tf class __magic_name__ ( unittest.TestCase): @slow def _UpperCAmelCase ( self : Any ): UpperCAmelCase = TFLayoutLMModel.from_pretrained("microsoft/layoutlm-base-uncased" ) UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = prepare_layoutlm_batch_inputs() # forward pass UpperCAmelCase = model(input_ids=__SCREAMING_SNAKE_CASE ,bbox=__SCREAMING_SNAKE_CASE ,attention_mask=__SCREAMING_SNAKE_CASE ,token_type_ids=__SCREAMING_SNAKE_CASE ) # test the sequence output on [0, :3, :3] UpperCAmelCase = tf.convert_to_tensor( [[0.1785, -0.1947, -0.0425], [-0.3254, -0.2807, 0.2553], [-0.5391, -0.3322, 0.3364]] ,) self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3] ,__SCREAMING_SNAKE_CASE ,atol=1e-3 ) ) # test the pooled output on [1, :3] UpperCAmelCase = tf.convert_to_tensor([-0.6580, -0.0214, 0.8552] ) self.assertTrue(np.allclose(outputs.pooler_output[1, :3] ,__SCREAMING_SNAKE_CASE ,atol=1e-3 ) ) @slow def _UpperCAmelCase ( self : Union[str, Any] ): # initialize model with randomly initialized sequence classification head UpperCAmelCase = TFLayoutLMForSequenceClassification.from_pretrained("microsoft/layoutlm-base-uncased" ,num_labels=2 ) UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = prepare_layoutlm_batch_inputs() # forward pass UpperCAmelCase = model( input_ids=__SCREAMING_SNAKE_CASE ,bbox=__SCREAMING_SNAKE_CASE ,attention_mask=__SCREAMING_SNAKE_CASE ,token_type_ids=__SCREAMING_SNAKE_CASE ,labels=tf.convert_to_tensor([1, 1] ) ,) # test whether we get a loss as a scalar UpperCAmelCase = outputs.loss UpperCAmelCase = (2,) self.assertEqual(loss.shape ,__SCREAMING_SNAKE_CASE ) # test the shape of the logits UpperCAmelCase = outputs.logits UpperCAmelCase = (2, 2) self.assertEqual(logits.shape ,__SCREAMING_SNAKE_CASE ) @slow def _UpperCAmelCase ( self : Tuple ): # initialize model with randomly initialized token classification head UpperCAmelCase = TFLayoutLMForTokenClassification.from_pretrained("microsoft/layoutlm-base-uncased" ,num_labels=1_3 ) UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = prepare_layoutlm_batch_inputs() # forward pass UpperCAmelCase = model( input_ids=__SCREAMING_SNAKE_CASE ,bbox=__SCREAMING_SNAKE_CASE ,attention_mask=__SCREAMING_SNAKE_CASE ,token_type_ids=__SCREAMING_SNAKE_CASE ,labels=__SCREAMING_SNAKE_CASE ) # test the shape of the logits UpperCAmelCase = outputs.logits UpperCAmelCase = tf.convert_to_tensor((2, 2_5, 1_3) ) self.assertEqual(logits.shape ,__SCREAMING_SNAKE_CASE ) @slow def _UpperCAmelCase ( self : List[Any] ): # initialize model with randomly initialized token classification head UpperCAmelCase = TFLayoutLMForQuestionAnswering.from_pretrained("microsoft/layoutlm-base-uncased" ) UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = prepare_layoutlm_batch_inputs() # forward pass UpperCAmelCase = model(input_ids=__SCREAMING_SNAKE_CASE ,bbox=__SCREAMING_SNAKE_CASE ,attention_mask=__SCREAMING_SNAKE_CASE ,token_type_ids=__SCREAMING_SNAKE_CASE ) # test the shape of the logits UpperCAmelCase = tf.convert_to_tensor((2, 2_5) ) self.assertEqual(outputs.start_logits.shape ,__SCREAMING_SNAKE_CASE ) self.assertEqual(outputs.end_logits.shape ,__SCREAMING_SNAKE_CASE )
333
1
'''simple docstring''' import os import tempfile import unittest from transformers import DistilBertConfig, is_torch_available from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, DistilBertModel, ) class A ( _A ): def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=13 , SCREAMING_SNAKE_CASE=7 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=99 , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=5 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=37 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=512 , SCREAMING_SNAKE_CASE=16 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=None , ) -> Tuple: """simple docstring""" A : Optional[Any] = parent A : int = batch_size A : Dict = seq_length A : Any = is_training A : Tuple = use_input_mask A : Optional[int] = use_token_type_ids A : Union[str, Any] = use_labels A : Dict = vocab_size A : str = hidden_size A : int = num_hidden_layers A : Optional[Any] = num_attention_heads A : Any = intermediate_size A : Optional[int] = hidden_act A : Optional[Any] = hidden_dropout_prob A : str = attention_probs_dropout_prob A : Dict = max_position_embeddings A : Union[str, Any] = type_vocab_size A : List[str] = type_sequence_label_size A : List[Any] = initializer_range A : Tuple = num_labels A : Union[str, Any] = num_choices A : Tuple = scope def __lowerCAmelCase ( self ) -> str: """simple docstring""" A : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A : Tuple = None if self.use_input_mask: A : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) A : Optional[int] = None A : Dict = None A : List[Any] = None if self.use_labels: A : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) A : Union[str, Any] = ids_tensor([self.batch_size] , self.num_choices ) A : Optional[Any] = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowerCAmelCase ( self ) -> str: """simple docstring""" return DistilBertConfig( vocab_size=self.vocab_size , dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , hidden_dim=self.intermediate_size , hidden_act=self.hidden_act , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" A : Optional[Any] = DistilBertModel(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() A : Dict = model(__lowerCamelCase , __lowerCamelCase ) A : Dict = model(__lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" A : Dict = DistilBertForMaskedLM(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() A : int = model(__lowerCamelCase , attention_mask=__lowerCamelCase , labels=__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" A : Dict = DistilBertForQuestionAnswering(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() A : Optional[int] = model( __lowerCamelCase , attention_mask=__lowerCamelCase , start_positions=__lowerCamelCase , end_positions=__lowerCamelCase ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" A : Tuple = self.num_labels A : int = DistilBertForSequenceClassification(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() A : Tuple = model(__lowerCamelCase , attention_mask=__lowerCamelCase , labels=__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" A : Optional[int] = self.num_labels A : List[str] = DistilBertForTokenClassification(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() A : List[str] = model(__lowerCamelCase , attention_mask=__lowerCamelCase , labels=__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" A : Union[str, Any] = self.num_choices A : Optional[Any] = DistilBertForMultipleChoice(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() A : int = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() A : Tuple = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() A : Union[str, Any] = model( __lowerCamelCase , attention_mask=__lowerCamelCase , labels=__lowerCamelCase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" A : Optional[Any] = self.prepare_config_and_inputs() (A) : int = config_and_inputs A : Union[str, Any] = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class A ( _A , _A , unittest.TestCase ): __magic_name__ = ( ( DistilBertModel, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, ) if is_torch_available() else None ) __magic_name__ = ( { '''feature-extraction''': DistilBertModel, '''fill-mask''': DistilBertForMaskedLM, '''question-answering''': DistilBertForQuestionAnswering, '''text-classification''': DistilBertForSequenceClassification, '''token-classification''': DistilBertForTokenClassification, '''zero-shot''': DistilBertForSequenceClassification, } if is_torch_available() else {} ) __magic_name__ = True __magic_name__ = True __magic_name__ = True __magic_name__ = True def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" A : Optional[int] = DistilBertModelTester(self ) A : List[str] = ConfigTester(self , config_class=__lowerCamelCase , dim=37 ) def __lowerCAmelCase ( self ) -> Any: """simple docstring""" self.config_tester.run_common_tests() def __lowerCAmelCase ( self ) -> Any: """simple docstring""" A : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_model(*__lowerCamelCase ) def __lowerCAmelCase ( self ) -> str: """simple docstring""" A : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_masked_lm(*__lowerCamelCase ) def __lowerCAmelCase ( self ) -> Any: """simple docstring""" A : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_question_answering(*__lowerCamelCase ) def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" A : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_sequence_classification(*__lowerCamelCase ) def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" A : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_token_classification(*__lowerCamelCase ) def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" A : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_multiple_choice(*__lowerCamelCase ) @slow def __lowerCAmelCase ( self ) -> str: """simple docstring""" for model_name in DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A : Optional[Any] = DistilBertModel.from_pretrained(__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) @slow @require_torch_gpu def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" A : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # BertForMultipleChoice behaves incorrectly in JIT environments. if model_class == DistilBertForMultipleChoice: return A : List[str] = True A : int = model_class(config=__lowerCamelCase ) A : Dict = self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) A : str = torch.jit.trace( __lowerCamelCase , (inputs_dict['''input_ids'''].to('''cpu''' ), inputs_dict['''attention_mask'''].to('''cpu''' )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(__lowerCamelCase , os.path.join(__lowerCamelCase , '''traced_model.pt''' ) ) A : List[str] = torch.jit.load(os.path.join(__lowerCamelCase , '''traced_model.pt''' ) , map_location=__lowerCamelCase ) loaded(inputs_dict['''input_ids'''].to(__lowerCamelCase ) , inputs_dict['''attention_mask'''].to(__lowerCamelCase ) ) @require_torch class A ( unittest.TestCase ): @slow def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" A : List[Any] = DistilBertModel.from_pretrained('''distilbert-base-uncased''' ) A : Union[str, Any] = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] ) A : List[str] = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): A : Union[str, Any] = model(__lowerCamelCase , attention_mask=__lowerCamelCase )[0] A : Optional[Any] = torch.Size((1, 11, 768) ) self.assertEqual(output.shape , __lowerCamelCase ) A : List[str] = torch.tensor( [[[-0.1_639, 0.3_299, 0.1_648], [-0.1_746, 0.3_289, 0.1_710], [-0.1_884, 0.3_357, 0.1_810]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , __lowerCamelCase , atol=1e-4 ) )
717
'''simple docstring''' from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowercase : Optional[int] = { 'configuration_trajectory_transformer': [ 'TRAJECTORY_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'TrajectoryTransformerConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : str = [ 'TRAJECTORY_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'TrajectoryTransformerModel', 'TrajectoryTransformerPreTrainedModel', 'load_tf_weights_in_trajectory_transformer', ] if TYPE_CHECKING: from .configuration_trajectory_transformer import ( TRAJECTORY_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TrajectoryTransformerConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_trajectory_transformer import ( TRAJECTORY_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TrajectoryTransformerModel, TrajectoryTransformerPreTrainedModel, load_tf_weights_in_trajectory_transformer, ) else: import sys lowercase : List[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
343
0
"""simple docstring""" import gc import random import unittest import numpy as np import torch from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import floats_tensor, load_image, load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class SCREAMING_SNAKE_CASE__ ( UpperCAmelCase__ , unittest.TestCase ): __lowerCAmelCase : Any = ShapEImgaImgPipeline __lowerCAmelCase : Any = ['image'] __lowerCAmelCase : List[Any] = ['image'] __lowerCAmelCase : List[str] = [ 'num_images_per_prompt', 'num_inference_steps', 'generator', 'latents', 'guidance_scale', 'frame_size', 'output_type', 'return_dict', ] __lowerCAmelCase : int = False @property def SCREAMING_SNAKE_CASE ( self ) -> Any: '''simple docstring''' return 32 @property def SCREAMING_SNAKE_CASE ( self ) -> Dict: '''simple docstring''' return 32 @property def SCREAMING_SNAKE_CASE ( self ) -> str: '''simple docstring''' return self.time_input_dim * 4 @property def SCREAMING_SNAKE_CASE ( self ) -> Dict: '''simple docstring''' return 8 @property def SCREAMING_SNAKE_CASE ( self ) -> Any: '''simple docstring''' torch.manual_seed(0 ) UpperCAmelCase : Optional[Any] = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=64 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=1 , ) UpperCAmelCase : int = CLIPVisionModel(_SCREAMING_SNAKE_CASE ) return model @property def SCREAMING_SNAKE_CASE ( self ) -> Dict: '''simple docstring''' UpperCAmelCase : Union[str, Any] = CLIPImageProcessor( crop_size=224 , do_center_crop=_SCREAMING_SNAKE_CASE , do_normalize=_SCREAMING_SNAKE_CASE , do_resize=_SCREAMING_SNAKE_CASE , image_mean=[0.4814_5466, 0.457_8275, 0.4082_1073] , image_std=[0.2686_2954, 0.2613_0258, 0.2757_7711] , resample=3 , size=224 , ) return image_processor @property def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: '''simple docstring''' torch.manual_seed(0 ) UpperCAmelCase : Any = { """num_attention_heads""": 2, """attention_head_dim""": 16, """embedding_dim""": self.time_input_dim, """num_embeddings""": 32, """embedding_proj_dim""": self.text_embedder_hidden_size, """time_embed_dim""": self.time_embed_dim, """num_layers""": 1, """clip_embed_dim""": self.time_input_dim * 2, """additional_embeddings""": 0, """time_embed_act_fn""": """gelu""", """norm_in_type""": """layer""", """embedding_proj_norm_type""": """layer""", """encoder_hid_proj_type""": None, """added_emb_type""": None, } UpperCAmelCase : int = PriorTransformer(**_SCREAMING_SNAKE_CASE ) return model @property def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: '''simple docstring''' torch.manual_seed(0 ) UpperCAmelCase : Any = { """param_shapes""": ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), """d_latent""": self.time_input_dim, """d_hidden""": self.renderer_dim, """n_output""": 12, """background""": ( 0.1, 0.1, 0.1, ), } UpperCAmelCase : Optional[int] = ShapERenderer(**_SCREAMING_SNAKE_CASE ) return model def SCREAMING_SNAKE_CASE ( self ) -> int: '''simple docstring''' UpperCAmelCase : int = self.dummy_prior UpperCAmelCase : Union[str, Any] = self.dummy_image_encoder UpperCAmelCase : Optional[Any] = self.dummy_image_processor UpperCAmelCase : Union[str, Any] = self.dummy_renderer UpperCAmelCase : str = HeunDiscreteScheduler( beta_schedule="""exp""" , num_train_timesteps=1024 , prediction_type="""sample""" , use_karras_sigmas=_SCREAMING_SNAKE_CASE , clip_sample=_SCREAMING_SNAKE_CASE , clip_sample_range=1.0 , ) UpperCAmelCase : Union[str, Any] = { """prior""": prior, """image_encoder""": image_encoder, """image_processor""": image_processor, """renderer""": renderer, """scheduler""": scheduler, } return components def SCREAMING_SNAKE_CASE ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=0 ) -> List[Any]: '''simple docstring''' UpperCAmelCase : Any = floats_tensor((1, 3, 64, 64) , rng=random.Random(_SCREAMING_SNAKE_CASE ) ).to(_SCREAMING_SNAKE_CASE ) if str(_SCREAMING_SNAKE_CASE ).startswith("""mps""" ): UpperCAmelCase : Optional[int] = torch.manual_seed(_SCREAMING_SNAKE_CASE ) else: UpperCAmelCase : int = torch.Generator(device=_SCREAMING_SNAKE_CASE ).manual_seed(_SCREAMING_SNAKE_CASE ) UpperCAmelCase : Union[str, Any] = { """image""": input_image, """generator""": generator, """num_inference_steps""": 1, """frame_size""": 32, """output_type""": """np""", } return inputs def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: '''simple docstring''' UpperCAmelCase : List[str] = """cpu""" UpperCAmelCase : List[str] = self.get_dummy_components() UpperCAmelCase : str = self.pipeline_class(**_SCREAMING_SNAKE_CASE ) UpperCAmelCase : Dict = pipe.to(_SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) UpperCAmelCase : Dict = pipe(**self.get_dummy_inputs(_SCREAMING_SNAKE_CASE ) ) UpperCAmelCase : Union[str, Any] = output.images[0] UpperCAmelCase : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) UpperCAmelCase : Any = np.array( [ 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: '''simple docstring''' self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def SCREAMING_SNAKE_CASE ( self ) -> Dict: '''simple docstring''' UpperCAmelCase : Optional[Any] = torch_device == """cpu""" UpperCAmelCase : int = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=_SCREAMING_SNAKE_CASE , relax_max_difference=_SCREAMING_SNAKE_CASE , ) def SCREAMING_SNAKE_CASE ( self ) -> str: '''simple docstring''' UpperCAmelCase : Union[str, Any] = self.get_dummy_components() UpperCAmelCase : Optional[int] = self.pipeline_class(**_SCREAMING_SNAKE_CASE ) UpperCAmelCase : int = pipe.to(_SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) UpperCAmelCase : int = 1 UpperCAmelCase : Optional[int] = 2 UpperCAmelCase : Optional[int] = self.get_dummy_inputs(_SCREAMING_SNAKE_CASE ) for key in inputs.keys(): if key in self.batch_params: UpperCAmelCase : Tuple = batch_size * [inputs[key]] UpperCAmelCase : Any = pipe(**_SCREAMING_SNAKE_CASE , num_images_per_prompt=_SCREAMING_SNAKE_CASE )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def SCREAMING_SNAKE_CASE ( self ) -> Dict: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE ( self ) -> int: '''simple docstring''' UpperCAmelCase : Any = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/shap_e/corgi.png""" ) UpperCAmelCase : List[Any] = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/shap_e/test_shap_e_img2img_out.npy""" ) UpperCAmelCase : List[Any] = ShapEImgaImgPipeline.from_pretrained("""openai/shap-e-img2img""" ) UpperCAmelCase : Dict = pipe.to(_SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) UpperCAmelCase : List[Any] = torch.Generator(device=_SCREAMING_SNAKE_CASE ).manual_seed(0 ) UpperCAmelCase : Dict = pipe( _SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , guidance_scale=3.0 , num_inference_steps=64 , frame_size=64 , output_type="""np""" , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
160
"""simple docstring""" from __future__ import annotations def _snake_case ( UpperCamelCase : list[int] , UpperCamelCase : int ): if len(UpperCamelCase ) < k or k < 0: raise ValueError("""Invalid Input""" ) UpperCAmelCase : Optional[Any] = sum(array[:k] ) for i in range(len(UpperCamelCase ) - k ): UpperCAmelCase : str = current_sum - array[i] + array[i + k] UpperCAmelCase : Tuple = max(UpperCamelCase , UpperCamelCase ) return max_sum if __name__ == "__main__": from doctest import testmod from random import randint testmod() A: str = [randint(-1_0_0_0, 1_0_0_0) for i in range(1_0_0)] A: int = randint(0, 1_1_0) print(f"""The maximum sum of {k} consecutive elements is {max_sum_in_array(array,k)}""")
160
1
import pytest from datasets.parallel import ParallelBackendConfig, parallel_backend from datasets.utils.py_utils import map_nested from .utils import require_dill_gt_0_3_2, require_joblibspark, require_not_windows def lowerCamelCase_ ( _a : List[str] ): # picklable for multiprocessing '''simple docstring''' return i + 1 @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows def lowerCamelCase_ ( ): '''simple docstring''' with parallel_backend("""spark""" ): assert ParallelBackendConfig.backend_name == "spark" UpperCAmelCase_ : List[str] = [1, 2, 3] with pytest.raises(_a ): with parallel_backend("""unsupported backend""" ): map_nested(_a , _a , num_proc=2 ) with pytest.raises(_a ): with parallel_backend("""unsupported backend""" ): map_nested(_a , _a , num_proc=-1 ) @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows @pytest.mark.parametrize("""num_proc""" , [2, -1] ) def lowerCamelCase_ ( _a : Any ): '''simple docstring''' UpperCAmelCase_ : Any = [1, 2] UpperCAmelCase_ : Optional[Any] = {"""a""": 1, """b""": 2} UpperCAmelCase_ : Tuple = {"""a""": [1, 2], """b""": [3, 4]} UpperCAmelCase_ : int = {"""a""": {"""1""": 1}, """b""": 2} UpperCAmelCase_ : Dict = {"""a""": 1, """b""": 2, """c""": 3, """d""": 4} UpperCAmelCase_ : Union[str, Any] = [2, 3] UpperCAmelCase_ : Optional[int] = {"""a""": 2, """b""": 3} UpperCAmelCase_ : List[Any] = {"""a""": [2, 3], """b""": [4, 5]} UpperCAmelCase_ : int = {"""a""": {"""1""": 2}, """b""": 3} UpperCAmelCase_ : Tuple = {"""a""": 2, """b""": 3, """c""": 4, """d""": 5} with parallel_backend("""spark""" ): assert map_nested(_a , _a , num_proc=_a ) == expected_map_nested_sa assert map_nested(_a , _a , num_proc=_a ) == expected_map_nested_sa assert map_nested(_a , _a , num_proc=_a ) == expected_map_nested_sa assert map_nested(_a , _a , num_proc=_a ) == expected_map_nested_sa assert map_nested(_a , _a , num_proc=_a ) == expected_map_nested_sa
718
import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin class _snake_case ( unittest.TestCase , __snake_case ): '''simple docstring''' def A__ ( self: Any ) -> Optional[Any]: UpperCAmelCase_ : Dict = load_tool("""text-classification""" ) self.tool.setup() UpperCAmelCase_ : List[str] = load_tool("""text-classification""" ,remote=lowerCamelCase_ ) def A__ ( self: List[str] ) -> str: UpperCAmelCase_ : Tuple = self.tool("""That's quite cool""" ,["""positive""", """negative"""] ) self.assertEqual(lowerCamelCase_ ,"""positive""" ) def A__ ( self: List[Any] ) -> Dict: UpperCAmelCase_ : List[str] = self.remote_tool("""That's quite cool""" ,["""positive""", """negative"""] ) self.assertEqual(lowerCamelCase_ ,"""positive""" ) def A__ ( self: str ) -> Tuple: UpperCAmelCase_ : Optional[int] = self.tool(text="""That's quite cool""" ,labels=["""positive""", """negative"""] ) self.assertEqual(lowerCamelCase_ ,"""positive""" ) def A__ ( self: str ) -> Any: UpperCAmelCase_ : Union[str, Any] = self.remote_tool(text="""That's quite cool""" ,labels=["""positive""", """negative"""] ) self.assertEqual(lowerCamelCase_ ,"""positive""" )
322
0
import unittest from transformers import AutoConfig, AutoTokenizer, BertConfig, TensorType, is_flax_available from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, slow if is_flax_available(): import jax from transformers.models.auto.modeling_flax_auto import FlaxAutoModel from transformers.models.bert.modeling_flax_bert import FlaxBertModel from transformers.models.roberta.modeling_flax_roberta import FlaxRobertaModel @require_flax class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" @slow def a ( self : Dict ) -> List[Any]: for model_name in ["bert-base-cased", "bert-large-uncased"]: with self.subTest(SCREAMING_SNAKE_CASE__ ): lowerCAmelCase__ = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = FlaxAutoModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @slow def a ( self : List[Any] ) -> str: for model_name in ["roberta-base", "roberta-large"]: with self.subTest(SCREAMING_SNAKE_CASE__ ): lowerCAmelCase__ = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = FlaxAutoModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @slow def a ( self : List[Any] ) -> str: for model_name in ["bert-base-cased", "bert-large-uncased"]: lowerCAmelCase__ = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = FlaxBertModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer("Do you support jax jitted function?" , return_tensors=TensorType.JAX ) @jax.jit def eval(**SCREAMING_SNAKE_CASE__ : Union[str, Any] ): return model(**SCREAMING_SNAKE_CASE__ ) eval(**SCREAMING_SNAKE_CASE__ ).block_until_ready() @slow def a ( self : Tuple ) -> Any: for model_name in ["roberta-base", "roberta-large"]: lowerCAmelCase__ = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = FlaxRobertaModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer("Do you support jax jitted function?" , return_tensors=TensorType.JAX ) @jax.jit def eval(**SCREAMING_SNAKE_CASE__ : Dict ): return model(**SCREAMING_SNAKE_CASE__ ) eval(**SCREAMING_SNAKE_CASE__ ).block_until_ready() def a ( self : Union[str, Any] ) -> Dict: with self.assertRaisesRegex( SCREAMING_SNAKE_CASE__ , "bert-base is not a local folder and is not a valid model identifier" ): lowerCAmelCase__ = FlaxAutoModel.from_pretrained("bert-base" ) def a ( self : Dict ) -> Dict: with self.assertRaisesRegex( SCREAMING_SNAKE_CASE__ , r"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)" ): lowerCAmelCase__ = FlaxAutoModel.from_pretrained(SCREAMING_SNAKE_CASE__ , revision="aaaaaa" ) def a ( self : Optional[Any] ) -> int: with self.assertRaisesRegex( SCREAMING_SNAKE_CASE__ , "hf-internal-testing/config-no-model does not appear to have a file named flax_model.msgpack" , ): lowerCAmelCase__ = FlaxAutoModel.from_pretrained("hf-internal-testing/config-no-model" ) def a ( self : Dict ) -> Any: with self.assertRaisesRegex(SCREAMING_SNAKE_CASE__ , "Use `from_pt=True` to load this model" ): lowerCAmelCase__ = FlaxAutoModel.from_pretrained("hf-internal-testing/tiny-bert-pt-only" )
61
"""simple docstring""" import gzip import hashlib import json import multiprocessing import os import re import shutil import time from pathlib import Path import numpy as np from arguments import PreprocessingArguments from datasets import load_dataset from minhash_deduplication import deduplicate_dataset from transformers import AutoTokenizer, HfArgumentParser _SCREAMING_SNAKE_CASE : int = re.compile(R'''\s+''') def lowerCamelCase__ ( _lowerCamelCase : Dict ) -> List[str]: return {"hash": hashlib.mda(re.sub(_lowerCamelCase , '' , example['content'] ).encode('utf-8' ) ).hexdigest()} def lowerCamelCase__ ( _lowerCamelCase : Tuple ) -> int: lowerCamelCase_ = [len(_lowerCamelCase ) for line in example['content'].splitlines()] return {"line_mean": np.mean(_lowerCamelCase ), "line_max": max(_lowerCamelCase )} def lowerCamelCase__ ( _lowerCamelCase : List[str] ) -> int: lowerCamelCase_ = np.mean([c.isalnum() for c in example['content']] ) return {"alpha_frac": alpha_frac} def lowerCamelCase__ ( _lowerCamelCase : int , _lowerCamelCase : Optional[int] ) -> Optional[Any]: if example["hash"] in uniques: uniques.remove(example['hash'] ) return True else: return False def lowerCamelCase__ ( _lowerCamelCase : Any , _lowerCamelCase : Optional[Any]=5 ) -> int: lowerCamelCase_ = ['auto-generated', 'autogenerated', 'automatically generated'] lowerCamelCase_ = example['content'].splitlines() for _, line in zip(range(_lowerCamelCase ) , _lowerCamelCase ): for keyword in keywords: if keyword in line.lower(): return {"autogenerated": True} else: return {"autogenerated": False} def lowerCamelCase__ ( _lowerCamelCase : Tuple , _lowerCamelCase : Dict=5 , _lowerCamelCase : List[str]=0.05 ) -> Tuple: lowerCamelCase_ = ['unit tests', 'test file', 'configuration file'] lowerCamelCase_ = example['content'].splitlines() lowerCamelCase_ = 0 lowerCamelCase_ = 0 # first test for _, line in zip(range(_lowerCamelCase ) , _lowerCamelCase ): for keyword in keywords: if keyword in line.lower(): return {"config_or_test": True} # second test lowerCamelCase_ = example['content'].count('\n' ) lowerCamelCase_ = int(coeff * nlines ) for line in lines: count_config += line.lower().count('config' ) count_test += line.lower().count('test' ) if count_config > threshold or count_test > threshold: return {"config_or_test": True} return {"config_or_test": False} def lowerCamelCase__ ( _lowerCamelCase : Any ) -> List[str]: lowerCamelCase_ = ['def ', 'class ', 'for ', 'while '] lowerCamelCase_ = example['content'].splitlines() for line in lines: for keyword in keywords: if keyword in line.lower(): return {"has_no_keywords": False} return {"has_no_keywords": True} def lowerCamelCase__ ( _lowerCamelCase : Dict , _lowerCamelCase : Dict=4 ) -> Optional[Any]: lowerCamelCase_ = example['content'].splitlines() lowerCamelCase_ = 0 for line in lines: counter += line.lower().count('=' ) if counter > minimum: return {"has_few_assignments": False} return {"has_few_assignments": True} def lowerCamelCase__ ( _lowerCamelCase : Dict ) -> List[str]: lowerCamelCase_ = tokenizer(example['content'] , truncation=_lowerCamelCase )['input_ids'] lowerCamelCase_ = len(example['content'] ) / len(_lowerCamelCase ) return {"ratio": ratio} def lowerCamelCase__ ( _lowerCamelCase : Optional[Any] ) -> List[Any]: lowerCamelCase_ = {} results.update(get_hash(_lowerCamelCase ) ) results.update(line_stats(_lowerCamelCase ) ) results.update(alpha_stats(_lowerCamelCase ) ) results.update(char_token_ratio(_lowerCamelCase ) ) results.update(is_autogenerated(_lowerCamelCase ) ) results.update(is_config_or_test(_lowerCamelCase ) ) results.update(has_no_keywords(_lowerCamelCase ) ) results.update(has_few_assignments(_lowerCamelCase ) ) return results def lowerCamelCase__ ( _lowerCamelCase : Any , _lowerCamelCase : Dict , _lowerCamelCase : Optional[Any] ) -> Any: if not check_uniques(_lowerCamelCase , _lowerCamelCase ): return False elif example["autogenerated"]: return False elif example["line_max"] > args.line_max: return False elif example["line_mean"] > args.line_mean: return False elif example["alpha_frac"] < args.alpha_frac: return False elif example["ratio"] < args.min_token_ratio: return False elif example["config_or_test"] and np.random.rand() <= args.filter_proba: return False elif example["has_no_keywords"] and np.random.rand() <= args.filter_proba: return False elif example["has_few_assignments"]: return False else: return True def lowerCamelCase__ ( _lowerCamelCase : str ) -> int: with open(_lowerCamelCase , 'rb' ) as f_in: with gzip.open(str(_lowerCamelCase ) + '.gz' , 'wb' , compresslevel=6 ) as f_out: shutil.copyfileobj(_lowerCamelCase , _lowerCamelCase ) os.unlink(_lowerCamelCase ) # Settings _SCREAMING_SNAKE_CASE : Optional[Any] = HfArgumentParser(PreprocessingArguments) _SCREAMING_SNAKE_CASE : Any = parser.parse_args() if args.num_workers is None: _SCREAMING_SNAKE_CASE : List[str] = multiprocessing.cpu_count() _SCREAMING_SNAKE_CASE : str = AutoTokenizer.from_pretrained(args.tokenizer_dir) # Load dataset _SCREAMING_SNAKE_CASE : Optional[Any] = time.time() _SCREAMING_SNAKE_CASE : int = load_dataset(args.dataset_name, split='''train''') print(F'''Time to load dataset: {time.time()-t_start:.2f}''') # Run preprocessing _SCREAMING_SNAKE_CASE : Optional[Any] = time.time() _SCREAMING_SNAKE_CASE : Tuple = ds.map(preprocess, num_proc=args.num_workers) print(F'''Time to preprocess dataset: {time.time()-t_start:.2f}''') # Deduplicate hashes _SCREAMING_SNAKE_CASE : List[Any] = set(ds.unique('''hash''')) _SCREAMING_SNAKE_CASE : Optional[int] = len(uniques) / len(ds) print(F'''Fraction of duplicates: {1-frac:.2%}''') # Deduplicate data and apply heuristics _SCREAMING_SNAKE_CASE : Dict = time.time() _SCREAMING_SNAKE_CASE : Tuple = ds.filter(filter, fn_kwargs={'''uniques''': uniques, '''args''': args}) print(F'''Time to filter dataset: {time.time()-t_start:.2f}''') print(F'''Size of filtered dataset: {len(ds_filter)}''') # Deduplicate with minhash and jaccard similarity if args.near_deduplication: _SCREAMING_SNAKE_CASE : Optional[Any] = time.time() _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Union[str, Any] = deduplicate_dataset(ds_filter, args.jaccard_threshold) print(F'''Time to deduplicate dataset: {time.time()-t_start:.2f}''') print(F'''Size of deduplicate dataset: {len(ds_filter)}''') # Save data in batches of samples_per_file _SCREAMING_SNAKE_CASE : Dict = Path(args.output_dir) output_dir.mkdir(exist_ok=True) # save duplicate_clusters in the output_dir as artifacts # not sure it is the right place the save it if args.near_deduplication: with open(output_dir / '''duplicate_clusters.json''', '''w''') as f: json.dump(duplicate_clusters, f) _SCREAMING_SNAKE_CASE : Optional[Any] = output_dir / '''data''' data_dir.mkdir(exist_ok=True) _SCREAMING_SNAKE_CASE : Optional[Any] = time.time() for file_number, index in enumerate(range(0, len(ds_filter), args.samples_per_file)): _SCREAMING_SNAKE_CASE : Dict = str(data_dir / F'''file-{file_number+1:012}.json''') _SCREAMING_SNAKE_CASE : Any = min(len(ds_filter), index + args.samples_per_file) ds_filter.select(list(range(index, end_index))).to_json(file_path) compress_file(file_path) print(F'''Time to save dataset: {time.time()-t_start:.2f}''')
549
0
from typing import TYPE_CHECKING from ...utils import _LazyModule UpperCAmelCase__ = {"""tokenization_wav2vec2_phoneme""": ["""Wav2Vec2PhonemeCTCTokenizer"""]} if TYPE_CHECKING: from .tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizer else: import sys UpperCAmelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
714
"""simple docstring""" from unittest.mock import patch import pyspark from datasets.packaged_modules.spark.spark import ( Spark, SparkExamplesIterable, _generate_iterable_examples, ) from ..utils import ( require_dill_gt_0_3_2, require_not_windows, ) def __UpperCAmelCase ( lowercase ,lowercase ): """simple docstring""" _UpperCAmelCase = [] for part_id in partition_order: _UpperCAmelCase = df.where(f'''SPARK_PARTITION_ID() = {part_id}''' ).collect() for row_idx, row in enumerate(lowercase ): expected_row_ids_and_row_dicts.append((f'''{part_id}_{row_idx}''', row.asDict()) ) return expected_row_ids_and_row_dicts @require_not_windows @require_dill_gt_0_3_2 def __UpperCAmelCase ( ): """simple docstring""" _UpperCAmelCase = pyspark.sql.SparkSession.builder.master("""local[*]""" ).appName("""pyspark""" ).getOrCreate() _UpperCAmelCase = spark.range(1_00 ).repartition(1 ) _UpperCAmelCase = Spark(lowercase ) # The id ints will be converted to Pyarrow int64s, so each row will be 8 bytes. Setting a max_shard_size of 16 means # that each partition can hold 2 rows. spark_builder._repartition_df_if_needed(max_shard_size=16 ) # Given that the dataframe has 100 rows and each partition has 2 rows, we expect 50 partitions. assert spark_builder.df.rdd.getNumPartitions() == 50 @require_not_windows @require_dill_gt_0_3_2 def __UpperCAmelCase ( ): """simple docstring""" _UpperCAmelCase = pyspark.sql.SparkSession.builder.master("""local[*]""" ).appName("""pyspark""" ).getOrCreate() _UpperCAmelCase = spark.range(10 ).repartition(2 ) _UpperCAmelCase = [1, 0] _UpperCAmelCase = _generate_iterable_examples(lowercase ,lowercase ) # Reverse the partitions. _UpperCAmelCase = _get_expected_row_ids_and_row_dicts_for_partition_order(lowercase ,lowercase ) for i, (row_id, row_dict) in enumerate(generate_fn() ): _UpperCAmelCase , _UpperCAmelCase = expected_row_ids_and_row_dicts[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def __UpperCAmelCase ( ): """simple docstring""" _UpperCAmelCase = pyspark.sql.SparkSession.builder.master("""local[*]""" ).appName("""pyspark""" ).getOrCreate() _UpperCAmelCase = spark.range(10 ).repartition(1 ) _UpperCAmelCase = SparkExamplesIterable(lowercase ) assert it.n_shards == 1 for i, (row_id, row_dict) in enumerate(lowercase ): assert row_id == f'''0_{i}''' assert row_dict == {"id": i} @require_not_windows @require_dill_gt_0_3_2 def __UpperCAmelCase ( ): """simple docstring""" _UpperCAmelCase = pyspark.sql.SparkSession.builder.master("""local[*]""" ).appName("""pyspark""" ).getOrCreate() _UpperCAmelCase = spark.range(30 ).repartition(3 ) # Mock the generator so that shuffle reverses the partition indices. with patch("""numpy.random.Generator""" ) as generator_mock: _UpperCAmelCase = lambda lowercase : x.reverse() _UpperCAmelCase = _get_expected_row_ids_and_row_dicts_for_partition_order(lowercase ,[2, 1, 0] ) _UpperCAmelCase = SparkExamplesIterable(lowercase ).shuffle_data_sources(lowercase ) assert shuffled_it.n_shards == 3 for i, (row_id, row_dict) in enumerate(lowercase ): _UpperCAmelCase , _UpperCAmelCase = expected_row_ids_and_row_dicts[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def __UpperCAmelCase ( ): """simple docstring""" _UpperCAmelCase = pyspark.sql.SparkSession.builder.master("""local[*]""" ).appName("""pyspark""" ).getOrCreate() _UpperCAmelCase = spark.range(20 ).repartition(4 ) # Partitions 0 and 2 _UpperCAmelCase = SparkExamplesIterable(lowercase ).shard_data_sources(worker_id=0 ,num_workers=2 ) assert shard_it_a.n_shards == 2 _UpperCAmelCase = _get_expected_row_ids_and_row_dicts_for_partition_order(lowercase ,[0, 2] ) for i, (row_id, row_dict) in enumerate(lowercase ): _UpperCAmelCase , _UpperCAmelCase = expected_row_ids_and_row_dicts_a[i] assert row_id == expected_row_id assert row_dict == expected_row_dict # Partitions 1 and 3 _UpperCAmelCase = SparkExamplesIterable(lowercase ).shard_data_sources(worker_id=1 ,num_workers=2 ) assert shard_it_a.n_shards == 2 _UpperCAmelCase = _get_expected_row_ids_and_row_dicts_for_partition_order(lowercase ,[1, 3] ) for i, (row_id, row_dict) in enumerate(lowercase ): _UpperCAmelCase , _UpperCAmelCase = expected_row_ids_and_row_dicts_a[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def __UpperCAmelCase ( ): """simple docstring""" _UpperCAmelCase = pyspark.sql.SparkSession.builder.master("""local[*]""" ).appName("""pyspark""" ).getOrCreate() _UpperCAmelCase = spark.range(1_00 ).repartition(1 ) _UpperCAmelCase = Spark(lowercase ) # Choose a small max_shard_size for maximum partitioning. spark_builder._repartition_df_if_needed(max_shard_size=1 ) # The new number of partitions should not be greater than the number of rows. assert spark_builder.df.rdd.getNumPartitions() == 1_00
275
0
"""simple docstring""" import unittest import numpy as np from diffusers import OnnxStableDiffusionInpaintPipelineLegacy from diffusers.utils.testing_utils import ( is_onnx_available, load_image, load_numpy, nightly, require_onnxruntime, require_torch_gpu, ) if is_onnx_available(): import onnxruntime as ort @nightly @require_onnxruntime @require_torch_gpu class __UpperCamelCase ( unittest.TestCase ): @property def UpperCAmelCase__ ( self : Optional[Any] ) -> List[str]: return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def UpperCAmelCase__ ( self : List[str] ) -> Optional[Any]: lowerCAmelCase :str = ort.SessionOptions() lowerCAmelCase :Optional[Any] = False return options def UpperCAmelCase__ ( self : str ) -> str: lowerCAmelCase :str = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/in_paint/overture-creations-5sI6fQgYIuo.png' ) lowerCAmelCase :Optional[Any] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/in_paint/overture-creations-5sI6fQgYIuo_mask.png' ) lowerCAmelCase :Tuple = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/in_paint/red_cat_sitting_on_a_park_bench_onnx.npy' ) # using the PNDM scheduler by default lowerCAmelCase :Optional[Any] = OnnxStableDiffusionInpaintPipelineLegacy.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='onnx' , safety_checker=__lowerCamelCase , feature_extractor=__lowerCamelCase , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) lowerCAmelCase :Optional[int] = 'A red cat sitting on a park bench' lowerCAmelCase :Union[str, Any] = np.random.RandomState(0 ) lowerCAmelCase :str = pipe( prompt=__lowerCamelCase , image=__lowerCamelCase , mask_image=__lowerCamelCase , strength=0.7_5 , guidance_scale=7.5 , num_inference_steps=15 , generator=__lowerCamelCase , output_type='np' , ) lowerCAmelCase :Any = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 1e-2
553
from typing import Dict, List from nltk.translate import gleu_score import datasets from datasets import MetricInfo UpperCamelCase__ : Tuple = """\ @misc{wu2016googles, title={Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation}, author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes and Jeffrey Dean}, year={2016}, eprint={1609.08144}, archivePrefix={arXiv}, primaryClass={cs.CL} } """ UpperCamelCase__ : Union[str, Any] = """\ The BLEU score has some undesirable properties when used for single sentences, as it was designed to be a corpus measure. We therefore use a slightly different score for our RL experiments which we call the 'GLEU score'. For the GLEU score, we record all sub-sequences of 1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then compute a recall, which is the ratio of the number of matching n-grams to the number of total n-grams in the target (ground truth) sequence, and a precision, which is the ratio of the number of matching n-grams to the number of total n-grams in the generated output sequence. Then GLEU score is simply the minimum of recall and precision. This GLEU score's range is always between 0 (no matches) and 1 (all match) and it is symmetrical when switching output and target. According to our experiments, GLEU score correlates quite well with the BLEU metric on a corpus level but does not have its drawbacks for our per sentence reward objective. """ UpperCamelCase__ : Any = """\ Computes corpus-level Google BLEU (GLEU) score of translated segments against one or more references. Instead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching tokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values. Args: predictions (list of str): list of translations to score. Each translation should be tokenized into a list of tokens. references (list of list of str): list of lists of references for each translation. Each reference should be tokenized into a list of tokens. min_len (int): The minimum order of n-gram this function should extract. Defaults to 1. max_len (int): The maximum order of n-gram this function should extract. Defaults to 4. Returns: 'google_bleu': google_bleu score Examples: Example 1: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references) >>> print(round(results[\"google_bleu\"], 2)) 0.44 Example 2: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references) >>> print(round(results[\"google_bleu\"], 2)) 0.61 Example 3: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2) >>> print(round(results[\"google_bleu\"], 2)) 0.53 Example 4: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6) >>> print(round(results[\"google_bleu\"], 2)) 0.4 """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCamelCase_ ( datasets.Metric ): def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { '''predictions''': datasets.Sequence(datasets.Value('''string''' ,id='''token''' ) ,id='''sequence''' ), '''references''': datasets.Sequence( datasets.Sequence(datasets.Value('''string''' ,id='''token''' ) ,id='''sequence''' ) ,id='''references''' ), } ) ,) def SCREAMING_SNAKE_CASE_ ( self : List[str] ,__lowerCamelCase : List[List[List[str]]] ,__lowerCamelCase : List[List[str]] ,__lowerCamelCase : int = 1 ,__lowerCamelCase : int = 4 ,): '''simple docstring''' return { "google_bleu": gleu_score.corpus_gleu( list_of_references=__lowerCamelCase ,hypotheses=__lowerCamelCase ,min_len=__lowerCamelCase ,max_len=__lowerCamelCase ) }
387
0
'''simple docstring''' __lowercase = 0 # The first color of the flag. __lowercase = 1 # The second color of the flag. __lowercase = 2 # The third color of the flag. __lowercase = (red, white, blue) def snake_case__ ( _A: list ) -> List[str]: '''simple docstring''' if not sequence: return [] if len(__UpperCamelCase ) == 1: return list(__UpperCamelCase ) lowerCAmelCase = 0 lowerCAmelCase = len(__UpperCamelCase ) - 1 lowerCAmelCase = 0 while mid <= high: if sequence[mid] == colors[0]: lowerCAmelCase = sequence[mid], sequence[low] low += 1 mid += 1 elif sequence[mid] == colors[1]: mid += 1 elif sequence[mid] == colors[2]: lowerCAmelCase = sequence[high], sequence[mid] high -= 1 else: lowerCAmelCase = f"The elements inside the sequence must contains only {colors} values" raise ValueError(__UpperCamelCase ) return sequence if __name__ == "__main__": import doctest doctest.testmod() __lowercase = input('''Enter numbers separated by commas:\n''').strip() __lowercase = [int(item.strip()) for item in user_input.split(''',''')] print(f'{dutch_national_flag_sort(unsorted)}')
721
'''simple docstring''' from collections.abc import Generator from math import sin def snake_case__ ( _A: bytes ) -> bytes: '''simple docstring''' if len(_A ) != 32: raise ValueError("""Input must be of length 32""" ) lowerCAmelCase = b"""""" for i in [3, 2, 1, 0]: little_endian += string_aa[8 * i : 8 * i + 8] return little_endian def snake_case__ ( _A: int ) -> bytes: '''simple docstring''' if i < 0: raise ValueError("""Input must be non-negative""" ) lowerCAmelCase = format(_A , """08x""" )[-8:] lowerCAmelCase = b"""""" for i in [3, 2, 1, 0]: little_endian_hex += hex_rep[2 * i : 2 * i + 2].encode("""utf-8""" ) return little_endian_hex def snake_case__ ( _A: bytes ) -> bytes: '''simple docstring''' lowerCAmelCase = b"""""" for char in message: bit_string += format(_A , """08b""" ).encode("""utf-8""" ) lowerCAmelCase = format(len(_A ) , """064b""" ).encode("""utf-8""" ) # Pad bit_string to a multiple of 512 chars bit_string += b"1" while len(_A ) % 512 != 448: bit_string += b"0" bit_string += to_little_endian(start_len[32:] ) + to_little_endian(start_len[:32] ) return bit_string def snake_case__ ( _A: bytes ) -> Generator[list[int], None, None]: '''simple docstring''' if len(_A ) % 512 != 0: raise ValueError("""Input must have length that's a multiple of 512""" ) for pos in range(0 , len(_A ) , 512 ): lowerCAmelCase = bit_string[pos : pos + 512] lowerCAmelCase = [] for i in range(0 , 512 , 32 ): block_words.append(int(to_little_endian(block[i : i + 32] ) , 2 ) ) yield block_words def snake_case__ ( _A: int ) -> int: '''simple docstring''' if i < 0: raise ValueError("""Input must be non-negative""" ) lowerCAmelCase = format(_A , """032b""" ) lowerCAmelCase = """""" for c in i_str: new_str += "1" if c == "0" else "0" return int(_A , 2 ) def snake_case__ ( _A: int , _A: int ) -> int: '''simple docstring''' return (a + b) % 2**32 def snake_case__ ( _A: int , _A: int ) -> int: '''simple docstring''' if i < 0: raise ValueError("""Input must be non-negative""" ) if shift < 0: raise ValueError("""Shift must be non-negative""" ) return ((i << shift) ^ (i >> (32 - shift))) % 2**32 def snake_case__ ( _A: bytes ) -> bytes: '''simple docstring''' lowerCAmelCase = preprocess(_A ) lowerCAmelCase = [int(2**32 * abs(sin(i + 1 ) ) ) for i in range(64 )] # Starting states lowerCAmelCase = 0X6_7_4_5_2_3_0_1 lowerCAmelCase = 0Xe_f_c_d_a_b_8_9 lowerCAmelCase = 0X9_8_b_a_d_c_f_e lowerCAmelCase = 0X1_0_3_2_5_4_7_6 lowerCAmelCase = [ 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, ] # Process bit string in chunks, each with 16 32-char words for block_words in get_block_words(_A ): lowerCAmelCase = aa lowerCAmelCase = ba lowerCAmelCase = ca lowerCAmelCase = da # Hash current chunk for i in range(64 ): if i <= 15: # f = (b & c) | (not_32(b) & d) # Alternate definition for f lowerCAmelCase = d ^ (b & (c ^ d)) lowerCAmelCase = i elif i <= 31: # f = (d & b) | (not_32(d) & c) # Alternate definition for f lowerCAmelCase = c ^ (d & (b ^ c)) lowerCAmelCase = (5 * i + 1) % 16 elif i <= 47: lowerCAmelCase = b ^ c ^ d lowerCAmelCase = (3 * i + 5) % 16 else: lowerCAmelCase = c ^ (b | not_aa(_A )) lowerCAmelCase = (7 * i) % 16 lowerCAmelCase = (f + a + added_consts[i] + block_words[g]) % 2**32 lowerCAmelCase = d lowerCAmelCase = c lowerCAmelCase = b lowerCAmelCase = sum_aa(_A , left_rotate_aa(_A , shift_amounts[i] ) ) # Add hashed chunk to running total lowerCAmelCase = sum_aa(_A , _A ) lowerCAmelCase = sum_aa(_A , _A ) lowerCAmelCase = sum_aa(_A , _A ) lowerCAmelCase = sum_aa(_A , _A ) lowerCAmelCase = reformat_hex(_A ) + reformat_hex(_A ) + reformat_hex(_A ) + reformat_hex(_A ) return digest if __name__ == "__main__": import doctest doctest.testmod()
605
0